blob: 64008e109366fbb99f355b81b15031eb47e52348 [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"
Eli Friedmanfbc0dff2012-01-18 01:05:54 +000015#include "clang/Sema/DelayedDiagnostic.h"
Douglas Gregorc3a6ade2010-08-12 20:07:10 +000016#include "clang/Sema/Initialization.h"
17#include "clang/Sema/Lookup.h"
Eli Friedmanfbc0dff2012-01-18 01:05:54 +000018#include "clang/Sema/ScopeInfo.h"
Douglas Gregorc3a6ade2010-08-12 20:07:10 +000019#include "clang/Sema/AnalysisBasedWarnings.h"
Chris Lattnercb6a3822006-11-10 06:20:45 +000020#include "clang/AST/ASTContext.h"
Argyrios Kyrtzidise5dc5b32012-02-10 20:10:44 +000021#include "clang/AST/ASTConsumer.h"
Sebastian Redl2ac2c722011-04-29 08:19:30 +000022#include "clang/AST/ASTMutationListener.h"
Douglas Gregord1702062010-04-29 00:18:15 +000023#include "clang/AST/CXXInheritance.h"
Daniel Dunbar6e8aa532008-08-11 05:35:13 +000024#include "clang/AST/DeclObjC.h"
Anders Carlsson029fc692009-08-26 22:59:12 +000025#include "clang/AST/DeclTemplate.h"
Douglas Gregor8a01b2a2010-09-11 20:24:53 +000026#include "clang/AST/EvaluatedExprVisitor.h"
Douglas Gregor882211c2010-04-28 22:16:22 +000027#include "clang/AST/Expr.h"
Chris Lattneraa9c7ae2008-04-08 04:40:51 +000028#include "clang/AST/ExprCXX.h"
Steve Naroff021ca182008-05-29 21:12:08 +000029#include "clang/AST/ExprObjC.h"
Douglas Gregor5597ab42010-05-07 23:12:07 +000030#include "clang/AST/RecursiveASTVisitor.h"
Douglas Gregor882211c2010-04-28 22:16:22 +000031#include "clang/AST/TypeLoc.h"
Anders Carlsson029fc692009-08-26 22:59:12 +000032#include "clang/Basic/PartialDiagnostic.h"
Steve Narofff2fb89e2007-03-13 20:29:44 +000033#include "clang/Basic/SourceManager.h"
Chris Lattner5b183d82006-11-10 05:03:26 +000034#include "clang/Basic/TargetInfo.h"
Anders Carlsson029fc692009-08-26 22:59:12 +000035#include "clang/Lex/LiteralSupport.h"
36#include "clang/Lex/Preprocessor.h"
John McCall8b0666c2010-08-20 18:27:03 +000037#include "clang/Sema/DeclSpec.h"
38#include "clang/Sema/Designator.h"
39#include "clang/Sema/Scope.h"
John McCallaab3e412010-08-25 08:40:02 +000040#include "clang/Sema/ScopeInfo.h"
John McCall8b0666c2010-08-20 18:27:03 +000041#include "clang/Sema/ParsedTemplate.h"
Anna Zaks3b402712011-07-28 19:51:27 +000042#include "clang/Sema/SemaFixItUtils.h"
John McCallde6836a2010-08-24 07:21:54 +000043#include "clang/Sema/Template.h"
Eli Friedman456f0182012-01-20 01:26:23 +000044#include "TreeTransform.h"
Chris Lattner5b183d82006-11-10 05:03:26 +000045using namespace clang;
John McCallaab3e412010-08-25 08:40:02 +000046using namespace sema;
Chris Lattner5b183d82006-11-10 05:03:26 +000047
Sebastian Redlb49c46c2011-09-24 17:48:00 +000048/// \brief Determine whether the use of this declaration is valid, without
49/// emitting diagnostics.
50bool Sema::CanUseDecl(NamedDecl *D) {
51 // See if this is an auto-typed variable whose initializer we are parsing.
52 if (ParsingInitForAutoVars.count(D))
53 return false;
54
55 // See if this is a deleted function.
56 if (FunctionDecl *FD = dyn_cast<FunctionDecl>(D)) {
57 if (FD->isDeleted())
58 return false;
59 }
Sebastian Redl5999aec2011-10-16 18:19:16 +000060
61 // See if this function is unavailable.
62 if (D->getAvailability() == AR_Unavailable &&
63 cast<Decl>(CurContext)->getAvailability() != AR_Unavailable)
64 return false;
65
Sebastian Redlb49c46c2011-09-24 17:48:00 +000066 return true;
67}
David Chisnall9f57c292009-08-17 16:35:33 +000068
Ted Kremenek6eb25622012-02-10 02:45:47 +000069static AvailabilityResult DiagnoseAvailabilityOfDecl(Sema &S,
Fariborz Jahanian6b854c52011-09-29 22:45:21 +000070 NamedDecl *D, SourceLocation Loc,
71 const ObjCInterfaceDecl *UnknownObjCClass) {
72 // See if this declaration is unavailable or deprecated.
73 std::string Message;
74 AvailabilityResult Result = D->getAvailability(&Message);
Fariborz Jahanian25d09c22011-11-28 19:45:58 +000075 if (const EnumConstantDecl *ECD = dyn_cast<EnumConstantDecl>(D))
76 if (Result == AR_Available) {
77 const DeclContext *DC = ECD->getDeclContext();
78 if (const EnumDecl *TheEnumDecl = dyn_cast<EnumDecl>(DC))
79 Result = TheEnumDecl->getAvailability(&Message);
80 }
81
Fariborz Jahanian6b854c52011-09-29 22:45:21 +000082 switch (Result) {
83 case AR_Available:
84 case AR_NotYetIntroduced:
85 break;
86
87 case AR_Deprecated:
Ted Kremenek6eb25622012-02-10 02:45:47 +000088 S.EmitDeprecationWarning(D, Message, Loc, UnknownObjCClass);
Fariborz Jahanian6b854c52011-09-29 22:45:21 +000089 break;
90
91 case AR_Unavailable:
Ted Kremenek6eb25622012-02-10 02:45:47 +000092 if (S.getCurContextAvailability() != AR_Unavailable) {
Fariborz Jahanian6b854c52011-09-29 22:45:21 +000093 if (Message.empty()) {
94 if (!UnknownObjCClass)
Ted Kremenek6eb25622012-02-10 02:45:47 +000095 S.Diag(Loc, diag::err_unavailable) << D->getDeclName();
Fariborz Jahanian6b854c52011-09-29 22:45:21 +000096 else
Ted Kremenek6eb25622012-02-10 02:45:47 +000097 S.Diag(Loc, diag::warn_unavailable_fwdclass_message)
Fariborz Jahanian6b854c52011-09-29 22:45:21 +000098 << D->getDeclName();
99 }
100 else
Ted Kremenek6eb25622012-02-10 02:45:47 +0000101 S.Diag(Loc, diag::err_unavailable_message)
Fariborz Jahanian6b854c52011-09-29 22:45:21 +0000102 << D->getDeclName() << Message;
Ted Kremenek6eb25622012-02-10 02:45:47 +0000103 S.Diag(D->getLocation(), diag::note_unavailable_here)
Fariborz Jahanian6b854c52011-09-29 22:45:21 +0000104 << isa<FunctionDecl>(D) << false;
105 }
106 break;
107 }
108 return Result;
109}
110
Douglas Gregor171c45a2009-02-18 21:56:37 +0000111/// \brief Determine whether the use of this declaration is valid, and
112/// emit any corresponding diagnostics.
113///
114/// This routine diagnoses various problems with referencing
115/// declarations that can occur when using a declaration. For example,
116/// it might warn if a deprecated or unavailable declaration is being
117/// used, or produce an error (and return true) if a C++0x deleted
118/// function is being used.
119///
120/// \returns true if there was an error (this declaration cannot be
121/// referenced), false otherwise.
Chris Lattnerb7df3c62009-10-25 22:31:57 +0000122///
Fariborz Jahanian7d6e11a2010-12-21 00:44:01 +0000123bool Sema::DiagnoseUseOfDecl(NamedDecl *D, SourceLocation Loc,
Fariborz Jahanian6b854c52011-09-29 22:45:21 +0000124 const ObjCInterfaceDecl *UnknownObjCClass) {
Douglas Gregor5bb5e4a2010-10-12 23:32:35 +0000125 if (getLangOptions().CPlusPlus && isa<FunctionDecl>(D)) {
126 // If there were any diagnostics suppressed by template argument deduction,
127 // emit them now.
Chris Lattner0e62c1c2011-07-23 10:55:15 +0000128 llvm::DenseMap<Decl *, SmallVector<PartialDiagnosticAt, 1> >::iterator
Douglas Gregor5bb5e4a2010-10-12 23:32:35 +0000129 Pos = SuppressedDiagnostics.find(D->getCanonicalDecl());
130 if (Pos != SuppressedDiagnostics.end()) {
Chris Lattner0e62c1c2011-07-23 10:55:15 +0000131 SmallVectorImpl<PartialDiagnosticAt> &Suppressed = Pos->second;
Douglas Gregor5bb5e4a2010-10-12 23:32:35 +0000132 for (unsigned I = 0, N = Suppressed.size(); I != N; ++I)
133 Diag(Suppressed[I].first, Suppressed[I].second);
134
135 // Clear out the list of suppressed diagnostics, so that we don't emit
Douglas Gregor20b2ebd2011-03-23 00:50:03 +0000136 // them again for this specialization. However, we don't obsolete this
Douglas Gregor5bb5e4a2010-10-12 23:32:35 +0000137 // entry from the table, because we want to avoid ever emitting these
138 // diagnostics again.
139 Suppressed.clear();
140 }
141 }
142
Richard Smith30482bc2011-02-20 03:19:35 +0000143 // See if this is an auto-typed variable whose initializer we are parsing.
Richard Smithb2bc2e62011-02-21 20:05:19 +0000144 if (ParsingInitForAutoVars.count(D)) {
145 Diag(Loc, diag::err_auto_variable_cannot_appear_in_own_initializer)
146 << D->getDeclName();
147 return true;
Richard Smith30482bc2011-02-20 03:19:35 +0000148 }
149
Douglas Gregor171c45a2009-02-18 21:56:37 +0000150 // See if this is a deleted function.
Douglas Gregorde681d42009-02-24 04:26:15 +0000151 if (FunctionDecl *FD = dyn_cast<FunctionDecl>(D)) {
Douglas Gregor171c45a2009-02-18 21:56:37 +0000152 if (FD->isDeleted()) {
153 Diag(Loc, diag::err_deleted_function_use);
John McCall31168b02011-06-15 23:02:42 +0000154 Diag(D->getLocation(), diag::note_unavailable_here) << 1 << true;
Douglas Gregor171c45a2009-02-18 21:56:37 +0000155 return true;
156 }
Douglas Gregorde681d42009-02-24 04:26:15 +0000157 }
Ted Kremenek6eb25622012-02-10 02:45:47 +0000158 DiagnoseAvailabilityOfDecl(*this, D, Loc, UnknownObjCClass);
Douglas Gregor20b2ebd2011-03-23 00:50:03 +0000159
Anders Carlsson73067a02010-10-22 23:37:08 +0000160 // Warn if this is used but marked unused.
Fariborz Jahanian6b854c52011-09-29 22:45:21 +0000161 if (D->hasAttr<UnusedAttr>())
Anders Carlsson73067a02010-10-22 23:37:08 +0000162 Diag(Loc, diag::warn_used_but_marked_unused) << D->getDeclName();
Douglas Gregor171c45a2009-02-18 21:56:37 +0000163 return false;
Chris Lattner4bf74fd2009-02-15 22:43:40 +0000164}
165
Douglas Gregor20b2ebd2011-03-23 00:50:03 +0000166/// \brief Retrieve the message suffix that should be added to a
167/// diagnostic complaining about the given function being deleted or
168/// unavailable.
169std::string Sema::getDeletedOrUnavailableSuffix(const FunctionDecl *FD) {
170 // FIXME: C++0x implicitly-deleted special member functions could be
171 // detected here so that we could improve diagnostics to say, e.g.,
172 // "base class 'A' had a deleted copy constructor".
173 if (FD->isDeleted())
174 return std::string();
175
176 std::string Message;
177 if (FD->getAvailability(&Message))
178 return ": " + Message;
179
180 return std::string();
181}
182
John McCallb46f2872011-09-09 07:56:05 +0000183/// DiagnoseSentinelCalls - This routine checks whether a call or
184/// message-send is to a declaration with the sentinel attribute, and
185/// if so, it checks that the requirements of the sentinel are
186/// satisfied.
Fariborz Jahanian027b8862009-05-13 18:09:35 +0000187void Sema::DiagnoseSentinelCalls(NamedDecl *D, SourceLocation Loc,
John McCallb46f2872011-09-09 07:56:05 +0000188 Expr **args, unsigned numArgs) {
Argyrios Kyrtzidisb4b64ca2009-06-30 02:34:44 +0000189 const SentinelAttr *attr = D->getAttr<SentinelAttr>();
Mike Stump11289f42009-09-09 15:08:12 +0000190 if (!attr)
Fariborz Jahanian9e877212009-05-13 23:20:50 +0000191 return;
Douglas Gregorc298ffc2010-04-22 16:44:27 +0000192
John McCallb46f2872011-09-09 07:56:05 +0000193 // The number of formal parameters of the declaration.
194 unsigned numFormalParams;
Mike Stump11289f42009-09-09 15:08:12 +0000195
John McCallb46f2872011-09-09 07:56:05 +0000196 // The kind of declaration. This is also an index into a %select in
197 // the diagnostic.
198 enum CalleeType { CT_Function, CT_Method, CT_Block } calleeType;
199
Fariborz Jahanian4a528032009-05-14 18:00:00 +0000200 if (ObjCMethodDecl *MD = dyn_cast<ObjCMethodDecl>(D)) {
John McCallb46f2872011-09-09 07:56:05 +0000201 numFormalParams = MD->param_size();
202 calleeType = CT_Method;
Mike Stump12b8ce12009-08-04 21:02:39 +0000203 } else if (FunctionDecl *FD = dyn_cast<FunctionDecl>(D)) {
John McCallb46f2872011-09-09 07:56:05 +0000204 numFormalParams = FD->param_size();
205 calleeType = CT_Function;
206 } else if (isa<VarDecl>(D)) {
207 QualType type = cast<ValueDecl>(D)->getType();
208 const FunctionType *fn = 0;
209 if (const PointerType *ptr = type->getAs<PointerType>()) {
210 fn = ptr->getPointeeType()->getAs<FunctionType>();
211 if (!fn) return;
212 calleeType = CT_Function;
213 } else if (const BlockPointerType *ptr = type->getAs<BlockPointerType>()) {
214 fn = ptr->getPointeeType()->castAs<FunctionType>();
215 calleeType = CT_Block;
216 } else {
Fariborz Jahanian0aa5c452009-05-15 20:33:25 +0000217 return;
John McCallb46f2872011-09-09 07:56:05 +0000218 }
Fariborz Jahanian4a528032009-05-14 18:00:00 +0000219
John McCallb46f2872011-09-09 07:56:05 +0000220 if (const FunctionProtoType *proto = dyn_cast<FunctionProtoType>(fn)) {
221 numFormalParams = proto->getNumArgs();
222 } else {
223 numFormalParams = 0;
224 }
225 } else {
Fariborz Jahanian9e877212009-05-13 23:20:50 +0000226 return;
227 }
John McCallb46f2872011-09-09 07:56:05 +0000228
229 // "nullPos" is the number of formal parameters at the end which
230 // effectively count as part of the variadic arguments. This is
231 // useful if you would prefer to not have *any* formal parameters,
232 // but the language forces you to have at least one.
233 unsigned nullPos = attr->getNullPos();
234 assert((nullPos == 0 || nullPos == 1) && "invalid null position on sentinel");
235 numFormalParams = (nullPos > numFormalParams ? 0 : numFormalParams - nullPos);
236
237 // The number of arguments which should follow the sentinel.
238 unsigned numArgsAfterSentinel = attr->getSentinel();
239
240 // If there aren't enough arguments for all the formal parameters,
241 // the sentinel, and the args after the sentinel, complain.
242 if (numArgs < numFormalParams + numArgsAfterSentinel + 1) {
Fariborz Jahanian9e877212009-05-13 23:20:50 +0000243 Diag(Loc, diag::warn_not_enough_argument) << D->getDeclName();
John McCallb46f2872011-09-09 07:56:05 +0000244 Diag(D->getLocation(), diag::note_sentinel_here) << calleeType;
Fariborz Jahanian9e877212009-05-13 23:20:50 +0000245 return;
246 }
John McCallb46f2872011-09-09 07:56:05 +0000247
248 // Otherwise, find the sentinel expression.
249 Expr *sentinelExpr = args[numArgs - numArgsAfterSentinel - 1];
John McCall7ddbcf42010-05-06 23:53:00 +0000250 if (!sentinelExpr) return;
John McCall7ddbcf42010-05-06 23:53:00 +0000251 if (sentinelExpr->isValueDependent()) return;
Argyrios Kyrtzidis2e809ce2012-02-03 05:58:16 +0000252 if (Context.isSentinelNullExpr(sentinelExpr)) return;
John McCall7ddbcf42010-05-06 23:53:00 +0000253
John McCallb46f2872011-09-09 07:56:05 +0000254 // Pick a reasonable string to insert. Optimistically use 'nil' or
255 // 'NULL' if those are actually defined in the context. Only use
256 // 'nil' for ObjC methods, where it's much more likely that the
257 // variadic arguments form a list of object pointers.
258 SourceLocation MissingNilLoc
Douglas Gregor5ff4e982011-07-30 08:57:03 +0000259 = PP.getLocForEndOfToken(sentinelExpr->getLocEnd());
260 std::string NullValue;
John McCallb46f2872011-09-09 07:56:05 +0000261 if (calleeType == CT_Method &&
262 PP.getIdentifierInfo("nil")->hasMacroDefinition())
Douglas Gregor5ff4e982011-07-30 08:57:03 +0000263 NullValue = "nil";
264 else if (PP.getIdentifierInfo("NULL")->hasMacroDefinition())
265 NullValue = "NULL";
Douglas Gregor5ff4e982011-07-30 08:57:03 +0000266 else
John McCallb46f2872011-09-09 07:56:05 +0000267 NullValue = "(void*) 0";
Eli Friedman9ab36372011-09-27 23:46:37 +0000268
269 if (MissingNilLoc.isInvalid())
270 Diag(Loc, diag::warn_missing_sentinel) << calleeType;
271 else
272 Diag(MissingNilLoc, diag::warn_missing_sentinel)
273 << calleeType
274 << FixItHint::CreateInsertion(MissingNilLoc, ", " + NullValue);
John McCallb46f2872011-09-09 07:56:05 +0000275 Diag(D->getLocation(), diag::note_sentinel_here) << calleeType;
Fariborz Jahanian027b8862009-05-13 18:09:35 +0000276}
277
Richard Trieuba63ce62011-09-09 01:45:06 +0000278SourceRange Sema::getExprRange(Expr *E) const {
279 return E ? E->getSourceRange() : SourceRange();
Douglas Gregor87f95b02009-02-26 21:00:50 +0000280}
281
Chris Lattner513165e2008-07-25 21:10:04 +0000282//===----------------------------------------------------------------------===//
283// Standard Promotions and Conversions
284//===----------------------------------------------------------------------===//
285
Chris Lattner513165e2008-07-25 21:10:04 +0000286/// DefaultFunctionArrayConversion (C99 6.3.2.1p3, C99 6.3.2.1p4).
John Wiegley01296292011-04-08 18:41:53 +0000287ExprResult Sema::DefaultFunctionArrayConversion(Expr *E) {
John McCall50a2c2c2011-10-11 23:14:30 +0000288 // Handle any placeholder expressions which made it here.
289 if (E->getType()->isPlaceholderType()) {
290 ExprResult result = CheckPlaceholderExpr(E);
291 if (result.isInvalid()) return ExprError();
292 E = result.take();
293 }
294
Chris Lattner513165e2008-07-25 21:10:04 +0000295 QualType Ty = E->getType();
296 assert(!Ty.isNull() && "DefaultFunctionArrayConversion - missing type");
297
Chris Lattner513165e2008-07-25 21:10:04 +0000298 if (Ty->isFunctionType())
John Wiegley01296292011-04-08 18:41:53 +0000299 E = ImpCastExprToType(E, Context.getPointerType(Ty),
300 CK_FunctionToPointerDecay).take();
Chris Lattner61f60a02008-07-25 21:33:13 +0000301 else if (Ty->isArrayType()) {
302 // In C90 mode, arrays only promote to pointers if the array expression is
303 // an lvalue. The relevant legalese is C90 6.2.2.1p3: "an lvalue that has
304 // type 'array of type' is converted to an expression that has type 'pointer
305 // to type'...". In C99 this was changed to: C99 6.3.2.1p3: "an expression
306 // that has type 'array of type' ...". The relevant change is "an lvalue"
307 // (C90) to "an expression" (C99).
Argyrios Kyrtzidis9321c742008-09-11 04:25:59 +0000308 //
309 // C++ 4.2p1:
310 // An lvalue or rvalue of type "array of N T" or "array of unknown bound of
311 // T" can be converted to an rvalue of type "pointer to T".
312 //
John McCall086a4642010-11-24 05:12:34 +0000313 if (getLangOptions().C99 || getLangOptions().CPlusPlus || E->isLValue())
John Wiegley01296292011-04-08 18:41:53 +0000314 E = ImpCastExprToType(E, Context.getArrayDecayedType(Ty),
315 CK_ArrayToPointerDecay).take();
Chris Lattner61f60a02008-07-25 21:33:13 +0000316 }
John Wiegley01296292011-04-08 18:41:53 +0000317 return Owned(E);
Chris Lattner513165e2008-07-25 21:10:04 +0000318}
319
Argyrios Kyrtzidisa9b630e2011-04-26 17:41:22 +0000320static void CheckForNullPointerDereference(Sema &S, Expr *E) {
321 // Check to see if we are dereferencing a null pointer. If so,
322 // and if not volatile-qualified, this is undefined behavior that the
323 // optimizer will delete, so warn about it. People sometimes try to use this
324 // to get a deterministic trap and are surprised by clang's behavior. This
325 // only handles the pattern "*null", which is a very syntactic check.
326 if (UnaryOperator *UO = dyn_cast<UnaryOperator>(E->IgnoreParenCasts()))
327 if (UO->getOpcode() == UO_Deref &&
328 UO->getSubExpr()->IgnoreParenCasts()->
329 isNullPointerConstant(S.Context, Expr::NPC_ValueDependentIsNotNull) &&
330 !UO->getType().isVolatileQualified()) {
331 S.DiagRuntimeBehavior(UO->getOperatorLoc(), UO,
332 S.PDiag(diag::warn_indirection_through_null)
333 << UO->getSubExpr()->getSourceRange());
334 S.DiagRuntimeBehavior(UO->getOperatorLoc(), UO,
335 S.PDiag(diag::note_indirection_through_null));
336 }
337}
338
John Wiegley01296292011-04-08 18:41:53 +0000339ExprResult Sema::DefaultLvalueConversion(Expr *E) {
John McCall50a2c2c2011-10-11 23:14:30 +0000340 // Handle any placeholder expressions which made it here.
341 if (E->getType()->isPlaceholderType()) {
342 ExprResult result = CheckPlaceholderExpr(E);
343 if (result.isInvalid()) return ExprError();
344 E = result.take();
345 }
346
John McCallf3735e02010-12-01 04:43:34 +0000347 // C++ [conv.lval]p1:
348 // A glvalue of a non-function, non-array type T can be
349 // converted to a prvalue.
John Wiegley01296292011-04-08 18:41:53 +0000350 if (!E->isGLValue()) return Owned(E);
Kaelyn Uhrain2e7aa5a2011-08-05 23:18:04 +0000351
John McCall27584242010-12-06 20:48:59 +0000352 QualType T = E->getType();
353 assert(!T.isNull() && "r-value conversion on typeless expression?");
John McCall34376a62010-12-04 03:47:34 +0000354
Eli Friedman0dfb8892011-10-06 23:00:33 +0000355 // We can't do lvalue-to-rvalue on atomics yet.
John McCall526ab472011-10-25 17:37:35 +0000356 if (T->isAtomicType())
Eli Friedman0dfb8892011-10-06 23:00:33 +0000357 return Owned(E);
358
John McCall27584242010-12-06 20:48:59 +0000359 // We don't want to throw lvalue-to-rvalue casts on top of
360 // expressions of certain types in C++.
361 if (getLangOptions().CPlusPlus &&
362 (E->getType() == Context.OverloadTy ||
363 T->isDependentType() ||
364 T->isRecordType()))
John Wiegley01296292011-04-08 18:41:53 +0000365 return Owned(E);
John McCall27584242010-12-06 20:48:59 +0000366
367 // The C standard is actually really unclear on this point, and
368 // DR106 tells us what the result should be but not why. It's
369 // generally best to say that void types just doesn't undergo
370 // lvalue-to-rvalue at all. Note that expressions of unqualified
371 // 'void' type are never l-values, but qualified void can be.
372 if (T->isVoidType())
John Wiegley01296292011-04-08 18:41:53 +0000373 return Owned(E);
John McCall27584242010-12-06 20:48:59 +0000374
Argyrios Kyrtzidisa9b630e2011-04-26 17:41:22 +0000375 CheckForNullPointerDereference(*this, E);
376
John McCall27584242010-12-06 20:48:59 +0000377 // C++ [conv.lval]p1:
378 // [...] If T is a non-class type, the type of the prvalue is the
379 // cv-unqualified version of T. Otherwise, the type of the
380 // rvalue is T.
381 //
382 // C99 6.3.2.1p2:
383 // If the lvalue has qualified type, the value has the unqualified
384 // version of the type of the lvalue; otherwise, the value has the
Anton Korobeynikovf0c267e2011-10-14 23:23:15 +0000385 // type of the lvalue.
John McCall27584242010-12-06 20:48:59 +0000386 if (T.hasQualifiers())
387 T = T.getUnqualifiedType();
Anton Korobeynikovf0c267e2011-10-14 23:23:15 +0000388
Eli Friedman3bda6b12012-02-02 23:15:15 +0000389 UpdateMarkingForLValueToRValue(E);
390
Anton Korobeynikovf0c267e2011-10-14 23:23:15 +0000391 ExprResult Res = Owned(ImplicitCastExpr::Create(Context, T, CK_LValueToRValue,
392 E, 0, VK_RValue));
393
394 return Res;
John McCall27584242010-12-06 20:48:59 +0000395}
396
John Wiegley01296292011-04-08 18:41:53 +0000397ExprResult Sema::DefaultFunctionArrayLvalueConversion(Expr *E) {
398 ExprResult Res = DefaultFunctionArrayConversion(E);
399 if (Res.isInvalid())
400 return ExprError();
401 Res = DefaultLvalueConversion(Res.take());
402 if (Res.isInvalid())
403 return ExprError();
404 return move(Res);
Douglas Gregorb92a1562010-02-03 00:27:59 +0000405}
406
407
Chris Lattner513165e2008-07-25 21:10:04 +0000408/// UsualUnaryConversions - Performs various conversions that are common to most
Mike Stump11289f42009-09-09 15:08:12 +0000409/// operators (C99 6.3). The conversions of array and function types are
Chris Lattner57540c52011-04-15 05:22:18 +0000410/// sometimes suppressed. For example, the array->pointer conversion doesn't
Chris Lattner513165e2008-07-25 21:10:04 +0000411/// apply if the array is an argument to the sizeof or address (&) operators.
412/// In these instances, this routine should *not* be called.
John Wiegley01296292011-04-08 18:41:53 +0000413ExprResult Sema::UsualUnaryConversions(Expr *E) {
John McCallf3735e02010-12-01 04:43:34 +0000414 // First, convert to an r-value.
John Wiegley01296292011-04-08 18:41:53 +0000415 ExprResult Res = DefaultFunctionArrayLvalueConversion(E);
416 if (Res.isInvalid())
417 return Owned(E);
418 E = Res.take();
Anton Korobeynikovf0c267e2011-10-14 23:23:15 +0000419
John McCallf3735e02010-12-01 04:43:34 +0000420 QualType Ty = E->getType();
Chris Lattner513165e2008-07-25 21:10:04 +0000421 assert(!Ty.isNull() && "UsualUnaryConversions - missing type");
Anton Korobeynikovf0c267e2011-10-14 23:23:15 +0000422
423 // Half FP is a bit different: it's a storage-only type, meaning that any
424 // "use" of it should be promoted to float.
425 if (Ty->isHalfType())
426 return ImpCastExprToType(Res.take(), Context.FloatTy, CK_FloatingCast);
427
John McCallf3735e02010-12-01 04:43:34 +0000428 // Try to perform integral promotions if the object has a theoretically
429 // promotable type.
430 if (Ty->isIntegralOrUnscopedEnumerationType()) {
431 // C99 6.3.1.1p2:
432 //
433 // The following may be used in an expression wherever an int or
434 // unsigned int may be used:
435 // - an object or expression with an integer type whose integer
436 // conversion rank is less than or equal to the rank of int
437 // and unsigned int.
438 // - A bit-field of type _Bool, int, signed int, or unsigned int.
439 //
440 // If an int can represent all values of the original type, the
441 // value is converted to an int; otherwise, it is converted to an
442 // unsigned int. These are called the integer promotions. All
443 // other types are unchanged by the integer promotions.
Anton Korobeynikovf0c267e2011-10-14 23:23:15 +0000444
John McCallf3735e02010-12-01 04:43:34 +0000445 QualType PTy = Context.isPromotableBitField(E);
446 if (!PTy.isNull()) {
John Wiegley01296292011-04-08 18:41:53 +0000447 E = ImpCastExprToType(E, PTy, CK_IntegralCast).take();
448 return Owned(E);
John McCallf3735e02010-12-01 04:43:34 +0000449 }
450 if (Ty->isPromotableIntegerType()) {
451 QualType PT = Context.getPromotedIntegerType(Ty);
John Wiegley01296292011-04-08 18:41:53 +0000452 E = ImpCastExprToType(E, PT, CK_IntegralCast).take();
453 return Owned(E);
John McCallf3735e02010-12-01 04:43:34 +0000454 }
Eli Friedman629ffb92009-08-20 04:21:42 +0000455 }
John Wiegley01296292011-04-08 18:41:53 +0000456 return Owned(E);
Chris Lattner513165e2008-07-25 21:10:04 +0000457}
458
Chris Lattner2ce500f2008-07-25 22:25:12 +0000459/// DefaultArgumentPromotion (C99 6.5.2.2p6). Used for function calls that
Mike Stump11289f42009-09-09 15:08:12 +0000460/// do not have a prototype. Arguments that have type float are promoted to
Chris Lattner2ce500f2008-07-25 22:25:12 +0000461/// double. All other argument types are converted by UsualUnaryConversions().
John Wiegley01296292011-04-08 18:41:53 +0000462ExprResult Sema::DefaultArgumentPromotion(Expr *E) {
463 QualType Ty = E->getType();
Chris Lattner2ce500f2008-07-25 22:25:12 +0000464 assert(!Ty.isNull() && "DefaultArgumentPromotion - missing type");
Mike Stump11289f42009-09-09 15:08:12 +0000465
John Wiegley01296292011-04-08 18:41:53 +0000466 ExprResult Res = UsualUnaryConversions(E);
467 if (Res.isInvalid())
468 return Owned(E);
469 E = Res.take();
John McCall9bc26772010-12-06 18:36:11 +0000470
Chris Lattner2ce500f2008-07-25 22:25:12 +0000471 // If this is a 'float' (CVR qualified or typedef) promote to double.
Chris Lattnerbb53efb2010-05-16 04:01:30 +0000472 if (Ty->isSpecificBuiltinType(BuiltinType::Float))
John Wiegley01296292011-04-08 18:41:53 +0000473 E = ImpCastExprToType(E, Context.DoubleTy, CK_FloatingCast).take();
474
John McCall4bb057d2011-08-27 22:06:17 +0000475 // C++ performs lvalue-to-rvalue conversion as a default argument
John McCall0562caa2011-08-29 23:55:37 +0000476 // promotion, even on class types, but note:
477 // C++11 [conv.lval]p2:
478 // When an lvalue-to-rvalue conversion occurs in an unevaluated
479 // operand or a subexpression thereof the value contained in the
480 // referenced object is not accessed. Otherwise, if the glvalue
481 // has a class type, the conversion copy-initializes a temporary
482 // of type T from the glvalue and the result of the conversion
483 // is a prvalue for the temporary.
Eli Friedman05e28012012-01-17 02:13:45 +0000484 // FIXME: add some way to gate this entire thing for correctness in
485 // potentially potentially evaluated contexts.
486 if (getLangOptions().CPlusPlus && E->isGLValue() &&
487 ExprEvalContexts.back().Context != Unevaluated) {
488 ExprResult Temp = PerformCopyInitialization(
489 InitializedEntity::InitializeTemporary(E->getType()),
490 E->getExprLoc(),
491 Owned(E));
492 if (Temp.isInvalid())
493 return ExprError();
494 E = Temp.get();
John McCall29ad95b2011-08-27 01:09:30 +0000495 }
496
John Wiegley01296292011-04-08 18:41:53 +0000497 return Owned(E);
Chris Lattner2ce500f2008-07-25 22:25:12 +0000498}
499
Chris Lattnera8a7d0f2009-04-12 08:11:20 +0000500/// DefaultVariadicArgumentPromotion - Like DefaultArgumentPromotion, but
501/// will warn if the resulting type is not a POD type, and rejects ObjC
John Wiegley01296292011-04-08 18:41:53 +0000502/// interfaces passed by value.
503ExprResult Sema::DefaultVariadicArgumentPromotion(Expr *E, VariadicCallType CT,
John McCall31168b02011-06-15 23:02:42 +0000504 FunctionDecl *FDecl) {
John McCall4124c492011-10-17 18:40:02 +0000505 if (const BuiltinType *PlaceholderTy = E->getType()->getAsPlaceholderType()) {
506 // Strip the unbridged-cast placeholder expression off, if applicable.
507 if (PlaceholderTy->getKind() == BuiltinType::ARCUnbridgedCast &&
508 (CT == VariadicMethod ||
509 (FDecl && FDecl->hasAttr<CFAuditedTransferAttr>()))) {
510 E = stripARCUnbridgedCast(E);
511
512 // Otherwise, do normal placeholder checking.
513 } else {
514 ExprResult ExprRes = CheckPlaceholderExpr(E);
515 if (ExprRes.isInvalid())
516 return ExprError();
517 E = ExprRes.take();
518 }
519 }
Douglas Gregorcbd446d2011-06-17 00:15:10 +0000520
John McCall4124c492011-10-17 18:40:02 +0000521 ExprResult ExprRes = DefaultArgumentPromotion(E);
John Wiegley01296292011-04-08 18:41:53 +0000522 if (ExprRes.isInvalid())
523 return ExprError();
524 E = ExprRes.take();
Mike Stump11289f42009-09-09 15:08:12 +0000525
Douglas Gregor347e0f22011-05-21 19:26:31 +0000526 // Don't allow one to pass an Objective-C interface to a vararg.
John Wiegley01296292011-04-08 18:41:53 +0000527 if (E->getType()->isObjCObjectType() &&
Douglas Gregor347e0f22011-05-21 19:26:31 +0000528 DiagRuntimeBehavior(E->getLocStart(), 0,
529 PDiag(diag::err_cannot_pass_objc_interface_to_vararg)
530 << E->getType() << CT))
John Wiegley01296292011-04-08 18:41:53 +0000531 return ExprError();
John McCall29ad95b2011-08-27 01:09:30 +0000532
Douglas Gregor7e1aa5b2011-10-14 20:34:19 +0000533 // Complain about passing non-POD types through varargs. However, don't
534 // perform this check for incomplete types, which we can get here when we're
535 // in an unevaluated context.
536 if (!E->getType()->isIncompleteType() && !E->getType().isPODType(Context)) {
Douglas Gregor253cadf2011-05-21 16:27:21 +0000537 // C++0x [expr.call]p7:
538 // Passing a potentially-evaluated argument of class type (Clause 9)
539 // having a non-trivial copy constructor, a non-trivial move constructor,
540 // or a non-trivial destructor, with no corresponding parameter,
541 // is conditionally-supported with implementation-defined semantics.
542 bool TrivialEnough = false;
543 if (getLangOptions().CPlusPlus0x && !E->getType()->isDependentType()) {
544 if (CXXRecordDecl *Record = E->getType()->getAsCXXRecordDecl()) {
545 if (Record->hasTrivialCopyConstructor() &&
546 Record->hasTrivialMoveConstructor() &&
Richard Smith0bf8a4922011-10-18 20:49:44 +0000547 Record->hasTrivialDestructor()) {
548 DiagRuntimeBehavior(E->getLocStart(), 0,
549 PDiag(diag::warn_cxx98_compat_pass_non_pod_arg_to_vararg)
550 << E->getType() << CT);
Douglas Gregor253cadf2011-05-21 16:27:21 +0000551 TrivialEnough = true;
Richard Smith0bf8a4922011-10-18 20:49:44 +0000552 }
Douglas Gregor253cadf2011-05-21 16:27:21 +0000553 }
554 }
John McCall31168b02011-06-15 23:02:42 +0000555
556 if (!TrivialEnough &&
557 getLangOptions().ObjCAutoRefCount &&
558 E->getType()->isObjCLifetimeType())
559 TrivialEnough = true;
Douglas Gregor253cadf2011-05-21 16:27:21 +0000560
561 if (TrivialEnough) {
562 // Nothing to diagnose. This is okay.
563 } else if (DiagRuntimeBehavior(E->getLocStart(), 0,
Douglas Gregorda8cdbc2009-12-22 01:01:55 +0000564 PDiag(diag::warn_cannot_pass_non_pod_arg_to_vararg)
Douglas Gregor253cadf2011-05-21 16:27:21 +0000565 << getLangOptions().CPlusPlus0x << E->getType()
Douglas Gregor347e0f22011-05-21 19:26:31 +0000566 << CT)) {
567 // Turn this into a trap.
568 CXXScopeSpec SS;
Abramo Bagnara7945c982012-01-27 09:46:47 +0000569 SourceLocation TemplateKWLoc;
Douglas Gregor347e0f22011-05-21 19:26:31 +0000570 UnqualifiedId Name;
571 Name.setIdentifier(PP.getIdentifierInfo("__builtin_trap"),
572 E->getLocStart());
Abramo Bagnara7945c982012-01-27 09:46:47 +0000573 ExprResult TrapFn = ActOnIdExpression(TUScope, SS, TemplateKWLoc, Name,
574 true, false);
Douglas Gregor347e0f22011-05-21 19:26:31 +0000575 if (TrapFn.isInvalid())
576 return ExprError();
577
578 ExprResult Call = ActOnCallExpr(TUScope, TrapFn.get(), E->getLocStart(),
579 MultiExprArg(), E->getLocEnd());
580 if (Call.isInvalid())
581 return ExprError();
582
583 ExprResult Comma = ActOnBinOp(TUScope, E->getLocStart(), tok::comma,
584 Call.get(), E);
585 if (Comma.isInvalid())
John McCall1cd60a22011-08-26 18:41:18 +0000586 return ExprError();
Douglas Gregor347e0f22011-05-21 19:26:31 +0000587 E = Comma.get();
588 }
Douglas Gregor253cadf2011-05-21 16:27:21 +0000589 }
Fariborz Jahanianbf482812012-03-02 17:05:03 +0000590 // c++ rules are enforced elsewhere.
Fariborz Jahanian3854a552012-03-01 23:42:00 +0000591 if (!getLangOptions().CPlusPlus &&
Fariborz Jahanian3854a552012-03-01 23:42:00 +0000592 RequireCompleteType(E->getExprLoc(), E->getType(),
Fariborz Jahanianbf482812012-03-02 17:05:03 +0000593 diag::err_call_incomplete_argument))
Fariborz Jahanian3854a552012-03-01 23:42:00 +0000594 return ExprError();
Douglas Gregor253cadf2011-05-21 16:27:21 +0000595
John Wiegley01296292011-04-08 18:41:53 +0000596 return Owned(E);
Anders Carlssona7d069d2009-01-16 16:48:51 +0000597}
598
Richard Trieu7aa58f12011-09-02 20:58:51 +0000599/// \brief Converts an integer to complex float type. Helper function of
600/// UsualArithmeticConversions()
601///
602/// \return false if the integer expression is an integer type and is
603/// successfully converted to the complex type.
Richard Trieuba63ce62011-09-09 01:45:06 +0000604static bool handleIntegerToComplexFloatConversion(Sema &S, ExprResult &IntExpr,
605 ExprResult &ComplexExpr,
606 QualType IntTy,
607 QualType ComplexTy,
608 bool SkipCast) {
609 if (IntTy->isComplexType() || IntTy->isRealFloatingType()) return true;
610 if (SkipCast) return false;
611 if (IntTy->isIntegerType()) {
612 QualType fpTy = cast<ComplexType>(ComplexTy)->getElementType();
613 IntExpr = S.ImpCastExprToType(IntExpr.take(), fpTy, CK_IntegralToFloating);
614 IntExpr = S.ImpCastExprToType(IntExpr.take(), ComplexTy,
Richard Trieu7aa58f12011-09-02 20:58:51 +0000615 CK_FloatingRealToComplex);
616 } else {
Richard Trieuba63ce62011-09-09 01:45:06 +0000617 assert(IntTy->isComplexIntegerType());
618 IntExpr = S.ImpCastExprToType(IntExpr.take(), ComplexTy,
Richard Trieu7aa58f12011-09-02 20:58:51 +0000619 CK_IntegralComplexToFloatingComplex);
620 }
621 return false;
622}
623
624/// \brief Takes two complex float types and converts them to the same type.
625/// Helper function of UsualArithmeticConversions()
626static QualType
Richard Trieu5065cdd2011-09-06 18:25:09 +0000627handleComplexFloatToComplexFloatConverstion(Sema &S, ExprResult &LHS,
628 ExprResult &RHS, QualType LHSType,
629 QualType RHSType,
Richard Trieuba63ce62011-09-09 01:45:06 +0000630 bool IsCompAssign) {
Richard Trieu5065cdd2011-09-06 18:25:09 +0000631 int order = S.Context.getFloatingTypeOrder(LHSType, RHSType);
Richard Trieu7aa58f12011-09-02 20:58:51 +0000632
633 if (order < 0) {
634 // _Complex float -> _Complex double
Richard Trieuba63ce62011-09-09 01:45:06 +0000635 if (!IsCompAssign)
Richard Trieu5065cdd2011-09-06 18:25:09 +0000636 LHS = S.ImpCastExprToType(LHS.take(), RHSType, CK_FloatingComplexCast);
637 return RHSType;
Richard Trieu7aa58f12011-09-02 20:58:51 +0000638 }
639 if (order > 0)
640 // _Complex float -> _Complex double
Richard Trieu5065cdd2011-09-06 18:25:09 +0000641 RHS = S.ImpCastExprToType(RHS.take(), LHSType, CK_FloatingComplexCast);
642 return LHSType;
Richard Trieu7aa58f12011-09-02 20:58:51 +0000643}
644
645/// \brief Converts otherExpr to complex float and promotes complexExpr if
646/// necessary. Helper function of UsualArithmeticConversions()
647static QualType handleOtherComplexFloatConversion(Sema &S,
Richard Trieuba63ce62011-09-09 01:45:06 +0000648 ExprResult &ComplexExpr,
649 ExprResult &OtherExpr,
650 QualType ComplexTy,
651 QualType OtherTy,
652 bool ConvertComplexExpr,
653 bool ConvertOtherExpr) {
654 int order = S.Context.getFloatingTypeOrder(ComplexTy, OtherTy);
Richard Trieu7aa58f12011-09-02 20:58:51 +0000655
656 // If just the complexExpr is complex, the otherExpr needs to be converted,
657 // and the complexExpr might need to be promoted.
658 if (order > 0) { // complexExpr is wider
659 // float -> _Complex double
Richard Trieuba63ce62011-09-09 01:45:06 +0000660 if (ConvertOtherExpr) {
661 QualType fp = cast<ComplexType>(ComplexTy)->getElementType();
662 OtherExpr = S.ImpCastExprToType(OtherExpr.take(), fp, CK_FloatingCast);
663 OtherExpr = S.ImpCastExprToType(OtherExpr.take(), ComplexTy,
Richard Trieu7aa58f12011-09-02 20:58:51 +0000664 CK_FloatingRealToComplex);
665 }
Richard Trieuba63ce62011-09-09 01:45:06 +0000666 return ComplexTy;
Richard Trieu7aa58f12011-09-02 20:58:51 +0000667 }
668
669 // otherTy is at least as wide. Find its corresponding complex type.
Richard Trieuba63ce62011-09-09 01:45:06 +0000670 QualType result = (order == 0 ? ComplexTy :
671 S.Context.getComplexType(OtherTy));
Richard Trieu7aa58f12011-09-02 20:58:51 +0000672
673 // double -> _Complex double
Richard Trieuba63ce62011-09-09 01:45:06 +0000674 if (ConvertOtherExpr)
675 OtherExpr = S.ImpCastExprToType(OtherExpr.take(), result,
Richard Trieu7aa58f12011-09-02 20:58:51 +0000676 CK_FloatingRealToComplex);
677
678 // _Complex float -> _Complex double
Richard Trieuba63ce62011-09-09 01:45:06 +0000679 if (ConvertComplexExpr && order < 0)
680 ComplexExpr = S.ImpCastExprToType(ComplexExpr.take(), result,
Richard Trieu7aa58f12011-09-02 20:58:51 +0000681 CK_FloatingComplexCast);
682
683 return result;
684}
685
686/// \brief Handle arithmetic conversion with complex types. Helper function of
687/// UsualArithmeticConversions()
Richard Trieu5065cdd2011-09-06 18:25:09 +0000688static QualType handleComplexFloatConversion(Sema &S, ExprResult &LHS,
689 ExprResult &RHS, QualType LHSType,
690 QualType RHSType,
Richard Trieuba63ce62011-09-09 01:45:06 +0000691 bool IsCompAssign) {
Richard Trieu7aa58f12011-09-02 20:58:51 +0000692 // if we have an integer operand, the result is the complex type.
Richard Trieu5065cdd2011-09-06 18:25:09 +0000693 if (!handleIntegerToComplexFloatConversion(S, RHS, LHS, RHSType, LHSType,
Richard Trieu7aa58f12011-09-02 20:58:51 +0000694 /*skipCast*/false))
Richard Trieu5065cdd2011-09-06 18:25:09 +0000695 return LHSType;
696 if (!handleIntegerToComplexFloatConversion(S, LHS, RHS, LHSType, RHSType,
Richard Trieuba63ce62011-09-09 01:45:06 +0000697 /*skipCast*/IsCompAssign))
Richard Trieu5065cdd2011-09-06 18:25:09 +0000698 return RHSType;
Richard Trieu7aa58f12011-09-02 20:58:51 +0000699
700 // This handles complex/complex, complex/float, or float/complex.
701 // When both operands are complex, the shorter operand is converted to the
702 // type of the longer, and that is the type of the result. This corresponds
703 // to what is done when combining two real floating-point operands.
704 // The fun begins when size promotion occur across type domains.
705 // From H&S 6.3.4: When one operand is complex and the other is a real
706 // floating-point type, the less precise type is converted, within it's
707 // real or complex domain, to the precision of the other type. For example,
708 // when combining a "long double" with a "double _Complex", the
709 // "double _Complex" is promoted to "long double _Complex".
710
Richard Trieu5065cdd2011-09-06 18:25:09 +0000711 bool LHSComplexFloat = LHSType->isComplexType();
712 bool RHSComplexFloat = RHSType->isComplexType();
Richard Trieu7aa58f12011-09-02 20:58:51 +0000713
714 // If both are complex, just cast to the more precise type.
715 if (LHSComplexFloat && RHSComplexFloat)
Richard Trieu5065cdd2011-09-06 18:25:09 +0000716 return handleComplexFloatToComplexFloatConverstion(S, LHS, RHS,
717 LHSType, RHSType,
Richard Trieuba63ce62011-09-09 01:45:06 +0000718 IsCompAssign);
Richard Trieu7aa58f12011-09-02 20:58:51 +0000719
720 // If only one operand is complex, promote it if necessary and convert the
721 // other operand to complex.
722 if (LHSComplexFloat)
723 return handleOtherComplexFloatConversion(
Richard Trieuba63ce62011-09-09 01:45:06 +0000724 S, LHS, RHS, LHSType, RHSType, /*convertComplexExpr*/!IsCompAssign,
Richard Trieu7aa58f12011-09-02 20:58:51 +0000725 /*convertOtherExpr*/ true);
726
727 assert(RHSComplexFloat);
728 return handleOtherComplexFloatConversion(
Richard Trieu5065cdd2011-09-06 18:25:09 +0000729 S, RHS, LHS, RHSType, LHSType, /*convertComplexExpr*/true,
Richard Trieuba63ce62011-09-09 01:45:06 +0000730 /*convertOtherExpr*/ !IsCompAssign);
Richard Trieu7aa58f12011-09-02 20:58:51 +0000731}
732
733/// \brief Hande arithmetic conversion from integer to float. Helper function
734/// of UsualArithmeticConversions()
Richard Trieuba63ce62011-09-09 01:45:06 +0000735static QualType handleIntToFloatConversion(Sema &S, ExprResult &FloatExpr,
736 ExprResult &IntExpr,
737 QualType FloatTy, QualType IntTy,
738 bool ConvertFloat, bool ConvertInt) {
739 if (IntTy->isIntegerType()) {
740 if (ConvertInt)
Richard Trieu7aa58f12011-09-02 20:58:51 +0000741 // Convert intExpr to the lhs floating point type.
Richard Trieuba63ce62011-09-09 01:45:06 +0000742 IntExpr = S.ImpCastExprToType(IntExpr.take(), FloatTy,
Richard Trieu7aa58f12011-09-02 20:58:51 +0000743 CK_IntegralToFloating);
Richard Trieuba63ce62011-09-09 01:45:06 +0000744 return FloatTy;
Richard Trieu7aa58f12011-09-02 20:58:51 +0000745 }
746
747 // Convert both sides to the appropriate complex float.
Richard Trieuba63ce62011-09-09 01:45:06 +0000748 assert(IntTy->isComplexIntegerType());
749 QualType result = S.Context.getComplexType(FloatTy);
Richard Trieu7aa58f12011-09-02 20:58:51 +0000750
751 // _Complex int -> _Complex float
Richard Trieuba63ce62011-09-09 01:45:06 +0000752 if (ConvertInt)
753 IntExpr = S.ImpCastExprToType(IntExpr.take(), result,
Richard Trieu7aa58f12011-09-02 20:58:51 +0000754 CK_IntegralComplexToFloatingComplex);
755
756 // float -> _Complex float
Richard Trieuba63ce62011-09-09 01:45:06 +0000757 if (ConvertFloat)
758 FloatExpr = S.ImpCastExprToType(FloatExpr.take(), result,
Richard Trieu7aa58f12011-09-02 20:58:51 +0000759 CK_FloatingRealToComplex);
760
761 return result;
762}
763
764/// \brief Handle arithmethic conversion with floating point types. Helper
765/// function of UsualArithmeticConversions()
Richard Trieucfe3f212011-09-06 18:38:41 +0000766static QualType handleFloatConversion(Sema &S, ExprResult &LHS,
767 ExprResult &RHS, QualType LHSType,
Richard Trieuba63ce62011-09-09 01:45:06 +0000768 QualType RHSType, bool IsCompAssign) {
Richard Trieucfe3f212011-09-06 18:38:41 +0000769 bool LHSFloat = LHSType->isRealFloatingType();
770 bool RHSFloat = RHSType->isRealFloatingType();
Richard Trieu7aa58f12011-09-02 20:58:51 +0000771
772 // If we have two real floating types, convert the smaller operand
773 // to the bigger result.
774 if (LHSFloat && RHSFloat) {
Richard Trieucfe3f212011-09-06 18:38:41 +0000775 int order = S.Context.getFloatingTypeOrder(LHSType, RHSType);
Richard Trieu7aa58f12011-09-02 20:58:51 +0000776 if (order > 0) {
Richard Trieucfe3f212011-09-06 18:38:41 +0000777 RHS = S.ImpCastExprToType(RHS.take(), LHSType, CK_FloatingCast);
778 return LHSType;
Richard Trieu7aa58f12011-09-02 20:58:51 +0000779 }
780
781 assert(order < 0 && "illegal float comparison");
Richard Trieuba63ce62011-09-09 01:45:06 +0000782 if (!IsCompAssign)
Richard Trieucfe3f212011-09-06 18:38:41 +0000783 LHS = S.ImpCastExprToType(LHS.take(), RHSType, CK_FloatingCast);
784 return RHSType;
Richard Trieu7aa58f12011-09-02 20:58:51 +0000785 }
786
787 if (LHSFloat)
Richard Trieucfe3f212011-09-06 18:38:41 +0000788 return handleIntToFloatConversion(S, LHS, RHS, LHSType, RHSType,
Richard Trieuba63ce62011-09-09 01:45:06 +0000789 /*convertFloat=*/!IsCompAssign,
Richard Trieu7aa58f12011-09-02 20:58:51 +0000790 /*convertInt=*/ true);
791 assert(RHSFloat);
Richard Trieucfe3f212011-09-06 18:38:41 +0000792 return handleIntToFloatConversion(S, RHS, LHS, RHSType, LHSType,
Richard Trieu7aa58f12011-09-02 20:58:51 +0000793 /*convertInt=*/ true,
Richard Trieuba63ce62011-09-09 01:45:06 +0000794 /*convertFloat=*/!IsCompAssign);
Richard Trieu7aa58f12011-09-02 20:58:51 +0000795}
796
797/// \brief Handle conversions with GCC complex int extension. Helper function
Benjamin Kramer499c68b2011-09-06 19:57:14 +0000798/// of UsualArithmeticConversions()
Richard Trieu7aa58f12011-09-02 20:58:51 +0000799// FIXME: if the operands are (int, _Complex long), we currently
800// don't promote the complex. Also, signedness?
Benjamin Kramer499c68b2011-09-06 19:57:14 +0000801static QualType handleComplexIntConversion(Sema &S, ExprResult &LHS,
802 ExprResult &RHS, QualType LHSType,
803 QualType RHSType,
Richard Trieuba63ce62011-09-09 01:45:06 +0000804 bool IsCompAssign) {
Richard Trieucfe3f212011-09-06 18:38:41 +0000805 const ComplexType *LHSComplexInt = LHSType->getAsComplexIntegerType();
806 const ComplexType *RHSComplexInt = RHSType->getAsComplexIntegerType();
Richard Trieu7aa58f12011-09-02 20:58:51 +0000807
Richard Trieucfe3f212011-09-06 18:38:41 +0000808 if (LHSComplexInt && RHSComplexInt) {
809 int order = S.Context.getIntegerTypeOrder(LHSComplexInt->getElementType(),
810 RHSComplexInt->getElementType());
Richard Trieu7aa58f12011-09-02 20:58:51 +0000811 assert(order && "inequal types with equal element ordering");
812 if (order > 0) {
813 // _Complex int -> _Complex long
Richard Trieucfe3f212011-09-06 18:38:41 +0000814 RHS = S.ImpCastExprToType(RHS.take(), LHSType, CK_IntegralComplexCast);
815 return LHSType;
Richard Trieu7aa58f12011-09-02 20:58:51 +0000816 }
817
Richard Trieuba63ce62011-09-09 01:45:06 +0000818 if (!IsCompAssign)
Richard Trieucfe3f212011-09-06 18:38:41 +0000819 LHS = S.ImpCastExprToType(LHS.take(), RHSType, CK_IntegralComplexCast);
820 return RHSType;
Richard Trieu7aa58f12011-09-02 20:58:51 +0000821 }
822
Richard Trieucfe3f212011-09-06 18:38:41 +0000823 if (LHSComplexInt) {
Richard Trieu7aa58f12011-09-02 20:58:51 +0000824 // int -> _Complex int
Eli Friedman47133be2011-11-12 03:56:23 +0000825 // FIXME: This needs to take integer ranks into account
826 RHS = S.ImpCastExprToType(RHS.take(), LHSComplexInt->getElementType(),
827 CK_IntegralCast);
Richard Trieucfe3f212011-09-06 18:38:41 +0000828 RHS = S.ImpCastExprToType(RHS.take(), LHSType, CK_IntegralRealToComplex);
829 return LHSType;
Richard Trieu7aa58f12011-09-02 20:58:51 +0000830 }
831
Richard Trieucfe3f212011-09-06 18:38:41 +0000832 assert(RHSComplexInt);
Richard Trieu7aa58f12011-09-02 20:58:51 +0000833 // int -> _Complex int
Eli Friedman47133be2011-11-12 03:56:23 +0000834 // FIXME: This needs to take integer ranks into account
835 if (!IsCompAssign) {
836 LHS = S.ImpCastExprToType(LHS.take(), RHSComplexInt->getElementType(),
837 CK_IntegralCast);
Richard Trieucfe3f212011-09-06 18:38:41 +0000838 LHS = S.ImpCastExprToType(LHS.take(), RHSType, CK_IntegralRealToComplex);
Eli Friedman47133be2011-11-12 03:56:23 +0000839 }
Richard Trieucfe3f212011-09-06 18:38:41 +0000840 return RHSType;
Richard Trieu7aa58f12011-09-02 20:58:51 +0000841}
842
843/// \brief Handle integer arithmetic conversions. Helper function of
844/// UsualArithmeticConversions()
Richard Trieu9a52fbb2011-09-06 19:52:52 +0000845static QualType handleIntegerConversion(Sema &S, ExprResult &LHS,
846 ExprResult &RHS, QualType LHSType,
Richard Trieuba63ce62011-09-09 01:45:06 +0000847 QualType RHSType, bool IsCompAssign) {
Richard Trieu7aa58f12011-09-02 20:58:51 +0000848 // The rules for this case are in C99 6.3.1.8
Richard Trieu9a52fbb2011-09-06 19:52:52 +0000849 int order = S.Context.getIntegerTypeOrder(LHSType, RHSType);
850 bool LHSSigned = LHSType->hasSignedIntegerRepresentation();
851 bool RHSSigned = RHSType->hasSignedIntegerRepresentation();
852 if (LHSSigned == RHSSigned) {
Richard Trieu7aa58f12011-09-02 20:58:51 +0000853 // Same signedness; use the higher-ranked type
854 if (order >= 0) {
Richard Trieu9a52fbb2011-09-06 19:52:52 +0000855 RHS = S.ImpCastExprToType(RHS.take(), LHSType, CK_IntegralCast);
856 return LHSType;
Richard Trieuba63ce62011-09-09 01:45:06 +0000857 } else if (!IsCompAssign)
Richard Trieu9a52fbb2011-09-06 19:52:52 +0000858 LHS = S.ImpCastExprToType(LHS.take(), RHSType, CK_IntegralCast);
859 return RHSType;
860 } else if (order != (LHSSigned ? 1 : -1)) {
Richard Trieu7aa58f12011-09-02 20:58:51 +0000861 // The unsigned type has greater than or equal rank to the
862 // signed type, so use the unsigned type
Richard Trieu9a52fbb2011-09-06 19:52:52 +0000863 if (RHSSigned) {
864 RHS = S.ImpCastExprToType(RHS.take(), LHSType, CK_IntegralCast);
865 return LHSType;
Richard Trieuba63ce62011-09-09 01:45:06 +0000866 } else if (!IsCompAssign)
Richard Trieu9a52fbb2011-09-06 19:52:52 +0000867 LHS = S.ImpCastExprToType(LHS.take(), RHSType, CK_IntegralCast);
868 return RHSType;
869 } else if (S.Context.getIntWidth(LHSType) != S.Context.getIntWidth(RHSType)) {
Richard Trieu7aa58f12011-09-02 20:58:51 +0000870 // The two types are different widths; if we are here, that
871 // means the signed type is larger than the unsigned type, so
872 // use the signed type.
Richard Trieu9a52fbb2011-09-06 19:52:52 +0000873 if (LHSSigned) {
874 RHS = S.ImpCastExprToType(RHS.take(), LHSType, CK_IntegralCast);
875 return LHSType;
Richard Trieuba63ce62011-09-09 01:45:06 +0000876 } else if (!IsCompAssign)
Richard Trieu9a52fbb2011-09-06 19:52:52 +0000877 LHS = S.ImpCastExprToType(LHS.take(), RHSType, CK_IntegralCast);
878 return RHSType;
Richard Trieu7aa58f12011-09-02 20:58:51 +0000879 } else {
880 // The signed type is higher-ranked than the unsigned type,
881 // but isn't actually any bigger (like unsigned int and long
882 // on most 32-bit systems). Use the unsigned type corresponding
883 // to the signed type.
884 QualType result =
Richard Trieu9a52fbb2011-09-06 19:52:52 +0000885 S.Context.getCorrespondingUnsignedType(LHSSigned ? LHSType : RHSType);
886 RHS = S.ImpCastExprToType(RHS.take(), result, CK_IntegralCast);
Richard Trieuba63ce62011-09-09 01:45:06 +0000887 if (!IsCompAssign)
Richard Trieu9a52fbb2011-09-06 19:52:52 +0000888 LHS = S.ImpCastExprToType(LHS.take(), result, CK_IntegralCast);
Richard Trieu7aa58f12011-09-02 20:58:51 +0000889 return result;
890 }
891}
892
Chris Lattner513165e2008-07-25 21:10:04 +0000893/// UsualArithmeticConversions - Performs various conversions that are common to
894/// binary operators (C99 6.3.1.8). If both operands aren't arithmetic, this
Mike Stump11289f42009-09-09 15:08:12 +0000895/// routine returns the first non-arithmetic type found. The client is
Chris Lattner513165e2008-07-25 21:10:04 +0000896/// responsible for emitting appropriate error diagnostics.
897/// FIXME: verify the conversion rules for "complex int" are consistent with
898/// GCC.
Richard Trieu9a52fbb2011-09-06 19:52:52 +0000899QualType Sema::UsualArithmeticConversions(ExprResult &LHS, ExprResult &RHS,
Richard Trieuba63ce62011-09-09 01:45:06 +0000900 bool IsCompAssign) {
901 if (!IsCompAssign) {
Richard Trieu9a52fbb2011-09-06 19:52:52 +0000902 LHS = UsualUnaryConversions(LHS.take());
903 if (LHS.isInvalid())
John Wiegley01296292011-04-08 18:41:53 +0000904 return QualType();
905 }
Eli Friedman8b7b1b12009-03-28 01:22:36 +0000906
Richard Trieu9a52fbb2011-09-06 19:52:52 +0000907 RHS = UsualUnaryConversions(RHS.take());
908 if (RHS.isInvalid())
John Wiegley01296292011-04-08 18:41:53 +0000909 return QualType();
Douglas Gregora11693b2008-11-12 17:17:38 +0000910
Mike Stump11289f42009-09-09 15:08:12 +0000911 // For conversion purposes, we ignore any qualifiers.
Chris Lattner513165e2008-07-25 21:10:04 +0000912 // For example, "const float" and "float" are equivalent.
Richard Trieu9a52fbb2011-09-06 19:52:52 +0000913 QualType LHSType =
914 Context.getCanonicalType(LHS.get()->getType()).getUnqualifiedType();
915 QualType RHSType =
916 Context.getCanonicalType(RHS.get()->getType()).getUnqualifiedType();
Douglas Gregora11693b2008-11-12 17:17:38 +0000917
918 // If both types are identical, no conversion is needed.
Richard Trieu9a52fbb2011-09-06 19:52:52 +0000919 if (LHSType == RHSType)
920 return LHSType;
Douglas Gregora11693b2008-11-12 17:17:38 +0000921
922 // If either side is a non-arithmetic type (e.g. a pointer), we are done.
923 // The caller can deal with this (e.g. pointer + int).
Richard Trieu9a52fbb2011-09-06 19:52:52 +0000924 if (!LHSType->isArithmeticType() || !RHSType->isArithmeticType())
925 return LHSType;
Douglas Gregora11693b2008-11-12 17:17:38 +0000926
John McCalld005ac92010-11-13 08:17:45 +0000927 // Apply unary and bitfield promotions to the LHS's type.
Richard Trieu9a52fbb2011-09-06 19:52:52 +0000928 QualType LHSUnpromotedType = LHSType;
929 if (LHSType->isPromotableIntegerType())
930 LHSType = Context.getPromotedIntegerType(LHSType);
931 QualType LHSBitfieldPromoteTy = Context.isPromotableBitField(LHS.get());
Douglas Gregord2c2d172009-05-02 00:36:19 +0000932 if (!LHSBitfieldPromoteTy.isNull())
Richard Trieu9a52fbb2011-09-06 19:52:52 +0000933 LHSType = LHSBitfieldPromoteTy;
Richard Trieuba63ce62011-09-09 01:45:06 +0000934 if (LHSType != LHSUnpromotedType && !IsCompAssign)
Richard Trieu9a52fbb2011-09-06 19:52:52 +0000935 LHS = ImpCastExprToType(LHS.take(), LHSType, CK_IntegralCast);
Douglas Gregord2c2d172009-05-02 00:36:19 +0000936
John McCalld005ac92010-11-13 08:17:45 +0000937 // If both types are identical, no conversion is needed.
Richard Trieu9a52fbb2011-09-06 19:52:52 +0000938 if (LHSType == RHSType)
939 return LHSType;
John McCalld005ac92010-11-13 08:17:45 +0000940
941 // At this point, we have two different arithmetic types.
942
943 // Handle complex types first (C99 6.3.1.8p1).
Richard Trieu9a52fbb2011-09-06 19:52:52 +0000944 if (LHSType->isComplexType() || RHSType->isComplexType())
945 return handleComplexFloatConversion(*this, LHS, RHS, LHSType, RHSType,
Richard Trieuba63ce62011-09-09 01:45:06 +0000946 IsCompAssign);
John McCalld005ac92010-11-13 08:17:45 +0000947
948 // Now handle "real" floating types (i.e. float, double, long double).
Richard Trieu9a52fbb2011-09-06 19:52:52 +0000949 if (LHSType->isRealFloatingType() || RHSType->isRealFloatingType())
950 return handleFloatConversion(*this, LHS, RHS, LHSType, RHSType,
Richard Trieuba63ce62011-09-09 01:45:06 +0000951 IsCompAssign);
John McCalld005ac92010-11-13 08:17:45 +0000952
953 // Handle GCC complex int extension.
Richard Trieu9a52fbb2011-09-06 19:52:52 +0000954 if (LHSType->isComplexIntegerType() || RHSType->isComplexIntegerType())
Benjamin Kramer499c68b2011-09-06 19:57:14 +0000955 return handleComplexIntConversion(*this, LHS, RHS, LHSType, RHSType,
Richard Trieuba63ce62011-09-09 01:45:06 +0000956 IsCompAssign);
John McCalld005ac92010-11-13 08:17:45 +0000957
958 // Finally, we have two differing integer types.
Richard Trieu9a52fbb2011-09-06 19:52:52 +0000959 return handleIntegerConversion(*this, LHS, RHS, LHSType, RHSType,
Richard Trieuba63ce62011-09-09 01:45:06 +0000960 IsCompAssign);
Douglas Gregora11693b2008-11-12 17:17:38 +0000961}
962
Chris Lattner513165e2008-07-25 21:10:04 +0000963//===----------------------------------------------------------------------===//
964// Semantic Analysis for various Expression Types
965//===----------------------------------------------------------------------===//
966
967
Peter Collingbourne91147592011-04-15 00:35:48 +0000968ExprResult
969Sema::ActOnGenericSelectionExpr(SourceLocation KeyLoc,
970 SourceLocation DefaultLoc,
971 SourceLocation RParenLoc,
972 Expr *ControllingExpr,
Richard Trieuba63ce62011-09-09 01:45:06 +0000973 MultiTypeArg ArgTypes,
974 MultiExprArg ArgExprs) {
975 unsigned NumAssocs = ArgTypes.size();
976 assert(NumAssocs == ArgExprs.size());
Peter Collingbourne91147592011-04-15 00:35:48 +0000977
Richard Trieuba63ce62011-09-09 01:45:06 +0000978 ParsedType *ParsedTypes = ArgTypes.release();
979 Expr **Exprs = ArgExprs.release();
Peter Collingbourne91147592011-04-15 00:35:48 +0000980
981 TypeSourceInfo **Types = new TypeSourceInfo*[NumAssocs];
982 for (unsigned i = 0; i < NumAssocs; ++i) {
983 if (ParsedTypes[i])
984 (void) GetTypeFromParser(ParsedTypes[i], &Types[i]);
985 else
986 Types[i] = 0;
987 }
988
989 ExprResult ER = CreateGenericSelectionExpr(KeyLoc, DefaultLoc, RParenLoc,
990 ControllingExpr, Types, Exprs,
991 NumAssocs);
Benjamin Kramer34623762011-04-15 11:21:57 +0000992 delete [] Types;
Peter Collingbourne91147592011-04-15 00:35:48 +0000993 return ER;
994}
995
996ExprResult
997Sema::CreateGenericSelectionExpr(SourceLocation KeyLoc,
998 SourceLocation DefaultLoc,
999 SourceLocation RParenLoc,
1000 Expr *ControllingExpr,
1001 TypeSourceInfo **Types,
1002 Expr **Exprs,
1003 unsigned NumAssocs) {
1004 bool TypeErrorFound = false,
1005 IsResultDependent = ControllingExpr->isTypeDependent(),
1006 ContainsUnexpandedParameterPack
1007 = ControllingExpr->containsUnexpandedParameterPack();
1008
1009 for (unsigned i = 0; i < NumAssocs; ++i) {
1010 if (Exprs[i]->containsUnexpandedParameterPack())
1011 ContainsUnexpandedParameterPack = true;
1012
1013 if (Types[i]) {
1014 if (Types[i]->getType()->containsUnexpandedParameterPack())
1015 ContainsUnexpandedParameterPack = true;
1016
1017 if (Types[i]->getType()->isDependentType()) {
1018 IsResultDependent = true;
1019 } else {
Benjamin Kramere56f3932011-12-23 17:00:35 +00001020 // C11 6.5.1.1p2 "The type name in a generic association shall specify a
Peter Collingbourne91147592011-04-15 00:35:48 +00001021 // complete object type other than a variably modified type."
1022 unsigned D = 0;
1023 if (Types[i]->getType()->isIncompleteType())
1024 D = diag::err_assoc_type_incomplete;
1025 else if (!Types[i]->getType()->isObjectType())
1026 D = diag::err_assoc_type_nonobject;
1027 else if (Types[i]->getType()->isVariablyModifiedType())
1028 D = diag::err_assoc_type_variably_modified;
1029
1030 if (D != 0) {
1031 Diag(Types[i]->getTypeLoc().getBeginLoc(), D)
1032 << Types[i]->getTypeLoc().getSourceRange()
1033 << Types[i]->getType();
1034 TypeErrorFound = true;
1035 }
1036
Benjamin Kramere56f3932011-12-23 17:00:35 +00001037 // C11 6.5.1.1p2 "No two generic associations in the same generic
Peter Collingbourne91147592011-04-15 00:35:48 +00001038 // selection shall specify compatible types."
1039 for (unsigned j = i+1; j < NumAssocs; ++j)
1040 if (Types[j] && !Types[j]->getType()->isDependentType() &&
1041 Context.typesAreCompatible(Types[i]->getType(),
1042 Types[j]->getType())) {
1043 Diag(Types[j]->getTypeLoc().getBeginLoc(),
1044 diag::err_assoc_compatible_types)
1045 << Types[j]->getTypeLoc().getSourceRange()
1046 << Types[j]->getType()
1047 << Types[i]->getType();
1048 Diag(Types[i]->getTypeLoc().getBeginLoc(),
1049 diag::note_compat_assoc)
1050 << Types[i]->getTypeLoc().getSourceRange()
1051 << Types[i]->getType();
1052 TypeErrorFound = true;
1053 }
1054 }
1055 }
1056 }
1057 if (TypeErrorFound)
1058 return ExprError();
1059
1060 // If we determined that the generic selection is result-dependent, don't
1061 // try to compute the result expression.
1062 if (IsResultDependent)
1063 return Owned(new (Context) GenericSelectionExpr(
1064 Context, KeyLoc, ControllingExpr,
1065 Types, Exprs, NumAssocs, DefaultLoc,
1066 RParenLoc, ContainsUnexpandedParameterPack));
1067
Chris Lattner0e62c1c2011-07-23 10:55:15 +00001068 SmallVector<unsigned, 1> CompatIndices;
Peter Collingbourne91147592011-04-15 00:35:48 +00001069 unsigned DefaultIndex = -1U;
1070 for (unsigned i = 0; i < NumAssocs; ++i) {
1071 if (!Types[i])
1072 DefaultIndex = i;
1073 else if (Context.typesAreCompatible(ControllingExpr->getType(),
1074 Types[i]->getType()))
1075 CompatIndices.push_back(i);
1076 }
1077
Benjamin Kramere56f3932011-12-23 17:00:35 +00001078 // C11 6.5.1.1p2 "The controlling expression of a generic selection shall have
Peter Collingbourne91147592011-04-15 00:35:48 +00001079 // type compatible with at most one of the types named in its generic
1080 // association list."
1081 if (CompatIndices.size() > 1) {
1082 // We strip parens here because the controlling expression is typically
1083 // parenthesized in macro definitions.
1084 ControllingExpr = ControllingExpr->IgnoreParens();
1085 Diag(ControllingExpr->getLocStart(), diag::err_generic_sel_multi_match)
1086 << ControllingExpr->getSourceRange() << ControllingExpr->getType()
1087 << (unsigned) CompatIndices.size();
Chris Lattner0e62c1c2011-07-23 10:55:15 +00001088 for (SmallVector<unsigned, 1>::iterator I = CompatIndices.begin(),
Peter Collingbourne91147592011-04-15 00:35:48 +00001089 E = CompatIndices.end(); I != E; ++I) {
1090 Diag(Types[*I]->getTypeLoc().getBeginLoc(),
1091 diag::note_compat_assoc)
1092 << Types[*I]->getTypeLoc().getSourceRange()
1093 << Types[*I]->getType();
1094 }
1095 return ExprError();
1096 }
1097
Benjamin Kramere56f3932011-12-23 17:00:35 +00001098 // C11 6.5.1.1p2 "If a generic selection has no default generic association,
Peter Collingbourne91147592011-04-15 00:35:48 +00001099 // its controlling expression shall have type compatible with exactly one of
1100 // the types named in its generic association list."
1101 if (DefaultIndex == -1U && CompatIndices.size() == 0) {
1102 // We strip parens here because the controlling expression is typically
1103 // parenthesized in macro definitions.
1104 ControllingExpr = ControllingExpr->IgnoreParens();
1105 Diag(ControllingExpr->getLocStart(), diag::err_generic_sel_no_match)
1106 << ControllingExpr->getSourceRange() << ControllingExpr->getType();
1107 return ExprError();
1108 }
1109
Benjamin Kramere56f3932011-12-23 17:00:35 +00001110 // C11 6.5.1.1p3 "If a generic selection has a generic association with a
Peter Collingbourne91147592011-04-15 00:35:48 +00001111 // type name that is compatible with the type of the controlling expression,
1112 // then the result expression of the generic selection is the expression
1113 // in that generic association. Otherwise, the result expression of the
1114 // generic selection is the expression in the default generic association."
1115 unsigned ResultIndex =
1116 CompatIndices.size() ? CompatIndices[0] : DefaultIndex;
1117
1118 return Owned(new (Context) GenericSelectionExpr(
1119 Context, KeyLoc, ControllingExpr,
1120 Types, Exprs, NumAssocs, DefaultLoc,
1121 RParenLoc, ContainsUnexpandedParameterPack,
1122 ResultIndex));
1123}
1124
Richard Smith75b67d62012-03-08 01:34:56 +00001125/// getUDSuffixLoc - Create a SourceLocation for a ud-suffix, given the
1126/// location of the token and the offset of the ud-suffix within it.
1127static SourceLocation getUDSuffixLoc(Sema &S, SourceLocation TokLoc,
1128 unsigned Offset) {
1129 return Lexer::AdvanceToTokenCharacter(TokLoc, Offset, S.getSourceManager(),
1130 S.getLangOptions());
1131}
1132
Steve Naroff83895f72007-09-16 03:34:24 +00001133/// ActOnStringLiteral - The specified tokens were lexed as pasted string
Chris Lattner5b183d82006-11-10 05:03:26 +00001134/// fragments (e.g. "foo" "bar" L"baz"). The result string has to handle string
1135/// concatenation ([C99 5.1.1.2, translation phase #6]), so it may come from
1136/// multiple tokens. However, the common case is that StringToks points to one
1137/// string.
Sebastian Redlffbcf962009-01-18 18:53:16 +00001138///
John McCalldadc5752010-08-24 06:29:42 +00001139ExprResult
Alexis Hunt3b791862010-08-30 17:47:05 +00001140Sema::ActOnStringLiteral(const Token *StringToks, unsigned NumStringToks) {
Chris Lattner5b183d82006-11-10 05:03:26 +00001141 assert(NumStringToks && "Must have at least one string!");
1142
Chris Lattner8a24e582009-01-16 18:51:42 +00001143 StringLiteralParser Literal(StringToks, NumStringToks, PP);
Steve Naroff4f88b312007-03-13 22:37:02 +00001144 if (Literal.hadError)
Sebastian Redlffbcf962009-01-18 18:53:16 +00001145 return ExprError();
Chris Lattner5b183d82006-11-10 05:03:26 +00001146
Chris Lattner0e62c1c2011-07-23 10:55:15 +00001147 SmallVector<SourceLocation, 4> StringTokLocs;
Chris Lattner5b183d82006-11-10 05:03:26 +00001148 for (unsigned i = 0; i != NumStringToks; ++i)
1149 StringTokLocs.push_back(StringToks[i].getLocation());
Chris Lattner36fc8792008-02-11 00:02:17 +00001150
Chris Lattner36fc8792008-02-11 00:02:17 +00001151 QualType StrTy = Context.CharTy;
Douglas Gregorfb65e592011-07-27 05:40:30 +00001152 if (Literal.isWide())
Anders Carlsson6b06e182011-04-06 18:42:48 +00001153 StrTy = Context.getWCharType();
Douglas Gregorfb65e592011-07-27 05:40:30 +00001154 else if (Literal.isUTF16())
1155 StrTy = Context.Char16Ty;
1156 else if (Literal.isUTF32())
1157 StrTy = Context.Char32Ty;
Eli Friedmanfcec6302011-11-01 02:23:42 +00001158 else if (Literal.isPascal())
Anders Carlsson6b06e182011-04-06 18:42:48 +00001159 StrTy = Context.UnsignedCharTy;
Douglas Gregoraa1e21d2008-09-12 00:47:35 +00001160
Douglas Gregorfb65e592011-07-27 05:40:30 +00001161 StringLiteral::StringKind Kind = StringLiteral::Ascii;
1162 if (Literal.isWide())
1163 Kind = StringLiteral::Wide;
1164 else if (Literal.isUTF8())
1165 Kind = StringLiteral::UTF8;
1166 else if (Literal.isUTF16())
1167 Kind = StringLiteral::UTF16;
1168 else if (Literal.isUTF32())
1169 Kind = StringLiteral::UTF32;
1170
Douglas Gregoraa1e21d2008-09-12 00:47:35 +00001171 // A C++ string literal has a const-qualified element type (C++ 2.13.4p1).
Chris Lattnera8687ae2010-06-15 18:05:34 +00001172 if (getLangOptions().CPlusPlus || getLangOptions().ConstStrings)
Douglas Gregoraa1e21d2008-09-12 00:47:35 +00001173 StrTy.addConst();
Sebastian Redlffbcf962009-01-18 18:53:16 +00001174
Chris Lattner36fc8792008-02-11 00:02:17 +00001175 // Get an array type for the string, according to C99 6.4.5. This includes
1176 // the nul terminator character as well as the string length for pascal
1177 // strings.
1178 StrTy = Context.getConstantArrayType(StrTy,
Chris Lattnerd42c29f2009-02-26 23:01:51 +00001179 llvm::APInt(32, Literal.GetNumStringChars()+1),
Chris Lattner36fc8792008-02-11 00:02:17 +00001180 ArrayType::Normal, 0);
Mike Stump11289f42009-09-09 15:08:12 +00001181
Chris Lattner5b183d82006-11-10 05:03:26 +00001182 // Pass &StringTokLocs[0], StringTokLocs.size() to factory!
Richard Smithc67fdd42012-03-07 08:35:16 +00001183 StringLiteral *Lit = StringLiteral::Create(Context, Literal.GetString(),
1184 Kind, Literal.Pascal, StrTy,
1185 &StringTokLocs[0],
1186 StringTokLocs.size());
1187 if (Literal.getUDSuffix().empty())
1188 return Owned(Lit);
1189
1190 // We're building a user-defined literal.
1191 IdentifierInfo *UDSuffix = &Context.Idents.get(Literal.getUDSuffix());
Richard Smith75b67d62012-03-08 01:34:56 +00001192 SourceLocation UDSuffixLoc =
1193 getUDSuffixLoc(*this, StringTokLocs[Literal.getUDSuffixToken()],
1194 Literal.getUDSuffixOffset());
Richard Smithc67fdd42012-03-07 08:35:16 +00001195
1196 // C++11 [lex.ext]p5: The literal L is treated as a call of the form
1197 // operator "" X (str, len)
1198 QualType SizeType = Context.getSizeType();
1199 llvm::APInt Len(Context.getIntWidth(SizeType), Literal.GetNumStringChars());
1200 IntegerLiteral *LenArg = IntegerLiteral::Create(Context, Len, SizeType,
1201 StringTokLocs[0]);
1202 Expr *Args[] = { Lit, LenArg };
1203 return BuildLiteralOperatorCall(UDSuffix, UDSuffixLoc, Args,
1204 StringTokLocs.back());
Chris Lattner5b183d82006-11-10 05:03:26 +00001205}
1206
John McCalldadc5752010-08-24 06:29:42 +00001207ExprResult
John McCall7decc9e2010-11-18 06:31:45 +00001208Sema::BuildDeclRefExpr(ValueDecl *D, QualType Ty, ExprValueKind VK,
John McCallf4cd4f92011-02-09 01:13:10 +00001209 SourceLocation Loc,
1210 const CXXScopeSpec *SS) {
Abramo Bagnarad6d2f182010-08-11 22:01:17 +00001211 DeclarationNameInfo NameInfo(D->getDeclName(), Loc);
John McCall7decc9e2010-11-18 06:31:45 +00001212 return BuildDeclRefExpr(D, Ty, VK, NameInfo, SS);
Abramo Bagnarad6d2f182010-08-11 22:01:17 +00001213}
1214
John McCallf4cd4f92011-02-09 01:13:10 +00001215/// BuildDeclRefExpr - Build an expression that references a
1216/// declaration that does not require a closure capture.
John McCalldadc5752010-08-24 06:29:42 +00001217ExprResult
John McCallf4cd4f92011-02-09 01:13:10 +00001218Sema::BuildDeclRefExpr(ValueDecl *D, QualType Ty, ExprValueKind VK,
Abramo Bagnarad6d2f182010-08-11 22:01:17 +00001219 const DeclarationNameInfo &NameInfo,
1220 const CXXScopeSpec *SS) {
Peter Collingbourne7277fe82011-10-02 23:49:40 +00001221 if (getLangOptions().CUDA)
1222 if (const FunctionDecl *Caller = dyn_cast<FunctionDecl>(CurContext))
1223 if (const FunctionDecl *Callee = dyn_cast<FunctionDecl>(D)) {
1224 CUDAFunctionTarget CallerTarget = IdentifyCUDATarget(Caller),
1225 CalleeTarget = IdentifyCUDATarget(Callee);
1226 if (CheckCUDATarget(CallerTarget, CalleeTarget)) {
1227 Diag(NameInfo.getLoc(), diag::err_ref_bad_target)
1228 << CalleeTarget << D->getIdentifier() << CallerTarget;
1229 Diag(D->getLocation(), diag::note_previous_decl)
1230 << D->getIdentifier();
1231 return ExprError();
1232 }
1233 }
1234
Eli Friedmanfa0df832012-02-02 03:46:19 +00001235 DeclRefExpr *E = DeclRefExpr::Create(Context,
1236 SS ? SS->getWithLocInContext(Context)
1237 : NestedNameSpecifierLoc(),
1238 SourceLocation(),
1239 D, NameInfo, Ty, VK);
Mike Stump11289f42009-09-09 15:08:12 +00001240
Eli Friedmanfa0df832012-02-02 03:46:19 +00001241 MarkDeclRefReferenced(E);
John McCall086a4642010-11-24 05:12:34 +00001242
1243 // Just in case we're building an illegal pointer-to-member.
Richard Smithcaf33902011-10-10 18:28:20 +00001244 FieldDecl *FD = dyn_cast<FieldDecl>(D);
1245 if (FD && FD->isBitField())
John McCall086a4642010-11-24 05:12:34 +00001246 E->setObjectKind(OK_BitField);
1247
1248 return Owned(E);
Douglas Gregorc7acfdf2009-01-06 05:10:23 +00001249}
1250
Abramo Bagnarad6d2f182010-08-11 22:01:17 +00001251/// Decomposes the given name into a DeclarationNameInfo, its location, and
John McCall10eae182009-11-30 22:42:35 +00001252/// possibly a list of template arguments.
1253///
1254/// If this produces template arguments, it is permitted to call
1255/// DecomposeTemplateName.
1256///
1257/// This actually loses a lot of source location information for
1258/// non-standard name kinds; we should consider preserving that in
1259/// some way.
Richard Trieucfc491d2011-08-02 04:35:43 +00001260void
1261Sema::DecomposeUnqualifiedId(const UnqualifiedId &Id,
1262 TemplateArgumentListInfo &Buffer,
1263 DeclarationNameInfo &NameInfo,
1264 const TemplateArgumentListInfo *&TemplateArgs) {
John McCall10eae182009-11-30 22:42:35 +00001265 if (Id.getKind() == UnqualifiedId::IK_TemplateId) {
1266 Buffer.setLAngleLoc(Id.TemplateId->LAngleLoc);
1267 Buffer.setRAngleLoc(Id.TemplateId->RAngleLoc);
1268
Douglas Gregor5476205b2011-06-23 00:49:38 +00001269 ASTTemplateArgsPtr TemplateArgsPtr(*this,
John McCall10eae182009-11-30 22:42:35 +00001270 Id.TemplateId->getTemplateArgs(),
1271 Id.TemplateId->NumArgs);
Douglas Gregor5476205b2011-06-23 00:49:38 +00001272 translateTemplateArguments(TemplateArgsPtr, Buffer);
John McCall10eae182009-11-30 22:42:35 +00001273 TemplateArgsPtr.release();
1274
John McCall3e56fd42010-08-23 07:28:44 +00001275 TemplateName TName = Id.TemplateId->Template.get();
Abramo Bagnarad6d2f182010-08-11 22:01:17 +00001276 SourceLocation TNameLoc = Id.TemplateId->TemplateNameLoc;
Douglas Gregor5476205b2011-06-23 00:49:38 +00001277 NameInfo = Context.getNameForTemplate(TName, TNameLoc);
John McCall10eae182009-11-30 22:42:35 +00001278 TemplateArgs = &Buffer;
1279 } else {
Douglas Gregor5476205b2011-06-23 00:49:38 +00001280 NameInfo = GetNameFromUnqualifiedId(Id);
John McCall10eae182009-11-30 22:42:35 +00001281 TemplateArgs = 0;
1282 }
1283}
1284
John McCalld681c392009-12-16 08:11:27 +00001285/// Diagnose an empty lookup.
1286///
1287/// \return false if new lookup candidates were found
Nick Lewyckyc96c37f2010-07-06 19:51:49 +00001288bool Sema::DiagnoseEmptyLookup(Scope *S, CXXScopeSpec &SS, LookupResult &R,
Kaelyn Uhrain79d01c12012-01-18 05:58:54 +00001289 CorrectionCandidateCallback &CCC,
Kaelyn Uhrain42830922011-08-05 00:09:52 +00001290 TemplateArgumentListInfo *ExplicitTemplateArgs,
Ahmed Charlesb24b9aa2012-02-25 11:00:22 +00001291 llvm::ArrayRef<Expr *> Args) {
John McCalld681c392009-12-16 08:11:27 +00001292 DeclarationName Name = R.getLookupName();
1293
John McCalld681c392009-12-16 08:11:27 +00001294 unsigned diagnostic = diag::err_undeclared_var_use;
Douglas Gregor598b08f2009-12-31 05:20:13 +00001295 unsigned diagnostic_suggest = diag::err_undeclared_var_use_suggest;
John McCalld681c392009-12-16 08:11:27 +00001296 if (Name.getNameKind() == DeclarationName::CXXOperatorName ||
1297 Name.getNameKind() == DeclarationName::CXXLiteralOperatorName ||
Douglas Gregor598b08f2009-12-31 05:20:13 +00001298 Name.getNameKind() == DeclarationName::CXXConversionFunctionName) {
John McCalld681c392009-12-16 08:11:27 +00001299 diagnostic = diag::err_undeclared_use;
Douglas Gregor598b08f2009-12-31 05:20:13 +00001300 diagnostic_suggest = diag::err_undeclared_use_suggest;
1301 }
John McCalld681c392009-12-16 08:11:27 +00001302
Douglas Gregor598b08f2009-12-31 05:20:13 +00001303 // If the original lookup was an unqualified lookup, fake an
1304 // unqualified lookup. This is useful when (for example) the
1305 // original lookup would not have found something because it was a
1306 // dependent name.
Francois Pichetde232cb2011-11-25 01:10:54 +00001307 DeclContext *DC = SS.isEmpty() ? CurContext : 0;
1308 while (DC) {
John McCalld681c392009-12-16 08:11:27 +00001309 if (isa<CXXRecordDecl>(DC)) {
1310 LookupQualifiedName(R, DC);
1311
1312 if (!R.empty()) {
1313 // Don't give errors about ambiguities in this lookup.
1314 R.suppressDiagnostics();
1315
Francois Pichet857f9d62011-11-17 03:44:24 +00001316 // During a default argument instantiation the CurContext points
1317 // to a CXXMethodDecl; but we can't apply a this-> fixit inside a
1318 // function parameter list, hence add an explicit check.
1319 bool isDefaultArgument = !ActiveTemplateInstantiations.empty() &&
1320 ActiveTemplateInstantiations.back().Kind ==
1321 ActiveTemplateInstantiation::DefaultFunctionArgumentInstantiation;
John McCalld681c392009-12-16 08:11:27 +00001322 CXXMethodDecl *CurMethod = dyn_cast<CXXMethodDecl>(CurContext);
1323 bool isInstance = CurMethod &&
1324 CurMethod->isInstance() &&
Francois Pichet857f9d62011-11-17 03:44:24 +00001325 DC == CurMethod->getParent() && !isDefaultArgument;
1326
John McCalld681c392009-12-16 08:11:27 +00001327
1328 // Give a code modification hint to insert 'this->'.
1329 // TODO: fixit for inserting 'Base<T>::' in the other cases.
1330 // Actually quite difficult!
Nick Lewyckyc96c37f2010-07-06 19:51:49 +00001331 if (isInstance) {
Nick Lewyckyc96c37f2010-07-06 19:51:49 +00001332 UnresolvedLookupExpr *ULE = cast<UnresolvedLookupExpr>(
1333 CallsUndergoingInstantiation.back()->getCallee());
Nick Lewyckyfe712382010-08-20 20:54:15 +00001334 CXXMethodDecl *DepMethod = cast_or_null<CXXMethodDecl>(
Nick Lewyckyc96c37f2010-07-06 19:51:49 +00001335 CurMethod->getInstantiatedFromMemberFunction());
Eli Friedman04831922010-08-22 01:00:03 +00001336 if (DepMethod) {
Francois Pichet78286b22011-11-15 23:33:34 +00001337 if (getLangOptions().MicrosoftMode)
Francois Pichetbcf64712011-09-07 00:14:57 +00001338 diagnostic = diag::warn_found_via_dependent_bases_lookup;
Nick Lewyckyfe712382010-08-20 20:54:15 +00001339 Diag(R.getNameLoc(), diagnostic) << Name
1340 << FixItHint::CreateInsertion(R.getNameLoc(), "this->");
1341 QualType DepThisType = DepMethod->getThisType(Context);
Eli Friedman73a04092012-01-07 04:59:52 +00001342 CheckCXXThisCapture(R.getNameLoc());
Nick Lewyckyfe712382010-08-20 20:54:15 +00001343 CXXThisExpr *DepThis = new (Context) CXXThisExpr(
1344 R.getNameLoc(), DepThisType, false);
1345 TemplateArgumentListInfo TList;
1346 if (ULE->hasExplicitTemplateArgs())
1347 ULE->copyTemplateArgumentsInto(TList);
Douglas Gregore16af532011-02-28 18:50:33 +00001348
Douglas Gregore16af532011-02-28 18:50:33 +00001349 CXXScopeSpec SS;
Douglas Gregor0da1d432011-02-28 20:01:57 +00001350 SS.Adopt(ULE->getQualifierLoc());
Nick Lewyckyfe712382010-08-20 20:54:15 +00001351 CXXDependentScopeMemberExpr *DepExpr =
1352 CXXDependentScopeMemberExpr::Create(
1353 Context, DepThis, DepThisType, true, SourceLocation(),
Abramo Bagnara7945c982012-01-27 09:46:47 +00001354 SS.getWithLocInContext(Context),
1355 ULE->getTemplateKeywordLoc(), 0,
Francois Pichet4391c752011-09-04 23:00:48 +00001356 R.getLookupNameInfo(),
1357 ULE->hasExplicitTemplateArgs() ? &TList : 0);
Nick Lewyckyfe712382010-08-20 20:54:15 +00001358 CallsUndergoingInstantiation.back()->setCallee(DepExpr);
Eli Friedman04831922010-08-22 01:00:03 +00001359 } else {
Nick Lewyckyfe712382010-08-20 20:54:15 +00001360 // FIXME: we should be able to handle this case too. It is correct
1361 // to add this-> here. This is a workaround for PR7947.
1362 Diag(R.getNameLoc(), diagnostic) << Name;
Eli Friedman04831922010-08-22 01:00:03 +00001363 }
Nick Lewyckyc96c37f2010-07-06 19:51:49 +00001364 } else {
Francois Pichet78286b22011-11-15 23:33:34 +00001365 if (getLangOptions().MicrosoftMode)
1366 diagnostic = diag::warn_found_via_dependent_bases_lookup;
John McCalld681c392009-12-16 08:11:27 +00001367 Diag(R.getNameLoc(), diagnostic) << Name;
Nick Lewyckyc96c37f2010-07-06 19:51:49 +00001368 }
John McCalld681c392009-12-16 08:11:27 +00001369
1370 // Do we really want to note all of these?
1371 for (LookupResult::iterator I = R.begin(), E = R.end(); I != E; ++I)
1372 Diag((*I)->getLocation(), diag::note_dependent_var_use);
1373
Francois Pichet857f9d62011-11-17 03:44:24 +00001374 // Return true if we are inside a default argument instantiation
1375 // and the found name refers to an instance member function, otherwise
1376 // the function calling DiagnoseEmptyLookup will try to create an
1377 // implicit member call and this is wrong for default argument.
1378 if (isDefaultArgument && ((*R.begin())->isCXXInstanceMember())) {
1379 Diag(R.getNameLoc(), diag::err_member_call_without_object);
1380 return true;
1381 }
1382
John McCalld681c392009-12-16 08:11:27 +00001383 // Tell the callee to try to recover.
1384 return false;
1385 }
Douglas Gregor86b8d9f2010-08-09 22:38:14 +00001386
1387 R.clear();
John McCalld681c392009-12-16 08:11:27 +00001388 }
Francois Pichetde232cb2011-11-25 01:10:54 +00001389
1390 // In Microsoft mode, if we are performing lookup from within a friend
1391 // function definition declared at class scope then we must set
1392 // DC to the lexical parent to be able to search into the parent
1393 // class.
Lang Hamesc8c3b402011-11-29 22:37:13 +00001394 if (getLangOptions().MicrosoftMode && isa<FunctionDecl>(DC) &&
Francois Pichetde232cb2011-11-25 01:10:54 +00001395 cast<FunctionDecl>(DC)->getFriendObjectKind() &&
1396 DC->getLexicalParent()->isRecord())
1397 DC = DC->getLexicalParent();
1398 else
1399 DC = DC->getParent();
John McCalld681c392009-12-16 08:11:27 +00001400 }
1401
Douglas Gregor598b08f2009-12-31 05:20:13 +00001402 // We didn't find anything, so try to correct for a typo.
Douglas Gregorc2fa1692011-06-28 16:20:02 +00001403 TypoCorrection Corrected;
1404 if (S && (Corrected = CorrectTypo(R.getLookupNameInfo(), R.getLookupKind(),
Kaelyn Uhrain4e8942c2012-01-31 23:49:25 +00001405 S, &SS, CCC))) {
Douglas Gregorc2fa1692011-06-28 16:20:02 +00001406 std::string CorrectedStr(Corrected.getAsString(getLangOptions()));
1407 std::string CorrectedQuotedStr(Corrected.getQuoted(getLangOptions()));
1408 R.setLookupName(Corrected.getCorrection());
1409
Hans Wennborg38198de2011-07-12 08:45:31 +00001410 if (NamedDecl *ND = Corrected.getCorrectionDecl()) {
Kaelyn Uhrainacbdc572011-08-03 20:36:05 +00001411 if (Corrected.isOverloaded()) {
1412 OverloadCandidateSet OCS(R.getNameLoc());
1413 OverloadCandidateSet::iterator Best;
1414 for (TypoCorrection::decl_iterator CD = Corrected.begin(),
1415 CDEnd = Corrected.end();
1416 CD != CDEnd; ++CD) {
Kaelyn Uhrain62422202011-08-08 17:35:31 +00001417 if (FunctionTemplateDecl *FTD =
Kaelyn Uhrain42830922011-08-05 00:09:52 +00001418 dyn_cast<FunctionTemplateDecl>(*CD))
1419 AddTemplateOverloadCandidate(
1420 FTD, DeclAccessPair::make(FTD, AS_none), ExplicitTemplateArgs,
Ahmed Charlesb24b9aa2012-02-25 11:00:22 +00001421 Args, OCS);
Kaelyn Uhrain62422202011-08-08 17:35:31 +00001422 else if (FunctionDecl *FD = dyn_cast<FunctionDecl>(*CD))
1423 if (!ExplicitTemplateArgs || ExplicitTemplateArgs->size() == 0)
1424 AddOverloadCandidate(FD, DeclAccessPair::make(FD, AS_none),
Ahmed Charlesb24b9aa2012-02-25 11:00:22 +00001425 Args, OCS);
Kaelyn Uhrainacbdc572011-08-03 20:36:05 +00001426 }
1427 switch (OCS.BestViableFunction(*this, R.getNameLoc(), Best)) {
1428 case OR_Success:
1429 ND = Best->Function;
1430 break;
1431 default:
Kaelyn Uhrainea350182011-08-04 23:30:54 +00001432 break;
Kaelyn Uhrainacbdc572011-08-03 20:36:05 +00001433 }
1434 }
Douglas Gregorc2fa1692011-06-28 16:20:02 +00001435 R.addDecl(ND);
1436 if (isa<ValueDecl>(ND) || isa<FunctionTemplateDecl>(ND)) {
Douglas Gregor280e1ee2010-04-14 20:04:41 +00001437 if (SS.isEmpty())
Douglas Gregorc2fa1692011-06-28 16:20:02 +00001438 Diag(R.getNameLoc(), diagnostic_suggest) << Name << CorrectedQuotedStr
1439 << FixItHint::CreateReplacement(R.getNameLoc(), CorrectedStr);
Douglas Gregor280e1ee2010-04-14 20:04:41 +00001440 else
1441 Diag(R.getNameLoc(), diag::err_no_member_suggest)
Douglas Gregorc2fa1692011-06-28 16:20:02 +00001442 << Name << computeDeclContext(SS, false) << CorrectedQuotedStr
Douglas Gregor280e1ee2010-04-14 20:04:41 +00001443 << SS.getRange()
Douglas Gregorc2fa1692011-06-28 16:20:02 +00001444 << FixItHint::CreateReplacement(R.getNameLoc(), CorrectedStr);
1445 if (ND)
Douglas Gregor280e1ee2010-04-14 20:04:41 +00001446 Diag(ND->getLocation(), diag::note_previous_decl)
Douglas Gregorc2fa1692011-06-28 16:20:02 +00001447 << CorrectedQuotedStr;
Douglas Gregor280e1ee2010-04-14 20:04:41 +00001448
1449 // Tell the callee to try to recover.
1450 return false;
1451 }
Alexis Huntc46382e2010-04-28 23:02:27 +00001452
Douglas Gregorc2fa1692011-06-28 16:20:02 +00001453 if (isa<TypeDecl>(ND) || isa<ObjCInterfaceDecl>(ND)) {
Douglas Gregor280e1ee2010-04-14 20:04:41 +00001454 // FIXME: If we ended up with a typo for a type name or
1455 // Objective-C class name, we're in trouble because the parser
1456 // is in the wrong place to recover. Suggest the typo
1457 // correction, but don't make it a fix-it since we're not going
1458 // to recover well anyway.
1459 if (SS.isEmpty())
Richard Trieucfc491d2011-08-02 04:35:43 +00001460 Diag(R.getNameLoc(), diagnostic_suggest)
1461 << Name << CorrectedQuotedStr;
Douglas Gregor280e1ee2010-04-14 20:04:41 +00001462 else
1463 Diag(R.getNameLoc(), diag::err_no_member_suggest)
Douglas Gregorc2fa1692011-06-28 16:20:02 +00001464 << Name << computeDeclContext(SS, false) << CorrectedQuotedStr
Douglas Gregor280e1ee2010-04-14 20:04:41 +00001465 << SS.getRange();
1466
1467 // Don't try to recover; it won't work.
1468 return true;
1469 }
1470 } else {
Alexis Huntc46382e2010-04-28 23:02:27 +00001471 // FIXME: We found a keyword. Suggest it, but don't provide a fix-it
Douglas Gregor280e1ee2010-04-14 20:04:41 +00001472 // because we aren't able to recover.
Douglas Gregor25363982010-01-01 00:15:04 +00001473 if (SS.isEmpty())
Douglas Gregorc2fa1692011-06-28 16:20:02 +00001474 Diag(R.getNameLoc(), diagnostic_suggest) << Name << CorrectedQuotedStr;
Kovarththanan Rajaratnamba2c6522010-03-13 10:17:05 +00001475 else
Douglas Gregor25363982010-01-01 00:15:04 +00001476 Diag(R.getNameLoc(), diag::err_no_member_suggest)
Douglas Gregorc2fa1692011-06-28 16:20:02 +00001477 << Name << computeDeclContext(SS, false) << CorrectedQuotedStr
Douglas Gregor280e1ee2010-04-14 20:04:41 +00001478 << SS.getRange();
Douglas Gregor25363982010-01-01 00:15:04 +00001479 return true;
1480 }
Douglas Gregor598b08f2009-12-31 05:20:13 +00001481 }
Douglas Gregorc2fa1692011-06-28 16:20:02 +00001482 R.clear();
Douglas Gregor598b08f2009-12-31 05:20:13 +00001483
1484 // Emit a special diagnostic for failed member lookups.
1485 // FIXME: computing the declaration context might fail here (?)
1486 if (!SS.isEmpty()) {
1487 Diag(R.getNameLoc(), diag::err_no_member)
1488 << Name << computeDeclContext(SS, false)
1489 << SS.getRange();
1490 return true;
1491 }
1492
John McCalld681c392009-12-16 08:11:27 +00001493 // Give up, we can't recover.
1494 Diag(R.getNameLoc(), diagnostic) << Name;
1495 return true;
1496}
1497
John McCalldadc5752010-08-24 06:29:42 +00001498ExprResult Sema::ActOnIdExpression(Scope *S,
John McCall24d18942010-08-24 22:52:39 +00001499 CXXScopeSpec &SS,
Abramo Bagnara7945c982012-01-27 09:46:47 +00001500 SourceLocation TemplateKWLoc,
John McCall24d18942010-08-24 22:52:39 +00001501 UnqualifiedId &Id,
1502 bool HasTrailingLParen,
Kaelyn Uhrain77e21fc2012-01-25 20:49:08 +00001503 bool IsAddressOfOperand,
1504 CorrectionCandidateCallback *CCC) {
Richard Trieuba63ce62011-09-09 01:45:06 +00001505 assert(!(IsAddressOfOperand && HasTrailingLParen) &&
John McCalle66edc12009-11-24 19:00:30 +00001506 "cannot be direct & operand and have a trailing lparen");
1507
1508 if (SS.isInvalid())
Douglas Gregored8f2882009-01-30 01:04:22 +00001509 return ExprError();
Douglas Gregor90a1a652009-03-19 17:26:29 +00001510
John McCall10eae182009-11-30 22:42:35 +00001511 TemplateArgumentListInfo TemplateArgsBuffer;
John McCalle66edc12009-11-24 19:00:30 +00001512
1513 // Decompose the UnqualifiedId into the following data.
Abramo Bagnarad6d2f182010-08-11 22:01:17 +00001514 DeclarationNameInfo NameInfo;
John McCalle66edc12009-11-24 19:00:30 +00001515 const TemplateArgumentListInfo *TemplateArgs;
Douglas Gregor5476205b2011-06-23 00:49:38 +00001516 DecomposeUnqualifiedId(Id, TemplateArgsBuffer, NameInfo, TemplateArgs);
Douglas Gregor90a1a652009-03-19 17:26:29 +00001517
Abramo Bagnarad6d2f182010-08-11 22:01:17 +00001518 DeclarationName Name = NameInfo.getName();
Douglas Gregor4ea80432008-11-18 15:03:34 +00001519 IdentifierInfo *II = Name.getAsIdentifierInfo();
Abramo Bagnarad6d2f182010-08-11 22:01:17 +00001520 SourceLocation NameLoc = NameInfo.getLoc();
John McCalld14a8642009-11-21 08:51:07 +00001521
John McCalle66edc12009-11-24 19:00:30 +00001522 // C++ [temp.dep.expr]p3:
1523 // An id-expression is type-dependent if it contains:
Douglas Gregorea0a0a92010-01-11 18:40:55 +00001524 // -- an identifier that was declared with a dependent type,
1525 // (note: handled after lookup)
1526 // -- a template-id that is dependent,
1527 // (note: handled in BuildTemplateIdExpr)
1528 // -- a conversion-function-id that specifies a dependent type,
John McCalle66edc12009-11-24 19:00:30 +00001529 // -- a nested-name-specifier that contains a class-name that
1530 // names a dependent type.
1531 // Determine whether this is a member of an unknown specialization;
1532 // we need to handle these differently.
Eli Friedman964dbda2010-08-06 23:41:47 +00001533 bool DependentID = false;
1534 if (Name.getNameKind() == DeclarationName::CXXConversionFunctionName &&
1535 Name.getCXXNameType()->isDependentType()) {
1536 DependentID = true;
1537 } else if (SS.isSet()) {
Chris Lattnerebb5c6c2011-02-18 01:27:55 +00001538 if (DeclContext *DC = computeDeclContext(SS, false)) {
Eli Friedman964dbda2010-08-06 23:41:47 +00001539 if (RequireCompleteDeclContext(SS, DC))
1540 return ExprError();
Eli Friedman964dbda2010-08-06 23:41:47 +00001541 } else {
1542 DependentID = true;
1543 }
1544 }
1545
Chris Lattnerebb5c6c2011-02-18 01:27:55 +00001546 if (DependentID)
Abramo Bagnara7945c982012-01-27 09:46:47 +00001547 return ActOnDependentIdExpression(SS, TemplateKWLoc, NameInfo,
1548 IsAddressOfOperand, TemplateArgs);
Chris Lattnerebb5c6c2011-02-18 01:27:55 +00001549
John McCalle66edc12009-11-24 19:00:30 +00001550 // Perform the required lookup.
Fariborz Jahanian7f4427f2011-07-12 17:16:56 +00001551 LookupResult R(*this, NameInfo,
1552 (Id.getKind() == UnqualifiedId::IK_ImplicitSelfParam)
1553 ? LookupObjCImplicitSelfParam : LookupOrdinaryName);
John McCalle66edc12009-11-24 19:00:30 +00001554 if (TemplateArgs) {
Douglas Gregor3e51e172010-05-20 20:58:56 +00001555 // Lookup the template name again to correctly establish the context in
1556 // which it was found. This is really unfortunate as we already did the
1557 // lookup to determine that it was a template name in the first place. If
1558 // this becomes a performance hit, we can work harder to preserve those
1559 // results until we get here but it's likely not worth it.
Douglas Gregor786123d2010-05-21 23:18:07 +00001560 bool MemberOfUnknownSpecialization;
1561 LookupTemplateName(R, S, SS, QualType(), /*EnteringContext=*/false,
1562 MemberOfUnknownSpecialization);
Douglas Gregora5226932011-02-04 13:35:07 +00001563
1564 if (MemberOfUnknownSpecialization ||
1565 (R.getResultKind() == LookupResult::NotFoundInCurrentInstantiation))
Abramo Bagnara7945c982012-01-27 09:46:47 +00001566 return ActOnDependentIdExpression(SS, TemplateKWLoc, NameInfo,
1567 IsAddressOfOperand, TemplateArgs);
John McCalle66edc12009-11-24 19:00:30 +00001568 } else {
Benjamin Kramer46921442012-01-20 14:57:34 +00001569 bool IvarLookupFollowUp = II && !SS.isSet() && getCurMethodDecl();
Fariborz Jahanian6fada5b2010-01-12 23:58:59 +00001570 LookupParsedName(R, S, &SS, !IvarLookupFollowUp);
Mike Stump11289f42009-09-09 15:08:12 +00001571
Douglas Gregora5226932011-02-04 13:35:07 +00001572 // If the result might be in a dependent base class, this is a dependent
1573 // id-expression.
1574 if (R.getResultKind() == LookupResult::NotFoundInCurrentInstantiation)
Abramo Bagnara7945c982012-01-27 09:46:47 +00001575 return ActOnDependentIdExpression(SS, TemplateKWLoc, NameInfo,
1576 IsAddressOfOperand, TemplateArgs);
1577
John McCalle66edc12009-11-24 19:00:30 +00001578 // If this reference is in an Objective-C method, then we need to do
1579 // some special Objective-C lookup, too.
Fariborz Jahanian6fada5b2010-01-12 23:58:59 +00001580 if (IvarLookupFollowUp) {
John McCalldadc5752010-08-24 06:29:42 +00001581 ExprResult E(LookupInObjCMethod(R, S, II, true));
John McCalle66edc12009-11-24 19:00:30 +00001582 if (E.isInvalid())
1583 return ExprError();
Mike Stump11289f42009-09-09 15:08:12 +00001584
Chris Lattnerebb5c6c2011-02-18 01:27:55 +00001585 if (Expr *Ex = E.takeAs<Expr>())
1586 return Owned(Ex);
Steve Naroffebf4cb42008-06-02 23:03:37 +00001587 }
Chris Lattner59a25942008-03-31 00:36:02 +00001588 }
Douglas Gregorf15f5d32009-02-16 19:28:42 +00001589
John McCalle66edc12009-11-24 19:00:30 +00001590 if (R.isAmbiguous())
1591 return ExprError();
1592
Douglas Gregor171c45a2009-02-18 21:56:37 +00001593 // Determine whether this name might be a candidate for
1594 // argument-dependent lookup.
John McCalle66edc12009-11-24 19:00:30 +00001595 bool ADL = UseArgumentDependentLookup(SS, R, HasTrailingLParen);
Douglas Gregor171c45a2009-02-18 21:56:37 +00001596
John McCalle66edc12009-11-24 19:00:30 +00001597 if (R.empty() && !ADL) {
Bill Wendling4073ed52007-02-13 01:51:42 +00001598 // Otherwise, this could be an implicitly declared function reference (legal
John McCalle66edc12009-11-24 19:00:30 +00001599 // in C90, extension in C99, forbidden in C++).
1600 if (HasTrailingLParen && II && !getLangOptions().CPlusPlus) {
1601 NamedDecl *D = ImplicitlyDefineFunction(NameLoc, *II, S);
1602 if (D) R.addDecl(D);
1603 }
1604
1605 // If this name wasn't predeclared and if this is not a function
1606 // call, diagnose the problem.
1607 if (R.empty()) {
Francois Pichetd8e4e412011-09-24 10:38:05 +00001608
1609 // In Microsoft mode, if we are inside a template class member function
1610 // and we can't resolve an identifier then assume the identifier is type
1611 // dependent. The goal is to postpone name lookup to instantiation time
1612 // to be able to search into type dependent base classes.
1613 if (getLangOptions().MicrosoftMode && CurContext->isDependentContext() &&
1614 isa<CXXMethodDecl>(CurContext))
Abramo Bagnara7945c982012-01-27 09:46:47 +00001615 return ActOnDependentIdExpression(SS, TemplateKWLoc, NameInfo,
1616 IsAddressOfOperand, TemplateArgs);
Francois Pichetd8e4e412011-09-24 10:38:05 +00001617
Kaelyn Uhrain79d01c12012-01-18 05:58:54 +00001618 CorrectionCandidateCallback DefaultValidator;
Kaelyn Uhrain77e21fc2012-01-25 20:49:08 +00001619 if (DiagnoseEmptyLookup(S, SS, R, CCC ? *CCC : DefaultValidator))
John McCalld681c392009-12-16 08:11:27 +00001620 return ExprError();
1621
1622 assert(!R.empty() &&
1623 "DiagnoseEmptyLookup returned false but added no results");
Douglas Gregor35b0bac2010-01-03 18:01:57 +00001624
1625 // If we found an Objective-C instance variable, let
1626 // LookupInObjCMethod build the appropriate expression to
Kovarththanan Rajaratnamba2c6522010-03-13 10:17:05 +00001627 // reference the ivar.
Douglas Gregor35b0bac2010-01-03 18:01:57 +00001628 if (ObjCIvarDecl *Ivar = R.getAsSingle<ObjCIvarDecl>()) {
1629 R.clear();
John McCalldadc5752010-08-24 06:29:42 +00001630 ExprResult E(LookupInObjCMethod(R, S, Ivar->getIdentifier()));
Fariborz Jahanian44653702011-09-23 23:11:38 +00001631 // In a hopelessly buggy code, Objective-C instance variable
1632 // lookup fails and no expression will be built to reference it.
1633 if (!E.isInvalid() && !E.get())
1634 return ExprError();
Douglas Gregor35b0bac2010-01-03 18:01:57 +00001635 return move(E);
1636 }
Steve Naroff92e30f82007-04-02 22:35:25 +00001637 }
Chris Lattner17ed4872006-11-20 04:58:19 +00001638 }
Mike Stump11289f42009-09-09 15:08:12 +00001639
John McCalle66edc12009-11-24 19:00:30 +00001640 // This is guaranteed from this point on.
1641 assert(!R.empty() || ADL);
1642
John McCall2d74de92009-12-01 22:10:20 +00001643 // Check whether this might be a C++ implicit instance member access.
John McCall24d18942010-08-24 22:52:39 +00001644 // C++ [class.mfct.non-static]p3:
1645 // When an id-expression that is not part of a class member access
1646 // syntax and not used to form a pointer to member is used in the
1647 // body of a non-static member function of class X, if name lookup
1648 // resolves the name in the id-expression to a non-static non-type
1649 // member of some class C, the id-expression is transformed into a
1650 // class member access expression using (*this) as the
1651 // postfix-expression to the left of the . operator.
John McCall8d08b9b2010-08-27 09:08:28 +00001652 //
1653 // But we don't actually need to do this for '&' operands if R
1654 // resolved to a function or overloaded function set, because the
1655 // expression is ill-formed if it actually works out to be a
1656 // non-static member function:
1657 //
1658 // C++ [expr.ref]p4:
1659 // Otherwise, if E1.E2 refers to a non-static member function. . .
1660 // [t]he expression can be used only as the left-hand operand of a
1661 // member function call.
1662 //
1663 // There are other safeguards against such uses, but it's important
1664 // to get this right here so that we don't end up making a
1665 // spuriously dependent expression if we're inside a dependent
1666 // instance method.
John McCall57500772009-12-16 12:17:52 +00001667 if (!R.empty() && (*R.begin())->isCXXClassMember()) {
John McCall8d08b9b2010-08-27 09:08:28 +00001668 bool MightBeImplicitMember;
Richard Trieuba63ce62011-09-09 01:45:06 +00001669 if (!IsAddressOfOperand)
John McCall8d08b9b2010-08-27 09:08:28 +00001670 MightBeImplicitMember = true;
1671 else if (!SS.isEmpty())
1672 MightBeImplicitMember = false;
1673 else if (R.isOverloadedResult())
1674 MightBeImplicitMember = false;
Douglas Gregor1262b062010-08-30 16:00:47 +00001675 else if (R.isUnresolvableResult())
1676 MightBeImplicitMember = true;
John McCall8d08b9b2010-08-27 09:08:28 +00001677 else
Francois Pichet783dd6e2010-11-21 06:08:52 +00001678 MightBeImplicitMember = isa<FieldDecl>(R.getFoundDecl()) ||
1679 isa<IndirectFieldDecl>(R.getFoundDecl());
John McCall8d08b9b2010-08-27 09:08:28 +00001680
1681 if (MightBeImplicitMember)
Abramo Bagnara7945c982012-01-27 09:46:47 +00001682 return BuildPossibleImplicitMemberExpr(SS, TemplateKWLoc,
1683 R, TemplateArgs);
John McCallb53bbd42009-11-22 01:44:31 +00001684 }
1685
Abramo Bagnara65f7c3d2012-02-06 14:31:00 +00001686 if (TemplateArgs || TemplateKWLoc.isValid())
1687 return BuildTemplateIdExpr(SS, TemplateKWLoc, R, ADL, TemplateArgs);
John McCallb53bbd42009-11-22 01:44:31 +00001688
John McCalle66edc12009-11-24 19:00:30 +00001689 return BuildDeclarationNameExpr(SS, R, ADL);
1690}
1691
John McCall10eae182009-11-30 22:42:35 +00001692/// BuildQualifiedDeclarationNameExpr - Build a C++ qualified
1693/// declaration name, generally during template instantiation.
1694/// There's a large number of things which don't need to be done along
1695/// this path.
John McCalldadc5752010-08-24 06:29:42 +00001696ExprResult
Jeffrey Yasskinc76498d2010-04-08 16:38:48 +00001697Sema::BuildQualifiedDeclarationNameExpr(CXXScopeSpec &SS,
Abramo Bagnarad6d2f182010-08-11 22:01:17 +00001698 const DeclarationNameInfo &NameInfo) {
John McCalle66edc12009-11-24 19:00:30 +00001699 DeclContext *DC;
Douglas Gregora02bb342010-04-28 07:04:26 +00001700 if (!(DC = computeDeclContext(SS, false)) || DC->isDependentContext())
Abramo Bagnara65f7c3d2012-02-06 14:31:00 +00001701 return BuildDependentDeclRefExpr(SS, /*TemplateKWLoc=*/SourceLocation(),
1702 NameInfo, /*TemplateArgs=*/0);
John McCalle66edc12009-11-24 19:00:30 +00001703
John McCall0b66eb32010-05-01 00:40:08 +00001704 if (RequireCompleteDeclContext(SS, DC))
Douglas Gregora02bb342010-04-28 07:04:26 +00001705 return ExprError();
1706
Abramo Bagnarad6d2f182010-08-11 22:01:17 +00001707 LookupResult R(*this, NameInfo, LookupOrdinaryName);
John McCalle66edc12009-11-24 19:00:30 +00001708 LookupQualifiedName(R, DC);
1709
1710 if (R.isAmbiguous())
1711 return ExprError();
1712
1713 if (R.empty()) {
Abramo Bagnarad6d2f182010-08-11 22:01:17 +00001714 Diag(NameInfo.getLoc(), diag::err_no_member)
1715 << NameInfo.getName() << DC << SS.getRange();
John McCalle66edc12009-11-24 19:00:30 +00001716 return ExprError();
1717 }
1718
1719 return BuildDeclarationNameExpr(SS, R, /*ADL*/ false);
1720}
1721
1722/// LookupInObjCMethod - The parser has read a name in, and Sema has
1723/// detected that we're currently inside an ObjC method. Perform some
1724/// additional lookup.
1725///
1726/// Ideally, most of this would be done by lookup, but there's
1727/// actually quite a lot of extra work involved.
1728///
1729/// Returns a null sentinel to indicate trivial success.
John McCalldadc5752010-08-24 06:29:42 +00001730ExprResult
John McCalle66edc12009-11-24 19:00:30 +00001731Sema::LookupInObjCMethod(LookupResult &Lookup, Scope *S,
Chris Lattnera36ec422010-04-11 08:28:14 +00001732 IdentifierInfo *II, bool AllowBuiltinCreation) {
John McCalle66edc12009-11-24 19:00:30 +00001733 SourceLocation Loc = Lookup.getNameLoc();
Chris Lattner87313662010-04-12 05:10:17 +00001734 ObjCMethodDecl *CurMethod = getCurMethodDecl();
Alexis Huntc46382e2010-04-28 23:02:27 +00001735
John McCalle66edc12009-11-24 19:00:30 +00001736 // There are two cases to handle here. 1) scoped lookup could have failed,
1737 // in which case we should look for an ivar. 2) scoped lookup could have
1738 // found a decl, but that decl is outside the current instance method (i.e.
1739 // a global variable). In these two cases, we do a lookup for an ivar with
1740 // this name, if the lookup sucedes, we replace it our current decl.
1741
1742 // If we're in a class method, we don't normally want to look for
1743 // ivars. But if we don't find anything else, and there's an
1744 // ivar, that's an error.
Chris Lattner87313662010-04-12 05:10:17 +00001745 bool IsClassMethod = CurMethod->isClassMethod();
John McCalle66edc12009-11-24 19:00:30 +00001746
1747 bool LookForIvars;
1748 if (Lookup.empty())
1749 LookForIvars = true;
1750 else if (IsClassMethod)
1751 LookForIvars = false;
1752 else
1753 LookForIvars = (Lookup.isSingleResult() &&
1754 Lookup.getFoundDecl()->isDefinedOutsideFunctionOrMethod());
Fariborz Jahanian45878032010-02-09 19:31:38 +00001755 ObjCInterfaceDecl *IFace = 0;
John McCalle66edc12009-11-24 19:00:30 +00001756 if (LookForIvars) {
Chris Lattner87313662010-04-12 05:10:17 +00001757 IFace = CurMethod->getClassInterface();
John McCalle66edc12009-11-24 19:00:30 +00001758 ObjCInterfaceDecl *ClassDeclared;
Argyrios Kyrtzidis4e8b1362011-10-19 02:25:16 +00001759 ObjCIvarDecl *IV = 0;
1760 if (IFace && (IV = IFace->lookupInstanceVariable(II, ClassDeclared))) {
John McCalle66edc12009-11-24 19:00:30 +00001761 // Diagnose using an ivar in a class method.
1762 if (IsClassMethod)
1763 return ExprError(Diag(Loc, diag::error_ivar_use_in_class_method)
1764 << IV->getDeclName());
1765
1766 // If we're referencing an invalid decl, just return this as a silent
1767 // error node. The error diagnostic was already emitted on the decl.
1768 if (IV->isInvalidDecl())
1769 return ExprError();
1770
1771 // Check if referencing a field with __attribute__((deprecated)).
1772 if (DiagnoseUseOfDecl(IV, Loc))
1773 return ExprError();
1774
1775 // Diagnose the use of an ivar outside of the declaring class.
1776 if (IV->getAccessControl() == ObjCIvarDecl::Private &&
Fariborz Jahaniand6cb4a82012-03-07 00:58:41 +00001777 !declaresSameEntity(ClassDeclared, IFace) &&
1778 !getLangOptions().DebuggerSupport)
John McCalle66edc12009-11-24 19:00:30 +00001779 Diag(Loc, diag::error_private_ivar_access) << IV->getDeclName();
1780
1781 // FIXME: This should use a new expr for a direct reference, don't
1782 // turn this into Self->ivar, just return a BareIVarExpr or something.
1783 IdentifierInfo &II = Context.Idents.get("self");
1784 UnqualifiedId SelfName;
Kovarththanan Rajaratnamba2c6522010-03-13 10:17:05 +00001785 SelfName.setIdentifier(&II, SourceLocation());
Fariborz Jahanian7f4427f2011-07-12 17:16:56 +00001786 SelfName.setKind(UnqualifiedId::IK_ImplicitSelfParam);
John McCalle66edc12009-11-24 19:00:30 +00001787 CXXScopeSpec SelfScopeSpec;
Abramo Bagnara7945c982012-01-27 09:46:47 +00001788 SourceLocation TemplateKWLoc;
1789 ExprResult SelfExpr = ActOnIdExpression(S, SelfScopeSpec, TemplateKWLoc,
Douglas Gregora1ed39b2010-09-22 16:33:13 +00001790 SelfName, false, false);
1791 if (SelfExpr.isInvalid())
1792 return ExprError();
1793
John Wiegley01296292011-04-08 18:41:53 +00001794 SelfExpr = DefaultLvalueConversion(SelfExpr.take());
1795 if (SelfExpr.isInvalid())
1796 return ExprError();
John McCall27584242010-12-06 20:48:59 +00001797
Eli Friedmanfa0df832012-02-02 03:46:19 +00001798 MarkAnyDeclReferenced(Loc, IV);
John McCalle66edc12009-11-24 19:00:30 +00001799 return Owned(new (Context)
1800 ObjCIvarRefExpr(IV, IV->getType(), Loc,
John Wiegley01296292011-04-08 18:41:53 +00001801 SelfExpr.take(), true, true));
John McCalle66edc12009-11-24 19:00:30 +00001802 }
Chris Lattner87313662010-04-12 05:10:17 +00001803 } else if (CurMethod->isInstanceMethod()) {
John McCalle66edc12009-11-24 19:00:30 +00001804 // We should warn if a local variable hides an ivar.
Fariborz Jahanian557fc9a2011-11-08 22:51:27 +00001805 if (ObjCInterfaceDecl *IFace = CurMethod->getClassInterface()) {
1806 ObjCInterfaceDecl *ClassDeclared;
1807 if (ObjCIvarDecl *IV = IFace->lookupInstanceVariable(II, ClassDeclared)) {
1808 if (IV->getAccessControl() != ObjCIvarDecl::Private ||
Douglas Gregor0b144e12011-12-15 00:29:59 +00001809 declaresSameEntity(IFace, ClassDeclared))
Fariborz Jahanian557fc9a2011-11-08 22:51:27 +00001810 Diag(Loc, diag::warn_ivar_use_hidden) << IV->getDeclName();
1811 }
John McCalle66edc12009-11-24 19:00:30 +00001812 }
Fariborz Jahanian028b9e12011-12-20 22:21:08 +00001813 } else if (Lookup.isSingleResult() &&
1814 Lookup.getFoundDecl()->isDefinedOutsideFunctionOrMethod()) {
1815 // If accessing a stand-alone ivar in a class method, this is an error.
1816 if (const ObjCIvarDecl *IV = dyn_cast<ObjCIvarDecl>(Lookup.getFoundDecl()))
1817 return ExprError(Diag(Loc, diag::error_ivar_use_in_class_method)
1818 << IV->getDeclName());
John McCalle66edc12009-11-24 19:00:30 +00001819 }
1820
Fariborz Jahanian6fada5b2010-01-12 23:58:59 +00001821 if (Lookup.empty() && II && AllowBuiltinCreation) {
1822 // FIXME. Consolidate this with similar code in LookupName.
1823 if (unsigned BuiltinID = II->getBuiltinID()) {
1824 if (!(getLangOptions().CPlusPlus &&
1825 Context.BuiltinInfo.isPredefinedLibFunction(BuiltinID))) {
1826 NamedDecl *D = LazilyCreateBuiltin((IdentifierInfo *)II, BuiltinID,
1827 S, Lookup.isForRedeclaration(),
1828 Lookup.getNameLoc());
1829 if (D) Lookup.addDecl(D);
1830 }
1831 }
1832 }
John McCalle66edc12009-11-24 19:00:30 +00001833 // Sentinel value saying that we didn't do anything special.
1834 return Owned((Expr*) 0);
Douglas Gregor3256d042009-06-30 15:47:41 +00001835}
John McCalld14a8642009-11-21 08:51:07 +00001836
John McCall16df1e52010-03-30 21:47:33 +00001837/// \brief Cast a base object to a member's actual type.
1838///
1839/// Logically this happens in three phases:
1840///
1841/// * First we cast from the base type to the naming class.
1842/// The naming class is the class into which we were looking
1843/// when we found the member; it's the qualifier type if a
1844/// qualifier was provided, and otherwise it's the base type.
1845///
1846/// * Next we cast from the naming class to the declaring class.
1847/// If the member we found was brought into a class's scope by
1848/// a using declaration, this is that class; otherwise it's
1849/// the class declaring the member.
1850///
1851/// * Finally we cast from the declaring class to the "true"
1852/// declaring class of the member. This conversion does not
1853/// obey access control.
John Wiegley01296292011-04-08 18:41:53 +00001854ExprResult
1855Sema::PerformObjectMemberConversion(Expr *From,
Douglas Gregorcc3f3252010-03-03 23:55:11 +00001856 NestedNameSpecifier *Qualifier,
John McCall16df1e52010-03-30 21:47:33 +00001857 NamedDecl *FoundDecl,
Douglas Gregorcc3f3252010-03-03 23:55:11 +00001858 NamedDecl *Member) {
1859 CXXRecordDecl *RD = dyn_cast<CXXRecordDecl>(Member->getDeclContext());
1860 if (!RD)
John Wiegley01296292011-04-08 18:41:53 +00001861 return Owned(From);
Kovarththanan Rajaratnamba2c6522010-03-13 10:17:05 +00001862
Douglas Gregorcc3f3252010-03-03 23:55:11 +00001863 QualType DestRecordType;
1864 QualType DestType;
1865 QualType FromRecordType;
1866 QualType FromType = From->getType();
1867 bool PointerConversions = false;
1868 if (isa<FieldDecl>(Member)) {
1869 DestRecordType = Context.getCanonicalType(Context.getTypeDeclType(RD));
Kovarththanan Rajaratnamba2c6522010-03-13 10:17:05 +00001870
Douglas Gregorcc3f3252010-03-03 23:55:11 +00001871 if (FromType->getAs<PointerType>()) {
1872 DestType = Context.getPointerType(DestRecordType);
1873 FromRecordType = FromType->getPointeeType();
1874 PointerConversions = true;
1875 } else {
1876 DestType = DestRecordType;
1877 FromRecordType = FromType;
Fariborz Jahanianbb67b822009-07-29 18:40:24 +00001878 }
Douglas Gregorcc3f3252010-03-03 23:55:11 +00001879 } else if (CXXMethodDecl *Method = dyn_cast<CXXMethodDecl>(Member)) {
1880 if (Method->isStatic())
John Wiegley01296292011-04-08 18:41:53 +00001881 return Owned(From);
Kovarththanan Rajaratnamba2c6522010-03-13 10:17:05 +00001882
Douglas Gregorcc3f3252010-03-03 23:55:11 +00001883 DestType = Method->getThisType(Context);
1884 DestRecordType = DestType->getPointeeType();
Kovarththanan Rajaratnamba2c6522010-03-13 10:17:05 +00001885
Douglas Gregorcc3f3252010-03-03 23:55:11 +00001886 if (FromType->getAs<PointerType>()) {
1887 FromRecordType = FromType->getPointeeType();
1888 PointerConversions = true;
1889 } else {
1890 FromRecordType = FromType;
1891 DestType = DestRecordType;
1892 }
1893 } else {
1894 // No conversion necessary.
John Wiegley01296292011-04-08 18:41:53 +00001895 return Owned(From);
Douglas Gregorcc3f3252010-03-03 23:55:11 +00001896 }
Kovarththanan Rajaratnamba2c6522010-03-13 10:17:05 +00001897
Douglas Gregorcc3f3252010-03-03 23:55:11 +00001898 if (DestType->isDependentType() || FromType->isDependentType())
John Wiegley01296292011-04-08 18:41:53 +00001899 return Owned(From);
Kovarththanan Rajaratnamba2c6522010-03-13 10:17:05 +00001900
Douglas Gregorcc3f3252010-03-03 23:55:11 +00001901 // If the unqualified types are the same, no conversion is necessary.
1902 if (Context.hasSameUnqualifiedType(FromRecordType, DestRecordType))
John Wiegley01296292011-04-08 18:41:53 +00001903 return Owned(From);
Kovarththanan Rajaratnamba2c6522010-03-13 10:17:05 +00001904
John McCall16df1e52010-03-30 21:47:33 +00001905 SourceRange FromRange = From->getSourceRange();
1906 SourceLocation FromLoc = FromRange.getBegin();
1907
Eli Friedmanbe4b3632011-09-27 21:58:52 +00001908 ExprValueKind VK = From->getValueKind();
Sebastian Redlc57d34b2010-07-20 04:20:21 +00001909
Douglas Gregorcc3f3252010-03-03 23:55:11 +00001910 // C++ [class.member.lookup]p8:
Kovarththanan Rajaratnamba2c6522010-03-13 10:17:05 +00001911 // [...] Ambiguities can often be resolved by qualifying a name with its
Douglas Gregorcc3f3252010-03-03 23:55:11 +00001912 // class name.
1913 //
1914 // If the member was a qualified name and the qualified referred to a
1915 // specific base subobject type, we'll cast to that intermediate type
1916 // first and then to the object in which the member is declared. That allows
1917 // one to resolve ambiguities in, e.g., a diamond-shaped hierarchy such as:
1918 //
1919 // class Base { public: int x; };
1920 // class Derived1 : public Base { };
1921 // class Derived2 : public Base { };
1922 // class VeryDerived : public Derived1, public Derived2 { void f(); };
1923 //
1924 // void VeryDerived::f() {
1925 // x = 17; // error: ambiguous base subobjects
1926 // Derived1::x = 17; // okay, pick the Base subobject of Derived1
1927 // }
Douglas Gregorcc3f3252010-03-03 23:55:11 +00001928 if (Qualifier) {
John McCall16df1e52010-03-30 21:47:33 +00001929 QualType QType = QualType(Qualifier->getAsType(), 0);
1930 assert(!QType.isNull() && "lookup done with dependent qualifier?");
1931 assert(QType->isRecordType() && "lookup done with non-record type");
1932
1933 QualType QRecordType = QualType(QType->getAs<RecordType>(), 0);
1934
1935 // In C++98, the qualifier type doesn't actually have to be a base
1936 // type of the object type, in which case we just ignore it.
1937 // Otherwise build the appropriate casts.
1938 if (IsDerivedFrom(FromRecordType, QRecordType)) {
John McCallcf142162010-08-07 06:22:56 +00001939 CXXCastPath BasePath;
John McCall16df1e52010-03-30 21:47:33 +00001940 if (CheckDerivedToBaseConversion(FromRecordType, QRecordType,
Anders Carlssonb78feca2010-04-24 19:22:20 +00001941 FromLoc, FromRange, &BasePath))
John Wiegley01296292011-04-08 18:41:53 +00001942 return ExprError();
John McCall16df1e52010-03-30 21:47:33 +00001943
Douglas Gregorcc3f3252010-03-03 23:55:11 +00001944 if (PointerConversions)
John McCall16df1e52010-03-30 21:47:33 +00001945 QType = Context.getPointerType(QType);
John Wiegley01296292011-04-08 18:41:53 +00001946 From = ImpCastExprToType(From, QType, CK_UncheckedDerivedToBase,
1947 VK, &BasePath).take();
John McCall16df1e52010-03-30 21:47:33 +00001948
1949 FromType = QType;
1950 FromRecordType = QRecordType;
1951
1952 // If the qualifier type was the same as the destination type,
1953 // we're done.
1954 if (Context.hasSameUnqualifiedType(FromRecordType, DestRecordType))
John Wiegley01296292011-04-08 18:41:53 +00001955 return Owned(From);
Douglas Gregorcc3f3252010-03-03 23:55:11 +00001956 }
1957 }
Kovarththanan Rajaratnamba2c6522010-03-13 10:17:05 +00001958
John McCall16df1e52010-03-30 21:47:33 +00001959 bool IgnoreAccess = false;
Douglas Gregorcc3f3252010-03-03 23:55:11 +00001960
John McCall16df1e52010-03-30 21:47:33 +00001961 // If we actually found the member through a using declaration, cast
1962 // down to the using declaration's type.
1963 //
1964 // Pointer equality is fine here because only one declaration of a
1965 // class ever has member declarations.
1966 if (FoundDecl->getDeclContext() != Member->getDeclContext()) {
1967 assert(isa<UsingShadowDecl>(FoundDecl));
1968 QualType URecordType = Context.getTypeDeclType(
1969 cast<CXXRecordDecl>(FoundDecl->getDeclContext()));
1970
1971 // We only need to do this if the naming-class to declaring-class
1972 // conversion is non-trivial.
1973 if (!Context.hasSameUnqualifiedType(FromRecordType, URecordType)) {
1974 assert(IsDerivedFrom(FromRecordType, URecordType));
John McCallcf142162010-08-07 06:22:56 +00001975 CXXCastPath BasePath;
John McCall16df1e52010-03-30 21:47:33 +00001976 if (CheckDerivedToBaseConversion(FromRecordType, URecordType,
Anders Carlssonb78feca2010-04-24 19:22:20 +00001977 FromLoc, FromRange, &BasePath))
John Wiegley01296292011-04-08 18:41:53 +00001978 return ExprError();
Alexis Huntc46382e2010-04-28 23:02:27 +00001979
John McCall16df1e52010-03-30 21:47:33 +00001980 QualType UType = URecordType;
1981 if (PointerConversions)
1982 UType = Context.getPointerType(UType);
John Wiegley01296292011-04-08 18:41:53 +00001983 From = ImpCastExprToType(From, UType, CK_UncheckedDerivedToBase,
1984 VK, &BasePath).take();
John McCall16df1e52010-03-30 21:47:33 +00001985 FromType = UType;
1986 FromRecordType = URecordType;
1987 }
1988
1989 // We don't do access control for the conversion from the
1990 // declaring class to the true declaring class.
1991 IgnoreAccess = true;
Douglas Gregorcc3f3252010-03-03 23:55:11 +00001992 }
Kovarththanan Rajaratnamba2c6522010-03-13 10:17:05 +00001993
John McCallcf142162010-08-07 06:22:56 +00001994 CXXCastPath BasePath;
Anders Carlssonb78feca2010-04-24 19:22:20 +00001995 if (CheckDerivedToBaseConversion(FromRecordType, DestRecordType,
1996 FromLoc, FromRange, &BasePath,
John McCall16df1e52010-03-30 21:47:33 +00001997 IgnoreAccess))
John Wiegley01296292011-04-08 18:41:53 +00001998 return ExprError();
Kovarththanan Rajaratnamba2c6522010-03-13 10:17:05 +00001999
John Wiegley01296292011-04-08 18:41:53 +00002000 return ImpCastExprToType(From, DestType, CK_UncheckedDerivedToBase,
2001 VK, &BasePath);
Fariborz Jahanianbb67b822009-07-29 18:40:24 +00002002}
Douglas Gregor3256d042009-06-30 15:47:41 +00002003
John McCalle66edc12009-11-24 19:00:30 +00002004bool Sema::UseArgumentDependentLookup(const CXXScopeSpec &SS,
John McCallb53bbd42009-11-22 01:44:31 +00002005 const LookupResult &R,
2006 bool HasTrailingLParen) {
John McCalld14a8642009-11-21 08:51:07 +00002007 // Only when used directly as the postfix-expression of a call.
2008 if (!HasTrailingLParen)
2009 return false;
2010
2011 // Never if a scope specifier was provided.
John McCalle66edc12009-11-24 19:00:30 +00002012 if (SS.isSet())
John McCalld14a8642009-11-21 08:51:07 +00002013 return false;
2014
2015 // Only in C++ or ObjC++.
John McCallb53bbd42009-11-22 01:44:31 +00002016 if (!getLangOptions().CPlusPlus)
John McCalld14a8642009-11-21 08:51:07 +00002017 return false;
2018
2019 // Turn off ADL when we find certain kinds of declarations during
2020 // normal lookup:
2021 for (LookupResult::iterator I = R.begin(), E = R.end(); I != E; ++I) {
2022 NamedDecl *D = *I;
2023
2024 // C++0x [basic.lookup.argdep]p3:
2025 // -- a declaration of a class member
2026 // Since using decls preserve this property, we check this on the
2027 // original decl.
John McCall57500772009-12-16 12:17:52 +00002028 if (D->isCXXClassMember())
John McCalld14a8642009-11-21 08:51:07 +00002029 return false;
2030
2031 // C++0x [basic.lookup.argdep]p3:
2032 // -- a block-scope function declaration that is not a
2033 // using-declaration
2034 // NOTE: we also trigger this for function templates (in fact, we
2035 // don't check the decl type at all, since all other decl types
2036 // turn off ADL anyway).
2037 if (isa<UsingShadowDecl>(D))
2038 D = cast<UsingShadowDecl>(D)->getTargetDecl();
2039 else if (D->getDeclContext()->isFunctionOrMethod())
2040 return false;
2041
2042 // C++0x [basic.lookup.argdep]p3:
2043 // -- a declaration that is neither a function or a function
2044 // template
2045 // And also for builtin functions.
2046 if (isa<FunctionDecl>(D)) {
2047 FunctionDecl *FDecl = cast<FunctionDecl>(D);
2048
2049 // But also builtin functions.
2050 if (FDecl->getBuiltinID() && FDecl->isImplicit())
2051 return false;
2052 } else if (!isa<FunctionTemplateDecl>(D))
2053 return false;
2054 }
2055
2056 return true;
2057}
2058
2059
John McCalld14a8642009-11-21 08:51:07 +00002060/// Diagnoses obvious problems with the use of the given declaration
2061/// as an expression. This is only actually called for lookups that
2062/// were not overloaded, and it doesn't promise that the declaration
2063/// will in fact be used.
2064static bool CheckDeclInExpr(Sema &S, SourceLocation Loc, NamedDecl *D) {
Richard Smithdda56e42011-04-15 14:24:37 +00002065 if (isa<TypedefNameDecl>(D)) {
John McCalld14a8642009-11-21 08:51:07 +00002066 S.Diag(Loc, diag::err_unexpected_typedef) << D->getDeclName();
2067 return true;
2068 }
2069
2070 if (isa<ObjCInterfaceDecl>(D)) {
2071 S.Diag(Loc, diag::err_unexpected_interface) << D->getDeclName();
2072 return true;
2073 }
2074
2075 if (isa<NamespaceDecl>(D)) {
2076 S.Diag(Loc, diag::err_unexpected_namespace) << D->getDeclName();
2077 return true;
2078 }
2079
2080 return false;
2081}
2082
John McCalldadc5752010-08-24 06:29:42 +00002083ExprResult
John McCalle66edc12009-11-24 19:00:30 +00002084Sema::BuildDeclarationNameExpr(const CXXScopeSpec &SS,
John McCallb53bbd42009-11-22 01:44:31 +00002085 LookupResult &R,
2086 bool NeedsADL) {
John McCall3a60c872009-12-08 22:45:53 +00002087 // If this is a single, fully-resolved result and we don't need ADL,
2088 // just build an ordinary singleton decl ref.
Douglas Gregor4b4844f2010-01-29 17:15:43 +00002089 if (!NeedsADL && R.isSingleResult() && !R.getAsSingle<FunctionTemplateDecl>())
Abramo Bagnarad6d2f182010-08-11 22:01:17 +00002090 return BuildDeclarationNameExpr(SS, R.getLookupNameInfo(),
2091 R.getFoundDecl());
John McCalld14a8642009-11-21 08:51:07 +00002092
2093 // We only need to check the declaration if there's exactly one
2094 // result, because in the overloaded case the results can only be
2095 // functions and function templates.
John McCallb53bbd42009-11-22 01:44:31 +00002096 if (R.isSingleResult() &&
2097 CheckDeclInExpr(*this, R.getNameLoc(), R.getFoundDecl()))
John McCalld14a8642009-11-21 08:51:07 +00002098 return ExprError();
2099
John McCall58cc69d2010-01-27 01:50:18 +00002100 // Otherwise, just build an unresolved lookup expression. Suppress
2101 // any lookup-related diagnostics; we'll hash these out later, when
2102 // we've picked a target.
2103 R.suppressDiagnostics();
2104
John McCalld14a8642009-11-21 08:51:07 +00002105 UnresolvedLookupExpr *ULE
Douglas Gregora6e053e2010-12-15 01:34:56 +00002106 = UnresolvedLookupExpr::Create(Context, R.getNamingClass(),
Douglas Gregor0da1d432011-02-28 20:01:57 +00002107 SS.getWithLocInContext(Context),
2108 R.getLookupNameInfo(),
Douglas Gregor30a4f4c2010-05-23 18:57:34 +00002109 NeedsADL, R.isOverloadedResult(),
2110 R.begin(), R.end());
John McCalld14a8642009-11-21 08:51:07 +00002111
2112 return Owned(ULE);
2113}
Kovarththanan Rajaratnamba2c6522010-03-13 10:17:05 +00002114
Eli Friedman9bb33f52012-02-03 02:04:35 +00002115static bool shouldBuildBlockDeclRef(ValueDecl *D, Sema &S) {
2116 // Check for a variable with local storage not from the current scope;
2117 // we need to create BlockDeclRefExprs for these.
2118 // FIXME: BlockDeclRefExpr shouldn't exist!
2119 VarDecl *var = dyn_cast<VarDecl>(D);
2120 if (!var)
2121 return false;
2122 if (var->getDeclContext() == S.CurContext)
2123 return false;
2124 if (!var->hasLocalStorage())
2125 return false;
2126 return S.getCurBlock() != 0;
2127}
2128
Eli Friedman9bb33f52012-02-03 02:04:35 +00002129static ExprResult BuildBlockDeclRefExpr(Sema &S, ValueDecl *VD,
2130 const DeclarationNameInfo &NameInfo) {
2131 VarDecl *var = cast<VarDecl>(VD);
2132 QualType exprType = var->getType().getNonReferenceType();
2133
2134 bool HasBlockAttr = var->hasAttr<BlocksAttr>();
2135 bool ConstAdded = false;
2136 if (!HasBlockAttr) {
2137 ConstAdded = !exprType.isConstQualified();
2138 exprType.addConst();
2139 }
2140
2141 BlockDeclRefExpr *BDRE =
2142 new (S.Context) BlockDeclRefExpr(var, exprType, VK_LValue,
2143 NameInfo.getLoc(), HasBlockAttr,
2144 ConstAdded);
2145
2146 S.MarkBlockDeclRefReferenced(BDRE);
2147
2148 return S.Owned(BDRE);
2149}
2150
John McCalld14a8642009-11-21 08:51:07 +00002151/// \brief Complete semantic analysis for a reference to the given declaration.
John McCalldadc5752010-08-24 06:29:42 +00002152ExprResult
John McCalle66edc12009-11-24 19:00:30 +00002153Sema::BuildDeclarationNameExpr(const CXXScopeSpec &SS,
Abramo Bagnarad6d2f182010-08-11 22:01:17 +00002154 const DeclarationNameInfo &NameInfo,
2155 NamedDecl *D) {
John McCalld14a8642009-11-21 08:51:07 +00002156 assert(D && "Cannot refer to a NULL declaration");
John McCall283b9012009-11-22 00:44:51 +00002157 assert(!isa<FunctionTemplateDecl>(D) &&
2158 "Cannot refer unambiguously to a function template");
John McCalld14a8642009-11-21 08:51:07 +00002159
Abramo Bagnarad6d2f182010-08-11 22:01:17 +00002160 SourceLocation Loc = NameInfo.getLoc();
John McCalld14a8642009-11-21 08:51:07 +00002161 if (CheckDeclInExpr(*this, Loc, D))
2162 return ExprError();
Steve Narofff1e53692007-03-23 22:27:02 +00002163
Douglas Gregore7488b92009-12-01 16:58:18 +00002164 if (TemplateDecl *Template = dyn_cast<TemplateDecl>(D)) {
2165 // Specifically diagnose references to class templates that are missing
2166 // a template argument list.
2167 Diag(Loc, diag::err_template_decl_ref)
2168 << Template << SS.getRange();
2169 Diag(Template->getLocation(), diag::note_template_decl_here);
2170 return ExprError();
2171 }
2172
2173 // Make sure that we're referring to a value.
2174 ValueDecl *VD = dyn_cast<ValueDecl>(D);
2175 if (!VD) {
Kovarththanan Rajaratnamba2c6522010-03-13 10:17:05 +00002176 Diag(Loc, diag::err_ref_non_value)
Douglas Gregore7488b92009-12-01 16:58:18 +00002177 << D << SS.getRange();
John McCallb48971d2009-12-18 18:35:10 +00002178 Diag(D->getLocation(), diag::note_declared_at);
Douglas Gregore7488b92009-12-01 16:58:18 +00002179 return ExprError();
2180 }
Sebastian Redlffbcf962009-01-18 18:53:16 +00002181
Douglas Gregor171c45a2009-02-18 21:56:37 +00002182 // Check whether this declaration can be used. Note that we suppress
2183 // this check when we're going to perform argument-dependent lookup
2184 // on this function name, because this might not be the function
2185 // that overload resolution actually selects.
John McCalld14a8642009-11-21 08:51:07 +00002186 if (DiagnoseUseOfDecl(VD, Loc))
Douglas Gregor171c45a2009-02-18 21:56:37 +00002187 return ExprError();
2188
Steve Naroff8de9c3a2008-09-05 22:11:13 +00002189 // Only create DeclRefExpr's for valid Decl's.
2190 if (VD->isInvalidDecl())
Sebastian Redlffbcf962009-01-18 18:53:16 +00002191 return ExprError();
2192
John McCallf3a88602011-02-03 08:15:49 +00002193 // Handle members of anonymous structs and unions. If we got here,
2194 // and the reference is to a class member indirect field, then this
2195 // must be the subject of a pointer-to-member expression.
2196 if (IndirectFieldDecl *indirectField = dyn_cast<IndirectFieldDecl>(VD))
2197 if (!indirectField->isCXXClassMember())
2198 return BuildAnonymousStructUnionMemberReference(SS, NameInfo.getLoc(),
2199 indirectField);
Francois Pichet783dd6e2010-11-21 06:08:52 +00002200
Eli Friedman9bb33f52012-02-03 02:04:35 +00002201 {
John McCallf4cd4f92011-02-09 01:13:10 +00002202 QualType type = VD->getType();
Daniel Dunbar7c2dc362011-02-10 18:29:28 +00002203 ExprValueKind valueKind = VK_RValue;
John McCallf4cd4f92011-02-09 01:13:10 +00002204
2205 switch (D->getKind()) {
2206 // Ignore all the non-ValueDecl kinds.
2207#define ABSTRACT_DECL(kind)
2208#define VALUE(type, base)
2209#define DECL(type, base) \
2210 case Decl::type:
2211#include "clang/AST/DeclNodes.inc"
2212 llvm_unreachable("invalid value decl kind");
John McCallf4cd4f92011-02-09 01:13:10 +00002213
2214 // These shouldn't make it here.
2215 case Decl::ObjCAtDefsField:
2216 case Decl::ObjCIvar:
2217 llvm_unreachable("forming non-member reference to ivar?");
John McCallf4cd4f92011-02-09 01:13:10 +00002218
2219 // Enum constants are always r-values and never references.
2220 // Unresolved using declarations are dependent.
2221 case Decl::EnumConstant:
2222 case Decl::UnresolvedUsingValue:
2223 valueKind = VK_RValue;
2224 break;
2225
2226 // Fields and indirect fields that got here must be for
2227 // pointer-to-member expressions; we just call them l-values for
2228 // internal consistency, because this subexpression doesn't really
2229 // exist in the high-level semantics.
2230 case Decl::Field:
2231 case Decl::IndirectField:
2232 assert(getLangOptions().CPlusPlus &&
2233 "building reference to field in C?");
2234
2235 // These can't have reference type in well-formed programs, but
2236 // for internal consistency we do this anyway.
2237 type = type.getNonReferenceType();
2238 valueKind = VK_LValue;
2239 break;
2240
2241 // Non-type template parameters are either l-values or r-values
2242 // depending on the type.
2243 case Decl::NonTypeTemplateParm: {
2244 if (const ReferenceType *reftype = type->getAs<ReferenceType>()) {
2245 type = reftype->getPointeeType();
2246 valueKind = VK_LValue; // even if the parameter is an r-value reference
2247 break;
2248 }
2249
2250 // For non-references, we need to strip qualifiers just in case
2251 // the template parameter was declared as 'const int' or whatever.
2252 valueKind = VK_RValue;
2253 type = type.getUnqualifiedType();
2254 break;
2255 }
2256
2257 case Decl::Var:
2258 // In C, "extern void blah;" is valid and is an r-value.
2259 if (!getLangOptions().CPlusPlus &&
2260 !type.hasQualifiers() &&
2261 type->isVoidType()) {
2262 valueKind = VK_RValue;
2263 break;
2264 }
2265 // fallthrough
2266
2267 case Decl::ImplicitParam:
Douglas Gregor812d8f62012-02-18 05:51:20 +00002268 case Decl::ParmVar: {
John McCallf4cd4f92011-02-09 01:13:10 +00002269 // These are always l-values.
2270 valueKind = VK_LValue;
2271 type = type.getNonReferenceType();
Eli Friedman9bb33f52012-02-03 02:04:35 +00002272
2273 if (shouldBuildBlockDeclRef(VD, *this))
2274 return BuildBlockDeclRefExpr(*this, VD, NameInfo);
2275
Douglas Gregor812d8f62012-02-18 05:51:20 +00002276 // FIXME: Does the addition of const really only apply in
2277 // potentially-evaluated contexts? Since the variable isn't actually
2278 // captured in an unevaluated context, it seems that the answer is no.
2279 if (ExprEvalContexts.back().Context != Sema::Unevaluated) {
2280 QualType CapturedType = getCapturedDeclRefType(cast<VarDecl>(VD), Loc);
2281 if (!CapturedType.isNull())
2282 type = CapturedType;
2283 }
2284
John McCallf4cd4f92011-02-09 01:13:10 +00002285 break;
Douglas Gregor812d8f62012-02-18 05:51:20 +00002286 }
2287
John McCallf4cd4f92011-02-09 01:13:10 +00002288 case Decl::Function: {
John McCall2979fe02011-04-12 00:42:48 +00002289 const FunctionType *fty = type->castAs<FunctionType>();
2290
2291 // If we're referring to a function with an __unknown_anytype
2292 // result type, make the entire expression __unknown_anytype.
2293 if (fty->getResultType() == Context.UnknownAnyTy) {
2294 type = Context.UnknownAnyTy;
2295 valueKind = VK_RValue;
2296 break;
2297 }
2298
John McCallf4cd4f92011-02-09 01:13:10 +00002299 // Functions are l-values in C++.
2300 if (getLangOptions().CPlusPlus) {
2301 valueKind = VK_LValue;
2302 break;
2303 }
2304
2305 // C99 DR 316 says that, if a function type comes from a
2306 // function definition (without a prototype), that type is only
2307 // used for checking compatibility. Therefore, when referencing
2308 // the function, we pretend that we don't have the full function
2309 // type.
John McCall2979fe02011-04-12 00:42:48 +00002310 if (!cast<FunctionDecl>(VD)->hasPrototype() &&
2311 isa<FunctionProtoType>(fty))
2312 type = Context.getFunctionNoProtoType(fty->getResultType(),
2313 fty->getExtInfo());
John McCallf4cd4f92011-02-09 01:13:10 +00002314
2315 // Functions are r-values in C.
2316 valueKind = VK_RValue;
2317 break;
2318 }
2319
2320 case Decl::CXXMethod:
John McCall2979fe02011-04-12 00:42:48 +00002321 // If we're referring to a method with an __unknown_anytype
2322 // result type, make the entire expression __unknown_anytype.
2323 // This should only be possible with a type written directly.
Richard Trieucfc491d2011-08-02 04:35:43 +00002324 if (const FunctionProtoType *proto
2325 = dyn_cast<FunctionProtoType>(VD->getType()))
John McCall2979fe02011-04-12 00:42:48 +00002326 if (proto->getResultType() == Context.UnknownAnyTy) {
2327 type = Context.UnknownAnyTy;
2328 valueKind = VK_RValue;
2329 break;
2330 }
2331
John McCallf4cd4f92011-02-09 01:13:10 +00002332 // C++ methods are l-values if static, r-values if non-static.
2333 if (cast<CXXMethodDecl>(VD)->isStatic()) {
2334 valueKind = VK_LValue;
2335 break;
2336 }
2337 // fallthrough
2338
2339 case Decl::CXXConversion:
2340 case Decl::CXXDestructor:
2341 case Decl::CXXConstructor:
2342 valueKind = VK_RValue;
2343 break;
2344 }
2345
2346 return BuildDeclRefExpr(VD, type, valueKind, NameInfo, &SS);
2347 }
Chris Lattner17ed4872006-11-20 04:58:19 +00002348}
Chris Lattnere168f762006-11-10 05:29:30 +00002349
John McCall2979fe02011-04-12 00:42:48 +00002350ExprResult Sema::ActOnPredefinedExpr(SourceLocation Loc, tok::TokenKind Kind) {
Chris Lattner6307f192008-08-10 01:53:14 +00002351 PredefinedExpr::IdentType IT;
Sebastian Redlffbcf962009-01-18 18:53:16 +00002352
Chris Lattnere168f762006-11-10 05:29:30 +00002353 switch (Kind) {
David Blaikie83d382b2011-09-23 05:06:16 +00002354 default: llvm_unreachable("Unknown simple primary expr!");
Chris Lattner6307f192008-08-10 01:53:14 +00002355 case tok::kw___func__: IT = PredefinedExpr::Func; break; // [C99 6.4.2.2]
2356 case tok::kw___FUNCTION__: IT = PredefinedExpr::Function; break;
2357 case tok::kw___PRETTY_FUNCTION__: IT = PredefinedExpr::PrettyFunction; break;
Chris Lattnere168f762006-11-10 05:29:30 +00002358 }
Chris Lattner317e6ba2008-01-12 18:39:25 +00002359
Chris Lattnera81a0272008-01-12 08:14:25 +00002360 // Pre-defined identifiers are of type char[x], where x is the length of the
2361 // string.
Mike Stump11289f42009-09-09 15:08:12 +00002362
Anders Carlsson2fb08242009-09-08 18:24:21 +00002363 Decl *currentDecl = getCurFunctionOrMethodDecl();
Fariborz Jahanian94627442010-07-23 21:53:24 +00002364 if (!currentDecl && getCurBlock())
2365 currentDecl = getCurBlock()->TheDecl;
Anders Carlsson2fb08242009-09-08 18:24:21 +00002366 if (!currentDecl) {
Chris Lattnerf45c5ec2008-12-12 05:05:20 +00002367 Diag(Loc, diag::ext_predef_outside_function);
Anders Carlsson2fb08242009-09-08 18:24:21 +00002368 currentDecl = Context.getTranslationUnitDecl();
Chris Lattnerf45c5ec2008-12-12 05:05:20 +00002369 }
Sebastian Redlffbcf962009-01-18 18:53:16 +00002370
Anders Carlsson0b209a82009-09-11 01:22:35 +00002371 QualType ResTy;
2372 if (cast<DeclContext>(currentDecl)->isDependentContext()) {
2373 ResTy = Context.DependentTy;
2374 } else {
Anders Carlsson5bd8d192010-02-11 18:20:28 +00002375 unsigned Length = PredefinedExpr::ComputeName(IT, currentDecl).length();
Sebastian Redlffbcf962009-01-18 18:53:16 +00002376
Anders Carlsson0b209a82009-09-11 01:22:35 +00002377 llvm::APInt LengthI(32, Length + 1);
John McCall8ccfcb52009-09-24 19:53:00 +00002378 ResTy = Context.CharTy.withConst();
Anders Carlsson0b209a82009-09-11 01:22:35 +00002379 ResTy = Context.getConstantArrayType(ResTy, LengthI, ArrayType::Normal, 0);
2380 }
Steve Narofff6009ed2009-01-21 00:14:39 +00002381 return Owned(new (Context) PredefinedExpr(Loc, ResTy, IT));
Chris Lattnere168f762006-11-10 05:29:30 +00002382}
2383
John McCalldadc5752010-08-24 06:29:42 +00002384ExprResult Sema::ActOnCharacterConstant(const Token &Tok) {
Dylan Noblesmith2c1dd272012-02-05 02:13:05 +00002385 SmallString<16> CharBuffer;
Douglas Gregordc970f02010-03-16 22:30:13 +00002386 bool Invalid = false;
Chris Lattner0e62c1c2011-07-23 10:55:15 +00002387 StringRef ThisTok = PP.getSpelling(Tok, CharBuffer, &Invalid);
Douglas Gregordc970f02010-03-16 22:30:13 +00002388 if (Invalid)
2389 return ExprError();
Sebastian Redlffbcf962009-01-18 18:53:16 +00002390
Benjamin Kramer0a1abd42010-02-27 13:44:12 +00002391 CharLiteralParser Literal(ThisTok.begin(), ThisTok.end(), Tok.getLocation(),
Douglas Gregorfb65e592011-07-27 05:40:30 +00002392 PP, Tok.getKind());
Steve Naroffae4143e2007-04-26 20:39:23 +00002393 if (Literal.hadError())
Sebastian Redlffbcf962009-01-18 18:53:16 +00002394 return ExprError();
Chris Lattneref24b382008-03-01 08:32:21 +00002395
Chris Lattnerc3847ba2009-12-30 21:19:39 +00002396 QualType Ty;
Seth Cantrell02f86052012-01-18 12:27:06 +00002397 if (Literal.isWide())
2398 Ty = Context.WCharTy; // L'x' -> wchar_t in C and C++.
Douglas Gregorfb65e592011-07-27 05:40:30 +00002399 else if (Literal.isUTF16())
Seth Cantrell02f86052012-01-18 12:27:06 +00002400 Ty = Context.Char16Ty; // u'x' -> char16_t in C11 and C++11.
Douglas Gregorfb65e592011-07-27 05:40:30 +00002401 else if (Literal.isUTF32())
Seth Cantrell02f86052012-01-18 12:27:06 +00002402 Ty = Context.Char32Ty; // U'x' -> char32_t in C11 and C++11.
2403 else if (!getLangOptions().CPlusPlus || Literal.isMultiChar())
2404 Ty = Context.IntTy; // 'x' -> int in C, 'wxyz' -> int in C++.
Chris Lattnerc3847ba2009-12-30 21:19:39 +00002405 else
2406 Ty = Context.CharTy; // 'x' -> char in C++
Chris Lattneref24b382008-03-01 08:32:21 +00002407
Douglas Gregorfb65e592011-07-27 05:40:30 +00002408 CharacterLiteral::CharacterKind Kind = CharacterLiteral::Ascii;
2409 if (Literal.isWide())
2410 Kind = CharacterLiteral::Wide;
2411 else if (Literal.isUTF16())
2412 Kind = CharacterLiteral::UTF16;
2413 else if (Literal.isUTF32())
2414 Kind = CharacterLiteral::UTF32;
2415
Richard Smith75b67d62012-03-08 01:34:56 +00002416 Expr *Lit = new (Context) CharacterLiteral(Literal.getValue(), Kind, Ty,
2417 Tok.getLocation());
2418
2419 if (Literal.getUDSuffix().empty())
2420 return Owned(Lit);
2421
2422 // We're building a user-defined literal.
2423 IdentifierInfo *UDSuffix = &Context.Idents.get(Literal.getUDSuffix());
2424 SourceLocation UDSuffixLoc =
2425 getUDSuffixLoc(*this, Tok.getLocation(), Literal.getUDSuffixOffset());
2426
2427 // C++11 [lex.ext]p6: The literal L is treated as a call of the form
2428 // operator "" X (ch)
2429 return BuildLiteralOperatorCall(UDSuffix, UDSuffixLoc,
2430 llvm::makeArrayRef(&Lit, 1),
2431 Tok.getLocation());
Steve Naroffae4143e2007-04-26 20:39:23 +00002432}
2433
Ted Kremeneke65b0862012-03-06 20:05:56 +00002434ExprResult Sema::ActOnIntegerConstant(SourceLocation Loc, uint64_t Val) {
2435 unsigned IntSize = Context.getTargetInfo().getIntWidth();
2436 return Owned(IntegerLiteral::Create(Context, llvm::APInt(IntSize, Val),
2437 Context.IntTy, Loc));
2438}
2439
Richard Smith39570d002012-03-08 08:45:32 +00002440static Expr *BuildFloatingLiteral(Sema &S, NumericLiteralParser &Literal,
2441 QualType Ty, SourceLocation Loc) {
2442 const llvm::fltSemantics &Format = S.Context.getFloatTypeSemantics(Ty);
2443
2444 using llvm::APFloat;
2445 APFloat Val(Format);
2446
2447 APFloat::opStatus result = Literal.GetFloatValue(Val);
2448
2449 // Overflow is always an error, but underflow is only an error if
2450 // we underflowed to zero (APFloat reports denormals as underflow).
2451 if ((result & APFloat::opOverflow) ||
2452 ((result & APFloat::opUnderflow) && Val.isZero())) {
2453 unsigned diagnostic;
2454 SmallString<20> buffer;
2455 if (result & APFloat::opOverflow) {
2456 diagnostic = diag::warn_float_overflow;
2457 APFloat::getLargest(Format).toString(buffer);
2458 } else {
2459 diagnostic = diag::warn_float_underflow;
2460 APFloat::getSmallest(Format).toString(buffer);
2461 }
2462
2463 S.Diag(Loc, diagnostic)
2464 << Ty
2465 << StringRef(buffer.data(), buffer.size());
2466 }
2467
2468 bool isExact = (result == APFloat::opOK);
2469 return FloatingLiteral::Create(S.Context, Val, isExact, Ty, Loc);
2470}
2471
John McCalldadc5752010-08-24 06:29:42 +00002472ExprResult Sema::ActOnNumericConstant(const Token &Tok) {
Sebastian Redlffbcf962009-01-18 18:53:16 +00002473 // Fast path for a single digit (which is quite common). A single digit
Steve Narofff2fb89e2007-03-13 20:29:44 +00002474 // cannot have a trigraph, escaped newline, radix prefix, or type suffix.
2475 if (Tok.getLength() == 1) {
Chris Lattner9240b3e2009-01-26 22:36:52 +00002476 const char Val = PP.getSpellingOfSingleCharacterNumericConstant(Tok);
Ted Kremeneke65b0862012-03-06 20:05:56 +00002477 return ActOnIntegerConstant(Tok.getLocation(), Val-'0');
Steve Narofff2fb89e2007-03-13 20:29:44 +00002478 }
Ted Kremeneke9814182009-01-13 23:19:12 +00002479
Dylan Noblesmith2c1dd272012-02-05 02:13:05 +00002480 SmallString<512> IntegerBuffer;
Chris Lattnera1cf5f92008-09-30 20:53:45 +00002481 // Add padding so that NumericLiteralParser can overread by one character.
2482 IntegerBuffer.resize(Tok.getLength()+1);
Steve Naroff8160ea22007-03-06 01:09:46 +00002483 const char *ThisTokBegin = &IntegerBuffer[0];
Sebastian Redlffbcf962009-01-18 18:53:16 +00002484
Chris Lattner67ca9252007-05-21 01:08:44 +00002485 // Get the spelling of the token, which eliminates trigraphs, etc.
Douglas Gregordc970f02010-03-16 22:30:13 +00002486 bool Invalid = false;
2487 unsigned ActualLength = PP.getSpelling(Tok, ThisTokBegin, &Invalid);
2488 if (Invalid)
2489 return ExprError();
Sebastian Redlffbcf962009-01-18 18:53:16 +00002490
Mike Stump11289f42009-09-09 15:08:12 +00002491 NumericLiteralParser Literal(ThisTokBegin, ThisTokBegin+ActualLength,
Steve Naroff451d8f162007-03-12 23:22:38 +00002492 Tok.getLocation(), PP);
Steve Narofff2fb89e2007-03-13 20:29:44 +00002493 if (Literal.hadError)
Sebastian Redlffbcf962009-01-18 18:53:16 +00002494 return ExprError();
2495
Richard Smith39570d002012-03-08 08:45:32 +00002496 if (Literal.hasUDSuffix()) {
2497 // We're building a user-defined literal.
2498 IdentifierInfo *UDSuffix = &Context.Idents.get(Literal.getUDSuffix());
2499 SourceLocation UDSuffixLoc =
2500 getUDSuffixLoc(*this, Tok.getLocation(), Literal.getUDSuffixOffset());
2501
2502 // FIXME: Perform literal operator lookup now, and build a raw literal if
2503 // there is no usable operator.
2504
2505 QualType Ty;
2506 Expr *Lit;
2507 if (Literal.isFloatingLiteral()) {
2508 // C++11 [lex.ext]p4: If S contains a literal operator with parameter type
2509 // long double, the literal is treated as a call of the form
2510 // operator "" X (f L)
2511 Lit = BuildFloatingLiteral(*this, Literal, Context.LongDoubleTy,
2512 Tok.getLocation());
2513 } else {
2514 // C++11 [lex.ext]p3: If S contains a literal operator with parameter type
2515 // unsigned long long, the literal is treated as a call of the form
2516 // operator "" X (n ULL)
2517 llvm::APInt ResultVal(Context.getTargetInfo().getLongLongWidth(), 0);
2518 if (Literal.GetIntegerValue(ResultVal))
2519 Diag(Tok.getLocation(), diag::warn_integer_too_large);
2520
2521 QualType Ty = Context.UnsignedLongLongTy;
2522 Lit = IntegerLiteral::Create(Context, ResultVal, Ty, Tok.getLocation());
2523 }
2524
2525 return BuildLiteralOperatorCall(UDSuffix, UDSuffixLoc,
2526 llvm::makeArrayRef(&Lit, 1),
2527 Tok.getLocation());
2528 }
2529
Chris Lattner1c20a172007-08-26 03:42:43 +00002530 Expr *Res;
Sebastian Redlffbcf962009-01-18 18:53:16 +00002531
Chris Lattner1c20a172007-08-26 03:42:43 +00002532 if (Literal.isFloatingLiteral()) {
Chris Lattnerec0a6d92007-09-22 18:29:59 +00002533 QualType Ty;
Chris Lattner9a8d1d92008-06-30 18:32:54 +00002534 if (Literal.isFloat)
Chris Lattnerec0a6d92007-09-22 18:29:59 +00002535 Ty = Context.FloatTy;
Chris Lattner9a8d1d92008-06-30 18:32:54 +00002536 else if (!Literal.isLong)
Chris Lattnerec0a6d92007-09-22 18:29:59 +00002537 Ty = Context.DoubleTy;
Chris Lattner9a8d1d92008-06-30 18:32:54 +00002538 else
Chris Lattner7570e9c2008-03-08 08:52:55 +00002539 Ty = Context.LongDoubleTy;
Chris Lattner9a8d1d92008-06-30 18:32:54 +00002540
Richard Smith39570d002012-03-08 08:45:32 +00002541 Res = BuildFloatingLiteral(*this, Literal, Ty, Tok.getLocation());
Sebastian Redlffbcf962009-01-18 18:53:16 +00002542
Peter Collingbournec77f85b2011-03-11 19:24:59 +00002543 if (Ty == Context.DoubleTy) {
2544 if (getLangOptions().SinglePrecisionConstants) {
John Wiegley01296292011-04-08 18:41:53 +00002545 Res = ImpCastExprToType(Res, Context.FloatTy, CK_FloatingCast).take();
Peter Collingbournec77f85b2011-03-11 19:24:59 +00002546 } else if (getLangOptions().OpenCL && !getOpenCLOptions().cl_khr_fp64) {
2547 Diag(Tok.getLocation(), diag::warn_double_const_requires_fp64);
John Wiegley01296292011-04-08 18:41:53 +00002548 Res = ImpCastExprToType(Res, Context.FloatTy, CK_FloatingCast).take();
Peter Collingbournec77f85b2011-03-11 19:24:59 +00002549 }
2550 }
Chris Lattner1c20a172007-08-26 03:42:43 +00002551 } else if (!Literal.isIntegerLiteral()) {
Sebastian Redlffbcf962009-01-18 18:53:16 +00002552 return ExprError();
Chris Lattner1c20a172007-08-26 03:42:43 +00002553 } else {
Chris Lattner24d5bfe2008-04-02 04:24:33 +00002554 QualType Ty;
Chris Lattner67ca9252007-05-21 01:08:44 +00002555
Neil Boothac582c52007-08-29 22:00:19 +00002556 // long long is a C99 feature.
Richard Smith0bf8a4922011-10-18 20:49:44 +00002557 if (!getLangOptions().C99 && Literal.isLongLong)
2558 Diag(Tok.getLocation(),
2559 getLangOptions().CPlusPlus0x ?
2560 diag::warn_cxx98_compat_longlong : diag::ext_longlong);
Neil Boothac582c52007-08-29 22:00:19 +00002561
Chris Lattner67ca9252007-05-21 01:08:44 +00002562 // Get the value in the widest-possible width.
Douglas Gregore8bbc122011-09-02 00:18:52 +00002563 llvm::APInt ResultVal(Context.getTargetInfo().getIntMaxTWidth(), 0);
Sebastian Redlffbcf962009-01-18 18:53:16 +00002564
Chris Lattner67ca9252007-05-21 01:08:44 +00002565 if (Literal.GetIntegerValue(ResultVal)) {
2566 // If this value didn't fit into uintmax_t, warn and force to ull.
2567 Diag(Tok.getLocation(), diag::warn_integer_too_large);
Chris Lattner24d5bfe2008-04-02 04:24:33 +00002568 Ty = Context.UnsignedLongLongTy;
2569 assert(Context.getTypeSize(Ty) == ResultVal.getBitWidth() &&
Chris Lattner37e05872008-03-05 18:54:05 +00002570 "long long is not intmax_t?");
Steve Naroff09ef4742007-03-09 23:16:33 +00002571 } else {
Chris Lattner67ca9252007-05-21 01:08:44 +00002572 // If this value fits into a ULL, try to figure out what else it fits into
2573 // according to the rules of C99 6.4.4.1p5.
Sebastian Redlffbcf962009-01-18 18:53:16 +00002574
Chris Lattner67ca9252007-05-21 01:08:44 +00002575 // Octal, Hexadecimal, and integers with a U suffix are allowed to
2576 // be an unsigned int.
2577 bool AllowUnsigned = Literal.isUnsigned || Literal.getRadix() != 10;
2578
2579 // Check from smallest to largest, picking the smallest type we can.
Chris Lattner55258cf2008-05-09 05:59:00 +00002580 unsigned Width = 0;
Chris Lattner7b939cf2007-08-23 21:58:08 +00002581 if (!Literal.isLong && !Literal.isLongLong) {
2582 // Are int/unsigned possibilities?
Douglas Gregore8bbc122011-09-02 00:18:52 +00002583 unsigned IntSize = Context.getTargetInfo().getIntWidth();
Sebastian Redlffbcf962009-01-18 18:53:16 +00002584
Chris Lattner67ca9252007-05-21 01:08:44 +00002585 // Does it fit in a unsigned int?
2586 if (ResultVal.isIntN(IntSize)) {
2587 // Does it fit in a signed int?
2588 if (!Literal.isUnsigned && ResultVal[IntSize-1] == 0)
Chris Lattner24d5bfe2008-04-02 04:24:33 +00002589 Ty = Context.IntTy;
Chris Lattner67ca9252007-05-21 01:08:44 +00002590 else if (AllowUnsigned)
Chris Lattner24d5bfe2008-04-02 04:24:33 +00002591 Ty = Context.UnsignedIntTy;
Chris Lattner55258cf2008-05-09 05:59:00 +00002592 Width = IntSize;
Chris Lattner67ca9252007-05-21 01:08:44 +00002593 }
Chris Lattner67ca9252007-05-21 01:08:44 +00002594 }
Sebastian Redlffbcf962009-01-18 18:53:16 +00002595
Chris Lattner67ca9252007-05-21 01:08:44 +00002596 // Are long/unsigned long possibilities?
Chris Lattner24d5bfe2008-04-02 04:24:33 +00002597 if (Ty.isNull() && !Literal.isLongLong) {
Douglas Gregore8bbc122011-09-02 00:18:52 +00002598 unsigned LongSize = Context.getTargetInfo().getLongWidth();
Sebastian Redlffbcf962009-01-18 18:53:16 +00002599
Chris Lattner67ca9252007-05-21 01:08:44 +00002600 // Does it fit in a unsigned long?
2601 if (ResultVal.isIntN(LongSize)) {
2602 // Does it fit in a signed long?
2603 if (!Literal.isUnsigned && ResultVal[LongSize-1] == 0)
Chris Lattner24d5bfe2008-04-02 04:24:33 +00002604 Ty = Context.LongTy;
Chris Lattner67ca9252007-05-21 01:08:44 +00002605 else if (AllowUnsigned)
Chris Lattner24d5bfe2008-04-02 04:24:33 +00002606 Ty = Context.UnsignedLongTy;
Chris Lattner55258cf2008-05-09 05:59:00 +00002607 Width = LongSize;
Chris Lattner67ca9252007-05-21 01:08:44 +00002608 }
Sebastian Redlffbcf962009-01-18 18:53:16 +00002609 }
2610
Chris Lattner67ca9252007-05-21 01:08:44 +00002611 // Finally, check long long if needed.
Chris Lattner24d5bfe2008-04-02 04:24:33 +00002612 if (Ty.isNull()) {
Douglas Gregore8bbc122011-09-02 00:18:52 +00002613 unsigned LongLongSize = Context.getTargetInfo().getLongLongWidth();
Sebastian Redlffbcf962009-01-18 18:53:16 +00002614
Chris Lattner67ca9252007-05-21 01:08:44 +00002615 // Does it fit in a unsigned long long?
2616 if (ResultVal.isIntN(LongLongSize)) {
2617 // Does it fit in a signed long long?
Francois Pichetc3e73b32011-01-11 23:38:13 +00002618 // To be compatible with MSVC, hex integer literals ending with the
2619 // LL or i64 suffix are always signed in Microsoft mode.
Francois Pichetbf711d92011-01-11 12:23:00 +00002620 if (!Literal.isUnsigned && (ResultVal[LongLongSize-1] == 0 ||
Francois Pichet0706d202011-09-17 17:15:52 +00002621 (getLangOptions().MicrosoftExt && Literal.isLongLong)))
Chris Lattner24d5bfe2008-04-02 04:24:33 +00002622 Ty = Context.LongLongTy;
Chris Lattner67ca9252007-05-21 01:08:44 +00002623 else if (AllowUnsigned)
Chris Lattner24d5bfe2008-04-02 04:24:33 +00002624 Ty = Context.UnsignedLongLongTy;
Chris Lattner55258cf2008-05-09 05:59:00 +00002625 Width = LongLongSize;
Chris Lattner67ca9252007-05-21 01:08:44 +00002626 }
2627 }
Sebastian Redlffbcf962009-01-18 18:53:16 +00002628
Chris Lattner67ca9252007-05-21 01:08:44 +00002629 // If we still couldn't decide a type, we probably have something that
2630 // does not fit in a signed long long, but has no U suffix.
Chris Lattner24d5bfe2008-04-02 04:24:33 +00002631 if (Ty.isNull()) {
Chris Lattner67ca9252007-05-21 01:08:44 +00002632 Diag(Tok.getLocation(), diag::warn_integer_too_large_for_signed);
Chris Lattner24d5bfe2008-04-02 04:24:33 +00002633 Ty = Context.UnsignedLongLongTy;
Douglas Gregore8bbc122011-09-02 00:18:52 +00002634 Width = Context.getTargetInfo().getLongLongWidth();
Chris Lattner67ca9252007-05-21 01:08:44 +00002635 }
Sebastian Redlffbcf962009-01-18 18:53:16 +00002636
Chris Lattner55258cf2008-05-09 05:59:00 +00002637 if (ResultVal.getBitWidth() != Width)
Jay Foad6d4db0c2010-12-07 08:25:34 +00002638 ResultVal = ResultVal.trunc(Width);
Steve Naroff09ef4742007-03-09 23:16:33 +00002639 }
Argyrios Kyrtzidis43b20572010-08-28 09:06:06 +00002640 Res = IntegerLiteral::Create(Context, ResultVal, Ty, Tok.getLocation());
Steve Naroff09ef4742007-03-09 23:16:33 +00002641 }
Sebastian Redlffbcf962009-01-18 18:53:16 +00002642
Chris Lattner1c20a172007-08-26 03:42:43 +00002643 // If this is an imaginary literal, create the ImaginaryLiteral wrapper.
2644 if (Literal.isImaginary)
Mike Stump11289f42009-09-09 15:08:12 +00002645 Res = new (Context) ImaginaryLiteral(Res,
Steve Narofff6009ed2009-01-21 00:14:39 +00002646 Context.getComplexType(Res->getType()));
Sebastian Redlffbcf962009-01-18 18:53:16 +00002647
2648 return Owned(Res);
Chris Lattnere168f762006-11-10 05:29:30 +00002649}
2650
Richard Trieuba63ce62011-09-09 01:45:06 +00002651ExprResult Sema::ActOnParenExpr(SourceLocation L, SourceLocation R, Expr *E) {
Chris Lattner24d5bfe2008-04-02 04:24:33 +00002652 assert((E != 0) && "ActOnParenExpr() missing expr");
Steve Narofff6009ed2009-01-21 00:14:39 +00002653 return Owned(new (Context) ParenExpr(L, R, E));
Chris Lattnere168f762006-11-10 05:29:30 +00002654}
2655
Chandler Carruth62da79c2011-05-26 08:53:12 +00002656static bool CheckVecStepTraitOperandType(Sema &S, QualType T,
2657 SourceLocation Loc,
2658 SourceRange ArgRange) {
2659 // [OpenCL 1.1 6.11.12] "The vec_step built-in function takes a built-in
2660 // scalar or vector data type argument..."
2661 // Every built-in scalar type (OpenCL 1.1 6.1.1) is either an arithmetic
2662 // type (C99 6.2.5p18) or void.
2663 if (!(T->isArithmeticType() || T->isVoidType() || T->isVectorType())) {
2664 S.Diag(Loc, diag::err_vecstep_non_scalar_vector_type)
2665 << T << ArgRange;
2666 return true;
2667 }
2668
2669 assert((T->isVoidType() || !T->isIncompleteType()) &&
2670 "Scalar types should always be complete");
2671 return false;
2672}
2673
Chandler Carruthcea1aac2011-05-26 08:53:16 +00002674static bool CheckExtensionTraitOperandType(Sema &S, QualType T,
2675 SourceLocation Loc,
2676 SourceRange ArgRange,
2677 UnaryExprOrTypeTrait TraitKind) {
2678 // C99 6.5.3.4p1:
2679 if (T->isFunctionType()) {
2680 // alignof(function) is allowed as an extension.
2681 if (TraitKind == UETT_SizeOf)
2682 S.Diag(Loc, diag::ext_sizeof_function_type) << ArgRange;
2683 return false;
2684 }
2685
2686 // Allow sizeof(void)/alignof(void) as an extension.
2687 if (T->isVoidType()) {
2688 S.Diag(Loc, diag::ext_sizeof_void_type) << TraitKind << ArgRange;
2689 return false;
2690 }
2691
2692 return true;
2693}
2694
2695static bool CheckObjCTraitOperandConstraints(Sema &S, QualType T,
2696 SourceLocation Loc,
2697 SourceRange ArgRange,
2698 UnaryExprOrTypeTrait TraitKind) {
2699 // Reject sizeof(interface) and sizeof(interface<proto>) in 64-bit mode.
2700 if (S.LangOpts.ObjCNonFragileABI && T->isObjCObjectType()) {
2701 S.Diag(Loc, diag::err_sizeof_nonfragile_interface)
2702 << T << (TraitKind == UETT_SizeOf)
2703 << ArgRange;
2704 return true;
2705 }
2706
2707 return false;
2708}
2709
Chandler Carruth14502c22011-05-26 08:53:10 +00002710/// \brief Check the constrains on expression operands to unary type expression
2711/// and type traits.
2712///
Chandler Carruth7c430c02011-05-27 01:33:31 +00002713/// Completes any types necessary and validates the constraints on the operand
2714/// expression. The logic mostly mirrors the type-based overload, but may modify
2715/// the expression as it completes the type for that expression through template
2716/// instantiation, etc.
Richard Trieuba63ce62011-09-09 01:45:06 +00002717bool Sema::CheckUnaryExprOrTypeTraitOperand(Expr *E,
Chandler Carruth14502c22011-05-26 08:53:10 +00002718 UnaryExprOrTypeTrait ExprKind) {
Richard Trieuba63ce62011-09-09 01:45:06 +00002719 QualType ExprTy = E->getType();
Chandler Carruth7c430c02011-05-27 01:33:31 +00002720
2721 // C++ [expr.sizeof]p2: "When applied to a reference or a reference type,
2722 // the result is the size of the referenced type."
2723 // C++ [expr.alignof]p3: "When alignof is applied to a reference type, the
2724 // result shall be the alignment of the referenced type."
2725 if (const ReferenceType *Ref = ExprTy->getAs<ReferenceType>())
2726 ExprTy = Ref->getPointeeType();
2727
2728 if (ExprKind == UETT_VecStep)
Richard Trieuba63ce62011-09-09 01:45:06 +00002729 return CheckVecStepTraitOperandType(*this, ExprTy, E->getExprLoc(),
2730 E->getSourceRange());
Chandler Carruth7c430c02011-05-27 01:33:31 +00002731
2732 // Whitelist some types as extensions
Richard Trieuba63ce62011-09-09 01:45:06 +00002733 if (!CheckExtensionTraitOperandType(*this, ExprTy, E->getExprLoc(),
2734 E->getSourceRange(), ExprKind))
Chandler Carruth7c430c02011-05-27 01:33:31 +00002735 return false;
2736
Richard Trieuba63ce62011-09-09 01:45:06 +00002737 if (RequireCompleteExprType(E,
Chandler Carruth7c430c02011-05-27 01:33:31 +00002738 PDiag(diag::err_sizeof_alignof_incomplete_type)
Richard Trieuba63ce62011-09-09 01:45:06 +00002739 << ExprKind << E->getSourceRange(),
Chandler Carruth7c430c02011-05-27 01:33:31 +00002740 std::make_pair(SourceLocation(), PDiag(0))))
2741 return true;
2742
2743 // Completeing the expression's type may have changed it.
Richard Trieuba63ce62011-09-09 01:45:06 +00002744 ExprTy = E->getType();
Chandler Carruth7c430c02011-05-27 01:33:31 +00002745 if (const ReferenceType *Ref = ExprTy->getAs<ReferenceType>())
2746 ExprTy = Ref->getPointeeType();
2747
Richard Trieuba63ce62011-09-09 01:45:06 +00002748 if (CheckObjCTraitOperandConstraints(*this, ExprTy, E->getExprLoc(),
2749 E->getSourceRange(), ExprKind))
Chandler Carruth7c430c02011-05-27 01:33:31 +00002750 return true;
2751
Nico Weber0870deb2011-06-15 02:47:03 +00002752 if (ExprKind == UETT_SizeOf) {
Richard Trieuba63ce62011-09-09 01:45:06 +00002753 if (DeclRefExpr *DeclRef = dyn_cast<DeclRefExpr>(E->IgnoreParens())) {
Nico Weber0870deb2011-06-15 02:47:03 +00002754 if (ParmVarDecl *PVD = dyn_cast<ParmVarDecl>(DeclRef->getFoundDecl())) {
2755 QualType OType = PVD->getOriginalType();
2756 QualType Type = PVD->getType();
2757 if (Type->isPointerType() && OType->isArrayType()) {
Richard Trieuba63ce62011-09-09 01:45:06 +00002758 Diag(E->getExprLoc(), diag::warn_sizeof_array_param)
Nico Weber0870deb2011-06-15 02:47:03 +00002759 << Type << OType;
2760 Diag(PVD->getLocation(), diag::note_declared_at);
2761 }
2762 }
2763 }
2764 }
2765
Chandler Carruth7c430c02011-05-27 01:33:31 +00002766 return false;
Chandler Carruth14502c22011-05-26 08:53:10 +00002767}
2768
2769/// \brief Check the constraints on operands to unary expression and type
2770/// traits.
2771///
2772/// This will complete any types necessary, and validate the various constraints
2773/// on those operands.
2774///
Steve Naroff71b59a92007-06-04 22:22:31 +00002775/// The UsualUnaryConversions() function is *not* called by this routine.
Chandler Carruth14502c22011-05-26 08:53:10 +00002776/// C99 6.3.2.1p[2-4] all state:
2777/// Except when it is the operand of the sizeof operator ...
2778///
2779/// C++ [expr.sizeof]p4
2780/// The lvalue-to-rvalue, array-to-pointer, and function-to-pointer
2781/// standard conversions are not applied to the operand of sizeof.
2782///
2783/// This policy is followed for all of the unary trait expressions.
Richard Trieuba63ce62011-09-09 01:45:06 +00002784bool Sema::CheckUnaryExprOrTypeTraitOperand(QualType ExprType,
Peter Collingbournee190dee2011-03-11 19:24:49 +00002785 SourceLocation OpLoc,
2786 SourceRange ExprRange,
2787 UnaryExprOrTypeTrait ExprKind) {
Richard Trieuba63ce62011-09-09 01:45:06 +00002788 if (ExprType->isDependentType())
Sebastian Redl8d2ccae2009-02-26 14:39:58 +00002789 return false;
2790
Sebastian Redl22e2e5c2009-11-23 17:18:46 +00002791 // C++ [expr.sizeof]p2: "When applied to a reference or a reference type,
2792 // the result is the size of the referenced type."
2793 // C++ [expr.alignof]p3: "When alignof is applied to a reference type, the
2794 // result shall be the alignment of the referenced type."
Richard Trieuba63ce62011-09-09 01:45:06 +00002795 if (const ReferenceType *Ref = ExprType->getAs<ReferenceType>())
2796 ExprType = Ref->getPointeeType();
Sebastian Redl22e2e5c2009-11-23 17:18:46 +00002797
Chandler Carruth62da79c2011-05-26 08:53:12 +00002798 if (ExprKind == UETT_VecStep)
Richard Trieuba63ce62011-09-09 01:45:06 +00002799 return CheckVecStepTraitOperandType(*this, ExprType, OpLoc, ExprRange);
Peter Collingbournee190dee2011-03-11 19:24:49 +00002800
Chandler Carruthcea1aac2011-05-26 08:53:16 +00002801 // Whitelist some types as extensions
Richard Trieuba63ce62011-09-09 01:45:06 +00002802 if (!CheckExtensionTraitOperandType(*this, ExprType, OpLoc, ExprRange,
Chandler Carruthcea1aac2011-05-26 08:53:16 +00002803 ExprKind))
Chris Lattnerb1355b12009-01-24 19:46:37 +00002804 return false;
Mike Stump11289f42009-09-09 15:08:12 +00002805
Richard Trieuba63ce62011-09-09 01:45:06 +00002806 if (RequireCompleteType(OpLoc, ExprType,
Douglas Gregor906db8a2009-12-15 16:44:32 +00002807 PDiag(diag::err_sizeof_alignof_incomplete_type)
Peter Collingbournee190dee2011-03-11 19:24:49 +00002808 << ExprKind << ExprRange))
Chris Lattner62975a72009-04-24 00:30:45 +00002809 return true;
Mike Stump11289f42009-09-09 15:08:12 +00002810
Richard Trieuba63ce62011-09-09 01:45:06 +00002811 if (CheckObjCTraitOperandConstraints(*this, ExprType, OpLoc, ExprRange,
Chandler Carruthcea1aac2011-05-26 08:53:16 +00002812 ExprKind))
Chris Lattnercd2a8c52009-04-24 22:30:50 +00002813 return true;
Mike Stump11289f42009-09-09 15:08:12 +00002814
Chris Lattner62975a72009-04-24 00:30:45 +00002815 return false;
Steve Naroff043d45d2007-05-15 02:32:35 +00002816}
2817
Chandler Carruth14502c22011-05-26 08:53:10 +00002818static bool CheckAlignOfExpr(Sema &S, Expr *E) {
Chris Lattner8dff0172009-01-24 20:17:12 +00002819 E = E->IgnoreParens();
Sebastian Redl8d2ccae2009-02-26 14:39:58 +00002820
Mike Stump11289f42009-09-09 15:08:12 +00002821 // alignof decl is always ok.
Chris Lattner8dff0172009-01-24 20:17:12 +00002822 if (isa<DeclRefExpr>(E))
2823 return false;
Sebastian Redl8d2ccae2009-02-26 14:39:58 +00002824
2825 // Cannot know anything else if the expression is dependent.
2826 if (E->isTypeDependent())
2827 return false;
2828
Douglas Gregor71235ec2009-05-02 02:18:30 +00002829 if (E->getBitField()) {
Chandler Carruth14502c22011-05-26 08:53:10 +00002830 S.Diag(E->getExprLoc(), diag::err_sizeof_alignof_bitfield)
2831 << 1 << E->getSourceRange();
Douglas Gregor71235ec2009-05-02 02:18:30 +00002832 return true;
Chris Lattner8dff0172009-01-24 20:17:12 +00002833 }
Douglas Gregor71235ec2009-05-02 02:18:30 +00002834
2835 // Alignment of a field access is always okay, so long as it isn't a
2836 // bit-field.
2837 if (MemberExpr *ME = dyn_cast<MemberExpr>(E))
Mike Stump212005c2009-07-22 18:58:19 +00002838 if (isa<FieldDecl>(ME->getMemberDecl()))
Douglas Gregor71235ec2009-05-02 02:18:30 +00002839 return false;
2840
Chandler Carruth14502c22011-05-26 08:53:10 +00002841 return S.CheckUnaryExprOrTypeTraitOperand(E, UETT_AlignOf);
Peter Collingbournee190dee2011-03-11 19:24:49 +00002842}
2843
Chandler Carruth14502c22011-05-26 08:53:10 +00002844bool Sema::CheckVecStepExpr(Expr *E) {
Peter Collingbournee190dee2011-03-11 19:24:49 +00002845 E = E->IgnoreParens();
2846
2847 // Cannot know anything else if the expression is dependent.
2848 if (E->isTypeDependent())
2849 return false;
2850
Chandler Carruth14502c22011-05-26 08:53:10 +00002851 return CheckUnaryExprOrTypeTraitOperand(E, UETT_VecStep);
Chris Lattner8dff0172009-01-24 20:17:12 +00002852}
2853
Douglas Gregor0950e412009-03-13 21:01:28 +00002854/// \brief Build a sizeof or alignof expression given a type operand.
John McCalldadc5752010-08-24 06:29:42 +00002855ExprResult
Peter Collingbournee190dee2011-03-11 19:24:49 +00002856Sema::CreateUnaryExprOrTypeTraitExpr(TypeSourceInfo *TInfo,
2857 SourceLocation OpLoc,
2858 UnaryExprOrTypeTrait ExprKind,
2859 SourceRange R) {
John McCallbcd03502009-12-07 02:54:59 +00002860 if (!TInfo)
Douglas Gregor0950e412009-03-13 21:01:28 +00002861 return ExprError();
2862
John McCallbcd03502009-12-07 02:54:59 +00002863 QualType T = TInfo->getType();
John McCall4c98fd82009-11-04 07:28:41 +00002864
Douglas Gregor0950e412009-03-13 21:01:28 +00002865 if (!T->isDependentType() &&
Peter Collingbournee190dee2011-03-11 19:24:49 +00002866 CheckUnaryExprOrTypeTraitOperand(T, OpLoc, R, ExprKind))
Douglas Gregor0950e412009-03-13 21:01:28 +00002867 return ExprError();
2868
2869 // C99 6.5.3.4p4: the type (an unsigned integer type) is size_t.
Peter Collingbournee190dee2011-03-11 19:24:49 +00002870 return Owned(new (Context) UnaryExprOrTypeTraitExpr(ExprKind, TInfo,
2871 Context.getSizeType(),
2872 OpLoc, R.getEnd()));
Douglas Gregor0950e412009-03-13 21:01:28 +00002873}
2874
2875/// \brief Build a sizeof or alignof expression given an expression
2876/// operand.
John McCalldadc5752010-08-24 06:29:42 +00002877ExprResult
Chandler Carrutha923fb22011-05-29 07:32:14 +00002878Sema::CreateUnaryExprOrTypeTraitExpr(Expr *E, SourceLocation OpLoc,
2879 UnaryExprOrTypeTrait ExprKind) {
Douglas Gregor835af982011-06-22 23:21:00 +00002880 ExprResult PE = CheckPlaceholderExpr(E);
2881 if (PE.isInvalid())
2882 return ExprError();
2883
2884 E = PE.get();
2885
Douglas Gregor0950e412009-03-13 21:01:28 +00002886 // Verify that the operand is valid.
2887 bool isInvalid = false;
2888 if (E->isTypeDependent()) {
2889 // Delay type-checking for type-dependent expressions.
Peter Collingbournee190dee2011-03-11 19:24:49 +00002890 } else if (ExprKind == UETT_AlignOf) {
Chandler Carruth14502c22011-05-26 08:53:10 +00002891 isInvalid = CheckAlignOfExpr(*this, E);
Peter Collingbournee190dee2011-03-11 19:24:49 +00002892 } else if (ExprKind == UETT_VecStep) {
Chandler Carruth14502c22011-05-26 08:53:10 +00002893 isInvalid = CheckVecStepExpr(E);
Douglas Gregor71235ec2009-05-02 02:18:30 +00002894 } else if (E->getBitField()) { // C99 6.5.3.4p1.
Chandler Carruth14502c22011-05-26 08:53:10 +00002895 Diag(E->getExprLoc(), diag::err_sizeof_alignof_bitfield) << 0;
Douglas Gregor0950e412009-03-13 21:01:28 +00002896 isInvalid = true;
2897 } else {
Chandler Carruth14502c22011-05-26 08:53:10 +00002898 isInvalid = CheckUnaryExprOrTypeTraitOperand(E, UETT_SizeOf);
Douglas Gregor0950e412009-03-13 21:01:28 +00002899 }
2900
2901 if (isInvalid)
2902 return ExprError();
2903
Eli Friedmane0afc982012-01-21 01:01:51 +00002904 if (ExprKind == UETT_SizeOf && E->getType()->isVariableArrayType()) {
2905 PE = TranformToPotentiallyEvaluated(E);
2906 if (PE.isInvalid()) return ExprError();
2907 E = PE.take();
2908 }
2909
Douglas Gregor0950e412009-03-13 21:01:28 +00002910 // C99 6.5.3.4p4: the type (an unsigned integer type) is size_t.
Chandler Carruth14502c22011-05-26 08:53:10 +00002911 return Owned(new (Context) UnaryExprOrTypeTraitExpr(
Chandler Carrutha923fb22011-05-29 07:32:14 +00002912 ExprKind, E, Context.getSizeType(), OpLoc,
Chandler Carruth14502c22011-05-26 08:53:10 +00002913 E->getSourceRange().getEnd()));
Douglas Gregor0950e412009-03-13 21:01:28 +00002914}
2915
Peter Collingbournee190dee2011-03-11 19:24:49 +00002916/// ActOnUnaryExprOrTypeTraitExpr - Handle @c sizeof(type) and @c sizeof @c
2917/// expr and the same for @c alignof and @c __alignof
Sebastian Redl6f282892008-11-11 17:56:53 +00002918/// Note that the ArgRange is invalid if isType is false.
John McCalldadc5752010-08-24 06:29:42 +00002919ExprResult
Peter Collingbournee190dee2011-03-11 19:24:49 +00002920Sema::ActOnUnaryExprOrTypeTraitExpr(SourceLocation OpLoc,
Richard Trieuba63ce62011-09-09 01:45:06 +00002921 UnaryExprOrTypeTrait ExprKind, bool IsType,
Peter Collingbournee190dee2011-03-11 19:24:49 +00002922 void *TyOrEx, const SourceRange &ArgRange) {
Chris Lattner0d8b1a12006-11-20 04:34:45 +00002923 // If error parsing type, ignore.
Sebastian Redlc215cfc2009-01-19 00:08:26 +00002924 if (TyOrEx == 0) return ExprError();
Steve Naroff043d45d2007-05-15 02:32:35 +00002925
Richard Trieuba63ce62011-09-09 01:45:06 +00002926 if (IsType) {
John McCallbcd03502009-12-07 02:54:59 +00002927 TypeSourceInfo *TInfo;
John McCallba7bf592010-08-24 05:47:05 +00002928 (void) GetTypeFromParser(ParsedType::getFromOpaquePtr(TyOrEx), &TInfo);
Peter Collingbournee190dee2011-03-11 19:24:49 +00002929 return CreateUnaryExprOrTypeTraitExpr(TInfo, OpLoc, ExprKind, ArgRange);
Mike Stump11289f42009-09-09 15:08:12 +00002930 }
Sebastian Redl6f282892008-11-11 17:56:53 +00002931
Douglas Gregor0950e412009-03-13 21:01:28 +00002932 Expr *ArgEx = (Expr *)TyOrEx;
Chandler Carrutha923fb22011-05-29 07:32:14 +00002933 ExprResult Result = CreateUnaryExprOrTypeTraitExpr(ArgEx, OpLoc, ExprKind);
Douglas Gregor0950e412009-03-13 21:01:28 +00002934 return move(Result);
Chris Lattnere168f762006-11-10 05:29:30 +00002935}
2936
John Wiegley01296292011-04-08 18:41:53 +00002937static QualType CheckRealImagOperand(Sema &S, ExprResult &V, SourceLocation Loc,
Richard Trieuba63ce62011-09-09 01:45:06 +00002938 bool IsReal) {
John Wiegley01296292011-04-08 18:41:53 +00002939 if (V.get()->isTypeDependent())
John McCall4bc41ae2010-11-18 19:01:18 +00002940 return S.Context.DependentTy;
Mike Stump11289f42009-09-09 15:08:12 +00002941
John McCall34376a62010-12-04 03:47:34 +00002942 // _Real and _Imag are only l-values for normal l-values.
John Wiegley01296292011-04-08 18:41:53 +00002943 if (V.get()->getObjectKind() != OK_Ordinary) {
2944 V = S.DefaultLvalueConversion(V.take());
2945 if (V.isInvalid())
2946 return QualType();
2947 }
John McCall34376a62010-12-04 03:47:34 +00002948
Chris Lattnere267f5d2007-08-26 05:39:26 +00002949 // These operators return the element type of a complex type.
John Wiegley01296292011-04-08 18:41:53 +00002950 if (const ComplexType *CT = V.get()->getType()->getAs<ComplexType>())
Chris Lattner30b5dd02007-08-24 21:16:53 +00002951 return CT->getElementType();
Mike Stump11289f42009-09-09 15:08:12 +00002952
Chris Lattnere267f5d2007-08-26 05:39:26 +00002953 // Otherwise they pass through real integer and floating point types here.
John Wiegley01296292011-04-08 18:41:53 +00002954 if (V.get()->getType()->isArithmeticType())
2955 return V.get()->getType();
Mike Stump11289f42009-09-09 15:08:12 +00002956
John McCall36226622010-10-12 02:09:17 +00002957 // Test for placeholders.
John McCall3aef3d82011-04-10 19:13:55 +00002958 ExprResult PR = S.CheckPlaceholderExpr(V.get());
John McCall36226622010-10-12 02:09:17 +00002959 if (PR.isInvalid()) return QualType();
John Wiegley01296292011-04-08 18:41:53 +00002960 if (PR.get() != V.get()) {
2961 V = move(PR);
Richard Trieuba63ce62011-09-09 01:45:06 +00002962 return CheckRealImagOperand(S, V, Loc, IsReal);
John McCall36226622010-10-12 02:09:17 +00002963 }
2964
Chris Lattnere267f5d2007-08-26 05:39:26 +00002965 // Reject anything else.
John Wiegley01296292011-04-08 18:41:53 +00002966 S.Diag(Loc, diag::err_realimag_invalid_type) << V.get()->getType()
Richard Trieuba63ce62011-09-09 01:45:06 +00002967 << (IsReal ? "__real" : "__imag");
Chris Lattnere267f5d2007-08-26 05:39:26 +00002968 return QualType();
Chris Lattner30b5dd02007-08-24 21:16:53 +00002969}
2970
2971
Chris Lattnere168f762006-11-10 05:29:30 +00002972
John McCalldadc5752010-08-24 06:29:42 +00002973ExprResult
Sebastian Redlc215cfc2009-01-19 00:08:26 +00002974Sema::ActOnPostfixUnaryOp(Scope *S, SourceLocation OpLoc,
John McCallb268a282010-08-23 23:25:46 +00002975 tok::TokenKind Kind, Expr *Input) {
John McCalle3027922010-08-25 11:45:40 +00002976 UnaryOperatorKind Opc;
Chris Lattnere168f762006-11-10 05:29:30 +00002977 switch (Kind) {
David Blaikie83d382b2011-09-23 05:06:16 +00002978 default: llvm_unreachable("Unknown unary op!");
John McCalle3027922010-08-25 11:45:40 +00002979 case tok::plusplus: Opc = UO_PostInc; break;
2980 case tok::minusminus: Opc = UO_PostDec; break;
Chris Lattnere168f762006-11-10 05:29:30 +00002981 }
Sebastian Redlc215cfc2009-01-19 00:08:26 +00002982
Sebastian Redla9351792012-02-11 23:51:47 +00002983 // Since this might is a postfix expression, get rid of ParenListExprs.
2984 ExprResult Result = MaybeConvertParenListExprToParenExpr(S, Input);
2985 if (Result.isInvalid()) return ExprError();
2986 Input = Result.take();
2987
John McCallb268a282010-08-23 23:25:46 +00002988 return BuildUnaryOp(S, OpLoc, Opc, Input);
Chris Lattnere168f762006-11-10 05:29:30 +00002989}
2990
John McCalldadc5752010-08-24 06:29:42 +00002991ExprResult
John McCallb268a282010-08-23 23:25:46 +00002992Sema::ActOnArraySubscriptExpr(Scope *S, Expr *Base, SourceLocation LLoc,
2993 Expr *Idx, SourceLocation RLoc) {
Nate Begeman5ec4b312009-08-10 23:49:36 +00002994 // Since this might be a postfix expression, get rid of ParenListExprs.
John McCalldadc5752010-08-24 06:29:42 +00002995 ExprResult Result = MaybeConvertParenListExprToParenExpr(S, Base);
John McCallb268a282010-08-23 23:25:46 +00002996 if (Result.isInvalid()) return ExprError();
2997 Base = Result.take();
Nate Begeman5ec4b312009-08-10 23:49:36 +00002998
John McCallb268a282010-08-23 23:25:46 +00002999 Expr *LHSExp = Base, *RHSExp = Idx;
Mike Stump11289f42009-09-09 15:08:12 +00003000
Douglas Gregor40412ac2008-11-19 17:17:41 +00003001 if (getLangOptions().CPlusPlus &&
Douglas Gregor7a77a6b2009-05-19 00:01:19 +00003002 (LHSExp->isTypeDependent() || RHSExp->isTypeDependent())) {
Douglas Gregor7a77a6b2009-05-19 00:01:19 +00003003 return Owned(new (Context) ArraySubscriptExpr(LHSExp, RHSExp,
John McCall7decc9e2010-11-18 06:31:45 +00003004 Context.DependentTy,
3005 VK_LValue, OK_Ordinary,
3006 RLoc));
Douglas Gregor7a77a6b2009-05-19 00:01:19 +00003007 }
3008
Mike Stump11289f42009-09-09 15:08:12 +00003009 if (getLangOptions().CPlusPlus &&
Sebastian Redlc215cfc2009-01-19 00:08:26 +00003010 (LHSExp->getType()->isRecordType() ||
Eli Friedman254a1a22008-12-15 22:34:21 +00003011 LHSExp->getType()->isEnumeralType() ||
3012 RHSExp->getType()->isRecordType() ||
Ted Kremeneke65b0862012-03-06 20:05:56 +00003013 RHSExp->getType()->isEnumeralType()) &&
3014 !LHSExp->getType()->isObjCObjectPointerType()) {
John McCallb268a282010-08-23 23:25:46 +00003015 return CreateOverloadedArraySubscriptExpr(LLoc, RLoc, Base, Idx);
Douglas Gregor40412ac2008-11-19 17:17:41 +00003016 }
3017
John McCallb268a282010-08-23 23:25:46 +00003018 return CreateBuiltinArraySubscriptExpr(Base, LLoc, Idx, RLoc);
Sebastian Redladba46e2009-10-29 20:17:01 +00003019}
3020
3021
John McCalldadc5752010-08-24 06:29:42 +00003022ExprResult
John McCallb268a282010-08-23 23:25:46 +00003023Sema::CreateBuiltinArraySubscriptExpr(Expr *Base, SourceLocation LLoc,
Richard Trieuba63ce62011-09-09 01:45:06 +00003024 Expr *Idx, SourceLocation RLoc) {
John McCallb268a282010-08-23 23:25:46 +00003025 Expr *LHSExp = Base;
3026 Expr *RHSExp = Idx;
Sebastian Redladba46e2009-10-29 20:17:01 +00003027
Chris Lattner36d572b2007-07-16 00:14:47 +00003028 // Perform default conversions.
John Wiegley01296292011-04-08 18:41:53 +00003029 if (!LHSExp->getType()->getAs<VectorType>()) {
3030 ExprResult Result = DefaultFunctionArrayLvalueConversion(LHSExp);
3031 if (Result.isInvalid())
3032 return ExprError();
3033 LHSExp = Result.take();
3034 }
3035 ExprResult Result = DefaultFunctionArrayLvalueConversion(RHSExp);
3036 if (Result.isInvalid())
3037 return ExprError();
3038 RHSExp = Result.take();
Sebastian Redlc215cfc2009-01-19 00:08:26 +00003039
Chris Lattner36d572b2007-07-16 00:14:47 +00003040 QualType LHSTy = LHSExp->getType(), RHSTy = RHSExp->getType();
John McCall7decc9e2010-11-18 06:31:45 +00003041 ExprValueKind VK = VK_LValue;
3042 ExprObjectKind OK = OK_Ordinary;
Steve Narofff1e53692007-03-23 22:27:02 +00003043
Steve Naroffc1aadb12007-03-28 21:49:40 +00003044 // C99 6.5.2.1p2: the expression e1[e2] is by definition precisely equivalent
Chris Lattnerf17bd422007-08-30 17:45:32 +00003045 // to the expression *((e1)+(e2)). This means the array "Base" may actually be
Mike Stump4e1f26a2009-02-19 03:04:26 +00003046 // in the subscript position. As a result, we need to derive the array base
Steve Narofff1e53692007-03-23 22:27:02 +00003047 // and index from the expression types.
Chris Lattner36d572b2007-07-16 00:14:47 +00003048 Expr *BaseExpr, *IndexExpr;
3049 QualType ResultType;
Sebastian Redl8d2ccae2009-02-26 14:39:58 +00003050 if (LHSTy->isDependentType() || RHSTy->isDependentType()) {
3051 BaseExpr = LHSExp;
3052 IndexExpr = RHSExp;
3053 ResultType = Context.DependentTy;
Ted Kremenekc23c7e62009-07-29 21:53:49 +00003054 } else if (const PointerType *PTy = LHSTy->getAs<PointerType>()) {
Chris Lattner36d572b2007-07-16 00:14:47 +00003055 BaseExpr = LHSExp;
3056 IndexExpr = RHSExp;
Chris Lattner36d572b2007-07-16 00:14:47 +00003057 ResultType = PTy->getPointeeType();
Ted Kremenekc23c7e62009-07-29 21:53:49 +00003058 } else if (const PointerType *PTy = RHSTy->getAs<PointerType>()) {
Chris Lattneraee0cfd2007-07-16 00:23:25 +00003059 // Handle the uncommon case of "123[Ptr]".
Chris Lattner36d572b2007-07-16 00:14:47 +00003060 BaseExpr = RHSExp;
3061 IndexExpr = LHSExp;
Chris Lattner36d572b2007-07-16 00:14:47 +00003062 ResultType = PTy->getPointeeType();
Mike Stump11289f42009-09-09 15:08:12 +00003063 } else if (const ObjCObjectPointerType *PTy =
John McCall9dd450b2009-09-21 23:43:11 +00003064 LHSTy->getAs<ObjCObjectPointerType>()) {
Steve Naroff7cae42b2009-07-10 23:34:53 +00003065 BaseExpr = LHSExp;
3066 IndexExpr = RHSExp;
Ted Kremeneke65b0862012-03-06 20:05:56 +00003067 Result = BuildObjCSubscriptExpression(RLoc, BaseExpr, IndexExpr, 0, 0);
3068 if (!Result.isInvalid())
3069 return Owned(Result.take());
Steve Naroff7cae42b2009-07-10 23:34:53 +00003070 ResultType = PTy->getPointeeType();
Mike Stump11289f42009-09-09 15:08:12 +00003071 } else if (const ObjCObjectPointerType *PTy =
John McCall9dd450b2009-09-21 23:43:11 +00003072 RHSTy->getAs<ObjCObjectPointerType>()) {
Steve Naroff7cae42b2009-07-10 23:34:53 +00003073 // Handle the uncommon case of "123[Ptr]".
3074 BaseExpr = RHSExp;
3075 IndexExpr = LHSExp;
3076 ResultType = PTy->getPointeeType();
John McCall9dd450b2009-09-21 23:43:11 +00003077 } else if (const VectorType *VTy = LHSTy->getAs<VectorType>()) {
Chris Lattner41977962007-07-31 19:29:30 +00003078 BaseExpr = LHSExp; // vectors: V[123]
Chris Lattner36d572b2007-07-16 00:14:47 +00003079 IndexExpr = RHSExp;
John McCall7decc9e2010-11-18 06:31:45 +00003080 VK = LHSExp->getValueKind();
3081 if (VK != VK_RValue)
3082 OK = OK_VectorComponent;
Nate Begemanc1bf0612009-01-18 00:45:31 +00003083
Chris Lattner36d572b2007-07-16 00:14:47 +00003084 // FIXME: need to deal with const...
3085 ResultType = VTy->getElementType();
Eli Friedmanab2784f2009-04-25 23:46:54 +00003086 } else if (LHSTy->isArrayType()) {
3087 // If we see an array that wasn't promoted by
Douglas Gregorb92a1562010-02-03 00:27:59 +00003088 // DefaultFunctionArrayLvalueConversion, it must be an array that
Eli Friedmanab2784f2009-04-25 23:46:54 +00003089 // wasn't promoted because of the C90 rule that doesn't
3090 // allow promoting non-lvalue arrays. Warn, then
3091 // force the promotion here.
3092 Diag(LHSExp->getLocStart(), diag::ext_subscript_non_lvalue) <<
3093 LHSExp->getSourceRange();
John Wiegley01296292011-04-08 18:41:53 +00003094 LHSExp = ImpCastExprToType(LHSExp, Context.getArrayDecayedType(LHSTy),
3095 CK_ArrayToPointerDecay).take();
Eli Friedmanab2784f2009-04-25 23:46:54 +00003096 LHSTy = LHSExp->getType();
3097
3098 BaseExpr = LHSExp;
3099 IndexExpr = RHSExp;
Ted Kremenekc23c7e62009-07-29 21:53:49 +00003100 ResultType = LHSTy->getAs<PointerType>()->getPointeeType();
Eli Friedmanab2784f2009-04-25 23:46:54 +00003101 } else if (RHSTy->isArrayType()) {
3102 // Same as previous, except for 123[f().a] case
3103 Diag(RHSExp->getLocStart(), diag::ext_subscript_non_lvalue) <<
3104 RHSExp->getSourceRange();
John Wiegley01296292011-04-08 18:41:53 +00003105 RHSExp = ImpCastExprToType(RHSExp, Context.getArrayDecayedType(RHSTy),
3106 CK_ArrayToPointerDecay).take();
Eli Friedmanab2784f2009-04-25 23:46:54 +00003107 RHSTy = RHSExp->getType();
3108
3109 BaseExpr = RHSExp;
3110 IndexExpr = LHSExp;
Ted Kremenekc23c7e62009-07-29 21:53:49 +00003111 ResultType = RHSTy->getAs<PointerType>()->getPointeeType();
Steve Naroffb3096442007-06-09 03:47:53 +00003112 } else {
Chris Lattner003af242009-04-25 22:50:55 +00003113 return ExprError(Diag(LLoc, diag::err_typecheck_subscript_value)
3114 << LHSExp->getSourceRange() << RHSExp->getSourceRange());
Sebastian Redlc215cfc2009-01-19 00:08:26 +00003115 }
Steve Naroffc1aadb12007-03-28 21:49:40 +00003116 // C99 6.5.2.1p1
Douglas Gregor5cc2c8b2010-07-23 15:58:24 +00003117 if (!IndexExpr->getType()->isIntegerType() && !IndexExpr->isTypeDependent())
Chris Lattner003af242009-04-25 22:50:55 +00003118 return ExprError(Diag(LLoc, diag::err_typecheck_subscript_not_integer)
3119 << IndexExpr->getSourceRange());
Steve Naroffb29cdd52007-07-10 18:23:31 +00003120
Daniel Dunbar4782a6e2009-09-17 06:31:17 +00003121 if ((IndexExpr->getType()->isSpecificBuiltinType(BuiltinType::Char_S) ||
Sam Weinigb7608d72009-09-14 20:14:57 +00003122 IndexExpr->getType()->isSpecificBuiltinType(BuiltinType::Char_U))
3123 && !IndexExpr->isTypeDependent())
Sam Weinig914244e2009-09-14 01:58:58 +00003124 Diag(LLoc, diag::warn_subscript_is_char) << IndexExpr->getSourceRange();
3125
Douglas Gregorac1fb652009-03-24 19:52:54 +00003126 // C99 6.5.2.1p1: "shall have type "pointer to *object* type". Similarly,
Mike Stump11289f42009-09-09 15:08:12 +00003127 // C++ [expr.sub]p1: The type "T" shall be a completely-defined object
3128 // type. Note that Functions are not objects, and that (in C99 parlance)
Douglas Gregorac1fb652009-03-24 19:52:54 +00003129 // incomplete types are not object types.
3130 if (ResultType->isFunctionType()) {
3131 Diag(BaseExpr->getLocStart(), diag::err_subscript_function_type)
3132 << ResultType << BaseExpr->getSourceRange();
3133 return ExprError();
3134 }
Mike Stump11289f42009-09-09 15:08:12 +00003135
Abramo Bagnara3aabb4b2010-09-13 06:50:07 +00003136 if (ResultType->isVoidType() && !getLangOptions().CPlusPlus) {
3137 // GNU extension: subscripting on pointer to void
Chandler Carruth4cc3f292011-06-27 16:32:27 +00003138 Diag(LLoc, diag::ext_gnu_subscript_void_type)
3139 << BaseExpr->getSourceRange();
John McCall4bc41ae2010-11-18 19:01:18 +00003140
3141 // C forbids expressions of unqualified void type from being l-values.
3142 // See IsCForbiddenLValueType.
3143 if (!ResultType.hasQualifiers()) VK = VK_RValue;
Abramo Bagnara3aabb4b2010-09-13 06:50:07 +00003144 } else if (!ResultType->isDependentType() &&
Mike Stump11289f42009-09-09 15:08:12 +00003145 RequireCompleteType(LLoc, ResultType,
Anders Carlssond624e162009-08-26 23:45:07 +00003146 PDiag(diag::err_subscript_incomplete_type)
3147 << BaseExpr->getSourceRange()))
Douglas Gregorac1fb652009-03-24 19:52:54 +00003148 return ExprError();
Mike Stump11289f42009-09-09 15:08:12 +00003149
Chris Lattner62975a72009-04-24 00:30:45 +00003150 // Diagnose bad cases where we step over interface counts.
John McCall8b07ec22010-05-15 11:32:37 +00003151 if (ResultType->isObjCObjectType() && LangOpts.ObjCNonFragileABI) {
Chris Lattner62975a72009-04-24 00:30:45 +00003152 Diag(LLoc, diag::err_subscript_nonfragile_interface)
3153 << ResultType << BaseExpr->getSourceRange();
3154 return ExprError();
3155 }
Mike Stump11289f42009-09-09 15:08:12 +00003156
John McCall4bc41ae2010-11-18 19:01:18 +00003157 assert(VK == VK_RValue || LangOpts.CPlusPlus ||
Douglas Gregor5476205b2011-06-23 00:49:38 +00003158 !ResultType.isCForbiddenLValueType());
John McCall4bc41ae2010-11-18 19:01:18 +00003159
Mike Stump4e1f26a2009-02-19 03:04:26 +00003160 return Owned(new (Context) ArraySubscriptExpr(LHSExp, RHSExp,
John McCall7decc9e2010-11-18 06:31:45 +00003161 ResultType, VK, OK, RLoc));
Chris Lattnere168f762006-11-10 05:29:30 +00003162}
3163
John McCalldadc5752010-08-24 06:29:42 +00003164ExprResult Sema::BuildCXXDefaultArgExpr(SourceLocation CallLoc,
Nico Weber44887f62010-11-29 18:19:25 +00003165 FunctionDecl *FD,
3166 ParmVarDecl *Param) {
Anders Carlsson355933d2009-08-25 03:49:14 +00003167 if (Param->hasUnparsedDefaultArg()) {
Douglas Gregor8a01b2a2010-09-11 20:24:53 +00003168 Diag(CallLoc,
Nico Weberebd45a02010-11-30 04:44:33 +00003169 diag::err_use_of_default_argument_to_function_declared_later) <<
Anders Carlsson355933d2009-08-25 03:49:14 +00003170 FD << cast<CXXRecordDecl>(FD->getDeclContext())->getDeclName();
Mike Stump11289f42009-09-09 15:08:12 +00003171 Diag(UnparsedDefaultArgLocs[Param],
Nico Weberebd45a02010-11-30 04:44:33 +00003172 diag::note_default_argument_declared_here);
Douglas Gregor8a01b2a2010-09-11 20:24:53 +00003173 return ExprError();
3174 }
3175
3176 if (Param->hasUninstantiatedDefaultArg()) {
3177 Expr *UninstExpr = Param->getUninstantiatedDefaultArg();
Anders Carlsson355933d2009-08-25 03:49:14 +00003178
Douglas Gregor8a01b2a2010-09-11 20:24:53 +00003179 // Instantiate the expression.
3180 MultiLevelTemplateArgumentList ArgList
3181 = getTemplateInstantiationArgs(FD, 0, /*RelativeToPrimary=*/true);
Anders Carlsson657bad42009-09-05 05:14:19 +00003182
Nico Weber44887f62010-11-29 18:19:25 +00003183 std::pair<const TemplateArgument *, unsigned> Innermost
Douglas Gregor8a01b2a2010-09-11 20:24:53 +00003184 = ArgList.getInnermost();
3185 InstantiatingTemplate Inst(*this, CallLoc, Param, Innermost.first,
3186 Innermost.second);
Anders Carlsson355933d2009-08-25 03:49:14 +00003187
Nico Weber44887f62010-11-29 18:19:25 +00003188 ExprResult Result;
3189 {
3190 // C++ [dcl.fct.default]p5:
3191 // The names in the [default argument] expression are bound, and
3192 // the semantic constraints are checked, at the point where the
3193 // default argument expression appears.
Nico Weberebd45a02010-11-30 04:44:33 +00003194 ContextRAII SavedContext(*this, FD);
Douglas Gregora86bc002012-02-16 21:36:18 +00003195 LocalInstantiationScope Local(*this);
Nico Weber44887f62010-11-29 18:19:25 +00003196 Result = SubstExpr(UninstExpr, ArgList);
3197 }
Douglas Gregor8a01b2a2010-09-11 20:24:53 +00003198 if (Result.isInvalid())
3199 return ExprError();
Mike Stump11289f42009-09-09 15:08:12 +00003200
Douglas Gregor8a01b2a2010-09-11 20:24:53 +00003201 // Check the expression as an initializer for the parameter.
3202 InitializedEntity Entity
Fariborz Jahanian8fb87ae2010-09-24 17:30:16 +00003203 = InitializedEntity::InitializeParameter(Context, Param);
Douglas Gregor8a01b2a2010-09-11 20:24:53 +00003204 InitializationKind Kind
3205 = InitializationKind::CreateCopy(Param->getLocation(),
3206 /*FIXME:EqualLoc*/UninstExpr->getSourceRange().getBegin());
3207 Expr *ResultE = Result.takeAs<Expr>();
Douglas Gregor25ab25f2009-12-23 18:19:08 +00003208
Douglas Gregor8a01b2a2010-09-11 20:24:53 +00003209 InitializationSequence InitSeq(*this, Entity, Kind, &ResultE, 1);
3210 Result = InitSeq.Perform(*this, Entity, Kind,
3211 MultiExprArg(*this, &ResultE, 1));
3212 if (Result.isInvalid())
3213 return ExprError();
Kovarththanan Rajaratnamba2c6522010-03-13 10:17:05 +00003214
Douglas Gregor8a01b2a2010-09-11 20:24:53 +00003215 // Build the default argument expression.
3216 return Owned(CXXDefaultArgExpr::Create(Context, CallLoc, Param,
3217 Result.takeAs<Expr>()));
Anders Carlsson355933d2009-08-25 03:49:14 +00003218 }
3219
Douglas Gregor8a01b2a2010-09-11 20:24:53 +00003220 // If the default expression creates temporaries, we need to
3221 // push them to the current stack of expression temporaries so they'll
3222 // be properly destroyed.
3223 // FIXME: We should really be rebuilding the default argument with new
3224 // bound temporaries; see the comment in PR5810.
John McCall28fc7092011-11-10 05:35:25 +00003225 // We don't need to do that with block decls, though, because
3226 // blocks in default argument expression can never capture anything.
3227 if (isa<ExprWithCleanups>(Param->getInit())) {
3228 // Set the "needs cleanups" bit regardless of whether there are
3229 // any explicit objects.
John McCall31168b02011-06-15 23:02:42 +00003230 ExprNeedsCleanups = true;
John McCall28fc7092011-11-10 05:35:25 +00003231
3232 // Append all the objects to the cleanup list. Right now, this
3233 // should always be a no-op, because blocks in default argument
3234 // expressions should never be able to capture anything.
3235 assert(!cast<ExprWithCleanups>(Param->getInit())->getNumObjects() &&
3236 "default argument expression has capturing blocks?");
Douglas Gregor6ed2fee2010-09-14 22:55:20 +00003237 }
Douglas Gregor8a01b2a2010-09-11 20:24:53 +00003238
3239 // We already type-checked the argument, so we know it works.
Douglas Gregor32b3de52010-09-11 23:32:50 +00003240 // Just mark all of the declarations in this potentially-evaluated expression
3241 // as being "referenced".
Douglas Gregor680e9e02012-02-21 19:11:17 +00003242 MarkDeclarationsReferencedInExpr(Param->getDefaultArg(),
3243 /*SkipLocalVariables=*/true);
Douglas Gregor033f6752009-12-23 23:03:06 +00003244 return Owned(CXXDefaultArgExpr::Create(Context, CallLoc, Param));
Anders Carlsson355933d2009-08-25 03:49:14 +00003245}
3246
Douglas Gregor97fd6e22008-12-22 05:46:06 +00003247/// ConvertArgumentsForCall - Converts the arguments specified in
3248/// Args/NumArgs to the parameter types of the function FDecl with
3249/// function prototype Proto. Call is the call expression itself, and
3250/// Fn is the function expression. For a C++ member function, this
3251/// routine does not attempt to convert the object argument. Returns
3252/// true if the call is ill-formed.
Mike Stump4e1f26a2009-02-19 03:04:26 +00003253bool
3254Sema::ConvertArgumentsForCall(CallExpr *Call, Expr *Fn,
Douglas Gregor97fd6e22008-12-22 05:46:06 +00003255 FunctionDecl *FDecl,
Douglas Gregordeaad8c2009-02-26 23:50:07 +00003256 const FunctionProtoType *Proto,
Douglas Gregor97fd6e22008-12-22 05:46:06 +00003257 Expr **Args, unsigned NumArgs,
Peter Collingbourne619a8c72011-10-02 23:49:29 +00003258 SourceLocation RParenLoc,
3259 bool IsExecConfig) {
John McCallbebede42011-02-26 05:39:39 +00003260 // Bail out early if calling a builtin with custom typechecking.
3261 // We don't need to do this in the
3262 if (FDecl)
3263 if (unsigned ID = FDecl->getBuiltinID())
3264 if (Context.BuiltinInfo.hasCustomTypechecking(ID))
3265 return false;
3266
Mike Stump4e1f26a2009-02-19 03:04:26 +00003267 // C99 6.5.2.2p7 - the arguments are implicitly converted, as if by
Douglas Gregor97fd6e22008-12-22 05:46:06 +00003268 // assignment, to the types of the corresponding parameter, ...
3269 unsigned NumArgsInProto = Proto->getNumArgs();
Douglas Gregorb6b99612009-01-23 21:30:56 +00003270 bool Invalid = false;
Peter Collingbourne740afe22011-10-02 23:49:20 +00003271 unsigned MinArgs = FDecl ? FDecl->getMinRequiredArguments() : NumArgsInProto;
Peter Collingbourne619a8c72011-10-02 23:49:29 +00003272 unsigned FnKind = Fn->getType()->isBlockPointerType()
3273 ? 1 /* block */
3274 : (IsExecConfig ? 3 /* kernel function (exec config) */
3275 : 0 /* function */);
Kovarththanan Rajaratnamba2c6522010-03-13 10:17:05 +00003276
Douglas Gregor97fd6e22008-12-22 05:46:06 +00003277 // If too few arguments are available (and we don't have default
3278 // arguments for the remaining parameters), don't make the call.
3279 if (NumArgs < NumArgsInProto) {
Peter Collingbourne740afe22011-10-02 23:49:20 +00003280 if (NumArgs < MinArgs) {
3281 Diag(RParenLoc, MinArgs == NumArgsInProto
3282 ? diag::err_typecheck_call_too_few_args
3283 : diag::err_typecheck_call_too_few_args_at_least)
Peter Collingbourne619a8c72011-10-02 23:49:29 +00003284 << FnKind
Peter Collingbourne740afe22011-10-02 23:49:20 +00003285 << MinArgs << NumArgs << Fn->getSourceRange();
Peter Collingbourne3bc84ca2011-07-29 00:24:42 +00003286
3287 // Emit the location of the prototype.
Peter Collingbourne619a8c72011-10-02 23:49:29 +00003288 if (FDecl && !FDecl->getBuiltinID() && !IsExecConfig)
Peter Collingbourne3bc84ca2011-07-29 00:24:42 +00003289 Diag(FDecl->getLocStart(), diag::note_callee_decl)
3290 << FDecl;
3291
3292 return true;
3293 }
Ted Kremenek5a201952009-02-07 01:47:29 +00003294 Call->setNumArgs(Context, NumArgsInProto);
Douglas Gregor97fd6e22008-12-22 05:46:06 +00003295 }
3296
3297 // If too many are passed and not variadic, error on the extras and drop
3298 // them.
3299 if (NumArgs > NumArgsInProto) {
3300 if (!Proto->isVariadic()) {
3301 Diag(Args[NumArgsInProto]->getLocStart(),
Peter Collingbourne740afe22011-10-02 23:49:20 +00003302 MinArgs == NumArgsInProto
3303 ? diag::err_typecheck_call_too_many_args
3304 : diag::err_typecheck_call_too_many_args_at_most)
Peter Collingbourne619a8c72011-10-02 23:49:29 +00003305 << FnKind
Eric Christopher2a5aaff2010-04-16 04:56:46 +00003306 << NumArgsInProto << NumArgs << Fn->getSourceRange()
Douglas Gregor97fd6e22008-12-22 05:46:06 +00003307 << SourceRange(Args[NumArgsInProto]->getLocStart(),
3308 Args[NumArgs-1]->getLocEnd());
Ted Kremenek99a337e2011-04-04 17:22:27 +00003309
3310 // Emit the location of the prototype.
Peter Collingbourne619a8c72011-10-02 23:49:29 +00003311 if (FDecl && !FDecl->getBuiltinID() && !IsExecConfig)
Peter Collingbourne3bc84ca2011-07-29 00:24:42 +00003312 Diag(FDecl->getLocStart(), diag::note_callee_decl)
3313 << FDecl;
Ted Kremenek99a337e2011-04-04 17:22:27 +00003314
Douglas Gregor97fd6e22008-12-22 05:46:06 +00003315 // This deletes the extra arguments.
Ted Kremenek5a201952009-02-07 01:47:29 +00003316 Call->setNumArgs(Context, NumArgsInProto);
Fariborz Jahanian835026e2009-11-24 18:29:37 +00003317 return true;
Douglas Gregor97fd6e22008-12-22 05:46:06 +00003318 }
Douglas Gregor97fd6e22008-12-22 05:46:06 +00003319 }
Chris Lattner0e62c1c2011-07-23 10:55:15 +00003320 SmallVector<Expr *, 8> AllArgs;
Kovarththanan Rajaratnamba2c6522010-03-13 10:17:05 +00003321 VariadicCallType CallType =
Fariborz Jahanian6f2d25e2009-11-24 19:27:49 +00003322 Proto->isVariadic() ? VariadicFunction : VariadicDoesNotApply;
3323 if (Fn->getType()->isBlockPointerType())
3324 CallType = VariadicBlock; // Block
3325 else if (isa<MemberExpr>(Fn))
3326 CallType = VariadicMethod;
Fariborz Jahanian835026e2009-11-24 18:29:37 +00003327 Invalid = GatherArgumentsForCall(Call->getSourceRange().getBegin(), FDecl,
Fariborz Jahanian4fa66ce2009-11-24 21:37:28 +00003328 Proto, 0, Args, NumArgs, AllArgs, CallType);
Fariborz Jahanian835026e2009-11-24 18:29:37 +00003329 if (Invalid)
3330 return true;
3331 unsigned TotalNumArgs = AllArgs.size();
3332 for (unsigned i = 0; i < TotalNumArgs; ++i)
3333 Call->setArg(i, AllArgs[i]);
Kovarththanan Rajaratnamba2c6522010-03-13 10:17:05 +00003334
Fariborz Jahanian835026e2009-11-24 18:29:37 +00003335 return false;
3336}
Mike Stump4e1f26a2009-02-19 03:04:26 +00003337
Fariborz Jahanian835026e2009-11-24 18:29:37 +00003338bool Sema::GatherArgumentsForCall(SourceLocation CallLoc,
3339 FunctionDecl *FDecl,
3340 const FunctionProtoType *Proto,
3341 unsigned FirstProtoArg,
3342 Expr **Args, unsigned NumArgs,
Chris Lattner0e62c1c2011-07-23 10:55:15 +00003343 SmallVector<Expr *, 8> &AllArgs,
Douglas Gregor6073dca2012-02-24 23:56:31 +00003344 VariadicCallType CallType,
3345 bool AllowExplicit) {
Fariborz Jahanian835026e2009-11-24 18:29:37 +00003346 unsigned NumArgsInProto = Proto->getNumArgs();
3347 unsigned NumArgsToCheck = NumArgs;
3348 bool Invalid = false;
3349 if (NumArgs != NumArgsInProto)
3350 // Use default arguments for missing arguments
3351 NumArgsToCheck = NumArgsInProto;
3352 unsigned ArgIx = 0;
Douglas Gregor97fd6e22008-12-22 05:46:06 +00003353 // Continue to check argument types (even if we have too few/many args).
Fariborz Jahanian835026e2009-11-24 18:29:37 +00003354 for (unsigned i = FirstProtoArg; i != NumArgsToCheck; i++) {
Douglas Gregor97fd6e22008-12-22 05:46:06 +00003355 QualType ProtoArgType = Proto->getArgType(i);
Kovarththanan Rajaratnamba2c6522010-03-13 10:17:05 +00003356
Douglas Gregor97fd6e22008-12-22 05:46:06 +00003357 Expr *Arg;
Peter Collingbournea48f33f2011-10-19 00:16:45 +00003358 ParmVarDecl *Param;
Fariborz Jahanian835026e2009-11-24 18:29:37 +00003359 if (ArgIx < NumArgs) {
3360 Arg = Args[ArgIx++];
Kovarththanan Rajaratnamba2c6522010-03-13 10:17:05 +00003361
Eli Friedman3164fb12009-03-22 22:00:50 +00003362 if (RequireCompleteType(Arg->getSourceRange().getBegin(),
3363 ProtoArgType,
Anders Carlssond624e162009-08-26 23:45:07 +00003364 PDiag(diag::err_call_incomplete_argument)
Fariborz Jahanian835026e2009-11-24 18:29:37 +00003365 << Arg->getSourceRange()))
Eli Friedman3164fb12009-03-22 22:00:50 +00003366 return true;
Kovarththanan Rajaratnamba2c6522010-03-13 10:17:05 +00003367
Douglas Gregorbbeb5c32009-12-22 16:09:06 +00003368 // Pass the argument
Peter Collingbournea48f33f2011-10-19 00:16:45 +00003369 Param = 0;
Douglas Gregorbbeb5c32009-12-22 16:09:06 +00003370 if (FDecl && i < FDecl->getNumParams())
3371 Param = FDecl->getParamDecl(i);
Douglas Gregor96596c92009-12-22 07:24:36 +00003372
John McCall4124c492011-10-17 18:40:02 +00003373 // Strip the unbridged-cast placeholder expression off, if applicable.
3374 if (Arg->getType() == Context.ARCUnbridgedCastTy &&
3375 FDecl && FDecl->hasAttr<CFAuditedTransferAttr>() &&
3376 (!Param || !Param->hasAttr<CFConsumedAttr>()))
3377 Arg = stripARCUnbridgedCast(Arg);
3378
Douglas Gregorbbeb5c32009-12-22 16:09:06 +00003379 InitializedEntity Entity =
Fariborz Jahanian8fb87ae2010-09-24 17:30:16 +00003380 Param? InitializedEntity::InitializeParameter(Context, Param)
John McCall31168b02011-06-15 23:02:42 +00003381 : InitializedEntity::InitializeParameter(Context, ProtoArgType,
3382 Proto->isArgConsumed(i));
John McCalldadc5752010-08-24 06:29:42 +00003383 ExprResult ArgE = PerformCopyInitialization(Entity,
John McCall34376a62010-12-04 03:47:34 +00003384 SourceLocation(),
Douglas Gregor6073dca2012-02-24 23:56:31 +00003385 Owned(Arg),
3386 /*TopLevelOfInitList=*/false,
3387 AllowExplicit);
Douglas Gregorbbeb5c32009-12-22 16:09:06 +00003388 if (ArgE.isInvalid())
3389 return true;
3390
3391 Arg = ArgE.takeAs<Expr>();
Anders Carlsson84613c42009-06-12 16:51:40 +00003392 } else {
Peter Collingbournea48f33f2011-10-19 00:16:45 +00003393 Param = FDecl->getParamDecl(i);
Kovarththanan Rajaratnamba2c6522010-03-13 10:17:05 +00003394
John McCalldadc5752010-08-24 06:29:42 +00003395 ExprResult ArgExpr =
Fariborz Jahanian835026e2009-11-24 18:29:37 +00003396 BuildCXXDefaultArgExpr(CallLoc, FDecl, Param);
Anders Carlsson355933d2009-08-25 03:49:14 +00003397 if (ArgExpr.isInvalid())
3398 return true;
Kovarththanan Rajaratnamba2c6522010-03-13 10:17:05 +00003399
Anders Carlsson355933d2009-08-25 03:49:14 +00003400 Arg = ArgExpr.takeAs<Expr>();
Anders Carlsson84613c42009-06-12 16:51:40 +00003401 }
Kaelyn Uhrain2e7aa5a2011-08-05 23:18:04 +00003402
3403 // Check for array bounds violations for each argument to the call. This
3404 // check only triggers warnings when the argument isn't a more complex Expr
3405 // with its own checking, such as a BinaryOperator.
3406 CheckArrayAccess(Arg);
3407
Peter Collingbournea48f33f2011-10-19 00:16:45 +00003408 // Check for violations of C99 static array rules (C99 6.7.5.3p7).
3409 CheckStaticArrayArgument(CallLoc, Param, Arg);
3410
Fariborz Jahanian835026e2009-11-24 18:29:37 +00003411 AllArgs.push_back(Arg);
Douglas Gregor97fd6e22008-12-22 05:46:06 +00003412 }
Kovarththanan Rajaratnamba2c6522010-03-13 10:17:05 +00003413
Douglas Gregor97fd6e22008-12-22 05:46:06 +00003414 // If this is a variadic call, handle args passed through "...".
Fariborz Jahanian6f2d25e2009-11-24 19:27:49 +00003415 if (CallType != VariadicDoesNotApply) {
John McCall2979fe02011-04-12 00:42:48 +00003416
3417 // Assume that extern "C" functions with variadic arguments that
3418 // return __unknown_anytype aren't *really* variadic.
3419 if (Proto->getResultType() == Context.UnknownAnyTy &&
3420 FDecl && FDecl->isExternC()) {
3421 for (unsigned i = ArgIx; i != NumArgs; ++i) {
3422 ExprResult arg;
3423 if (isa<ExplicitCastExpr>(Args[i]->IgnoreParens()))
3424 arg = DefaultFunctionArrayLvalueConversion(Args[i]);
3425 else
3426 arg = DefaultVariadicArgumentPromotion(Args[i], CallType, FDecl);
3427 Invalid |= arg.isInvalid();
3428 AllArgs.push_back(arg.take());
3429 }
3430
3431 // Otherwise do argument promotion, (C99 6.5.2.2p7).
3432 } else {
3433 for (unsigned i = ArgIx; i != NumArgs; ++i) {
Richard Trieucfc491d2011-08-02 04:35:43 +00003434 ExprResult Arg = DefaultVariadicArgumentPromotion(Args[i], CallType,
3435 FDecl);
John McCall2979fe02011-04-12 00:42:48 +00003436 Invalid |= Arg.isInvalid();
3437 AllArgs.push_back(Arg.take());
3438 }
Douglas Gregor97fd6e22008-12-22 05:46:06 +00003439 }
Ted Kremenekd41f3462011-09-26 23:36:13 +00003440
3441 // Check for array bounds violations.
3442 for (unsigned i = ArgIx; i != NumArgs; ++i)
3443 CheckArrayAccess(Args[i]);
Douglas Gregor97fd6e22008-12-22 05:46:06 +00003444 }
Douglas Gregorb6b99612009-01-23 21:30:56 +00003445 return Invalid;
Douglas Gregor97fd6e22008-12-22 05:46:06 +00003446}
3447
Peter Collingbournea48f33f2011-10-19 00:16:45 +00003448static void DiagnoseCalleeStaticArrayParam(Sema &S, ParmVarDecl *PVD) {
3449 TypeLoc TL = PVD->getTypeSourceInfo()->getTypeLoc();
3450 if (ArrayTypeLoc *ATL = dyn_cast<ArrayTypeLoc>(&TL))
3451 S.Diag(PVD->getLocation(), diag::note_callee_static_array)
3452 << ATL->getLocalSourceRange();
3453}
3454
3455/// CheckStaticArrayArgument - If the given argument corresponds to a static
3456/// array parameter, check that it is non-null, and that if it is formed by
3457/// array-to-pointer decay, the underlying array is sufficiently large.
3458///
3459/// C99 6.7.5.3p7: If the keyword static also appears within the [ and ] of the
3460/// array type derivation, then for each call to the function, the value of the
3461/// corresponding actual argument shall provide access to the first element of
3462/// an array with at least as many elements as specified by the size expression.
3463void
3464Sema::CheckStaticArrayArgument(SourceLocation CallLoc,
3465 ParmVarDecl *Param,
3466 const Expr *ArgExpr) {
3467 // Static array parameters are not supported in C++.
3468 if (!Param || getLangOptions().CPlusPlus)
3469 return;
3470
3471 QualType OrigTy = Param->getOriginalType();
3472
3473 const ArrayType *AT = Context.getAsArrayType(OrigTy);
3474 if (!AT || AT->getSizeModifier() != ArrayType::Static)
3475 return;
3476
3477 if (ArgExpr->isNullPointerConstant(Context,
3478 Expr::NPC_NeverValueDependent)) {
3479 Diag(CallLoc, diag::warn_null_arg) << ArgExpr->getSourceRange();
3480 DiagnoseCalleeStaticArrayParam(*this, Param);
3481 return;
3482 }
3483
3484 const ConstantArrayType *CAT = dyn_cast<ConstantArrayType>(AT);
3485 if (!CAT)
3486 return;
3487
3488 const ConstantArrayType *ArgCAT =
3489 Context.getAsConstantArrayType(ArgExpr->IgnoreParenImpCasts()->getType());
3490 if (!ArgCAT)
3491 return;
3492
3493 if (ArgCAT->getSize().ult(CAT->getSize())) {
3494 Diag(CallLoc, diag::warn_static_array_too_small)
3495 << ArgExpr->getSourceRange()
3496 << (unsigned) ArgCAT->getSize().getZExtValue()
3497 << (unsigned) CAT->getSize().getZExtValue();
3498 DiagnoseCalleeStaticArrayParam(*this, Param);
3499 }
3500}
3501
John McCall2979fe02011-04-12 00:42:48 +00003502/// Given a function expression of unknown-any type, try to rebuild it
3503/// to have a function type.
3504static ExprResult rebuildUnknownAnyFunction(Sema &S, Expr *fn);
3505
Steve Naroff83895f72007-09-16 03:34:24 +00003506/// ActOnCallExpr - Handle a call to Fn with the specified array of arguments.
Chris Lattnere168f762006-11-10 05:29:30 +00003507/// This provides the location of the left/right parens and a list of comma
3508/// locations.
John McCalldadc5752010-08-24 06:29:42 +00003509ExprResult
John McCallb268a282010-08-23 23:25:46 +00003510Sema::ActOnCallExpr(Scope *S, Expr *Fn, SourceLocation LParenLoc,
Richard Trieuba63ce62011-09-09 01:45:06 +00003511 MultiExprArg ArgExprs, SourceLocation RParenLoc,
Peter Collingbourne619a8c72011-10-02 23:49:29 +00003512 Expr *ExecConfig, bool IsExecConfig) {
Richard Trieuba63ce62011-09-09 01:45:06 +00003513 unsigned NumArgs = ArgExprs.size();
Nate Begeman5ec4b312009-08-10 23:49:36 +00003514
3515 // Since this might be a postfix expression, get rid of ParenListExprs.
John McCalldadc5752010-08-24 06:29:42 +00003516 ExprResult Result = MaybeConvertParenListExprToParenExpr(S, Fn);
John McCallb268a282010-08-23 23:25:46 +00003517 if (Result.isInvalid()) return ExprError();
3518 Fn = Result.take();
Mike Stump11289f42009-09-09 15:08:12 +00003519
Richard Trieuba63ce62011-09-09 01:45:06 +00003520 Expr **Args = ArgExprs.release();
Mike Stump11289f42009-09-09 15:08:12 +00003521
Douglas Gregor97fd6e22008-12-22 05:46:06 +00003522 if (getLangOptions().CPlusPlus) {
Douglas Gregorad8a3362009-09-04 17:36:40 +00003523 // If this is a pseudo-destructor expression, build the call immediately.
3524 if (isa<CXXPseudoDestructorExpr>(Fn)) {
3525 if (NumArgs > 0) {
3526 // Pseudo-destructor calls should not have any arguments.
3527 Diag(Fn->getLocStart(), diag::err_pseudo_dtor_call_with_args)
Douglas Gregora771f462010-03-31 17:46:05 +00003528 << FixItHint::CreateRemoval(
Douglas Gregorad8a3362009-09-04 17:36:40 +00003529 SourceRange(Args[0]->getLocStart(),
3530 Args[NumArgs-1]->getLocEnd()));
Mike Stump11289f42009-09-09 15:08:12 +00003531
Douglas Gregorad8a3362009-09-04 17:36:40 +00003532 NumArgs = 0;
3533 }
Mike Stump11289f42009-09-09 15:08:12 +00003534
Douglas Gregorad8a3362009-09-04 17:36:40 +00003535 return Owned(new (Context) CallExpr(Context, Fn, 0, 0, Context.VoidTy,
John McCall7decc9e2010-11-18 06:31:45 +00003536 VK_RValue, RParenLoc));
Douglas Gregorad8a3362009-09-04 17:36:40 +00003537 }
Mike Stump11289f42009-09-09 15:08:12 +00003538
Douglas Gregorb8a9a412009-02-04 15:01:18 +00003539 // Determine whether this is a dependent call inside a C++ template,
Mike Stump4e1f26a2009-02-19 03:04:26 +00003540 // in which case we won't do any semantic analysis now.
Mike Stump87c57ac2009-05-16 07:39:55 +00003541 // FIXME: Will need to cache the results of name lookup (including ADL) in
3542 // Fn.
Douglas Gregorb8a9a412009-02-04 15:01:18 +00003543 bool Dependent = false;
3544 if (Fn->isTypeDependent())
3545 Dependent = true;
Ahmed Charlesb24b9aa2012-02-25 11:00:22 +00003546 else if (Expr::hasAnyTypeDependentArguments(
3547 llvm::makeArrayRef(Args, NumArgs)))
Douglas Gregorb8a9a412009-02-04 15:01:18 +00003548 Dependent = true;
3549
Peter Collingbourne41f85462011-02-09 21:07:24 +00003550 if (Dependent) {
3551 if (ExecConfig) {
3552 return Owned(new (Context) CUDAKernelCallExpr(
3553 Context, Fn, cast<CallExpr>(ExecConfig), Args, NumArgs,
3554 Context.DependentTy, VK_RValue, RParenLoc));
3555 } else {
3556 return Owned(new (Context) CallExpr(Context, Fn, Args, NumArgs,
3557 Context.DependentTy, VK_RValue,
3558 RParenLoc));
3559 }
3560 }
Douglas Gregorb8a9a412009-02-04 15:01:18 +00003561
3562 // Determine whether this is a call to an object (C++ [over.call.object]).
3563 if (Fn->getType()->isRecordType())
3564 return Owned(BuildCallToObjectOfClassType(S, Fn, LParenLoc, Args, NumArgs,
Douglas Gregorce5aa332010-09-09 16:33:13 +00003565 RParenLoc));
Douglas Gregorb8a9a412009-02-04 15:01:18 +00003566
John McCall2979fe02011-04-12 00:42:48 +00003567 if (Fn->getType() == Context.UnknownAnyTy) {
3568 ExprResult result = rebuildUnknownAnyFunction(*this, Fn);
3569 if (result.isInvalid()) return ExprError();
3570 Fn = result.take();
3571 }
3572
John McCall0009fcc2011-04-26 20:42:42 +00003573 if (Fn->getType() == Context.BoundMemberTy) {
John McCall2d74de92009-12-01 22:10:20 +00003574 return BuildCallToMemberFunction(S, Fn, LParenLoc, Args, NumArgs,
Douglas Gregorce5aa332010-09-09 16:33:13 +00003575 RParenLoc);
John McCall10eae182009-11-30 22:42:35 +00003576 }
John McCall0009fcc2011-04-26 20:42:42 +00003577 }
John McCall10eae182009-11-30 22:42:35 +00003578
John McCall0009fcc2011-04-26 20:42:42 +00003579 // Check for overloaded calls. This can happen even in C due to extensions.
3580 if (Fn->getType() == Context.OverloadTy) {
3581 OverloadExpr::FindResult find = OverloadExpr::find(Fn);
3582
Douglas Gregorcda22702011-10-13 18:10:35 +00003583 // We aren't supposed to apply this logic for if there's an '&' involved.
Douglas Gregorf4a06c22011-10-13 18:26:27 +00003584 if (!find.HasFormOfMemberPointer) {
John McCall0009fcc2011-04-26 20:42:42 +00003585 OverloadExpr *ovl = find.Expression;
3586 if (isa<UnresolvedLookupExpr>(ovl)) {
3587 UnresolvedLookupExpr *ULE = cast<UnresolvedLookupExpr>(ovl);
3588 return BuildOverloadedCallExpr(S, Fn, ULE, LParenLoc, Args, NumArgs,
3589 RParenLoc, ExecConfig);
3590 } else {
John McCall2d74de92009-12-01 22:10:20 +00003591 return BuildCallToMemberFunction(S, Fn, LParenLoc, Args, NumArgs,
Douglas Gregorce5aa332010-09-09 16:33:13 +00003592 RParenLoc);
Anders Carlsson61914b52009-10-03 17:40:22 +00003593 }
3594 }
Douglas Gregor97fd6e22008-12-22 05:46:06 +00003595 }
3596
Douglas Gregore254f902009-02-04 00:32:51 +00003597 // If we're directly calling a function, get the appropriate declaration.
Douglas Gregord8fb1e32011-12-01 01:37:36 +00003598 if (Fn->getType() == Context.UnknownAnyTy) {
3599 ExprResult result = rebuildUnknownAnyFunction(*this, Fn);
3600 if (result.isInvalid()) return ExprError();
3601 Fn = result.take();
3602 }
Mike Stump4e1f26a2009-02-19 03:04:26 +00003603
Eli Friedmane14b1992009-12-26 03:35:45 +00003604 Expr *NakedFn = Fn->IgnoreParens();
Douglas Gregor928479e2010-11-09 20:03:54 +00003605
John McCall57500772009-12-16 12:17:52 +00003606 NamedDecl *NDecl = 0;
Douglas Gregor59f16ed2010-10-25 20:48:33 +00003607 if (UnaryOperator *UnOp = dyn_cast<UnaryOperator>(NakedFn))
3608 if (UnOp->getOpcode() == UO_AddrOf)
3609 NakedFn = UnOp->getSubExpr()->IgnoreParens();
3610
John McCall57500772009-12-16 12:17:52 +00003611 if (isa<DeclRefExpr>(NakedFn))
3612 NDecl = cast<DeclRefExpr>(NakedFn)->getDecl();
John McCall0009fcc2011-04-26 20:42:42 +00003613 else if (isa<MemberExpr>(NakedFn))
3614 NDecl = cast<MemberExpr>(NakedFn)->getMemberDecl();
John McCall57500772009-12-16 12:17:52 +00003615
Peter Collingbourne41f85462011-02-09 21:07:24 +00003616 return BuildResolvedCallExpr(Fn, NDecl, LParenLoc, Args, NumArgs, RParenLoc,
Peter Collingbourne619a8c72011-10-02 23:49:29 +00003617 ExecConfig, IsExecConfig);
Peter Collingbourne41f85462011-02-09 21:07:24 +00003618}
3619
3620ExprResult
3621Sema::ActOnCUDAExecConfigExpr(Scope *S, SourceLocation LLLLoc,
Richard Trieuba63ce62011-09-09 01:45:06 +00003622 MultiExprArg ExecConfig, SourceLocation GGGLoc) {
Peter Collingbourne41f85462011-02-09 21:07:24 +00003623 FunctionDecl *ConfigDecl = Context.getcudaConfigureCallDecl();
3624 if (!ConfigDecl)
3625 return ExprError(Diag(LLLLoc, diag::err_undeclared_var_use)
3626 << "cudaConfigureCall");
3627 QualType ConfigQTy = ConfigDecl->getType();
3628
3629 DeclRefExpr *ConfigDR = new (Context) DeclRefExpr(
3630 ConfigDecl, ConfigQTy, VK_LValue, LLLLoc);
Eli Friedmanfa0df832012-02-02 03:46:19 +00003631 MarkFunctionReferenced(LLLLoc, ConfigDecl);
Peter Collingbourne41f85462011-02-09 21:07:24 +00003632
Peter Collingbourne619a8c72011-10-02 23:49:29 +00003633 return ActOnCallExpr(S, ConfigDR, LLLLoc, ExecConfig, GGGLoc, 0,
3634 /*IsExecConfig=*/true);
John McCall2d74de92009-12-01 22:10:20 +00003635}
3636
Tanya Lattner55808c12011-06-04 00:47:47 +00003637/// ActOnAsTypeExpr - create a new asType (bitcast) from the arguments.
3638///
3639/// __builtin_astype( value, dst type )
3640///
Richard Trieuba63ce62011-09-09 01:45:06 +00003641ExprResult Sema::ActOnAsTypeExpr(Expr *E, ParsedType ParsedDestTy,
Tanya Lattner55808c12011-06-04 00:47:47 +00003642 SourceLocation BuiltinLoc,
3643 SourceLocation RParenLoc) {
3644 ExprValueKind VK = VK_RValue;
3645 ExprObjectKind OK = OK_Ordinary;
Richard Trieuba63ce62011-09-09 01:45:06 +00003646 QualType DstTy = GetTypeFromParser(ParsedDestTy);
3647 QualType SrcTy = E->getType();
Tanya Lattner55808c12011-06-04 00:47:47 +00003648 if (Context.getTypeSize(DstTy) != Context.getTypeSize(SrcTy))
3649 return ExprError(Diag(BuiltinLoc,
3650 diag::err_invalid_astype_of_different_size)
Peter Collingbourne23f1bee2011-06-08 15:15:17 +00003651 << DstTy
3652 << SrcTy
Richard Trieuba63ce62011-09-09 01:45:06 +00003653 << E->getSourceRange());
3654 return Owned(new (Context) AsTypeExpr(E, DstTy, VK, OK, BuiltinLoc,
Richard Trieucfc491d2011-08-02 04:35:43 +00003655 RParenLoc));
Tanya Lattner55808c12011-06-04 00:47:47 +00003656}
3657
John McCall57500772009-12-16 12:17:52 +00003658/// BuildResolvedCallExpr - Build a call to a resolved expression,
3659/// i.e. an expression not of \p OverloadTy. The expression should
John McCall2d74de92009-12-01 22:10:20 +00003660/// unary-convert to an expression of function-pointer or
3661/// block-pointer type.
3662///
3663/// \param NDecl the declaration being called, if available
John McCalldadc5752010-08-24 06:29:42 +00003664ExprResult
John McCall2d74de92009-12-01 22:10:20 +00003665Sema::BuildResolvedCallExpr(Expr *Fn, NamedDecl *NDecl,
3666 SourceLocation LParenLoc,
3667 Expr **Args, unsigned NumArgs,
Peter Collingbourne41f85462011-02-09 21:07:24 +00003668 SourceLocation RParenLoc,
Peter Collingbourne619a8c72011-10-02 23:49:29 +00003669 Expr *Config, bool IsExecConfig) {
John McCall2d74de92009-12-01 22:10:20 +00003670 FunctionDecl *FDecl = dyn_cast_or_null<FunctionDecl>(NDecl);
3671
Chris Lattneraa9c7ae2008-04-08 04:40:51 +00003672 // Promote the function operand.
John Wiegley01296292011-04-08 18:41:53 +00003673 ExprResult Result = UsualUnaryConversions(Fn);
3674 if (Result.isInvalid())
3675 return ExprError();
3676 Fn = Result.take();
Chris Lattneraa9c7ae2008-04-08 04:40:51 +00003677
Chris Lattner08464942007-12-28 05:29:59 +00003678 // Make the call expr early, before semantic checks. This guarantees cleanup
3679 // of arguments and function on error.
Peter Collingbourne41f85462011-02-09 21:07:24 +00003680 CallExpr *TheCall;
3681 if (Config) {
3682 TheCall = new (Context) CUDAKernelCallExpr(Context, Fn,
3683 cast<CallExpr>(Config),
3684 Args, NumArgs,
3685 Context.BoolTy,
3686 VK_RValue,
3687 RParenLoc);
3688 } else {
3689 TheCall = new (Context) CallExpr(Context, Fn,
3690 Args, NumArgs,
3691 Context.BoolTy,
3692 VK_RValue,
3693 RParenLoc);
3694 }
Sebastian Redlc215cfc2009-01-19 00:08:26 +00003695
John McCallbebede42011-02-26 05:39:39 +00003696 unsigned BuiltinID = (FDecl ? FDecl->getBuiltinID() : 0);
3697
3698 // Bail out early if calling a builtin with custom typechecking.
3699 if (BuiltinID && Context.BuiltinInfo.hasCustomTypechecking(BuiltinID))
3700 return CheckBuiltinFunctionCall(BuiltinID, TheCall);
3701
John McCall31996342011-04-07 08:22:57 +00003702 retry:
Steve Naroff8de9c3a2008-09-05 22:11:13 +00003703 const FunctionType *FuncT;
John McCallbebede42011-02-26 05:39:39 +00003704 if (const PointerType *PT = Fn->getType()->getAs<PointerType>()) {
Steve Naroff8de9c3a2008-09-05 22:11:13 +00003705 // C99 6.5.2.2p1 - "The expression that denotes the called function shall
3706 // have type pointer to function".
John McCall9dd450b2009-09-21 23:43:11 +00003707 FuncT = PT->getPointeeType()->getAs<FunctionType>();
John McCallbebede42011-02-26 05:39:39 +00003708 if (FuncT == 0)
3709 return ExprError(Diag(LParenLoc, diag::err_typecheck_call_not_function)
3710 << Fn->getType() << Fn->getSourceRange());
3711 } else if (const BlockPointerType *BPT =
3712 Fn->getType()->getAs<BlockPointerType>()) {
3713 FuncT = BPT->getPointeeType()->castAs<FunctionType>();
3714 } else {
John McCall31996342011-04-07 08:22:57 +00003715 // Handle calls to expressions of unknown-any type.
3716 if (Fn->getType() == Context.UnknownAnyTy) {
John McCall2979fe02011-04-12 00:42:48 +00003717 ExprResult rewrite = rebuildUnknownAnyFunction(*this, Fn);
John McCall31996342011-04-07 08:22:57 +00003718 if (rewrite.isInvalid()) return ExprError();
3719 Fn = rewrite.take();
John McCall39439732011-04-09 22:50:59 +00003720 TheCall->setCallee(Fn);
John McCall31996342011-04-07 08:22:57 +00003721 goto retry;
3722 }
3723
Sebastian Redlc215cfc2009-01-19 00:08:26 +00003724 return ExprError(Diag(LParenLoc, diag::err_typecheck_call_not_function)
3725 << Fn->getType() << Fn->getSourceRange());
John McCallbebede42011-02-26 05:39:39 +00003726 }
Sebastian Redlc215cfc2009-01-19 00:08:26 +00003727
Peter Collingbourne4b66c472011-02-23 01:53:29 +00003728 if (getLangOptions().CUDA) {
3729 if (Config) {
3730 // CUDA: Kernel calls must be to global functions
3731 if (FDecl && !FDecl->hasAttr<CUDAGlobalAttr>())
3732 return ExprError(Diag(LParenLoc,diag::err_kern_call_not_global_function)
3733 << FDecl->getName() << Fn->getSourceRange());
3734
3735 // CUDA: Kernel function must have 'void' return type
3736 if (!FuncT->getResultType()->isVoidType())
3737 return ExprError(Diag(LParenLoc, diag::err_kern_type_not_void_return)
3738 << Fn->getType() << Fn->getSourceRange());
Peter Collingbourne34a20b02011-10-02 23:49:15 +00003739 } else {
3740 // CUDA: Calls to global functions must be configured
3741 if (FDecl && FDecl->hasAttr<CUDAGlobalAttr>())
3742 return ExprError(Diag(LParenLoc, diag::err_global_call_not_config)
3743 << FDecl->getName() << Fn->getSourceRange());
Peter Collingbourne4b66c472011-02-23 01:53:29 +00003744 }
3745 }
3746
Eli Friedman3164fb12009-03-22 22:00:50 +00003747 // Check for a valid return type
Kovarththanan Rajaratnamba2c6522010-03-13 10:17:05 +00003748 if (CheckCallReturnType(FuncT->getResultType(),
John McCallb268a282010-08-23 23:25:46 +00003749 Fn->getSourceRange().getBegin(), TheCall,
Anders Carlsson7f84ed92009-10-09 23:51:55 +00003750 FDecl))
Eli Friedman3164fb12009-03-22 22:00:50 +00003751 return ExprError();
3752
Chris Lattner08464942007-12-28 05:29:59 +00003753 // We know the result type of the call, set it.
Douglas Gregor603d81b2010-07-13 08:18:22 +00003754 TheCall->setType(FuncT->getCallResultType(Context));
John McCall7decc9e2010-11-18 06:31:45 +00003755 TheCall->setValueKind(Expr::getValueKindForType(FuncT->getResultType()));
Sebastian Redlc215cfc2009-01-19 00:08:26 +00003756
Douglas Gregordeaad8c2009-02-26 23:50:07 +00003757 if (const FunctionProtoType *Proto = dyn_cast<FunctionProtoType>(FuncT)) {
John McCallb268a282010-08-23 23:25:46 +00003758 if (ConvertArgumentsForCall(TheCall, Fn, FDecl, Proto, Args, NumArgs,
Peter Collingbourne619a8c72011-10-02 23:49:29 +00003759 RParenLoc, IsExecConfig))
Sebastian Redlc215cfc2009-01-19 00:08:26 +00003760 return ExprError();
Chris Lattner08464942007-12-28 05:29:59 +00003761 } else {
Douglas Gregordeaad8c2009-02-26 23:50:07 +00003762 assert(isa<FunctionNoProtoType>(FuncT) && "Unknown FunctionType!");
Sebastian Redlc215cfc2009-01-19 00:08:26 +00003763
Douglas Gregord8e97de2009-04-02 15:37:10 +00003764 if (FDecl) {
3765 // Check if we have too few/too many template arguments, based
3766 // on our knowledge of the function definition.
3767 const FunctionDecl *Def = 0;
Argyrios Kyrtzidis36ea3222010-07-07 11:31:19 +00003768 if (FDecl->hasBody(Def) && NumArgs != Def->param_size()) {
Douglas Gregor8e09a722010-10-25 20:39:23 +00003769 const FunctionProtoType *Proto
3770 = Def->getType()->getAs<FunctionProtoType>();
3771 if (!Proto || !(Proto->isVariadic() && NumArgs >= Def->param_size()))
Eli Friedmanfcbf7d22009-06-01 09:24:59 +00003772 Diag(RParenLoc, diag::warn_call_wrong_number_of_arguments)
3773 << (NumArgs > Def->param_size()) << FDecl << Fn->getSourceRange();
Eli Friedmanfcbf7d22009-06-01 09:24:59 +00003774 }
Douglas Gregor8e09a722010-10-25 20:39:23 +00003775
3776 // If the function we're calling isn't a function prototype, but we have
3777 // a function prototype from a prior declaratiom, use that prototype.
3778 if (!FDecl->hasPrototype())
3779 Proto = FDecl->getType()->getAs<FunctionProtoType>();
Douglas Gregord8e97de2009-04-02 15:37:10 +00003780 }
3781
Steve Naroff0b661582007-08-28 23:30:39 +00003782 // Promote the arguments (C99 6.5.2.2p6).
Chris Lattner08464942007-12-28 05:29:59 +00003783 for (unsigned i = 0; i != NumArgs; i++) {
3784 Expr *Arg = Args[i];
Douglas Gregor8e09a722010-10-25 20:39:23 +00003785
3786 if (Proto && i < Proto->getNumArgs()) {
Douglas Gregor8e09a722010-10-25 20:39:23 +00003787 InitializedEntity Entity
3788 = InitializedEntity::InitializeParameter(Context,
John McCall31168b02011-06-15 23:02:42 +00003789 Proto->getArgType(i),
3790 Proto->isArgConsumed(i));
Douglas Gregor8e09a722010-10-25 20:39:23 +00003791 ExprResult ArgE = PerformCopyInitialization(Entity,
3792 SourceLocation(),
3793 Owned(Arg));
3794 if (ArgE.isInvalid())
3795 return true;
3796
3797 Arg = ArgE.takeAs<Expr>();
3798
3799 } else {
John Wiegley01296292011-04-08 18:41:53 +00003800 ExprResult ArgE = DefaultArgumentPromotion(Arg);
3801
3802 if (ArgE.isInvalid())
3803 return true;
3804
3805 Arg = ArgE.takeAs<Expr>();
Douglas Gregor8e09a722010-10-25 20:39:23 +00003806 }
3807
Douglas Gregor83025412010-10-26 05:45:40 +00003808 if (RequireCompleteType(Arg->getSourceRange().getBegin(),
3809 Arg->getType(),
3810 PDiag(diag::err_call_incomplete_argument)
3811 << Arg->getSourceRange()))
3812 return ExprError();
3813
Chris Lattner08464942007-12-28 05:29:59 +00003814 TheCall->setArg(i, Arg);
Steve Naroff0b661582007-08-28 23:30:39 +00003815 }
Steve Naroffae4143e2007-04-26 20:39:23 +00003816 }
Chris Lattner08464942007-12-28 05:29:59 +00003817
Douglas Gregor97fd6e22008-12-22 05:46:06 +00003818 if (CXXMethodDecl *Method = dyn_cast_or_null<CXXMethodDecl>(FDecl))
3819 if (!Method->isStatic())
Sebastian Redlc215cfc2009-01-19 00:08:26 +00003820 return ExprError(Diag(LParenLoc, diag::err_member_call_without_object)
3821 << Fn->getSourceRange());
Douglas Gregor97fd6e22008-12-22 05:46:06 +00003822
Fariborz Jahanian0aa5c452009-05-15 20:33:25 +00003823 // Check for sentinels
3824 if (NDecl)
3825 DiagnoseSentinelCalls(NDecl, LParenLoc, Args, NumArgs);
Mike Stump11289f42009-09-09 15:08:12 +00003826
Chris Lattnerb87b1b32007-08-10 20:18:51 +00003827 // Do special checking on direct calls to functions.
Anders Carlssonbc4c1072009-08-16 01:56:34 +00003828 if (FDecl) {
John McCallb268a282010-08-23 23:25:46 +00003829 if (CheckFunctionCall(FDecl, TheCall))
Anders Carlssonbc4c1072009-08-16 01:56:34 +00003830 return ExprError();
Mike Stump11289f42009-09-09 15:08:12 +00003831
John McCallbebede42011-02-26 05:39:39 +00003832 if (BuiltinID)
Fariborz Jahaniane8473c22010-11-30 17:35:24 +00003833 return CheckBuiltinFunctionCall(BuiltinID, TheCall);
Anders Carlssonbc4c1072009-08-16 01:56:34 +00003834 } else if (NDecl) {
John McCallb268a282010-08-23 23:25:46 +00003835 if (CheckBlockCall(NDecl, TheCall))
Anders Carlssonbc4c1072009-08-16 01:56:34 +00003836 return ExprError();
3837 }
Chris Lattnerb87b1b32007-08-10 20:18:51 +00003838
John McCallb268a282010-08-23 23:25:46 +00003839 return MaybeBindToTemporary(TheCall);
Chris Lattnere168f762006-11-10 05:29:30 +00003840}
3841
John McCalldadc5752010-08-24 06:29:42 +00003842ExprResult
John McCallba7bf592010-08-24 05:47:05 +00003843Sema::ActOnCompoundLiteral(SourceLocation LParenLoc, ParsedType Ty,
John McCallb268a282010-08-23 23:25:46 +00003844 SourceLocation RParenLoc, Expr *InitExpr) {
Steve Naroff83895f72007-09-16 03:34:24 +00003845 assert((Ty != 0) && "ActOnCompoundLiteral(): missing type");
Steve Naroff57eb2c52007-07-19 21:32:11 +00003846 // FIXME: put back this assert when initializers are worked out.
Steve Naroff83895f72007-09-16 03:34:24 +00003847 //assert((InitExpr != 0) && "ActOnCompoundLiteral(): missing expression");
John McCalle15bbff2010-01-18 19:35:47 +00003848
3849 TypeSourceInfo *TInfo;
3850 QualType literalType = GetTypeFromParser(Ty, &TInfo);
3851 if (!TInfo)
3852 TInfo = Context.getTrivialTypeSourceInfo(literalType);
3853
John McCallb268a282010-08-23 23:25:46 +00003854 return BuildCompoundLiteralExpr(LParenLoc, TInfo, RParenLoc, InitExpr);
John McCalle15bbff2010-01-18 19:35:47 +00003855}
3856
John McCalldadc5752010-08-24 06:29:42 +00003857ExprResult
John McCalle15bbff2010-01-18 19:35:47 +00003858Sema::BuildCompoundLiteralExpr(SourceLocation LParenLoc, TypeSourceInfo *TInfo,
Richard Trieuba63ce62011-09-09 01:45:06 +00003859 SourceLocation RParenLoc, Expr *LiteralExpr) {
John McCalle15bbff2010-01-18 19:35:47 +00003860 QualType literalType = TInfo->getType();
Anders Carlsson2c1ec6d2007-12-05 07:24:19 +00003861
Eli Friedman37a186d2008-05-20 05:22:08 +00003862 if (literalType->isArrayType()) {
Argyrios Kyrtzidis85663562010-11-08 19:14:19 +00003863 if (RequireCompleteType(LParenLoc, Context.getBaseElementType(literalType),
3864 PDiag(diag::err_illegal_decl_array_incomplete_type)
3865 << SourceRange(LParenLoc,
Richard Trieuba63ce62011-09-09 01:45:06 +00003866 LiteralExpr->getSourceRange().getEnd())))
Argyrios Kyrtzidis85663562010-11-08 19:14:19 +00003867 return ExprError();
Chris Lattner7adf0762008-08-04 07:31:14 +00003868 if (literalType->isVariableArrayType())
Sebastian Redlb5d49352009-01-19 22:31:54 +00003869 return ExprError(Diag(LParenLoc, diag::err_variable_object_no_init)
Richard Trieuba63ce62011-09-09 01:45:06 +00003870 << SourceRange(LParenLoc, LiteralExpr->getSourceRange().getEnd()));
Douglas Gregor1c37d9e2009-05-21 23:48:18 +00003871 } else if (!literalType->isDependentType() &&
3872 RequireCompleteType(LParenLoc, literalType,
Anders Carlssond624e162009-08-26 23:45:07 +00003873 PDiag(diag::err_typecheck_decl_incomplete_type)
Mike Stump11289f42009-09-09 15:08:12 +00003874 << SourceRange(LParenLoc,
Richard Trieuba63ce62011-09-09 01:45:06 +00003875 LiteralExpr->getSourceRange().getEnd())))
Sebastian Redlb5d49352009-01-19 22:31:54 +00003876 return ExprError();
Eli Friedman37a186d2008-05-20 05:22:08 +00003877
Douglas Gregor85dabae2009-12-16 01:38:02 +00003878 InitializedEntity Entity
Douglas Gregor1b303932009-12-22 15:35:07 +00003879 = InitializedEntity::InitializeTemporary(literalType);
Douglas Gregor85dabae2009-12-16 01:38:02 +00003880 InitializationKind Kind
John McCall31168b02011-06-15 23:02:42 +00003881 = InitializationKind::CreateCStyleCast(LParenLoc,
Sebastian Redl0501c632012-02-12 16:37:36 +00003882 SourceRange(LParenLoc, RParenLoc),
3883 /*InitList=*/true);
Richard Trieuba63ce62011-09-09 01:45:06 +00003884 InitializationSequence InitSeq(*this, Entity, Kind, &LiteralExpr, 1);
John McCalldadc5752010-08-24 06:29:42 +00003885 ExprResult Result = InitSeq.Perform(*this, Entity, Kind,
Richard Trieuba63ce62011-09-09 01:45:06 +00003886 MultiExprArg(*this, &LiteralExpr, 1),
Eli Friedmana553d4a2009-12-22 02:35:53 +00003887 &literalType);
3888 if (Result.isInvalid())
Sebastian Redlb5d49352009-01-19 22:31:54 +00003889 return ExprError();
Richard Trieuba63ce62011-09-09 01:45:06 +00003890 LiteralExpr = Result.get();
Steve Naroffd32419d2008-01-14 18:19:28 +00003891
Chris Lattner79413952008-12-04 23:50:19 +00003892 bool isFileScope = getCurFunctionOrMethodDecl() == 0;
Steve Naroffd32419d2008-01-14 18:19:28 +00003893 if (isFileScope) { // 6.5.2.5p3
Richard Trieuba63ce62011-09-09 01:45:06 +00003894 if (CheckForConstantInitializer(LiteralExpr, literalType))
Sebastian Redlb5d49352009-01-19 22:31:54 +00003895 return ExprError();
Steve Naroff98f72032008-01-10 22:15:12 +00003896 }
Eli Friedmana553d4a2009-12-22 02:35:53 +00003897
John McCall7decc9e2010-11-18 06:31:45 +00003898 // In C, compound literals are l-values for some reason.
3899 ExprValueKind VK = getLangOptions().CPlusPlus ? VK_RValue : VK_LValue;
3900
Douglas Gregor9b71f0c2011-06-17 04:59:12 +00003901 return MaybeBindToTemporary(
3902 new (Context) CompoundLiteralExpr(LParenLoc, TInfo, literalType,
Richard Trieuba63ce62011-09-09 01:45:06 +00003903 VK, LiteralExpr, isFileScope));
Steve Narofffbd09832007-07-19 01:06:55 +00003904}
3905
John McCalldadc5752010-08-24 06:29:42 +00003906ExprResult
Richard Trieuba63ce62011-09-09 01:45:06 +00003907Sema::ActOnInitList(SourceLocation LBraceLoc, MultiExprArg InitArgList,
Sebastian Redlb5d49352009-01-19 22:31:54 +00003908 SourceLocation RBraceLoc) {
Richard Trieuba63ce62011-09-09 01:45:06 +00003909 unsigned NumInit = InitArgList.size();
3910 Expr **InitList = InitArgList.release();
Anders Carlsson4692db02007-08-31 04:56:16 +00003911
John McCall526ab472011-10-25 17:37:35 +00003912 // Immediately handle non-overload placeholders. Overloads can be
3913 // resolved contextually, but everything else here can't.
3914 for (unsigned I = 0; I != NumInit; ++I) {
John McCalld5c98ae2011-11-15 01:35:18 +00003915 if (InitList[I]->getType()->isNonOverloadPlaceholderType()) {
John McCall526ab472011-10-25 17:37:35 +00003916 ExprResult result = CheckPlaceholderExpr(InitList[I]);
3917
3918 // Ignore failures; dropping the entire initializer list because
3919 // of one failure would be terrible for indexing/etc.
3920 if (result.isInvalid()) continue;
3921
3922 InitList[I] = result.take();
3923 }
3924 }
3925
Steve Naroff30d242c2007-09-15 18:49:24 +00003926 // Semantic analysis for initializers is done by ActOnDeclarator() and
Mike Stump4e1f26a2009-02-19 03:04:26 +00003927 // CheckInitializer() - it requires knowledge of the object being intialized.
Sebastian Redlb5d49352009-01-19 22:31:54 +00003928
Ted Kremenekac034612010-04-13 23:39:13 +00003929 InitListExpr *E = new (Context) InitListExpr(Context, LBraceLoc, InitList,
3930 NumInit, RBraceLoc);
Chris Lattner24d5bfe2008-04-02 04:24:33 +00003931 E->setType(Context.VoidTy); // FIXME: just a place holder for now.
Sebastian Redlb5d49352009-01-19 22:31:54 +00003932 return Owned(E);
Steve Narofffbd09832007-07-19 01:06:55 +00003933}
3934
John McCallcd78e802011-09-10 01:16:55 +00003935/// Do an explicit extend of the given block pointer if we're in ARC.
3936static void maybeExtendBlockObject(Sema &S, ExprResult &E) {
3937 assert(E.get()->getType()->isBlockPointerType());
3938 assert(E.get()->isRValue());
3939
3940 // Only do this in an r-value context.
3941 if (!S.getLangOptions().ObjCAutoRefCount) return;
3942
3943 E = ImplicitCastExpr::Create(S.Context, E.get()->getType(),
John McCall2d637d22011-09-10 06:18:15 +00003944 CK_ARCExtendBlockObject, E.get(),
John McCallcd78e802011-09-10 01:16:55 +00003945 /*base path*/ 0, VK_RValue);
3946 S.ExprNeedsCleanups = true;
3947}
3948
3949/// Prepare a conversion of the given expression to an ObjC object
3950/// pointer type.
3951CastKind Sema::PrepareCastToObjCObjectPointer(ExprResult &E) {
3952 QualType type = E.get()->getType();
3953 if (type->isObjCObjectPointerType()) {
3954 return CK_BitCast;
3955 } else if (type->isBlockPointerType()) {
3956 maybeExtendBlockObject(*this, E);
3957 return CK_BlockPointerToObjCPointerCast;
3958 } else {
3959 assert(type->isPointerType());
3960 return CK_CPointerToObjCPointerCast;
3961 }
3962}
3963
John McCalld7646252010-11-14 08:17:51 +00003964/// Prepares for a scalar cast, performing all the necessary stages
3965/// except the final cast and returning the kind required.
John McCall9776e432011-10-06 23:25:11 +00003966CastKind Sema::PrepareScalarCast(ExprResult &Src, QualType DestTy) {
John McCalld7646252010-11-14 08:17:51 +00003967 // Both Src and Dest are scalar types, i.e. arithmetic or pointer.
3968 // Also, callers should have filtered out the invalid cases with
3969 // pointers. Everything else should be possible.
3970
John Wiegley01296292011-04-08 18:41:53 +00003971 QualType SrcTy = Src.get()->getType();
David Chisnallfa35df62012-01-16 17:27:18 +00003972 if (const AtomicType *SrcAtomicTy = SrcTy->getAs<AtomicType>())
3973 SrcTy = SrcAtomicTy->getValueType();
3974 if (const AtomicType *DestAtomicTy = DestTy->getAs<AtomicType>())
3975 DestTy = DestAtomicTy->getValueType();
3976
John McCall9776e432011-10-06 23:25:11 +00003977 if (Context.hasSameUnqualifiedType(SrcTy, DestTy))
John McCalle3027922010-08-25 11:45:40 +00003978 return CK_NoOp;
Anders Carlsson094c4592009-10-18 18:12:03 +00003979
John McCall9320b872011-09-09 05:25:32 +00003980 switch (Type::ScalarTypeKind SrcKind = SrcTy->getScalarTypeKind()) {
John McCall8cb679e2010-11-15 09:13:47 +00003981 case Type::STK_MemberPointer:
3982 llvm_unreachable("member pointer type in C");
Abramo Bagnaraba854972011-01-04 09:50:03 +00003983
John McCall9320b872011-09-09 05:25:32 +00003984 case Type::STK_CPointer:
3985 case Type::STK_BlockPointer:
3986 case Type::STK_ObjCObjectPointer:
John McCall8cb679e2010-11-15 09:13:47 +00003987 switch (DestTy->getScalarTypeKind()) {
John McCall9320b872011-09-09 05:25:32 +00003988 case Type::STK_CPointer:
3989 return CK_BitCast;
3990 case Type::STK_BlockPointer:
3991 return (SrcKind == Type::STK_BlockPointer
3992 ? CK_BitCast : CK_AnyPointerToBlockPointerCast);
3993 case Type::STK_ObjCObjectPointer:
3994 if (SrcKind == Type::STK_ObjCObjectPointer)
3995 return CK_BitCast;
David Blaikie8a40f702012-01-17 06:56:22 +00003996 if (SrcKind == Type::STK_CPointer)
John McCall9320b872011-09-09 05:25:32 +00003997 return CK_CPointerToObjCPointerCast;
David Blaikie8a40f702012-01-17 06:56:22 +00003998 maybeExtendBlockObject(*this, Src);
3999 return CK_BlockPointerToObjCPointerCast;
John McCall8cb679e2010-11-15 09:13:47 +00004000 case Type::STK_Bool:
4001 return CK_PointerToBoolean;
4002 case Type::STK_Integral:
4003 return CK_PointerToIntegral;
4004 case Type::STK_Floating:
4005 case Type::STK_FloatingComplex:
4006 case Type::STK_IntegralComplex:
4007 case Type::STK_MemberPointer:
4008 llvm_unreachable("illegal cast from pointer");
4009 }
David Blaikie8a40f702012-01-17 06:56:22 +00004010 llvm_unreachable("Should have returned before this");
Kovarththanan Rajaratnamba2c6522010-03-13 10:17:05 +00004011
John McCall8cb679e2010-11-15 09:13:47 +00004012 case Type::STK_Bool: // casting from bool is like casting from an integer
4013 case Type::STK_Integral:
4014 switch (DestTy->getScalarTypeKind()) {
John McCall9320b872011-09-09 05:25:32 +00004015 case Type::STK_CPointer:
4016 case Type::STK_ObjCObjectPointer:
4017 case Type::STK_BlockPointer:
John McCall9776e432011-10-06 23:25:11 +00004018 if (Src.get()->isNullPointerConstant(Context,
Richard Trieucfc491d2011-08-02 04:35:43 +00004019 Expr::NPC_ValueDependentIsNull))
John McCalle84af4e2010-11-13 01:35:44 +00004020 return CK_NullToPointer;
John McCalle3027922010-08-25 11:45:40 +00004021 return CK_IntegralToPointer;
John McCall8cb679e2010-11-15 09:13:47 +00004022 case Type::STK_Bool:
4023 return CK_IntegralToBoolean;
4024 case Type::STK_Integral:
John McCalld7646252010-11-14 08:17:51 +00004025 return CK_IntegralCast;
John McCall8cb679e2010-11-15 09:13:47 +00004026 case Type::STK_Floating:
John McCalle3027922010-08-25 11:45:40 +00004027 return CK_IntegralToFloating;
John McCall8cb679e2010-11-15 09:13:47 +00004028 case Type::STK_IntegralComplex:
John McCall9776e432011-10-06 23:25:11 +00004029 Src = ImpCastExprToType(Src.take(),
4030 DestTy->castAs<ComplexType>()->getElementType(),
4031 CK_IntegralCast);
John McCalld7646252010-11-14 08:17:51 +00004032 return CK_IntegralRealToComplex;
John McCall8cb679e2010-11-15 09:13:47 +00004033 case Type::STK_FloatingComplex:
John McCall9776e432011-10-06 23:25:11 +00004034 Src = ImpCastExprToType(Src.take(),
4035 DestTy->castAs<ComplexType>()->getElementType(),
4036 CK_IntegralToFloating);
John McCalld7646252010-11-14 08:17:51 +00004037 return CK_FloatingRealToComplex;
John McCall8cb679e2010-11-15 09:13:47 +00004038 case Type::STK_MemberPointer:
4039 llvm_unreachable("member pointer type in C");
John McCalld7646252010-11-14 08:17:51 +00004040 }
David Blaikie8a40f702012-01-17 06:56:22 +00004041 llvm_unreachable("Should have returned before this");
Kovarththanan Rajaratnamba2c6522010-03-13 10:17:05 +00004042
John McCall8cb679e2010-11-15 09:13:47 +00004043 case Type::STK_Floating:
4044 switch (DestTy->getScalarTypeKind()) {
4045 case Type::STK_Floating:
John McCalle3027922010-08-25 11:45:40 +00004046 return CK_FloatingCast;
John McCall8cb679e2010-11-15 09:13:47 +00004047 case Type::STK_Bool:
4048 return CK_FloatingToBoolean;
4049 case Type::STK_Integral:
John McCalle3027922010-08-25 11:45:40 +00004050 return CK_FloatingToIntegral;
John McCall8cb679e2010-11-15 09:13:47 +00004051 case Type::STK_FloatingComplex:
John McCall9776e432011-10-06 23:25:11 +00004052 Src = ImpCastExprToType(Src.take(),
4053 DestTy->castAs<ComplexType>()->getElementType(),
4054 CK_FloatingCast);
John McCalld7646252010-11-14 08:17:51 +00004055 return CK_FloatingRealToComplex;
John McCall8cb679e2010-11-15 09:13:47 +00004056 case Type::STK_IntegralComplex:
John McCall9776e432011-10-06 23:25:11 +00004057 Src = ImpCastExprToType(Src.take(),
4058 DestTy->castAs<ComplexType>()->getElementType(),
4059 CK_FloatingToIntegral);
John McCalld7646252010-11-14 08:17:51 +00004060 return CK_IntegralRealToComplex;
John McCall9320b872011-09-09 05:25:32 +00004061 case Type::STK_CPointer:
4062 case Type::STK_ObjCObjectPointer:
4063 case Type::STK_BlockPointer:
John McCall8cb679e2010-11-15 09:13:47 +00004064 llvm_unreachable("valid float->pointer cast?");
4065 case Type::STK_MemberPointer:
4066 llvm_unreachable("member pointer type in C");
John McCalld7646252010-11-14 08:17:51 +00004067 }
David Blaikie8a40f702012-01-17 06:56:22 +00004068 llvm_unreachable("Should have returned before this");
John McCalld7646252010-11-14 08:17:51 +00004069
John McCall8cb679e2010-11-15 09:13:47 +00004070 case Type::STK_FloatingComplex:
4071 switch (DestTy->getScalarTypeKind()) {
4072 case Type::STK_FloatingComplex:
John McCalld7646252010-11-14 08:17:51 +00004073 return CK_FloatingComplexCast;
John McCall8cb679e2010-11-15 09:13:47 +00004074 case Type::STK_IntegralComplex:
John McCalld7646252010-11-14 08:17:51 +00004075 return CK_FloatingComplexToIntegralComplex;
John McCallfcef3cf2010-12-14 17:51:41 +00004076 case Type::STK_Floating: {
John McCall9776e432011-10-06 23:25:11 +00004077 QualType ET = SrcTy->castAs<ComplexType>()->getElementType();
4078 if (Context.hasSameType(ET, DestTy))
John McCallfcef3cf2010-12-14 17:51:41 +00004079 return CK_FloatingComplexToReal;
John McCall9776e432011-10-06 23:25:11 +00004080 Src = ImpCastExprToType(Src.take(), ET, CK_FloatingComplexToReal);
John McCallfcef3cf2010-12-14 17:51:41 +00004081 return CK_FloatingCast;
4082 }
John McCall8cb679e2010-11-15 09:13:47 +00004083 case Type::STK_Bool:
John McCalld7646252010-11-14 08:17:51 +00004084 return CK_FloatingComplexToBoolean;
John McCall8cb679e2010-11-15 09:13:47 +00004085 case Type::STK_Integral:
John McCall9776e432011-10-06 23:25:11 +00004086 Src = ImpCastExprToType(Src.take(),
4087 SrcTy->castAs<ComplexType>()->getElementType(),
4088 CK_FloatingComplexToReal);
John McCalld7646252010-11-14 08:17:51 +00004089 return CK_FloatingToIntegral;
John McCall9320b872011-09-09 05:25:32 +00004090 case Type::STK_CPointer:
4091 case Type::STK_ObjCObjectPointer:
4092 case Type::STK_BlockPointer:
John McCall8cb679e2010-11-15 09:13:47 +00004093 llvm_unreachable("valid complex float->pointer cast?");
4094 case Type::STK_MemberPointer:
4095 llvm_unreachable("member pointer type in C");
John McCalld7646252010-11-14 08:17:51 +00004096 }
David Blaikie8a40f702012-01-17 06:56:22 +00004097 llvm_unreachable("Should have returned before this");
John McCalld7646252010-11-14 08:17:51 +00004098
John McCall8cb679e2010-11-15 09:13:47 +00004099 case Type::STK_IntegralComplex:
4100 switch (DestTy->getScalarTypeKind()) {
4101 case Type::STK_FloatingComplex:
John McCalld7646252010-11-14 08:17:51 +00004102 return CK_IntegralComplexToFloatingComplex;
John McCall8cb679e2010-11-15 09:13:47 +00004103 case Type::STK_IntegralComplex:
John McCalld7646252010-11-14 08:17:51 +00004104 return CK_IntegralComplexCast;
John McCallfcef3cf2010-12-14 17:51:41 +00004105 case Type::STK_Integral: {
John McCall9776e432011-10-06 23:25:11 +00004106 QualType ET = SrcTy->castAs<ComplexType>()->getElementType();
4107 if (Context.hasSameType(ET, DestTy))
John McCallfcef3cf2010-12-14 17:51:41 +00004108 return CK_IntegralComplexToReal;
John McCall9776e432011-10-06 23:25:11 +00004109 Src = ImpCastExprToType(Src.take(), ET, CK_IntegralComplexToReal);
John McCallfcef3cf2010-12-14 17:51:41 +00004110 return CK_IntegralCast;
4111 }
John McCall8cb679e2010-11-15 09:13:47 +00004112 case Type::STK_Bool:
John McCalld7646252010-11-14 08:17:51 +00004113 return CK_IntegralComplexToBoolean;
John McCall8cb679e2010-11-15 09:13:47 +00004114 case Type::STK_Floating:
John McCall9776e432011-10-06 23:25:11 +00004115 Src = ImpCastExprToType(Src.take(),
4116 SrcTy->castAs<ComplexType>()->getElementType(),
4117 CK_IntegralComplexToReal);
John McCalld7646252010-11-14 08:17:51 +00004118 return CK_IntegralToFloating;
John McCall9320b872011-09-09 05:25:32 +00004119 case Type::STK_CPointer:
4120 case Type::STK_ObjCObjectPointer:
4121 case Type::STK_BlockPointer:
John McCall8cb679e2010-11-15 09:13:47 +00004122 llvm_unreachable("valid complex int->pointer cast?");
4123 case Type::STK_MemberPointer:
4124 llvm_unreachable("member pointer type in C");
John McCalld7646252010-11-14 08:17:51 +00004125 }
David Blaikie8a40f702012-01-17 06:56:22 +00004126 llvm_unreachable("Should have returned before this");
Anders Carlsson094c4592009-10-18 18:12:03 +00004127 }
Kovarththanan Rajaratnamba2c6522010-03-13 10:17:05 +00004128
John McCalld7646252010-11-14 08:17:51 +00004129 llvm_unreachable("Unhandled scalar cast");
Anders Carlsson094c4592009-10-18 18:12:03 +00004130}
4131
Anders Carlsson525b76b2009-10-16 02:48:28 +00004132bool Sema::CheckVectorCast(SourceRange R, QualType VectorTy, QualType Ty,
John McCalle3027922010-08-25 11:45:40 +00004133 CastKind &Kind) {
Anders Carlssonde71adf2007-11-27 05:51:55 +00004134 assert(VectorTy->isVectorType() && "Not a vector type!");
Mike Stump4e1f26a2009-02-19 03:04:26 +00004135
Anders Carlssonde71adf2007-11-27 05:51:55 +00004136 if (Ty->isVectorType() || Ty->isIntegerType()) {
Chris Lattner37e05872008-03-05 18:54:05 +00004137 if (Context.getTypeSize(VectorTy) != Context.getTypeSize(Ty))
Anders Carlssonde71adf2007-11-27 05:51:55 +00004138 return Diag(R.getBegin(),
Mike Stump4e1f26a2009-02-19 03:04:26 +00004139 Ty->isVectorType() ?
Anders Carlssonde71adf2007-11-27 05:51:55 +00004140 diag::err_invalid_conversion_between_vectors :
Chris Lattner3b054132008-11-19 05:08:23 +00004141 diag::err_invalid_conversion_between_vector_and_integer)
Chris Lattner1e5665e2008-11-24 06:25:27 +00004142 << VectorTy << Ty << R;
Anders Carlssonde71adf2007-11-27 05:51:55 +00004143 } else
4144 return Diag(R.getBegin(),
Chris Lattner3b054132008-11-19 05:08:23 +00004145 diag::err_invalid_conversion_between_vector_and_scalar)
Chris Lattner1e5665e2008-11-24 06:25:27 +00004146 << VectorTy << Ty << R;
Mike Stump4e1f26a2009-02-19 03:04:26 +00004147
John McCalle3027922010-08-25 11:45:40 +00004148 Kind = CK_BitCast;
Anders Carlssonde71adf2007-11-27 05:51:55 +00004149 return false;
4150}
4151
John Wiegley01296292011-04-08 18:41:53 +00004152ExprResult Sema::CheckExtVectorCast(SourceRange R, QualType DestTy,
4153 Expr *CastExpr, CastKind &Kind) {
Nate Begemanc69b7402009-06-26 00:50:28 +00004154 assert(DestTy->isExtVectorType() && "Not an extended vector type!");
Kovarththanan Rajaratnamba2c6522010-03-13 10:17:05 +00004155
Anders Carlsson43d70f82009-10-16 05:23:41 +00004156 QualType SrcTy = CastExpr->getType();
Kovarththanan Rajaratnamba2c6522010-03-13 10:17:05 +00004157
Nate Begemanc8961a42009-06-27 22:05:55 +00004158 // If SrcTy is a VectorType, the total size must match to explicitly cast to
4159 // an ExtVectorType.
Tobias Grosser766bcc22011-09-22 13:03:14 +00004160 // In OpenCL, casts between vectors of different types are not allowed.
4161 // (See OpenCL 6.2).
Nate Begemanc69b7402009-06-26 00:50:28 +00004162 if (SrcTy->isVectorType()) {
Tobias Grosser766bcc22011-09-22 13:03:14 +00004163 if (Context.getTypeSize(DestTy) != Context.getTypeSize(SrcTy)
4164 || (getLangOptions().OpenCL &&
4165 (DestTy.getCanonicalType() != SrcTy.getCanonicalType()))) {
John Wiegley01296292011-04-08 18:41:53 +00004166 Diag(R.getBegin(),diag::err_invalid_conversion_between_ext_vectors)
Nate Begemanc69b7402009-06-26 00:50:28 +00004167 << DestTy << SrcTy << R;
John Wiegley01296292011-04-08 18:41:53 +00004168 return ExprError();
4169 }
John McCalle3027922010-08-25 11:45:40 +00004170 Kind = CK_BitCast;
John Wiegley01296292011-04-08 18:41:53 +00004171 return Owned(CastExpr);
Nate Begemanc69b7402009-06-26 00:50:28 +00004172 }
4173
Nate Begemanbd956c42009-06-28 02:36:38 +00004174 // All non-pointer scalars can be cast to ExtVector type. The appropriate
Nate Begemanc69b7402009-06-26 00:50:28 +00004175 // conversion will take place first from scalar to elt type, and then
4176 // splat from elt type to vector.
Nate Begemanbd956c42009-06-28 02:36:38 +00004177 if (SrcTy->isPointerType())
4178 return Diag(R.getBegin(),
4179 diag::err_invalid_conversion_between_vector_and_scalar)
4180 << DestTy << SrcTy << R;
Eli Friedman06ed2a52009-10-20 08:27:19 +00004181
4182 QualType DestElemTy = DestTy->getAs<ExtVectorType>()->getElementType();
John Wiegley01296292011-04-08 18:41:53 +00004183 ExprResult CastExprRes = Owned(CastExpr);
John McCall9776e432011-10-06 23:25:11 +00004184 CastKind CK = PrepareScalarCast(CastExprRes, DestElemTy);
John Wiegley01296292011-04-08 18:41:53 +00004185 if (CastExprRes.isInvalid())
4186 return ExprError();
4187 CastExpr = ImpCastExprToType(CastExprRes.take(), DestElemTy, CK).take();
Kovarththanan Rajaratnamba2c6522010-03-13 10:17:05 +00004188
John McCalle3027922010-08-25 11:45:40 +00004189 Kind = CK_VectorSplat;
John Wiegley01296292011-04-08 18:41:53 +00004190 return Owned(CastExpr);
Nate Begemanc69b7402009-06-26 00:50:28 +00004191}
4192
John McCalldadc5752010-08-24 06:29:42 +00004193ExprResult
Argyrios Kyrtzidis7192a3b2011-07-01 22:22:59 +00004194Sema::ActOnCastExpr(Scope *S, SourceLocation LParenLoc,
4195 Declarator &D, ParsedType &Ty,
Richard Trieuba63ce62011-09-09 01:45:06 +00004196 SourceLocation RParenLoc, Expr *CastExpr) {
4197 assert(!D.isInvalidType() && (CastExpr != 0) &&
Sebastian Redlb5d49352009-01-19 22:31:54 +00004198 "ActOnCastExpr(): missing type or expr");
Steve Naroff1a2cf6b2007-07-16 23:25:18 +00004199
Richard Trieuba63ce62011-09-09 01:45:06 +00004200 TypeSourceInfo *castTInfo = GetTypeForDeclaratorCast(D, CastExpr->getType());
Argyrios Kyrtzidis7192a3b2011-07-01 22:22:59 +00004201 if (D.isInvalidType())
4202 return ExprError();
4203
4204 if (getLangOptions().CPlusPlus) {
4205 // Check that there are no default arguments (C++ only).
4206 CheckExtraCXXDefaultArguments(D);
4207 }
4208
John McCall42856de2011-10-01 05:17:03 +00004209 checkUnusedDeclAttributes(D);
4210
Argyrios Kyrtzidis7192a3b2011-07-01 22:22:59 +00004211 QualType castType = castTInfo->getType();
4212 Ty = CreateParsedType(castType, castTInfo);
Mike Stump11289f42009-09-09 15:08:12 +00004213
Argyrios Kyrtzidisd8701b62011-07-01 22:22:54 +00004214 bool isVectorLiteral = false;
4215
4216 // Check for an altivec or OpenCL literal,
4217 // i.e. all the elements are integer constants.
Richard Trieuba63ce62011-09-09 01:45:06 +00004218 ParenExpr *PE = dyn_cast<ParenExpr>(CastExpr);
4219 ParenListExpr *PLE = dyn_cast<ParenListExpr>(CastExpr);
Tobias Grosser0a3a22f2011-09-21 18:28:29 +00004220 if ((getLangOptions().AltiVec || getLangOptions().OpenCL)
4221 && castType->isVectorType() && (PE || PLE)) {
Argyrios Kyrtzidisd8701b62011-07-01 22:22:54 +00004222 if (PLE && PLE->getNumExprs() == 0) {
4223 Diag(PLE->getExprLoc(), diag::err_altivec_empty_initializer);
4224 return ExprError();
4225 }
4226 if (PE || PLE->getNumExprs() == 1) {
4227 Expr *E = (PE ? PE->getSubExpr() : PLE->getExpr(0));
4228 if (!E->getType()->isVectorType())
4229 isVectorLiteral = true;
4230 }
4231 else
4232 isVectorLiteral = true;
4233 }
4234
4235 // If this is a vector initializer, '(' type ')' '(' init, ..., init ')'
4236 // then handle it as such.
4237 if (isVectorLiteral)
Richard Trieuba63ce62011-09-09 01:45:06 +00004238 return BuildVectorLiteral(LParenLoc, RParenLoc, CastExpr, castTInfo);
Argyrios Kyrtzidisd8701b62011-07-01 22:22:54 +00004239
Nate Begeman5ec4b312009-08-10 23:49:36 +00004240 // If the Expr being casted is a ParenListExpr, handle it specially.
Argyrios Kyrtzidisd8701b62011-07-01 22:22:54 +00004241 // This is not an AltiVec-style cast, so turn the ParenListExpr into a
4242 // sequence of BinOp comma operators.
Richard Trieuba63ce62011-09-09 01:45:06 +00004243 if (isa<ParenListExpr>(CastExpr)) {
4244 ExprResult Result = MaybeConvertParenListExprToParenExpr(S, CastExpr);
Argyrios Kyrtzidisd8701b62011-07-01 22:22:54 +00004245 if (Result.isInvalid()) return ExprError();
Richard Trieuba63ce62011-09-09 01:45:06 +00004246 CastExpr = Result.take();
Argyrios Kyrtzidisd8701b62011-07-01 22:22:54 +00004247 }
John McCallebe54742010-01-15 18:56:44 +00004248
Richard Trieuba63ce62011-09-09 01:45:06 +00004249 return BuildCStyleCastExpr(LParenLoc, castTInfo, RParenLoc, CastExpr);
John McCallebe54742010-01-15 18:56:44 +00004250}
4251
Argyrios Kyrtzidisd8701b62011-07-01 22:22:54 +00004252ExprResult Sema::BuildVectorLiteral(SourceLocation LParenLoc,
4253 SourceLocation RParenLoc, Expr *E,
4254 TypeSourceInfo *TInfo) {
4255 assert((isa<ParenListExpr>(E) || isa<ParenExpr>(E)) &&
4256 "Expected paren or paren list expression");
4257
4258 Expr **exprs;
4259 unsigned numExprs;
4260 Expr *subExpr;
4261 if (ParenListExpr *PE = dyn_cast<ParenListExpr>(E)) {
4262 exprs = PE->getExprs();
4263 numExprs = PE->getNumExprs();
4264 } else {
4265 subExpr = cast<ParenExpr>(E)->getSubExpr();
4266 exprs = &subExpr;
4267 numExprs = 1;
4268 }
4269
4270 QualType Ty = TInfo->getType();
4271 assert(Ty->isVectorType() && "Expected vector type");
4272
Chris Lattner0e62c1c2011-07-23 10:55:15 +00004273 SmallVector<Expr *, 8> initExprs;
Tanya Lattner83559382011-07-15 23:07:01 +00004274 const VectorType *VTy = Ty->getAs<VectorType>();
4275 unsigned numElems = Ty->getAs<VectorType>()->getNumElements();
4276
Argyrios Kyrtzidisd8701b62011-07-01 22:22:54 +00004277 // '(...)' form of vector initialization in AltiVec: the number of
4278 // initializers must be one or must match the size of the vector.
4279 // If a single value is specified in the initializer then it will be
4280 // replicated to all the components of the vector
Tanya Lattner83559382011-07-15 23:07:01 +00004281 if (VTy->getVectorKind() == VectorType::AltiVecVector) {
Argyrios Kyrtzidisd8701b62011-07-01 22:22:54 +00004282 // The number of initializers must be one or must match the size of the
4283 // vector. If a single value is specified in the initializer then it will
4284 // be replicated to all the components of the vector
4285 if (numExprs == 1) {
4286 QualType ElemTy = Ty->getAs<VectorType>()->getElementType();
Richard Smith01ebacd2011-10-27 23:31:58 +00004287 ExprResult Literal = DefaultLvalueConversion(exprs[0]);
4288 if (Literal.isInvalid())
4289 return ExprError();
Argyrios Kyrtzidisd8701b62011-07-01 22:22:54 +00004290 Literal = ImpCastExprToType(Literal.take(), ElemTy,
John McCall9776e432011-10-06 23:25:11 +00004291 PrepareScalarCast(Literal, ElemTy));
Argyrios Kyrtzidisd8701b62011-07-01 22:22:54 +00004292 return BuildCStyleCastExpr(LParenLoc, TInfo, RParenLoc, Literal.take());
4293 }
4294 else if (numExprs < numElems) {
4295 Diag(E->getExprLoc(),
4296 diag::err_incorrect_number_of_vector_initializers);
4297 return ExprError();
4298 }
4299 else
Benjamin Kramer8001f742012-02-14 12:06:21 +00004300 initExprs.append(exprs, exprs + numExprs);
Argyrios Kyrtzidisd8701b62011-07-01 22:22:54 +00004301 }
Tanya Lattner83559382011-07-15 23:07:01 +00004302 else {
4303 // For OpenCL, when the number of initializers is a single value,
4304 // it will be replicated to all components of the vector.
4305 if (getLangOptions().OpenCL &&
4306 VTy->getVectorKind() == VectorType::GenericVector &&
4307 numExprs == 1) {
4308 QualType ElemTy = Ty->getAs<VectorType>()->getElementType();
Richard Smith01ebacd2011-10-27 23:31:58 +00004309 ExprResult Literal = DefaultLvalueConversion(exprs[0]);
4310 if (Literal.isInvalid())
4311 return ExprError();
Tanya Lattner83559382011-07-15 23:07:01 +00004312 Literal = ImpCastExprToType(Literal.take(), ElemTy,
John McCall9776e432011-10-06 23:25:11 +00004313 PrepareScalarCast(Literal, ElemTy));
Tanya Lattner83559382011-07-15 23:07:01 +00004314 return BuildCStyleCastExpr(LParenLoc, TInfo, RParenLoc, Literal.take());
4315 }
4316
Benjamin Kramer8001f742012-02-14 12:06:21 +00004317 initExprs.append(exprs, exprs + numExprs);
Tanya Lattner83559382011-07-15 23:07:01 +00004318 }
Argyrios Kyrtzidisd8701b62011-07-01 22:22:54 +00004319 // FIXME: This means that pretty-printing the final AST will produce curly
4320 // braces instead of the original commas.
4321 InitListExpr *initE = new (Context) InitListExpr(Context, LParenLoc,
4322 &initExprs[0],
4323 initExprs.size(), RParenLoc);
4324 initE->setType(Ty);
4325 return BuildCompoundLiteralExpr(LParenLoc, TInfo, RParenLoc, initE);
4326}
4327
Sebastian Redla9351792012-02-11 23:51:47 +00004328/// This is not an AltiVec-style cast or or C++ direct-initialization, so turn
4329/// the ParenListExpr into a sequence of comma binary operators.
John McCalldadc5752010-08-24 06:29:42 +00004330ExprResult
Richard Trieuba63ce62011-09-09 01:45:06 +00004331Sema::MaybeConvertParenListExprToParenExpr(Scope *S, Expr *OrigExpr) {
4332 ParenListExpr *E = dyn_cast<ParenListExpr>(OrigExpr);
Nate Begeman5ec4b312009-08-10 23:49:36 +00004333 if (!E)
Richard Trieuba63ce62011-09-09 01:45:06 +00004334 return Owned(OrigExpr);
Mike Stump11289f42009-09-09 15:08:12 +00004335
John McCalldadc5752010-08-24 06:29:42 +00004336 ExprResult Result(E->getExpr(0));
Mike Stump11289f42009-09-09 15:08:12 +00004337
Nate Begeman5ec4b312009-08-10 23:49:36 +00004338 for (unsigned i = 1, e = E->getNumExprs(); i != e && !Result.isInvalid(); ++i)
John McCallb268a282010-08-23 23:25:46 +00004339 Result = ActOnBinOp(S, E->getExprLoc(), tok::comma, Result.get(),
4340 E->getExpr(i));
Mike Stump11289f42009-09-09 15:08:12 +00004341
John McCallb268a282010-08-23 23:25:46 +00004342 if (Result.isInvalid()) return ExprError();
4343
4344 return ActOnParenExpr(E->getLParenLoc(), E->getRParenLoc(), Result.get());
Nate Begeman5ec4b312009-08-10 23:49:36 +00004345}
4346
Sebastian Redla9351792012-02-11 23:51:47 +00004347ExprResult Sema::ActOnParenListExpr(SourceLocation L,
4348 SourceLocation R,
4349 MultiExprArg Val) {
Nate Begeman5ec4b312009-08-10 23:49:36 +00004350 unsigned nexprs = Val.size();
4351 Expr **exprs = reinterpret_cast<Expr**>(Val.release());
Fariborz Jahanian906d8712009-11-25 01:26:41 +00004352 assert((exprs != 0) && "ActOnParenOrParenListExpr() missing expr list");
Sebastian Redla9351792012-02-11 23:51:47 +00004353 Expr *expr = new (Context) ParenListExpr(Context, L, exprs, nexprs, R);
Nate Begeman5ec4b312009-08-10 23:49:36 +00004354 return Owned(expr);
4355}
4356
Chandler Carrutha8bea4b2011-02-18 23:54:50 +00004357/// \brief Emit a specialized diagnostic when one expression is a null pointer
Richard Trieu27ae4cb2011-09-02 01:51:02 +00004358/// constant and the other is not a pointer. Returns true if a diagnostic is
4359/// emitted.
Richard Trieud33e46e2011-09-06 20:06:39 +00004360bool Sema::DiagnoseConditionalForNull(Expr *LHSExpr, Expr *RHSExpr,
Chandler Carrutha8bea4b2011-02-18 23:54:50 +00004361 SourceLocation QuestionLoc) {
Richard Trieud33e46e2011-09-06 20:06:39 +00004362 Expr *NullExpr = LHSExpr;
4363 Expr *NonPointerExpr = RHSExpr;
Chandler Carrutha8bea4b2011-02-18 23:54:50 +00004364 Expr::NullPointerConstantKind NullKind =
4365 NullExpr->isNullPointerConstant(Context,
4366 Expr::NPC_ValueDependentIsNotNull);
4367
4368 if (NullKind == Expr::NPCK_NotNull) {
Richard Trieud33e46e2011-09-06 20:06:39 +00004369 NullExpr = RHSExpr;
4370 NonPointerExpr = LHSExpr;
Chandler Carrutha8bea4b2011-02-18 23:54:50 +00004371 NullKind =
4372 NullExpr->isNullPointerConstant(Context,
4373 Expr::NPC_ValueDependentIsNotNull);
4374 }
4375
4376 if (NullKind == Expr::NPCK_NotNull)
4377 return false;
4378
4379 if (NullKind == Expr::NPCK_ZeroInteger) {
4380 // In this case, check to make sure that we got here from a "NULL"
4381 // string in the source code.
4382 NullExpr = NullExpr->IgnoreParenImpCasts();
John McCall462c0552011-03-08 07:59:04 +00004383 SourceLocation loc = NullExpr->getExprLoc();
4384 if (!findMacroSpelling(loc, "NULL"))
Chandler Carrutha8bea4b2011-02-18 23:54:50 +00004385 return false;
4386 }
4387
4388 int DiagType = (NullKind == Expr::NPCK_CXX0X_nullptr);
4389 Diag(QuestionLoc, diag::err_typecheck_cond_incompatible_operands_null)
4390 << NonPointerExpr->getType() << DiagType
4391 << NonPointerExpr->getSourceRange();
4392 return true;
4393}
4394
Richard Trieu27ae4cb2011-09-02 01:51:02 +00004395/// \brief Return false if the condition expression is valid, true otherwise.
4396static bool checkCondition(Sema &S, Expr *Cond) {
4397 QualType CondTy = Cond->getType();
4398
4399 // C99 6.5.15p2
4400 if (CondTy->isScalarType()) return false;
4401
4402 // OpenCL: Sec 6.3.i says the condition is allowed to be a vector or scalar.
4403 if (S.getLangOptions().OpenCL && CondTy->isVectorType())
4404 return false;
4405
4406 // Emit the proper error message.
4407 S.Diag(Cond->getLocStart(), S.getLangOptions().OpenCL ?
4408 diag::err_typecheck_cond_expect_scalar :
4409 diag::err_typecheck_cond_expect_scalar_or_vector)
4410 << CondTy;
4411 return true;
4412}
4413
4414/// \brief Return false if the two expressions can be converted to a vector,
4415/// true otherwise
4416static bool checkConditionalConvertScalarsToVectors(Sema &S, ExprResult &LHS,
4417 ExprResult &RHS,
4418 QualType CondTy) {
4419 // Both operands should be of scalar type.
4420 if (!LHS.get()->getType()->isScalarType()) {
4421 S.Diag(LHS.get()->getLocStart(), diag::err_typecheck_cond_expect_scalar)
4422 << CondTy;
4423 return true;
4424 }
4425 if (!RHS.get()->getType()->isScalarType()) {
4426 S.Diag(RHS.get()->getLocStart(), diag::err_typecheck_cond_expect_scalar)
4427 << CondTy;
4428 return true;
4429 }
4430
4431 // Implicity convert these scalars to the type of the condition.
4432 LHS = S.ImpCastExprToType(LHS.take(), CondTy, CK_IntegralCast);
4433 RHS = S.ImpCastExprToType(RHS.take(), CondTy, CK_IntegralCast);
4434 return false;
4435}
4436
4437/// \brief Handle when one or both operands are void type.
4438static QualType checkConditionalVoidType(Sema &S, ExprResult &LHS,
4439 ExprResult &RHS) {
4440 Expr *LHSExpr = LHS.get();
4441 Expr *RHSExpr = RHS.get();
4442
4443 if (!LHSExpr->getType()->isVoidType())
4444 S.Diag(RHSExpr->getLocStart(), diag::ext_typecheck_cond_one_void)
4445 << RHSExpr->getSourceRange();
4446 if (!RHSExpr->getType()->isVoidType())
4447 S.Diag(LHSExpr->getLocStart(), diag::ext_typecheck_cond_one_void)
4448 << LHSExpr->getSourceRange();
4449 LHS = S.ImpCastExprToType(LHS.take(), S.Context.VoidTy, CK_ToVoid);
4450 RHS = S.ImpCastExprToType(RHS.take(), S.Context.VoidTy, CK_ToVoid);
4451 return S.Context.VoidTy;
4452}
4453
4454/// \brief Return false if the NullExpr can be promoted to PointerTy,
4455/// true otherwise.
4456static bool checkConditionalNullPointer(Sema &S, ExprResult &NullExpr,
4457 QualType PointerTy) {
4458 if ((!PointerTy->isAnyPointerType() && !PointerTy->isBlockPointerType()) ||
4459 !NullExpr.get()->isNullPointerConstant(S.Context,
4460 Expr::NPC_ValueDependentIsNull))
4461 return true;
4462
4463 NullExpr = S.ImpCastExprToType(NullExpr.take(), PointerTy, CK_NullToPointer);
4464 return false;
4465}
4466
4467/// \brief Checks compatibility between two pointers and return the resulting
4468/// type.
4469static QualType checkConditionalPointerCompatibility(Sema &S, ExprResult &LHS,
4470 ExprResult &RHS,
4471 SourceLocation Loc) {
4472 QualType LHSTy = LHS.get()->getType();
4473 QualType RHSTy = RHS.get()->getType();
4474
4475 if (S.Context.hasSameType(LHSTy, RHSTy)) {
4476 // Two identical pointers types are always compatible.
4477 return LHSTy;
4478 }
4479
4480 QualType lhptee, rhptee;
4481
4482 // Get the pointee types.
John McCall9320b872011-09-09 05:25:32 +00004483 if (const BlockPointerType *LHSBTy = LHSTy->getAs<BlockPointerType>()) {
4484 lhptee = LHSBTy->getPointeeType();
4485 rhptee = RHSTy->castAs<BlockPointerType>()->getPointeeType();
Richard Trieu27ae4cb2011-09-02 01:51:02 +00004486 } else {
John McCall9320b872011-09-09 05:25:32 +00004487 lhptee = LHSTy->castAs<PointerType>()->getPointeeType();
4488 rhptee = RHSTy->castAs<PointerType>()->getPointeeType();
Richard Trieu27ae4cb2011-09-02 01:51:02 +00004489 }
4490
4491 if (!S.Context.typesAreCompatible(lhptee.getUnqualifiedType(),
4492 rhptee.getUnqualifiedType())) {
4493 S.Diag(Loc, diag::warn_typecheck_cond_incompatible_pointers)
4494 << LHSTy << RHSTy << LHS.get()->getSourceRange()
4495 << RHS.get()->getSourceRange();
4496 // In this situation, we assume void* type. No especially good
4497 // reason, but this is what gcc does, and we do have to pick
4498 // to get a consistent AST.
4499 QualType incompatTy = S.Context.getPointerType(S.Context.VoidTy);
4500 LHS = S.ImpCastExprToType(LHS.take(), incompatTy, CK_BitCast);
4501 RHS = S.ImpCastExprToType(RHS.take(), incompatTy, CK_BitCast);
4502 return incompatTy;
4503 }
4504
4505 // The pointer types are compatible.
4506 // C99 6.5.15p6: If both operands are pointers to compatible types *or* to
4507 // differently qualified versions of compatible types, the result type is
4508 // a pointer to an appropriately qualified version of the *composite*
4509 // type.
4510 // FIXME: Need to calculate the composite type.
4511 // FIXME: Need to add qualifiers
4512
4513 LHS = S.ImpCastExprToType(LHS.take(), LHSTy, CK_BitCast);
4514 RHS = S.ImpCastExprToType(RHS.take(), LHSTy, CK_BitCast);
4515 return LHSTy;
4516}
4517
4518/// \brief Return the resulting type when the operands are both block pointers.
4519static QualType checkConditionalBlockPointerCompatibility(Sema &S,
4520 ExprResult &LHS,
4521 ExprResult &RHS,
4522 SourceLocation Loc) {
4523 QualType LHSTy = LHS.get()->getType();
4524 QualType RHSTy = RHS.get()->getType();
4525
4526 if (!LHSTy->isBlockPointerType() || !RHSTy->isBlockPointerType()) {
4527 if (LHSTy->isVoidPointerType() || RHSTy->isVoidPointerType()) {
4528 QualType destType = S.Context.getPointerType(S.Context.VoidTy);
4529 LHS = S.ImpCastExprToType(LHS.take(), destType, CK_BitCast);
4530 RHS = S.ImpCastExprToType(RHS.take(), destType, CK_BitCast);
4531 return destType;
4532 }
4533 S.Diag(Loc, diag::err_typecheck_cond_incompatible_operands)
4534 << LHSTy << RHSTy << LHS.get()->getSourceRange()
4535 << RHS.get()->getSourceRange();
4536 return QualType();
4537 }
4538
4539 // We have 2 block pointer types.
4540 return checkConditionalPointerCompatibility(S, LHS, RHS, Loc);
4541}
4542
4543/// \brief Return the resulting type when the operands are both pointers.
4544static QualType
4545checkConditionalObjectPointersCompatibility(Sema &S, ExprResult &LHS,
4546 ExprResult &RHS,
4547 SourceLocation Loc) {
4548 // get the pointer types
4549 QualType LHSTy = LHS.get()->getType();
4550 QualType RHSTy = RHS.get()->getType();
4551
4552 // get the "pointed to" types
4553 QualType lhptee = LHSTy->getAs<PointerType>()->getPointeeType();
4554 QualType rhptee = RHSTy->getAs<PointerType>()->getPointeeType();
4555
4556 // ignore qualifiers on void (C99 6.5.15p3, clause 6)
4557 if (lhptee->isVoidType() && rhptee->isIncompleteOrObjectType()) {
4558 // Figure out necessary qualifiers (C99 6.5.15p6)
4559 QualType destPointee
4560 = S.Context.getQualifiedType(lhptee, rhptee.getQualifiers());
4561 QualType destType = S.Context.getPointerType(destPointee);
4562 // Add qualifiers if necessary.
4563 LHS = S.ImpCastExprToType(LHS.take(), destType, CK_NoOp);
4564 // Promote to void*.
4565 RHS = S.ImpCastExprToType(RHS.take(), destType, CK_BitCast);
4566 return destType;
4567 }
4568 if (rhptee->isVoidType() && lhptee->isIncompleteOrObjectType()) {
4569 QualType destPointee
4570 = S.Context.getQualifiedType(rhptee, lhptee.getQualifiers());
4571 QualType destType = S.Context.getPointerType(destPointee);
4572 // Add qualifiers if necessary.
4573 RHS = S.ImpCastExprToType(RHS.take(), destType, CK_NoOp);
4574 // Promote to void*.
4575 LHS = S.ImpCastExprToType(LHS.take(), destType, CK_BitCast);
4576 return destType;
4577 }
4578
4579 return checkConditionalPointerCompatibility(S, LHS, RHS, Loc);
4580}
4581
4582/// \brief Return false if the first expression is not an integer and the second
4583/// expression is not a pointer, true otherwise.
4584static bool checkPointerIntegerMismatch(Sema &S, ExprResult &Int,
4585 Expr* PointerExpr, SourceLocation Loc,
Richard Trieuba63ce62011-09-09 01:45:06 +00004586 bool IsIntFirstExpr) {
Richard Trieu27ae4cb2011-09-02 01:51:02 +00004587 if (!PointerExpr->getType()->isPointerType() ||
4588 !Int.get()->getType()->isIntegerType())
4589 return false;
4590
Richard Trieuba63ce62011-09-09 01:45:06 +00004591 Expr *Expr1 = IsIntFirstExpr ? Int.get() : PointerExpr;
4592 Expr *Expr2 = IsIntFirstExpr ? PointerExpr : Int.get();
Richard Trieu27ae4cb2011-09-02 01:51:02 +00004593
4594 S.Diag(Loc, diag::warn_typecheck_cond_pointer_integer_mismatch)
4595 << Expr1->getType() << Expr2->getType()
4596 << Expr1->getSourceRange() << Expr2->getSourceRange();
4597 Int = S.ImpCastExprToType(Int.take(), PointerExpr->getType(),
4598 CK_IntegralToPointer);
4599 return true;
4600}
4601
Richard Trieud33e46e2011-09-06 20:06:39 +00004602/// Note that LHS is not null here, even if this is the gnu "x ?: y" extension.
4603/// In that case, LHS = cond.
Chris Lattner2c486602009-02-18 04:38:20 +00004604/// C99 6.5.15
Richard Trieucfc491d2011-08-02 04:35:43 +00004605QualType Sema::CheckConditionalOperands(ExprResult &Cond, ExprResult &LHS,
4606 ExprResult &RHS, ExprValueKind &VK,
4607 ExprObjectKind &OK,
Chris Lattner2c486602009-02-18 04:38:20 +00004608 SourceLocation QuestionLoc) {
Douglas Gregor1beec452011-03-12 01:48:56 +00004609
Richard Trieud33e46e2011-09-06 20:06:39 +00004610 ExprResult LHSResult = CheckPlaceholderExpr(LHS.get());
4611 if (!LHSResult.isUsable()) return QualType();
4612 LHS = move(LHSResult);
Douglas Gregor0124e9b2010-11-09 21:07:58 +00004613
Richard Trieud33e46e2011-09-06 20:06:39 +00004614 ExprResult RHSResult = CheckPlaceholderExpr(RHS.get());
4615 if (!RHSResult.isUsable()) return QualType();
4616 RHS = move(RHSResult);
Douglas Gregor0124e9b2010-11-09 21:07:58 +00004617
Sebastian Redl1a99f442009-04-16 17:51:27 +00004618 // C++ is sufficiently different to merit its own checker.
4619 if (getLangOptions().CPlusPlus)
John McCallc07a0c72011-02-17 10:25:35 +00004620 return CXXCheckConditionalOperands(Cond, LHS, RHS, VK, OK, QuestionLoc);
John McCall7decc9e2010-11-18 06:31:45 +00004621
4622 VK = VK_RValue;
John McCall4bc41ae2010-11-18 19:01:18 +00004623 OK = OK_Ordinary;
Sebastian Redl1a99f442009-04-16 17:51:27 +00004624
John Wiegley01296292011-04-08 18:41:53 +00004625 Cond = UsualUnaryConversions(Cond.take());
4626 if (Cond.isInvalid())
4627 return QualType();
4628 LHS = UsualUnaryConversions(LHS.take());
4629 if (LHS.isInvalid())
4630 return QualType();
4631 RHS = UsualUnaryConversions(RHS.take());
4632 if (RHS.isInvalid())
4633 return QualType();
4634
4635 QualType CondTy = Cond.get()->getType();
4636 QualType LHSTy = LHS.get()->getType();
4637 QualType RHSTy = RHS.get()->getType();
Steve Naroff31090012007-07-16 21:54:35 +00004638
Steve Naroffa78fe7e2007-05-16 19:47:19 +00004639 // first, check the condition.
Richard Trieu27ae4cb2011-09-02 01:51:02 +00004640 if (checkCondition(*this, Cond.get()))
4641 return QualType();
Mike Stump4e1f26a2009-02-19 03:04:26 +00004642
Chris Lattnere2949f42008-01-06 22:42:25 +00004643 // Now check the two expressions.
Nate Begeman5ec4b312009-08-10 23:49:36 +00004644 if (LHSTy->isVectorType() || RHSTy->isVectorType())
Eli Friedman1408bc92011-06-23 18:10:35 +00004645 return CheckVectorOperands(LHS, RHS, QuestionLoc, /*isCompAssign*/false);
Douglas Gregor4619e432008-12-05 23:32:09 +00004646
Nate Begemanabb5a732010-09-20 22:41:17 +00004647 // OpenCL: If the condition is a vector, and both operands are scalar,
4648 // attempt to implicity convert them to the vector type to act like the
4649 // built in select.
Richard Trieu27ae4cb2011-09-02 01:51:02 +00004650 if (getLangOptions().OpenCL && CondTy->isVectorType())
4651 if (checkConditionalConvertScalarsToVectors(*this, LHS, RHS, CondTy))
Nate Begemanabb5a732010-09-20 22:41:17 +00004652 return QualType();
Nate Begemanabb5a732010-09-20 22:41:17 +00004653
Chris Lattnere2949f42008-01-06 22:42:25 +00004654 // If both operands have arithmetic type, do the usual arithmetic conversions
4655 // to find a common type: C99 6.5.15p3,5.
Chris Lattner432cff52009-02-18 04:28:32 +00004656 if (LHSTy->isArithmeticType() && RHSTy->isArithmeticType()) {
4657 UsualArithmeticConversions(LHS, RHS);
John Wiegley01296292011-04-08 18:41:53 +00004658 if (LHS.isInvalid() || RHS.isInvalid())
4659 return QualType();
4660 return LHS.get()->getType();
Steve Naroffdbd9e892007-07-17 00:58:39 +00004661 }
Mike Stump4e1f26a2009-02-19 03:04:26 +00004662
Chris Lattnere2949f42008-01-06 22:42:25 +00004663 // If both operands are the same structure or union type, the result is that
4664 // type.
Ted Kremenekc23c7e62009-07-29 21:53:49 +00004665 if (const RecordType *LHSRT = LHSTy->getAs<RecordType>()) { // C99 6.5.15p3
4666 if (const RecordType *RHSRT = RHSTy->getAs<RecordType>())
Chris Lattner2ab40a62007-11-26 01:40:58 +00004667 if (LHSRT->getDecl() == RHSRT->getDecl())
Mike Stump4e1f26a2009-02-19 03:04:26 +00004668 // "If both the operands have structure or union type, the result has
Chris Lattnere2949f42008-01-06 22:42:25 +00004669 // that type." This implies that CV qualifiers are dropped.
Chris Lattner432cff52009-02-18 04:28:32 +00004670 return LHSTy.getUnqualifiedType();
Eli Friedmanba961a92009-03-23 00:24:07 +00004671 // FIXME: Type of conditional expression must be complete in C mode.
Steve Naroffa78fe7e2007-05-16 19:47:19 +00004672 }
Mike Stump4e1f26a2009-02-19 03:04:26 +00004673
Chris Lattnere2949f42008-01-06 22:42:25 +00004674 // C99 6.5.15p5: "If both operands have void type, the result has void type."
Steve Naroffbf1516c2008-05-12 21:44:38 +00004675 // The following || allows only one side to be void (a GCC-ism).
Chris Lattner432cff52009-02-18 04:28:32 +00004676 if (LHSTy->isVoidType() || RHSTy->isVoidType()) {
Richard Trieu27ae4cb2011-09-02 01:51:02 +00004677 return checkConditionalVoidType(*this, LHS, RHS);
Steve Naroffbf1516c2008-05-12 21:44:38 +00004678 }
Richard Trieu27ae4cb2011-09-02 01:51:02 +00004679
Steve Naroff039ad3c2008-01-08 01:11:38 +00004680 // C99 6.5.15p6 - "if one operand is a null pointer constant, the result has
4681 // the type of the other operand."
Richard Trieu27ae4cb2011-09-02 01:51:02 +00004682 if (!checkConditionalNullPointer(*this, RHS, LHSTy)) return LHSTy;
4683 if (!checkConditionalNullPointer(*this, LHS, RHSTy)) return RHSTy;
Kovarththanan Rajaratnamba2c6522010-03-13 10:17:05 +00004684
Fariborz Jahaniana430f712009-12-10 19:47:41 +00004685 // All objective-c pointer type analysis is done here.
4686 QualType compositeType = FindCompositeObjCPointerType(LHS, RHS,
4687 QuestionLoc);
John Wiegley01296292011-04-08 18:41:53 +00004688 if (LHS.isInvalid() || RHS.isInvalid())
4689 return QualType();
Fariborz Jahaniana430f712009-12-10 19:47:41 +00004690 if (!compositeType.isNull())
4691 return compositeType;
Kovarththanan Rajaratnamba2c6522010-03-13 10:17:05 +00004692
4693
Steve Naroff05efa972009-07-01 14:36:47 +00004694 // Handle block pointer types.
Richard Trieu27ae4cb2011-09-02 01:51:02 +00004695 if (LHSTy->isBlockPointerType() || RHSTy->isBlockPointerType())
4696 return checkConditionalBlockPointerCompatibility(*this, LHS, RHS,
4697 QuestionLoc);
Kovarththanan Rajaratnamba2c6522010-03-13 10:17:05 +00004698
Steve Naroff05efa972009-07-01 14:36:47 +00004699 // Check constraints for C object pointers types (C99 6.5.15p3,6).
Richard Trieu27ae4cb2011-09-02 01:51:02 +00004700 if (LHSTy->isPointerType() && RHSTy->isPointerType())
4701 return checkConditionalObjectPointersCompatibility(*this, LHS, RHS,
4702 QuestionLoc);
Mike Stump11289f42009-09-09 15:08:12 +00004703
John McCalle84af4e2010-11-13 01:35:44 +00004704 // GCC compatibility: soften pointer/integer mismatch. Note that
4705 // null pointers have been filtered out by this point.
Richard Trieu27ae4cb2011-09-02 01:51:02 +00004706 if (checkPointerIntegerMismatch(*this, LHS, RHS.get(), QuestionLoc,
4707 /*isIntFirstExpr=*/true))
Steve Naroff05efa972009-07-01 14:36:47 +00004708 return RHSTy;
Richard Trieu27ae4cb2011-09-02 01:51:02 +00004709 if (checkPointerIntegerMismatch(*this, RHS, LHS.get(), QuestionLoc,
4710 /*isIntFirstExpr=*/false))
Steve Naroff05efa972009-07-01 14:36:47 +00004711 return LHSTy;
Daniel Dunbar484603b2008-09-11 23:12:46 +00004712
Chandler Carrutha8bea4b2011-02-18 23:54:50 +00004713 // Emit a better diagnostic if one of the expressions is a null pointer
4714 // constant and the other is not a pointer type. In this case, the user most
4715 // likely forgot to take the address of the other expression.
John Wiegley01296292011-04-08 18:41:53 +00004716 if (DiagnoseConditionalForNull(LHS.get(), RHS.get(), QuestionLoc))
Chandler Carrutha8bea4b2011-02-18 23:54:50 +00004717 return QualType();
4718
Chris Lattnere2949f42008-01-06 22:42:25 +00004719 // Otherwise, the operands are not compatible.
Chris Lattner432cff52009-02-18 04:28:32 +00004720 Diag(QuestionLoc, diag::err_typecheck_cond_incompatible_operands)
Richard Trieucfc491d2011-08-02 04:35:43 +00004721 << LHSTy << RHSTy << LHS.get()->getSourceRange()
4722 << RHS.get()->getSourceRange();
Steve Naroffa78fe7e2007-05-16 19:47:19 +00004723 return QualType();
Steve Narofff8a28c52007-05-15 20:29:32 +00004724}
4725
Fariborz Jahaniana430f712009-12-10 19:47:41 +00004726/// FindCompositeObjCPointerType - Helper method to find composite type of
4727/// two objective-c pointer types of the two input expressions.
John Wiegley01296292011-04-08 18:41:53 +00004728QualType Sema::FindCompositeObjCPointerType(ExprResult &LHS, ExprResult &RHS,
Richard Trieucfc491d2011-08-02 04:35:43 +00004729 SourceLocation QuestionLoc) {
John Wiegley01296292011-04-08 18:41:53 +00004730 QualType LHSTy = LHS.get()->getType();
4731 QualType RHSTy = RHS.get()->getType();
Kovarththanan Rajaratnamba2c6522010-03-13 10:17:05 +00004732
Fariborz Jahaniana430f712009-12-10 19:47:41 +00004733 // Handle things like Class and struct objc_class*. Here we case the result
4734 // to the pseudo-builtin, because that will be implicitly cast back to the
4735 // redefinition type if an attempt is made to access its fields.
4736 if (LHSTy->isObjCClassType() &&
Douglas Gregor97673472011-08-11 20:58:55 +00004737 (Context.hasSameType(RHSTy, Context.getObjCClassRedefinitionType()))) {
John McCall9320b872011-09-09 05:25:32 +00004738 RHS = ImpCastExprToType(RHS.take(), LHSTy, CK_CPointerToObjCPointerCast);
Fariborz Jahaniana430f712009-12-10 19:47:41 +00004739 return LHSTy;
4740 }
4741 if (RHSTy->isObjCClassType() &&
Douglas Gregor97673472011-08-11 20:58:55 +00004742 (Context.hasSameType(LHSTy, Context.getObjCClassRedefinitionType()))) {
John McCall9320b872011-09-09 05:25:32 +00004743 LHS = ImpCastExprToType(LHS.take(), RHSTy, CK_CPointerToObjCPointerCast);
Fariborz Jahaniana430f712009-12-10 19:47:41 +00004744 return RHSTy;
4745 }
4746 // And the same for struct objc_object* / id
4747 if (LHSTy->isObjCIdType() &&
Douglas Gregor97673472011-08-11 20:58:55 +00004748 (Context.hasSameType(RHSTy, Context.getObjCIdRedefinitionType()))) {
John McCall9320b872011-09-09 05:25:32 +00004749 RHS = ImpCastExprToType(RHS.take(), LHSTy, CK_CPointerToObjCPointerCast);
Fariborz Jahaniana430f712009-12-10 19:47:41 +00004750 return LHSTy;
4751 }
4752 if (RHSTy->isObjCIdType() &&
Douglas Gregor97673472011-08-11 20:58:55 +00004753 (Context.hasSameType(LHSTy, Context.getObjCIdRedefinitionType()))) {
John McCall9320b872011-09-09 05:25:32 +00004754 LHS = ImpCastExprToType(LHS.take(), RHSTy, CK_CPointerToObjCPointerCast);
Fariborz Jahaniana430f712009-12-10 19:47:41 +00004755 return RHSTy;
4756 }
4757 // And the same for struct objc_selector* / SEL
4758 if (Context.isObjCSelType(LHSTy) &&
Douglas Gregor97673472011-08-11 20:58:55 +00004759 (Context.hasSameType(RHSTy, Context.getObjCSelRedefinitionType()))) {
John Wiegley01296292011-04-08 18:41:53 +00004760 RHS = ImpCastExprToType(RHS.take(), LHSTy, CK_BitCast);
Fariborz Jahaniana430f712009-12-10 19:47:41 +00004761 return LHSTy;
4762 }
4763 if (Context.isObjCSelType(RHSTy) &&
Douglas Gregor97673472011-08-11 20:58:55 +00004764 (Context.hasSameType(LHSTy, Context.getObjCSelRedefinitionType()))) {
John Wiegley01296292011-04-08 18:41:53 +00004765 LHS = ImpCastExprToType(LHS.take(), RHSTy, CK_BitCast);
Fariborz Jahaniana430f712009-12-10 19:47:41 +00004766 return RHSTy;
4767 }
4768 // Check constraints for Objective-C object pointers types.
4769 if (LHSTy->isObjCObjectPointerType() && RHSTy->isObjCObjectPointerType()) {
Kovarththanan Rajaratnamba2c6522010-03-13 10:17:05 +00004770
Fariborz Jahaniana430f712009-12-10 19:47:41 +00004771 if (Context.getCanonicalType(LHSTy) == Context.getCanonicalType(RHSTy)) {
4772 // Two identical object pointer types are always compatible.
4773 return LHSTy;
4774 }
John McCall9320b872011-09-09 05:25:32 +00004775 const ObjCObjectPointerType *LHSOPT = LHSTy->castAs<ObjCObjectPointerType>();
4776 const ObjCObjectPointerType *RHSOPT = RHSTy->castAs<ObjCObjectPointerType>();
Fariborz Jahaniana430f712009-12-10 19:47:41 +00004777 QualType compositeType = LHSTy;
Kovarththanan Rajaratnamba2c6522010-03-13 10:17:05 +00004778
Fariborz Jahaniana430f712009-12-10 19:47:41 +00004779 // If both operands are interfaces and either operand can be
4780 // assigned to the other, use that type as the composite
4781 // type. This allows
4782 // xxx ? (A*) a : (B*) b
4783 // where B is a subclass of A.
4784 //
4785 // Additionally, as for assignment, if either type is 'id'
4786 // allow silent coercion. Finally, if the types are
4787 // incompatible then make sure to use 'id' as the composite
4788 // type so the result is acceptable for sending messages to.
Kovarththanan Rajaratnamba2c6522010-03-13 10:17:05 +00004789
Fariborz Jahaniana430f712009-12-10 19:47:41 +00004790 // FIXME: Consider unifying with 'areComparableObjCPointerTypes'.
4791 // It could return the composite type.
4792 if (Context.canAssignObjCInterfaces(LHSOPT, RHSOPT)) {
4793 compositeType = RHSOPT->isObjCBuiltinType() ? RHSTy : LHSTy;
4794 } else if (Context.canAssignObjCInterfaces(RHSOPT, LHSOPT)) {
4795 compositeType = LHSOPT->isObjCBuiltinType() ? LHSTy : RHSTy;
4796 } else if ((LHSTy->isObjCQualifiedIdType() ||
4797 RHSTy->isObjCQualifiedIdType()) &&
4798 Context.ObjCQualifiedIdTypesAreCompatible(LHSTy, RHSTy, true)) {
4799 // Need to handle "id<xx>" explicitly.
4800 // GCC allows qualified id and any Objective-C type to devolve to
4801 // id. Currently localizing to here until clear this should be
4802 // part of ObjCQualifiedIdTypesAreCompatible.
4803 compositeType = Context.getObjCIdType();
4804 } else if (LHSTy->isObjCIdType() || RHSTy->isObjCIdType()) {
4805 compositeType = Context.getObjCIdType();
Kovarththanan Rajaratnamba2c6522010-03-13 10:17:05 +00004806 } else if (!(compositeType =
Fariborz Jahaniana430f712009-12-10 19:47:41 +00004807 Context.areCommonBaseCompatible(LHSOPT, RHSOPT)).isNull())
4808 ;
4809 else {
4810 Diag(QuestionLoc, diag::ext_typecheck_cond_incompatible_operands)
4811 << LHSTy << RHSTy
John Wiegley01296292011-04-08 18:41:53 +00004812 << LHS.get()->getSourceRange() << RHS.get()->getSourceRange();
Fariborz Jahaniana430f712009-12-10 19:47:41 +00004813 QualType incompatTy = Context.getObjCIdType();
John Wiegley01296292011-04-08 18:41:53 +00004814 LHS = ImpCastExprToType(LHS.take(), incompatTy, CK_BitCast);
4815 RHS = ImpCastExprToType(RHS.take(), incompatTy, CK_BitCast);
Fariborz Jahaniana430f712009-12-10 19:47:41 +00004816 return incompatTy;
4817 }
4818 // The object pointer types are compatible.
John Wiegley01296292011-04-08 18:41:53 +00004819 LHS = ImpCastExprToType(LHS.take(), compositeType, CK_BitCast);
4820 RHS = ImpCastExprToType(RHS.take(), compositeType, CK_BitCast);
Fariborz Jahaniana430f712009-12-10 19:47:41 +00004821 return compositeType;
4822 }
4823 // Check Objective-C object pointer types and 'void *'
4824 if (LHSTy->isVoidPointerType() && RHSTy->isObjCObjectPointerType()) {
Eli Friedman8a78a582012-02-25 00:23:44 +00004825 if (getLangOptions().ObjCAutoRefCount) {
4826 // ARC forbids the implicit conversion of object pointers to 'void *',
4827 // so these types are not compatible.
4828 Diag(QuestionLoc, diag::err_cond_voidptr_arc) << LHSTy << RHSTy
4829 << LHS.get()->getSourceRange() << RHS.get()->getSourceRange();
4830 LHS = RHS = true;
4831 return QualType();
4832 }
Fariborz Jahaniana430f712009-12-10 19:47:41 +00004833 QualType lhptee = LHSTy->getAs<PointerType>()->getPointeeType();
4834 QualType rhptee = RHSTy->getAs<ObjCObjectPointerType>()->getPointeeType();
4835 QualType destPointee
4836 = Context.getQualifiedType(lhptee, rhptee.getQualifiers());
4837 QualType destType = Context.getPointerType(destPointee);
4838 // Add qualifiers if necessary.
John Wiegley01296292011-04-08 18:41:53 +00004839 LHS = ImpCastExprToType(LHS.take(), destType, CK_NoOp);
Fariborz Jahaniana430f712009-12-10 19:47:41 +00004840 // Promote to void*.
John Wiegley01296292011-04-08 18:41:53 +00004841 RHS = ImpCastExprToType(RHS.take(), destType, CK_BitCast);
Fariborz Jahaniana430f712009-12-10 19:47:41 +00004842 return destType;
4843 }
4844 if (LHSTy->isObjCObjectPointerType() && RHSTy->isVoidPointerType()) {
Eli Friedman8a78a582012-02-25 00:23:44 +00004845 if (getLangOptions().ObjCAutoRefCount) {
4846 // ARC forbids the implicit conversion of object pointers to 'void *',
4847 // so these types are not compatible.
4848 Diag(QuestionLoc, diag::err_cond_voidptr_arc) << LHSTy << RHSTy
4849 << LHS.get()->getSourceRange() << RHS.get()->getSourceRange();
4850 LHS = RHS = true;
4851 return QualType();
4852 }
Fariborz Jahaniana430f712009-12-10 19:47:41 +00004853 QualType lhptee = LHSTy->getAs<ObjCObjectPointerType>()->getPointeeType();
4854 QualType rhptee = RHSTy->getAs<PointerType>()->getPointeeType();
4855 QualType destPointee
4856 = Context.getQualifiedType(rhptee, lhptee.getQualifiers());
4857 QualType destType = Context.getPointerType(destPointee);
4858 // Add qualifiers if necessary.
John Wiegley01296292011-04-08 18:41:53 +00004859 RHS = ImpCastExprToType(RHS.take(), destType, CK_NoOp);
Fariborz Jahaniana430f712009-12-10 19:47:41 +00004860 // Promote to void*.
John Wiegley01296292011-04-08 18:41:53 +00004861 LHS = ImpCastExprToType(LHS.take(), destType, CK_BitCast);
Fariborz Jahaniana430f712009-12-10 19:47:41 +00004862 return destType;
4863 }
4864 return QualType();
4865}
4866
Chandler Carruthb00e8c02011-06-16 01:05:14 +00004867/// SuggestParentheses - Emit a note with a fixit hint that wraps
Hans Wennborgcf9bac42011-06-03 18:00:36 +00004868/// ParenRange in parentheses.
4869static void SuggestParentheses(Sema &Self, SourceLocation Loc,
Chandler Carruthb00e8c02011-06-16 01:05:14 +00004870 const PartialDiagnostic &Note,
4871 SourceRange ParenRange) {
4872 SourceLocation EndLoc = Self.PP.getLocForEndOfToken(ParenRange.getEnd());
4873 if (ParenRange.getBegin().isFileID() && ParenRange.getEnd().isFileID() &&
4874 EndLoc.isValid()) {
4875 Self.Diag(Loc, Note)
4876 << FixItHint::CreateInsertion(ParenRange.getBegin(), "(")
4877 << FixItHint::CreateInsertion(EndLoc, ")");
4878 } else {
4879 // We can't display the parentheses, so just show the bare note.
4880 Self.Diag(Loc, Note) << ParenRange;
Hans Wennborgcf9bac42011-06-03 18:00:36 +00004881 }
Hans Wennborgcf9bac42011-06-03 18:00:36 +00004882}
4883
4884static bool IsArithmeticOp(BinaryOperatorKind Opc) {
4885 return Opc >= BO_Mul && Opc <= BO_Shr;
4886}
4887
Hans Wennborgde2e67e2011-06-09 17:06:51 +00004888/// IsArithmeticBinaryExpr - Returns true if E is an arithmetic binary
4889/// expression, either using a built-in or overloaded operator,
Richard Trieud33e46e2011-09-06 20:06:39 +00004890/// and sets *OpCode to the opcode and *RHSExprs to the right-hand side
4891/// expression.
Hans Wennborgde2e67e2011-06-09 17:06:51 +00004892static bool IsArithmeticBinaryExpr(Expr *E, BinaryOperatorKind *Opcode,
Richard Trieud33e46e2011-09-06 20:06:39 +00004893 Expr **RHSExprs) {
Hans Wennborgbe207b32011-09-12 12:07:30 +00004894 // Don't strip parenthesis: we should not warn if E is in parenthesis.
4895 E = E->IgnoreImpCasts();
Hans Wennborgde2e67e2011-06-09 17:06:51 +00004896 E = E->IgnoreConversionOperator();
Hans Wennborgbe207b32011-09-12 12:07:30 +00004897 E = E->IgnoreImpCasts();
Hans Wennborgde2e67e2011-06-09 17:06:51 +00004898
4899 // Built-in binary operator.
4900 if (BinaryOperator *OP = dyn_cast<BinaryOperator>(E)) {
4901 if (IsArithmeticOp(OP->getOpcode())) {
4902 *Opcode = OP->getOpcode();
Richard Trieud33e46e2011-09-06 20:06:39 +00004903 *RHSExprs = OP->getRHS();
Hans Wennborgde2e67e2011-06-09 17:06:51 +00004904 return true;
4905 }
4906 }
4907
4908 // Overloaded operator.
4909 if (CXXOperatorCallExpr *Call = dyn_cast<CXXOperatorCallExpr>(E)) {
4910 if (Call->getNumArgs() != 2)
4911 return false;
4912
4913 // Make sure this is really a binary operator that is safe to pass into
4914 // BinaryOperator::getOverloadedOpcode(), e.g. it's not a subscript op.
4915 OverloadedOperatorKind OO = Call->getOperator();
4916 if (OO < OO_Plus || OO > OO_Arrow)
4917 return false;
4918
4919 BinaryOperatorKind OpKind = BinaryOperator::getOverloadedOpcode(OO);
4920 if (IsArithmeticOp(OpKind)) {
4921 *Opcode = OpKind;
Richard Trieud33e46e2011-09-06 20:06:39 +00004922 *RHSExprs = Call->getArg(1);
Hans Wennborgde2e67e2011-06-09 17:06:51 +00004923 return true;
4924 }
4925 }
4926
4927 return false;
4928}
4929
Hans Wennborgcf9bac42011-06-03 18:00:36 +00004930static bool IsLogicOp(BinaryOperatorKind Opc) {
4931 return (Opc >= BO_LT && Opc <= BO_NE) || (Opc >= BO_LAnd && Opc <= BO_LOr);
4932}
4933
Hans Wennborgde2e67e2011-06-09 17:06:51 +00004934/// ExprLooksBoolean - Returns true if E looks boolean, i.e. it has boolean type
4935/// or is a logical expression such as (x==y) which has int type, but is
4936/// commonly interpreted as boolean.
4937static bool ExprLooksBoolean(Expr *E) {
4938 E = E->IgnoreParenImpCasts();
4939
4940 if (E->getType()->isBooleanType())
4941 return true;
4942 if (BinaryOperator *OP = dyn_cast<BinaryOperator>(E))
4943 return IsLogicOp(OP->getOpcode());
4944 if (UnaryOperator *OP = dyn_cast<UnaryOperator>(E))
4945 return OP->getOpcode() == UO_LNot;
4946
4947 return false;
4948}
4949
Hans Wennborgcf9bac42011-06-03 18:00:36 +00004950/// DiagnoseConditionalPrecedence - Emit a warning when a conditional operator
4951/// and binary operator are mixed in a way that suggests the programmer assumed
4952/// the conditional operator has higher precedence, for example:
4953/// "int x = a + someBinaryCondition ? 1 : 2".
4954static void DiagnoseConditionalPrecedence(Sema &Self,
4955 SourceLocation OpLoc,
Chandler Carruth08dc2ba2011-06-16 01:05:08 +00004956 Expr *Condition,
Richard Trieud33e46e2011-09-06 20:06:39 +00004957 Expr *LHSExpr,
4958 Expr *RHSExpr) {
Hans Wennborgde2e67e2011-06-09 17:06:51 +00004959 BinaryOperatorKind CondOpcode;
4960 Expr *CondRHS;
Hans Wennborgcf9bac42011-06-03 18:00:36 +00004961
Chandler Carruth08dc2ba2011-06-16 01:05:08 +00004962 if (!IsArithmeticBinaryExpr(Condition, &CondOpcode, &CondRHS))
Hans Wennborgde2e67e2011-06-09 17:06:51 +00004963 return;
4964 if (!ExprLooksBoolean(CondRHS))
4965 return;
Hans Wennborgcf9bac42011-06-03 18:00:36 +00004966
Hans Wennborgde2e67e2011-06-09 17:06:51 +00004967 // The condition is an arithmetic binary expression, with a right-
4968 // hand side that looks boolean, so warn.
Hans Wennborgcf9bac42011-06-03 18:00:36 +00004969
Chandler Carruthb00e8c02011-06-16 01:05:14 +00004970 Self.Diag(OpLoc, diag::warn_precedence_conditional)
Chandler Carruth08dc2ba2011-06-16 01:05:08 +00004971 << Condition->getSourceRange()
Hans Wennborgde2e67e2011-06-09 17:06:51 +00004972 << BinaryOperator::getOpcodeStr(CondOpcode);
Hans Wennborgcf9bac42011-06-03 18:00:36 +00004973
Chandler Carruthb00e8c02011-06-16 01:05:14 +00004974 SuggestParentheses(Self, OpLoc,
4975 Self.PDiag(diag::note_precedence_conditional_silence)
4976 << BinaryOperator::getOpcodeStr(CondOpcode),
4977 SourceRange(Condition->getLocStart(), Condition->getLocEnd()));
Chandler Carruthf51c5a52011-06-21 23:04:18 +00004978
4979 SuggestParentheses(Self, OpLoc,
4980 Self.PDiag(diag::note_precedence_conditional_first),
Richard Trieud33e46e2011-09-06 20:06:39 +00004981 SourceRange(CondRHS->getLocStart(), RHSExpr->getLocEnd()));
Hans Wennborgcf9bac42011-06-03 18:00:36 +00004982}
4983
Steve Naroff83895f72007-09-16 03:34:24 +00004984/// ActOnConditionalOp - Parse a ?: operation. Note that 'LHS' may be null
Chris Lattnere168f762006-11-10 05:29:30 +00004985/// in the case of a the GNU conditional expr extension.
John McCalldadc5752010-08-24 06:29:42 +00004986ExprResult Sema::ActOnConditionalOp(SourceLocation QuestionLoc,
John McCallc07a0c72011-02-17 10:25:35 +00004987 SourceLocation ColonLoc,
4988 Expr *CondExpr, Expr *LHSExpr,
4989 Expr *RHSExpr) {
Chris Lattner2ab40a62007-11-26 01:40:58 +00004990 // If this is the gnu "x ?: y" extension, analyze the types as though the LHS
4991 // was the condition.
John McCallc07a0c72011-02-17 10:25:35 +00004992 OpaqueValueExpr *opaqueValue = 0;
4993 Expr *commonExpr = 0;
4994 if (LHSExpr == 0) {
4995 commonExpr = CondExpr;
4996
4997 // We usually want to apply unary conversions *before* saving, except
4998 // in the special case of a C++ l-value conditional.
4999 if (!(getLangOptions().CPlusPlus
5000 && !commonExpr->isTypeDependent()
5001 && commonExpr->getValueKind() == RHSExpr->getValueKind()
5002 && commonExpr->isGLValue()
5003 && commonExpr->isOrdinaryOrBitFieldObject()
5004 && RHSExpr->isOrdinaryOrBitFieldObject()
5005 && Context.hasSameType(commonExpr->getType(), RHSExpr->getType()))) {
John Wiegley01296292011-04-08 18:41:53 +00005006 ExprResult commonRes = UsualUnaryConversions(commonExpr);
5007 if (commonRes.isInvalid())
5008 return ExprError();
5009 commonExpr = commonRes.take();
John McCallc07a0c72011-02-17 10:25:35 +00005010 }
5011
5012 opaqueValue = new (Context) OpaqueValueExpr(commonExpr->getExprLoc(),
5013 commonExpr->getType(),
5014 commonExpr->getValueKind(),
Douglas Gregor2d5aea02012-02-23 22:17:26 +00005015 commonExpr->getObjectKind(),
5016 commonExpr);
John McCallc07a0c72011-02-17 10:25:35 +00005017 LHSExpr = CondExpr = opaqueValue;
Fariborz Jahanianc6bf0bd2010-08-31 18:02:20 +00005018 }
Sebastian Redlb5d49352009-01-19 22:31:54 +00005019
John McCall7decc9e2010-11-18 06:31:45 +00005020 ExprValueKind VK = VK_RValue;
John McCall4bc41ae2010-11-18 19:01:18 +00005021 ExprObjectKind OK = OK_Ordinary;
John Wiegley01296292011-04-08 18:41:53 +00005022 ExprResult Cond = Owned(CondExpr), LHS = Owned(LHSExpr), RHS = Owned(RHSExpr);
5023 QualType result = CheckConditionalOperands(Cond, LHS, RHS,
John McCallc07a0c72011-02-17 10:25:35 +00005024 VK, OK, QuestionLoc);
John Wiegley01296292011-04-08 18:41:53 +00005025 if (result.isNull() || Cond.isInvalid() || LHS.isInvalid() ||
5026 RHS.isInvalid())
Sebastian Redlb5d49352009-01-19 22:31:54 +00005027 return ExprError();
5028
Hans Wennborgcf9bac42011-06-03 18:00:36 +00005029 DiagnoseConditionalPrecedence(*this, QuestionLoc, Cond.get(), LHS.get(),
5030 RHS.get());
5031
John McCallc07a0c72011-02-17 10:25:35 +00005032 if (!commonExpr)
John Wiegley01296292011-04-08 18:41:53 +00005033 return Owned(new (Context) ConditionalOperator(Cond.take(), QuestionLoc,
5034 LHS.take(), ColonLoc,
5035 RHS.take(), result, VK, OK));
John McCallc07a0c72011-02-17 10:25:35 +00005036
5037 return Owned(new (Context)
John Wiegley01296292011-04-08 18:41:53 +00005038 BinaryConditionalOperator(commonExpr, opaqueValue, Cond.take(), LHS.take(),
Richard Trieucfc491d2011-08-02 04:35:43 +00005039 RHS.take(), QuestionLoc, ColonLoc, result, VK,
5040 OK));
Chris Lattnere168f762006-11-10 05:29:30 +00005041}
5042
John McCallaba90822011-01-31 23:13:11 +00005043// checkPointerTypesForAssignment - This is a very tricky routine (despite
Mike Stump4e1f26a2009-02-19 03:04:26 +00005044// being closely modeled after the C99 spec:-). The odd characteristic of this
Steve Naroff3f597292007-05-11 22:18:03 +00005045// routine is it effectively iqnores the qualifiers on the top level pointee.
5046// This circumvents the usual type rules specified in 6.2.7p1 & 6.7.5.[1-3].
5047// FIXME: add a couple examples in this comment.
John McCallaba90822011-01-31 23:13:11 +00005048static Sema::AssignConvertType
Richard Trieua871b972011-09-06 20:21:22 +00005049checkPointerTypesForAssignment(Sema &S, QualType LHSType, QualType RHSType) {
5050 assert(LHSType.isCanonical() && "LHS not canonicalized!");
5051 assert(RHSType.isCanonical() && "RHS not canonicalized!");
Mike Stump4e1f26a2009-02-19 03:04:26 +00005052
Steve Naroff1f4d7272007-05-11 04:00:31 +00005053 // get the "pointed to" type (ignoring qualifiers at the top level)
John McCall4fff8f62011-02-01 00:10:29 +00005054 const Type *lhptee, *rhptee;
5055 Qualifiers lhq, rhq;
Richard Trieua871b972011-09-06 20:21:22 +00005056 llvm::tie(lhptee, lhq) = cast<PointerType>(LHSType)->getPointeeType().split();
5057 llvm::tie(rhptee, rhq) = cast<PointerType>(RHSType)->getPointeeType().split();
Mike Stump4e1f26a2009-02-19 03:04:26 +00005058
John McCallaba90822011-01-31 23:13:11 +00005059 Sema::AssignConvertType ConvTy = Sema::Compatible;
Mike Stump4e1f26a2009-02-19 03:04:26 +00005060
5061 // C99 6.5.16.1p1: This following citation is common to constraints
5062 // 3 & 4 (below). ...and the type *pointed to* by the left has all the
5063 // qualifiers of the type *pointed to* by the right;
John McCall4fff8f62011-02-01 00:10:29 +00005064 Qualifiers lq;
5065
John McCall31168b02011-06-15 23:02:42 +00005066 // As a special case, 'non-__weak A *' -> 'non-__weak const *' is okay.
5067 if (lhq.getObjCLifetime() != rhq.getObjCLifetime() &&
5068 lhq.compatiblyIncludesObjCLifetime(rhq)) {
5069 // Ignore lifetime for further calculation.
5070 lhq.removeObjCLifetime();
5071 rhq.removeObjCLifetime();
5072 }
5073
John McCall4fff8f62011-02-01 00:10:29 +00005074 if (!lhq.compatiblyIncludes(rhq)) {
5075 // Treat address-space mismatches as fatal. TODO: address subspaces
5076 if (lhq.getAddressSpace() != rhq.getAddressSpace())
5077 ConvTy = Sema::IncompatiblePointerDiscardsQualifiers;
5078
John McCall31168b02011-06-15 23:02:42 +00005079 // It's okay to add or remove GC or lifetime qualifiers when converting to
John McCall78535952011-03-26 02:56:45 +00005080 // and from void*.
John McCall18ce25e2012-02-08 00:46:36 +00005081 else if (lhq.withoutObjCGCAttr().withoutObjCLifetime()
John McCall31168b02011-06-15 23:02:42 +00005082 .compatiblyIncludes(
John McCall18ce25e2012-02-08 00:46:36 +00005083 rhq.withoutObjCGCAttr().withoutObjCLifetime())
John McCall78535952011-03-26 02:56:45 +00005084 && (lhptee->isVoidType() || rhptee->isVoidType()))
5085 ; // keep old
5086
John McCall31168b02011-06-15 23:02:42 +00005087 // Treat lifetime mismatches as fatal.
5088 else if (lhq.getObjCLifetime() != rhq.getObjCLifetime())
5089 ConvTy = Sema::IncompatiblePointerDiscardsQualifiers;
5090
John McCall4fff8f62011-02-01 00:10:29 +00005091 // For GCC compatibility, other qualifier mismatches are treated
5092 // as still compatible in C.
5093 else ConvTy = Sema::CompatiblePointerDiscardsQualifiers;
5094 }
Steve Naroff3f597292007-05-11 22:18:03 +00005095
Mike Stump4e1f26a2009-02-19 03:04:26 +00005096 // C99 6.5.16.1p1 (constraint 4): If one operand is a pointer to an object or
5097 // incomplete type and the other is a pointer to a qualified or unqualified
Steve Naroff3f597292007-05-11 22:18:03 +00005098 // version of void...
Chris Lattner0a788432008-01-03 22:56:36 +00005099 if (lhptee->isVoidType()) {
Chris Lattnerb3a176d2008-04-02 06:59:01 +00005100 if (rhptee->isIncompleteOrObjectType())
Chris Lattner9bad62c2008-01-04 18:04:52 +00005101 return ConvTy;
Mike Stump4e1f26a2009-02-19 03:04:26 +00005102
Chris Lattner0a788432008-01-03 22:56:36 +00005103 // As an extension, we allow cast to/from void* to function pointer.
Chris Lattnerb3a176d2008-04-02 06:59:01 +00005104 assert(rhptee->isFunctionType());
John McCallaba90822011-01-31 23:13:11 +00005105 return Sema::FunctionVoidPointer;
Chris Lattner0a788432008-01-03 22:56:36 +00005106 }
Mike Stump4e1f26a2009-02-19 03:04:26 +00005107
Chris Lattner0a788432008-01-03 22:56:36 +00005108 if (rhptee->isVoidType()) {
Chris Lattnerb3a176d2008-04-02 06:59:01 +00005109 if (lhptee->isIncompleteOrObjectType())
Chris Lattner9bad62c2008-01-04 18:04:52 +00005110 return ConvTy;
Chris Lattner0a788432008-01-03 22:56:36 +00005111
5112 // As an extension, we allow cast to/from void* to function pointer.
Chris Lattnerb3a176d2008-04-02 06:59:01 +00005113 assert(lhptee->isFunctionType());
John McCallaba90822011-01-31 23:13:11 +00005114 return Sema::FunctionVoidPointer;
Chris Lattner0a788432008-01-03 22:56:36 +00005115 }
John McCall4fff8f62011-02-01 00:10:29 +00005116
Mike Stump4e1f26a2009-02-19 03:04:26 +00005117 // C99 6.5.16.1p1 (constraint 3): both operands are pointers to qualified or
Steve Naroff3f597292007-05-11 22:18:03 +00005118 // unqualified versions of compatible types, ...
John McCall4fff8f62011-02-01 00:10:29 +00005119 QualType ltrans = QualType(lhptee, 0), rtrans = QualType(rhptee, 0);
5120 if (!S.Context.typesAreCompatible(ltrans, rtrans)) {
Eli Friedman80160bd2009-03-22 23:59:44 +00005121 // Check if the pointee types are compatible ignoring the sign.
5122 // We explicitly check for char so that we catch "char" vs
5123 // "unsigned char" on systems where "char" is unsigned.
Chris Lattnerec3a1562009-10-17 20:33:28 +00005124 if (lhptee->isCharType())
John McCall4fff8f62011-02-01 00:10:29 +00005125 ltrans = S.Context.UnsignedCharTy;
Douglas Gregor5cc2c8b2010-07-23 15:58:24 +00005126 else if (lhptee->hasSignedIntegerRepresentation())
John McCall4fff8f62011-02-01 00:10:29 +00005127 ltrans = S.Context.getCorrespondingUnsignedType(ltrans);
Kovarththanan Rajaratnamba2c6522010-03-13 10:17:05 +00005128
Chris Lattnerec3a1562009-10-17 20:33:28 +00005129 if (rhptee->isCharType())
John McCall4fff8f62011-02-01 00:10:29 +00005130 rtrans = S.Context.UnsignedCharTy;
Douglas Gregor5cc2c8b2010-07-23 15:58:24 +00005131 else if (rhptee->hasSignedIntegerRepresentation())
John McCall4fff8f62011-02-01 00:10:29 +00005132 rtrans = S.Context.getCorrespondingUnsignedType(rtrans);
Chris Lattnerec3a1562009-10-17 20:33:28 +00005133
John McCall4fff8f62011-02-01 00:10:29 +00005134 if (ltrans == rtrans) {
Eli Friedman80160bd2009-03-22 23:59:44 +00005135 // Types are compatible ignoring the sign. Qualifier incompatibility
5136 // takes priority over sign incompatibility because the sign
5137 // warning can be disabled.
John McCallaba90822011-01-31 23:13:11 +00005138 if (ConvTy != Sema::Compatible)
Eli Friedman80160bd2009-03-22 23:59:44 +00005139 return ConvTy;
John McCall4fff8f62011-02-01 00:10:29 +00005140
John McCallaba90822011-01-31 23:13:11 +00005141 return Sema::IncompatiblePointerSign;
Eli Friedman80160bd2009-03-22 23:59:44 +00005142 }
Kovarththanan Rajaratnamba2c6522010-03-13 10:17:05 +00005143
Fariborz Jahaniand7aa9d82009-11-07 20:20:40 +00005144 // If we are a multi-level pointer, it's possible that our issue is simply
5145 // one of qualification - e.g. char ** -> const char ** is not allowed. If
5146 // the eventual target type is the same and the pointers have the same
5147 // level of indirection, this must be the issue.
John McCallaba90822011-01-31 23:13:11 +00005148 if (isa<PointerType>(lhptee) && isa<PointerType>(rhptee)) {
Fariborz Jahaniand7aa9d82009-11-07 20:20:40 +00005149 do {
John McCall4fff8f62011-02-01 00:10:29 +00005150 lhptee = cast<PointerType>(lhptee)->getPointeeType().getTypePtr();
5151 rhptee = cast<PointerType>(rhptee)->getPointeeType().getTypePtr();
John McCallaba90822011-01-31 23:13:11 +00005152 } while (isa<PointerType>(lhptee) && isa<PointerType>(rhptee));
Kovarththanan Rajaratnamba2c6522010-03-13 10:17:05 +00005153
John McCall4fff8f62011-02-01 00:10:29 +00005154 if (lhptee == rhptee)
John McCallaba90822011-01-31 23:13:11 +00005155 return Sema::IncompatibleNestedPointerQualifiers;
Fariborz Jahaniand7aa9d82009-11-07 20:20:40 +00005156 }
Kovarththanan Rajaratnamba2c6522010-03-13 10:17:05 +00005157
Eli Friedman80160bd2009-03-22 23:59:44 +00005158 // General pointer incompatibility takes priority over qualifiers.
John McCallaba90822011-01-31 23:13:11 +00005159 return Sema::IncompatiblePointer;
Eli Friedman80160bd2009-03-22 23:59:44 +00005160 }
Fariborz Jahanian48c69102011-10-05 00:05:34 +00005161 if (!S.getLangOptions().CPlusPlus &&
5162 S.IsNoReturnConversion(ltrans, rtrans, ltrans))
5163 return Sema::IncompatiblePointer;
Chris Lattner9bad62c2008-01-04 18:04:52 +00005164 return ConvTy;
Steve Naroff1f4d7272007-05-11 04:00:31 +00005165}
5166
John McCallaba90822011-01-31 23:13:11 +00005167/// checkBlockPointerTypesForAssignment - This routine determines whether two
Steve Naroff081c7422008-09-04 15:10:53 +00005168/// block pointer types are compatible or whether a block and normal pointer
5169/// are compatible. It is more restrict than comparing two function pointer
5170// types.
John McCallaba90822011-01-31 23:13:11 +00005171static Sema::AssignConvertType
Richard Trieua871b972011-09-06 20:21:22 +00005172checkBlockPointerTypesForAssignment(Sema &S, QualType LHSType,
5173 QualType RHSType) {
5174 assert(LHSType.isCanonical() && "LHS not canonicalized!");
5175 assert(RHSType.isCanonical() && "RHS not canonicalized!");
John McCallaba90822011-01-31 23:13:11 +00005176
Steve Naroff081c7422008-09-04 15:10:53 +00005177 QualType lhptee, rhptee;
Mike Stump4e1f26a2009-02-19 03:04:26 +00005178
Steve Naroff081c7422008-09-04 15:10:53 +00005179 // get the "pointed to" type (ignoring qualifiers at the top level)
Richard Trieua871b972011-09-06 20:21:22 +00005180 lhptee = cast<BlockPointerType>(LHSType)->getPointeeType();
5181 rhptee = cast<BlockPointerType>(RHSType)->getPointeeType();
Mike Stump4e1f26a2009-02-19 03:04:26 +00005182
John McCallaba90822011-01-31 23:13:11 +00005183 // In C++, the types have to match exactly.
5184 if (S.getLangOptions().CPlusPlus)
5185 return Sema::IncompatibleBlockPointer;
Mike Stump4e1f26a2009-02-19 03:04:26 +00005186
John McCallaba90822011-01-31 23:13:11 +00005187 Sema::AssignConvertType ConvTy = Sema::Compatible;
Mike Stump4e1f26a2009-02-19 03:04:26 +00005188
Steve Naroff081c7422008-09-04 15:10:53 +00005189 // For blocks we enforce that qualifiers are identical.
John McCallaba90822011-01-31 23:13:11 +00005190 if (lhptee.getLocalQualifiers() != rhptee.getLocalQualifiers())
5191 ConvTy = Sema::CompatiblePointerDiscardsQualifiers;
Mike Stump4e1f26a2009-02-19 03:04:26 +00005192
Richard Trieua871b972011-09-06 20:21:22 +00005193 if (!S.Context.typesAreBlockPointerCompatible(LHSType, RHSType))
John McCallaba90822011-01-31 23:13:11 +00005194 return Sema::IncompatibleBlockPointer;
5195
Steve Naroff081c7422008-09-04 15:10:53 +00005196 return ConvTy;
5197}
5198
John McCallaba90822011-01-31 23:13:11 +00005199/// checkObjCPointerTypesForAssignment - Compares two objective-c pointer types
Fariborz Jahanian410f2eb2009-12-08 18:24:49 +00005200/// for assignment compatibility.
John McCallaba90822011-01-31 23:13:11 +00005201static Sema::AssignConvertType
Richard Trieua871b972011-09-06 20:21:22 +00005202checkObjCPointerTypesForAssignment(Sema &S, QualType LHSType,
5203 QualType RHSType) {
5204 assert(LHSType.isCanonical() && "LHS was not canonicalized!");
5205 assert(RHSType.isCanonical() && "RHS was not canonicalized!");
John McCallaba90822011-01-31 23:13:11 +00005206
Richard Trieua871b972011-09-06 20:21:22 +00005207 if (LHSType->isObjCBuiltinType()) {
Fariborz Jahaniand5bb8cb2010-03-19 18:06:10 +00005208 // Class is not compatible with ObjC object pointers.
Richard Trieua871b972011-09-06 20:21:22 +00005209 if (LHSType->isObjCClassType() && !RHSType->isObjCBuiltinType() &&
5210 !RHSType->isObjCQualifiedClassType())
John McCallaba90822011-01-31 23:13:11 +00005211 return Sema::IncompatiblePointer;
5212 return Sema::Compatible;
Fariborz Jahaniand5bb8cb2010-03-19 18:06:10 +00005213 }
Richard Trieua871b972011-09-06 20:21:22 +00005214 if (RHSType->isObjCBuiltinType()) {
Richard Trieua871b972011-09-06 20:21:22 +00005215 if (RHSType->isObjCClassType() && !LHSType->isObjCBuiltinType() &&
5216 !LHSType->isObjCQualifiedClassType())
Fariborz Jahaniand923eb02011-09-15 20:40:18 +00005217 return Sema::IncompatiblePointer;
John McCallaba90822011-01-31 23:13:11 +00005218 return Sema::Compatible;
Fariborz Jahaniand5bb8cb2010-03-19 18:06:10 +00005219 }
Richard Trieua871b972011-09-06 20:21:22 +00005220 QualType lhptee = LHSType->getAs<ObjCObjectPointerType>()->getPointeeType();
5221 QualType rhptee = RHSType->getAs<ObjCObjectPointerType>()->getPointeeType();
Kovarththanan Rajaratnamba2c6522010-03-13 10:17:05 +00005222
Fariborz Jahaniane74d47e2012-01-12 22:12:08 +00005223 if (!lhptee.isAtLeastAsQualifiedAs(rhptee) &&
5224 // make an exception for id<P>
5225 !LHSType->isObjCQualifiedIdType())
John McCallaba90822011-01-31 23:13:11 +00005226 return Sema::CompatiblePointerDiscardsQualifiers;
5227
Richard Trieua871b972011-09-06 20:21:22 +00005228 if (S.Context.typesAreCompatible(LHSType, RHSType))
John McCallaba90822011-01-31 23:13:11 +00005229 return Sema::Compatible;
Richard Trieua871b972011-09-06 20:21:22 +00005230 if (LHSType->isObjCQualifiedIdType() || RHSType->isObjCQualifiedIdType())
John McCallaba90822011-01-31 23:13:11 +00005231 return Sema::IncompatibleObjCQualifiedId;
5232 return Sema::IncompatiblePointer;
Fariborz Jahanian410f2eb2009-12-08 18:24:49 +00005233}
5234
John McCall29600e12010-11-16 02:32:08 +00005235Sema::AssignConvertType
Douglas Gregorc03a1082011-01-28 02:26:04 +00005236Sema::CheckAssignmentConstraints(SourceLocation Loc,
Richard Trieua871b972011-09-06 20:21:22 +00005237 QualType LHSType, QualType RHSType) {
John McCall29600e12010-11-16 02:32:08 +00005238 // Fake up an opaque expression. We don't actually care about what
5239 // cast operations are required, so if CheckAssignmentConstraints
5240 // adds casts to this they'll be wasted, but fortunately that doesn't
5241 // usually happen on valid code.
Richard Trieua871b972011-09-06 20:21:22 +00005242 OpaqueValueExpr RHSExpr(Loc, RHSType, VK_RValue);
5243 ExprResult RHSPtr = &RHSExpr;
John McCall29600e12010-11-16 02:32:08 +00005244 CastKind K = CK_Invalid;
5245
Richard Trieua871b972011-09-06 20:21:22 +00005246 return CheckAssignmentConstraints(LHSType, RHSPtr, K);
John McCall29600e12010-11-16 02:32:08 +00005247}
5248
Mike Stump4e1f26a2009-02-19 03:04:26 +00005249/// CheckAssignmentConstraints (C99 6.5.16) - This routine currently
5250/// has code to accommodate several GCC extensions when type checking
Steve Naroff17f76e02007-05-03 21:03:48 +00005251/// pointers. Here are some objectionable examples that GCC considers warnings:
5252///
5253/// int a, *pint;
5254/// short *pshort;
5255/// struct foo *pfoo;
5256///
5257/// pint = pshort; // warning: assignment from incompatible pointer type
5258/// a = pint; // warning: assignment makes integer from pointer without a cast
5259/// pint = a; // warning: assignment makes pointer from integer without a cast
5260/// pint = pfoo; // warning: assignment from incompatible pointer type
5261///
5262/// As a result, the code for dealing with pointers is more complex than the
Mike Stump4e1f26a2009-02-19 03:04:26 +00005263/// C99 spec dictates.
Steve Naroff17f76e02007-05-03 21:03:48 +00005264///
John McCall8cb679e2010-11-15 09:13:47 +00005265/// Sets 'Kind' for any result kind except Incompatible.
Chris Lattner9bad62c2008-01-04 18:04:52 +00005266Sema::AssignConvertType
Richard Trieude4958f2011-09-06 20:30:53 +00005267Sema::CheckAssignmentConstraints(QualType LHSType, ExprResult &RHS,
John McCall8cb679e2010-11-15 09:13:47 +00005268 CastKind &Kind) {
Richard Trieude4958f2011-09-06 20:30:53 +00005269 QualType RHSType = RHS.get()->getType();
5270 QualType OrigLHSType = LHSType;
John McCall29600e12010-11-16 02:32:08 +00005271
Chris Lattnera52c2f22008-01-04 23:18:45 +00005272 // Get canonical types. We're not formatting these types, just comparing
5273 // them.
Richard Trieude4958f2011-09-06 20:30:53 +00005274 LHSType = Context.getCanonicalType(LHSType).getUnqualifiedType();
5275 RHSType = Context.getCanonicalType(RHSType).getUnqualifiedType();
Eli Friedman3360d892008-05-30 18:07:22 +00005276
Eli Friedman0dfb8892011-10-06 23:00:33 +00005277
John McCalle5255932011-01-31 22:28:28 +00005278 // Common case: no conversion required.
Richard Trieude4958f2011-09-06 20:30:53 +00005279 if (LHSType == RHSType) {
John McCall8cb679e2010-11-15 09:13:47 +00005280 Kind = CK_NoOp;
John McCall8cb679e2010-11-15 09:13:47 +00005281 return Compatible;
David Chisnall9f57c292009-08-17 16:35:33 +00005282 }
5283
David Chisnallfa35df62012-01-16 17:27:18 +00005284 if (const AtomicType *AtomicTy = dyn_cast<AtomicType>(LHSType)) {
5285 if (AtomicTy->getValueType() == RHSType) {
5286 Kind = CK_NonAtomicToAtomic;
5287 return Compatible;
5288 }
5289 }
5290
5291 if (const AtomicType *AtomicTy = dyn_cast<AtomicType>(RHSType)) {
5292 if (AtomicTy->getValueType() == LHSType) {
5293 Kind = CK_AtomicToNonAtomic;
5294 return Compatible;
5295 }
5296 }
5297
5298
Douglas Gregor6b754842008-10-28 00:22:11 +00005299 // If the left-hand side is a reference type, then we are in a
5300 // (rare!) case where we've allowed the use of references in C,
5301 // e.g., as a parameter type in a built-in function. In this case,
5302 // just make sure that the type referenced is compatible with the
5303 // right-hand side type. The caller is responsible for adjusting
Richard Trieude4958f2011-09-06 20:30:53 +00005304 // LHSType so that the resulting expression does not have reference
Douglas Gregor6b754842008-10-28 00:22:11 +00005305 // type.
Richard Trieude4958f2011-09-06 20:30:53 +00005306 if (const ReferenceType *LHSTypeRef = LHSType->getAs<ReferenceType>()) {
5307 if (Context.typesAreCompatible(LHSTypeRef->getPointeeType(), RHSType)) {
John McCall8cb679e2010-11-15 09:13:47 +00005308 Kind = CK_LValueBitCast;
Anders Carlsson24ebce62007-10-12 23:56:29 +00005309 return Compatible;
John McCall8cb679e2010-11-15 09:13:47 +00005310 }
Chris Lattnera52c2f22008-01-04 23:18:45 +00005311 return Incompatible;
Fariborz Jahaniana1e34202007-12-19 17:45:58 +00005312 }
John McCalle5255932011-01-31 22:28:28 +00005313
Nate Begemanbd956c42009-06-28 02:36:38 +00005314 // Allow scalar to ExtVector assignments, and assignments of an ExtVector type
5315 // to the same ExtVector type.
Richard Trieude4958f2011-09-06 20:30:53 +00005316 if (LHSType->isExtVectorType()) {
5317 if (RHSType->isExtVectorType())
John McCall8cb679e2010-11-15 09:13:47 +00005318 return Incompatible;
Richard Trieude4958f2011-09-06 20:30:53 +00005319 if (RHSType->isArithmeticType()) {
John McCall29600e12010-11-16 02:32:08 +00005320 // CK_VectorSplat does T -> vector T, so first cast to the
5321 // element type.
Richard Trieude4958f2011-09-06 20:30:53 +00005322 QualType elType = cast<ExtVectorType>(LHSType)->getElementType();
5323 if (elType != RHSType) {
John McCall9776e432011-10-06 23:25:11 +00005324 Kind = PrepareScalarCast(RHS, elType);
Richard Trieude4958f2011-09-06 20:30:53 +00005325 RHS = ImpCastExprToType(RHS.take(), elType, Kind);
John McCall29600e12010-11-16 02:32:08 +00005326 }
5327 Kind = CK_VectorSplat;
Nate Begemanbd956c42009-06-28 02:36:38 +00005328 return Compatible;
John McCall8cb679e2010-11-15 09:13:47 +00005329 }
Nate Begemanbd956c42009-06-28 02:36:38 +00005330 }
Mike Stump11289f42009-09-09 15:08:12 +00005331
John McCalle5255932011-01-31 22:28:28 +00005332 // Conversions to or from vector type.
Richard Trieude4958f2011-09-06 20:30:53 +00005333 if (LHSType->isVectorType() || RHSType->isVectorType()) {
5334 if (LHSType->isVectorType() && RHSType->isVectorType()) {
Bob Wilson01856f32010-12-02 00:25:15 +00005335 // Allow assignments of an AltiVec vector type to an equivalent GCC
5336 // vector type and vice versa
Richard Trieude4958f2011-09-06 20:30:53 +00005337 if (Context.areCompatibleVectorTypes(LHSType, RHSType)) {
Bob Wilson01856f32010-12-02 00:25:15 +00005338 Kind = CK_BitCast;
5339 return Compatible;
5340 }
5341
Douglas Gregor59e8b3b2010-08-06 10:14:59 +00005342 // If we are allowing lax vector conversions, and LHS and RHS are both
5343 // vectors, the total size only needs to be the same. This is a bitcast;
5344 // no bits are changed but the result type is different.
5345 if (getLangOptions().LaxVectorConversions &&
Richard Trieude4958f2011-09-06 20:30:53 +00005346 (Context.getTypeSize(LHSType) == Context.getTypeSize(RHSType))) {
John McCall3065d042010-11-15 10:08:00 +00005347 Kind = CK_BitCast;
Anders Carlssondb5a9b62009-01-30 23:17:46 +00005348 return IncompatibleVectors;
John McCall8cb679e2010-11-15 09:13:47 +00005349 }
Chris Lattner881a2122008-01-04 23:32:24 +00005350 }
5351 return Incompatible;
Mike Stump4e1f26a2009-02-19 03:04:26 +00005352 }
Eli Friedman3360d892008-05-30 18:07:22 +00005353
John McCalle5255932011-01-31 22:28:28 +00005354 // Arithmetic conversions.
Richard Trieude4958f2011-09-06 20:30:53 +00005355 if (LHSType->isArithmeticType() && RHSType->isArithmeticType() &&
5356 !(getLangOptions().CPlusPlus && LHSType->isEnumeralType())) {
John McCall9776e432011-10-06 23:25:11 +00005357 Kind = PrepareScalarCast(RHS, LHSType);
Steve Naroff98cf3e92007-06-06 18:38:38 +00005358 return Compatible;
John McCall8cb679e2010-11-15 09:13:47 +00005359 }
Eli Friedman3360d892008-05-30 18:07:22 +00005360
John McCalle5255932011-01-31 22:28:28 +00005361 // Conversions to normal pointers.
Richard Trieude4958f2011-09-06 20:30:53 +00005362 if (const PointerType *LHSPointer = dyn_cast<PointerType>(LHSType)) {
John McCalle5255932011-01-31 22:28:28 +00005363 // U* -> T*
Richard Trieude4958f2011-09-06 20:30:53 +00005364 if (isa<PointerType>(RHSType)) {
John McCall8cb679e2010-11-15 09:13:47 +00005365 Kind = CK_BitCast;
Richard Trieude4958f2011-09-06 20:30:53 +00005366 return checkPointerTypesForAssignment(*this, LHSType, RHSType);
John McCall8cb679e2010-11-15 09:13:47 +00005367 }
Mike Stump4e1f26a2009-02-19 03:04:26 +00005368
John McCalle5255932011-01-31 22:28:28 +00005369 // int -> T*
Richard Trieude4958f2011-09-06 20:30:53 +00005370 if (RHSType->isIntegerType()) {
John McCalle5255932011-01-31 22:28:28 +00005371 Kind = CK_IntegralToPointer; // FIXME: null?
5372 return IntToPointer;
Steve Naroff7cae42b2009-07-10 23:34:53 +00005373 }
John McCalle5255932011-01-31 22:28:28 +00005374
5375 // C pointers are not compatible with ObjC object pointers,
5376 // with two exceptions:
Richard Trieude4958f2011-09-06 20:30:53 +00005377 if (isa<ObjCObjectPointerType>(RHSType)) {
John McCalle5255932011-01-31 22:28:28 +00005378 // - conversions to void*
Richard Trieude4958f2011-09-06 20:30:53 +00005379 if (LHSPointer->getPointeeType()->isVoidType()) {
John McCall9320b872011-09-09 05:25:32 +00005380 Kind = CK_BitCast;
John McCalle5255932011-01-31 22:28:28 +00005381 return Compatible;
5382 }
5383
5384 // - conversions from 'Class' to the redefinition type
Richard Trieude4958f2011-09-06 20:30:53 +00005385 if (RHSType->isObjCClassType() &&
5386 Context.hasSameType(LHSType,
Douglas Gregor97673472011-08-11 20:58:55 +00005387 Context.getObjCClassRedefinitionType())) {
John McCall8cb679e2010-11-15 09:13:47 +00005388 Kind = CK_BitCast;
Douglas Gregore7dd1452008-11-27 00:44:28 +00005389 return Compatible;
John McCall8cb679e2010-11-15 09:13:47 +00005390 }
Douglas Gregor486b74e2011-09-27 16:10:05 +00005391
John McCalle5255932011-01-31 22:28:28 +00005392 Kind = CK_BitCast;
5393 return IncompatiblePointer;
5394 }
5395
5396 // U^ -> void*
Richard Trieude4958f2011-09-06 20:30:53 +00005397 if (RHSType->getAs<BlockPointerType>()) {
5398 if (LHSPointer->getPointeeType()->isVoidType()) {
John McCalle5255932011-01-31 22:28:28 +00005399 Kind = CK_BitCast;
Steve Naroff32d072c2008-09-29 18:10:17 +00005400 return Compatible;
John McCall8cb679e2010-11-15 09:13:47 +00005401 }
Steve Naroff32d072c2008-09-29 18:10:17 +00005402 }
John McCalle5255932011-01-31 22:28:28 +00005403
Steve Naroff081c7422008-09-04 15:10:53 +00005404 return Incompatible;
5405 }
5406
John McCalle5255932011-01-31 22:28:28 +00005407 // Conversions to block pointers.
Richard Trieude4958f2011-09-06 20:30:53 +00005408 if (isa<BlockPointerType>(LHSType)) {
John McCalle5255932011-01-31 22:28:28 +00005409 // U^ -> T^
Richard Trieude4958f2011-09-06 20:30:53 +00005410 if (RHSType->isBlockPointerType()) {
John McCall9320b872011-09-09 05:25:32 +00005411 Kind = CK_BitCast;
Richard Trieude4958f2011-09-06 20:30:53 +00005412 return checkBlockPointerTypesForAssignment(*this, LHSType, RHSType);
John McCalle5255932011-01-31 22:28:28 +00005413 }
5414
5415 // int or null -> T^
Richard Trieude4958f2011-09-06 20:30:53 +00005416 if (RHSType->isIntegerType()) {
John McCall8cb679e2010-11-15 09:13:47 +00005417 Kind = CK_IntegralToPointer; // FIXME: null
Eli Friedman8163b7a2009-02-25 04:20:42 +00005418 return IntToBlockPointer;
John McCall8cb679e2010-11-15 09:13:47 +00005419 }
5420
John McCalle5255932011-01-31 22:28:28 +00005421 // id -> T^
Richard Trieude4958f2011-09-06 20:30:53 +00005422 if (getLangOptions().ObjC1 && RHSType->isObjCIdType()) {
John McCalle5255932011-01-31 22:28:28 +00005423 Kind = CK_AnyPointerToBlockPointerCast;
Steve Naroff32d072c2008-09-29 18:10:17 +00005424 return Compatible;
John McCalle5255932011-01-31 22:28:28 +00005425 }
Steve Naroff32d072c2008-09-29 18:10:17 +00005426
John McCalle5255932011-01-31 22:28:28 +00005427 // void* -> T^
Richard Trieude4958f2011-09-06 20:30:53 +00005428 if (const PointerType *RHSPT = RHSType->getAs<PointerType>())
John McCalle5255932011-01-31 22:28:28 +00005429 if (RHSPT->getPointeeType()->isVoidType()) {
5430 Kind = CK_AnyPointerToBlockPointerCast;
Douglas Gregore7dd1452008-11-27 00:44:28 +00005431 return Compatible;
John McCalle5255932011-01-31 22:28:28 +00005432 }
John McCall8cb679e2010-11-15 09:13:47 +00005433
Chris Lattnera52c2f22008-01-04 23:18:45 +00005434 return Incompatible;
5435 }
5436
John McCalle5255932011-01-31 22:28:28 +00005437 // Conversions to Objective-C pointers.
Richard Trieude4958f2011-09-06 20:30:53 +00005438 if (isa<ObjCObjectPointerType>(LHSType)) {
John McCalle5255932011-01-31 22:28:28 +00005439 // A* -> B*
Richard Trieude4958f2011-09-06 20:30:53 +00005440 if (RHSType->isObjCObjectPointerType()) {
John McCalle5255932011-01-31 22:28:28 +00005441 Kind = CK_BitCast;
Fariborz Jahanian6f472e82011-07-07 18:55:47 +00005442 Sema::AssignConvertType result =
Richard Trieude4958f2011-09-06 20:30:53 +00005443 checkObjCPointerTypesForAssignment(*this, LHSType, RHSType);
Fariborz Jahanian6f472e82011-07-07 18:55:47 +00005444 if (getLangOptions().ObjCAutoRefCount &&
5445 result == Compatible &&
Richard Trieude4958f2011-09-06 20:30:53 +00005446 !CheckObjCARCUnavailableWeakConversion(OrigLHSType, RHSType))
Fariborz Jahanian7fcce682011-07-07 23:04:17 +00005447 result = IncompatibleObjCWeakRef;
Fariborz Jahanian6f472e82011-07-07 18:55:47 +00005448 return result;
John McCalle5255932011-01-31 22:28:28 +00005449 }
5450
5451 // int or null -> A*
Richard Trieude4958f2011-09-06 20:30:53 +00005452 if (RHSType->isIntegerType()) {
John McCall8cb679e2010-11-15 09:13:47 +00005453 Kind = CK_IntegralToPointer; // FIXME: null
Steve Naroff7cae42b2009-07-10 23:34:53 +00005454 return IntToPointer;
John McCall8cb679e2010-11-15 09:13:47 +00005455 }
5456
John McCalle5255932011-01-31 22:28:28 +00005457 // In general, C pointers are not compatible with ObjC object pointers,
5458 // with two exceptions:
Richard Trieude4958f2011-09-06 20:30:53 +00005459 if (isa<PointerType>(RHSType)) {
John McCall9320b872011-09-09 05:25:32 +00005460 Kind = CK_CPointerToObjCPointerCast;
5461
John McCalle5255932011-01-31 22:28:28 +00005462 // - conversions from 'void*'
Richard Trieude4958f2011-09-06 20:30:53 +00005463 if (RHSType->isVoidPointerType()) {
Steve Naroffaccc4882009-07-20 17:56:53 +00005464 return Compatible;
John McCalle5255932011-01-31 22:28:28 +00005465 }
5466
5467 // - conversions to 'Class' from its redefinition type
Richard Trieude4958f2011-09-06 20:30:53 +00005468 if (LHSType->isObjCClassType() &&
5469 Context.hasSameType(RHSType,
Douglas Gregor97673472011-08-11 20:58:55 +00005470 Context.getObjCClassRedefinitionType())) {
John McCalle5255932011-01-31 22:28:28 +00005471 return Compatible;
5472 }
5473
Steve Naroffaccc4882009-07-20 17:56:53 +00005474 return IncompatiblePointer;
Steve Naroff7cae42b2009-07-10 23:34:53 +00005475 }
John McCalle5255932011-01-31 22:28:28 +00005476
5477 // T^ -> A*
Richard Trieude4958f2011-09-06 20:30:53 +00005478 if (RHSType->isBlockPointerType()) {
John McCallcd78e802011-09-10 01:16:55 +00005479 maybeExtendBlockObject(*this, RHS);
John McCall9320b872011-09-09 05:25:32 +00005480 Kind = CK_BlockPointerToObjCPointerCast;
Steve Naroff7cae42b2009-07-10 23:34:53 +00005481 return Compatible;
John McCalle5255932011-01-31 22:28:28 +00005482 }
5483
Steve Naroff7cae42b2009-07-10 23:34:53 +00005484 return Incompatible;
5485 }
John McCalle5255932011-01-31 22:28:28 +00005486
5487 // Conversions from pointers that are not covered by the above.
Richard Trieude4958f2011-09-06 20:30:53 +00005488 if (isa<PointerType>(RHSType)) {
John McCalle5255932011-01-31 22:28:28 +00005489 // T* -> _Bool
Richard Trieude4958f2011-09-06 20:30:53 +00005490 if (LHSType == Context.BoolTy) {
John McCall8cb679e2010-11-15 09:13:47 +00005491 Kind = CK_PointerToBoolean;
Eli Friedman3360d892008-05-30 18:07:22 +00005492 return Compatible;
John McCall8cb679e2010-11-15 09:13:47 +00005493 }
Eli Friedman3360d892008-05-30 18:07:22 +00005494
John McCalle5255932011-01-31 22:28:28 +00005495 // T* -> int
Richard Trieude4958f2011-09-06 20:30:53 +00005496 if (LHSType->isIntegerType()) {
John McCall8cb679e2010-11-15 09:13:47 +00005497 Kind = CK_PointerToIntegral;
Chris Lattner940cfeb2008-01-04 18:22:42 +00005498 return PointerToInt;
John McCall8cb679e2010-11-15 09:13:47 +00005499 }
Mike Stump4e1f26a2009-02-19 03:04:26 +00005500
Chris Lattnera52c2f22008-01-04 23:18:45 +00005501 return Incompatible;
Chris Lattnera52c2f22008-01-04 23:18:45 +00005502 }
John McCalle5255932011-01-31 22:28:28 +00005503
5504 // Conversions from Objective-C pointers that are not covered by the above.
Richard Trieude4958f2011-09-06 20:30:53 +00005505 if (isa<ObjCObjectPointerType>(RHSType)) {
John McCalle5255932011-01-31 22:28:28 +00005506 // T* -> _Bool
Richard Trieude4958f2011-09-06 20:30:53 +00005507 if (LHSType == Context.BoolTy) {
John McCall8cb679e2010-11-15 09:13:47 +00005508 Kind = CK_PointerToBoolean;
Steve Naroff7cae42b2009-07-10 23:34:53 +00005509 return Compatible;
John McCall8cb679e2010-11-15 09:13:47 +00005510 }
Steve Naroff7cae42b2009-07-10 23:34:53 +00005511
John McCalle5255932011-01-31 22:28:28 +00005512 // T* -> int
Richard Trieude4958f2011-09-06 20:30:53 +00005513 if (LHSType->isIntegerType()) {
John McCall8cb679e2010-11-15 09:13:47 +00005514 Kind = CK_PointerToIntegral;
Steve Naroff7cae42b2009-07-10 23:34:53 +00005515 return PointerToInt;
John McCall8cb679e2010-11-15 09:13:47 +00005516 }
5517
Steve Naroff7cae42b2009-07-10 23:34:53 +00005518 return Incompatible;
5519 }
Eli Friedman3360d892008-05-30 18:07:22 +00005520
John McCalle5255932011-01-31 22:28:28 +00005521 // struct A -> struct B
Richard Trieude4958f2011-09-06 20:30:53 +00005522 if (isa<TagType>(LHSType) && isa<TagType>(RHSType)) {
5523 if (Context.typesAreCompatible(LHSType, RHSType)) {
John McCall8cb679e2010-11-15 09:13:47 +00005524 Kind = CK_NoOp;
Steve Naroff98cf3e92007-06-06 18:38:38 +00005525 return Compatible;
John McCall8cb679e2010-11-15 09:13:47 +00005526 }
Bill Wendling216423b2007-05-30 06:30:29 +00005527 }
John McCalle5255932011-01-31 22:28:28 +00005528
Steve Naroff98cf3e92007-06-06 18:38:38 +00005529 return Incompatible;
Steve Naroff9eb24652007-05-02 21:58:15 +00005530}
5531
Douglas Gregor0cfbdab2009-04-29 22:16:16 +00005532/// \brief Constructs a transparent union from an expression that is
5533/// used to initialize the transparent union.
Richard Trieucfc491d2011-08-02 04:35:43 +00005534static void ConstructTransparentUnion(Sema &S, ASTContext &C,
5535 ExprResult &EResult, QualType UnionType,
5536 FieldDecl *Field) {
Douglas Gregor0cfbdab2009-04-29 22:16:16 +00005537 // Build an initializer list that designates the appropriate member
5538 // of the transparent union.
John Wiegley01296292011-04-08 18:41:53 +00005539 Expr *E = EResult.take();
Ted Kremenekac034612010-04-13 23:39:13 +00005540 InitListExpr *Initializer = new (C) InitListExpr(C, SourceLocation(),
Ted Kremenek013041e2010-02-19 01:50:18 +00005541 &E, 1,
Douglas Gregor0cfbdab2009-04-29 22:16:16 +00005542 SourceLocation());
5543 Initializer->setType(UnionType);
5544 Initializer->setInitializedFieldInUnion(Field);
5545
5546 // Build a compound literal constructing a value of the transparent
5547 // union type from this initializer list.
John McCalle15bbff2010-01-18 19:35:47 +00005548 TypeSourceInfo *unionTInfo = C.getTrivialTypeSourceInfo(UnionType);
John Wiegley01296292011-04-08 18:41:53 +00005549 EResult = S.Owned(
5550 new (C) CompoundLiteralExpr(SourceLocation(), unionTInfo, UnionType,
5551 VK_RValue, Initializer, false));
Douglas Gregor0cfbdab2009-04-29 22:16:16 +00005552}
5553
5554Sema::AssignConvertType
Richard Trieucfc491d2011-08-02 04:35:43 +00005555Sema::CheckTransparentUnionArgumentConstraints(QualType ArgType,
Richard Trieueb299142011-09-06 20:40:12 +00005556 ExprResult &RHS) {
5557 QualType RHSType = RHS.get()->getType();
Douglas Gregor0cfbdab2009-04-29 22:16:16 +00005558
Mike Stump11289f42009-09-09 15:08:12 +00005559 // If the ArgType is a Union type, we want to handle a potential
Douglas Gregor0cfbdab2009-04-29 22:16:16 +00005560 // transparent_union GCC extension.
5561 const RecordType *UT = ArgType->getAsUnionType();
Argyrios Kyrtzidisb4b64ca2009-06-30 02:34:44 +00005562 if (!UT || !UT->getDecl()->hasAttr<TransparentUnionAttr>())
Douglas Gregor0cfbdab2009-04-29 22:16:16 +00005563 return Incompatible;
5564
5565 // The field to initialize within the transparent union.
5566 RecordDecl *UD = UT->getDecl();
5567 FieldDecl *InitField = 0;
5568 // It's compatible if the expression matches any of the fields.
Argyrios Kyrtzidiscfbfe782009-06-30 02:36:12 +00005569 for (RecordDecl::field_iterator it = UD->field_begin(),
5570 itend = UD->field_end();
Douglas Gregor0cfbdab2009-04-29 22:16:16 +00005571 it != itend; ++it) {
5572 if (it->getType()->isPointerType()) {
5573 // If the transparent union contains a pointer type, we allow:
5574 // 1) void pointer
5575 // 2) null pointer constant
Richard Trieueb299142011-09-06 20:40:12 +00005576 if (RHSType->isPointerType())
John McCall9320b872011-09-09 05:25:32 +00005577 if (RHSType->castAs<PointerType>()->getPointeeType()->isVoidType()) {
Richard Trieueb299142011-09-06 20:40:12 +00005578 RHS = ImpCastExprToType(RHS.take(), it->getType(), CK_BitCast);
Douglas Gregor0cfbdab2009-04-29 22:16:16 +00005579 InitField = *it;
5580 break;
5581 }
Mike Stump11289f42009-09-09 15:08:12 +00005582
Richard Trieueb299142011-09-06 20:40:12 +00005583 if (RHS.get()->isNullPointerConstant(Context,
5584 Expr::NPC_ValueDependentIsNull)) {
5585 RHS = ImpCastExprToType(RHS.take(), it->getType(),
5586 CK_NullToPointer);
Douglas Gregor0cfbdab2009-04-29 22:16:16 +00005587 InitField = *it;
5588 break;
5589 }
5590 }
5591
John McCall8cb679e2010-11-15 09:13:47 +00005592 CastKind Kind = CK_Invalid;
Richard Trieueb299142011-09-06 20:40:12 +00005593 if (CheckAssignmentConstraints(it->getType(), RHS, Kind)
Douglas Gregor0cfbdab2009-04-29 22:16:16 +00005594 == Compatible) {
Richard Trieueb299142011-09-06 20:40:12 +00005595 RHS = ImpCastExprToType(RHS.take(), it->getType(), Kind);
Douglas Gregor0cfbdab2009-04-29 22:16:16 +00005596 InitField = *it;
5597 break;
5598 }
5599 }
5600
5601 if (!InitField)
5602 return Incompatible;
5603
Richard Trieueb299142011-09-06 20:40:12 +00005604 ConstructTransparentUnion(*this, Context, RHS, ArgType, InitField);
Douglas Gregor0cfbdab2009-04-29 22:16:16 +00005605 return Compatible;
5606}
5607
Chris Lattner9bad62c2008-01-04 18:04:52 +00005608Sema::AssignConvertType
Sebastian Redlb49c46c2011-09-24 17:48:00 +00005609Sema::CheckSingleAssignmentConstraints(QualType LHSType, ExprResult &RHS,
5610 bool Diagnose) {
Douglas Gregor9a657932008-10-21 23:43:52 +00005611 if (getLangOptions().CPlusPlus) {
Eli Friedman0dfb8892011-10-06 23:00:33 +00005612 if (!LHSType->isRecordType() && !LHSType->isAtomicType()) {
Douglas Gregor9a657932008-10-21 23:43:52 +00005613 // C++ 5.17p3: If the left operand is not of class type, the
5614 // expression is implicitly converted (C++ 4) to the
5615 // cv-unqualified type of the left operand.
Sebastian Redlcc152642011-10-16 18:19:06 +00005616 ExprResult Res;
5617 if (Diagnose) {
5618 Res = PerformImplicitConversion(RHS.get(), LHSType.getUnqualifiedType(),
5619 AA_Assigning);
5620 } else {
5621 ImplicitConversionSequence ICS =
5622 TryImplicitConversion(RHS.get(), LHSType.getUnqualifiedType(),
5623 /*SuppressUserConversions=*/false,
5624 /*AllowExplicit=*/false,
5625 /*InOverloadResolution=*/false,
5626 /*CStyle=*/false,
5627 /*AllowObjCWritebackConversion=*/false);
5628 if (ICS.isFailure())
5629 return Incompatible;
5630 Res = PerformImplicitConversion(RHS.get(), LHSType.getUnqualifiedType(),
5631 ICS, AA_Assigning);
5632 }
John Wiegley01296292011-04-08 18:41:53 +00005633 if (Res.isInvalid())
Douglas Gregor9a657932008-10-21 23:43:52 +00005634 return Incompatible;
Fariborz Jahanian7fcce682011-07-07 23:04:17 +00005635 Sema::AssignConvertType result = Compatible;
5636 if (getLangOptions().ObjCAutoRefCount &&
Richard Trieueb299142011-09-06 20:40:12 +00005637 !CheckObjCARCUnavailableWeakConversion(LHSType,
5638 RHS.get()->getType()))
Fariborz Jahanian7fcce682011-07-07 23:04:17 +00005639 result = IncompatibleObjCWeakRef;
Richard Trieueb299142011-09-06 20:40:12 +00005640 RHS = move(Res);
Fariborz Jahanian7fcce682011-07-07 23:04:17 +00005641 return result;
Douglas Gregor9a657932008-10-21 23:43:52 +00005642 }
5643
5644 // FIXME: Currently, we fall through and treat C++ classes like C
5645 // structures.
Eli Friedman0dfb8892011-10-06 23:00:33 +00005646 // FIXME: We also fall through for atomics; not sure what should
5647 // happen there, though.
Sebastian Redlb49c46c2011-09-24 17:48:00 +00005648 }
Douglas Gregor9a657932008-10-21 23:43:52 +00005649
Steve Naroff0ee0b0a2007-11-27 17:58:44 +00005650 // C99 6.5.16.1p1: the left operand is a pointer and the right is
5651 // a null pointer constant.
Richard Trieueb299142011-09-06 20:40:12 +00005652 if ((LHSType->isPointerType() ||
5653 LHSType->isObjCObjectPointerType() ||
5654 LHSType->isBlockPointerType())
5655 && RHS.get()->isNullPointerConstant(Context,
5656 Expr::NPC_ValueDependentIsNull)) {
5657 RHS = ImpCastExprToType(RHS.take(), LHSType, CK_NullToPointer);
Steve Naroff0ee0b0a2007-11-27 17:58:44 +00005658 return Compatible;
5659 }
Mike Stump4e1f26a2009-02-19 03:04:26 +00005660
Chris Lattnere6dcd502007-10-16 02:55:40 +00005661 // This check seems unnatural, however it is necessary to ensure the proper
Steve Naroffb8ea4fb2007-07-13 23:32:42 +00005662 // conversion of functions/arrays. If the conversion were done for all
Douglas Gregora121b752009-11-03 16:56:39 +00005663 // DeclExpr's (created by ActOnIdExpression), it would mess up the unary
Nick Lewyckyef7c0ff2010-08-05 06:27:49 +00005664 // expressions that suppress this implicit conversion (&, sizeof).
Chris Lattnere6dcd502007-10-16 02:55:40 +00005665 //
Mike Stump4e1f26a2009-02-19 03:04:26 +00005666 // Suppress this for references: C++ 8.5.3p5.
Richard Trieueb299142011-09-06 20:40:12 +00005667 if (!LHSType->isReferenceType()) {
5668 RHS = DefaultFunctionArrayLvalueConversion(RHS.take());
5669 if (RHS.isInvalid())
John Wiegley01296292011-04-08 18:41:53 +00005670 return Incompatible;
5671 }
Steve Naroff0c1c7ed2007-08-24 22:33:52 +00005672
John McCall8cb679e2010-11-15 09:13:47 +00005673 CastKind Kind = CK_Invalid;
Chris Lattner9bad62c2008-01-04 18:04:52 +00005674 Sema::AssignConvertType result =
Richard Trieueb299142011-09-06 20:40:12 +00005675 CheckAssignmentConstraints(LHSType, RHS, Kind);
Mike Stump4e1f26a2009-02-19 03:04:26 +00005676
Steve Naroff0c1c7ed2007-08-24 22:33:52 +00005677 // C99 6.5.16.1p2: The value of the right operand is converted to the
5678 // type of the assignment expression.
Douglas Gregor6b754842008-10-28 00:22:11 +00005679 // CheckAssignmentConstraints allows the left-hand side to be a reference,
5680 // so that we can use references in built-in functions even in C.
5681 // The getNonReferenceType() call makes sure that the resulting expression
5682 // does not have reference type.
Richard Trieueb299142011-09-06 20:40:12 +00005683 if (result != Incompatible && RHS.get()->getType() != LHSType)
5684 RHS = ImpCastExprToType(RHS.take(),
5685 LHSType.getNonLValueExprType(Context), Kind);
Steve Naroff0c1c7ed2007-08-24 22:33:52 +00005686 return result;
Steve Naroffb8ea4fb2007-07-13 23:32:42 +00005687}
5688
Richard Trieueb299142011-09-06 20:40:12 +00005689QualType Sema::InvalidOperands(SourceLocation Loc, ExprResult &LHS,
5690 ExprResult &RHS) {
Chris Lattner377d1f82008-11-18 22:52:51 +00005691 Diag(Loc, diag::err_typecheck_invalid_operands)
Richard Trieueb299142011-09-06 20:40:12 +00005692 << LHS.get()->getType() << RHS.get()->getType()
5693 << LHS.get()->getSourceRange() << RHS.get()->getSourceRange();
Chris Lattner5c11c412007-12-12 05:47:28 +00005694 return QualType();
Steve Naroff6f49f5d2007-05-29 14:23:36 +00005695}
5696
Richard Trieu859d23f2011-09-06 21:01:04 +00005697QualType Sema::CheckVectorOperands(ExprResult &LHS, ExprResult &RHS,
Richard Trieuba63ce62011-09-09 01:45:06 +00005698 SourceLocation Loc, bool IsCompAssign) {
Richard Smith508ebf32011-10-28 03:31:48 +00005699 if (!IsCompAssign) {
5700 LHS = DefaultFunctionArrayLvalueConversion(LHS.take());
5701 if (LHS.isInvalid())
5702 return QualType();
5703 }
5704 RHS = DefaultFunctionArrayLvalueConversion(RHS.take());
5705 if (RHS.isInvalid())
5706 return QualType();
5707
Mike Stump4e1f26a2009-02-19 03:04:26 +00005708 // For conversion purposes, we ignore any qualifiers.
Nate Begeman002e4bd2008-04-04 01:30:25 +00005709 // For example, "const float" and "float" are equivalent.
Richard Trieu859d23f2011-09-06 21:01:04 +00005710 QualType LHSType =
5711 Context.getCanonicalType(LHS.get()->getType()).getUnqualifiedType();
5712 QualType RHSType =
5713 Context.getCanonicalType(RHS.get()->getType()).getUnqualifiedType();
Mike Stump4e1f26a2009-02-19 03:04:26 +00005714
Nate Begeman191a6b12008-07-14 18:02:46 +00005715 // If the vector types are identical, return.
Richard Trieu859d23f2011-09-06 21:01:04 +00005716 if (LHSType == RHSType)
5717 return LHSType;
Nate Begeman330aaa72007-12-30 02:59:45 +00005718
Douglas Gregor59e8b3b2010-08-06 10:14:59 +00005719 // Handle the case of equivalent AltiVec and GCC vector types
Richard Trieu859d23f2011-09-06 21:01:04 +00005720 if (LHSType->isVectorType() && RHSType->isVectorType() &&
5721 Context.areCompatibleVectorTypes(LHSType, RHSType)) {
5722 if (LHSType->isExtVectorType()) {
5723 RHS = ImpCastExprToType(RHS.take(), LHSType, CK_BitCast);
5724 return LHSType;
Eli Friedman1408bc92011-06-23 18:10:35 +00005725 }
5726
Richard Trieuba63ce62011-09-09 01:45:06 +00005727 if (!IsCompAssign)
Richard Trieu859d23f2011-09-06 21:01:04 +00005728 LHS = ImpCastExprToType(LHS.take(), RHSType, CK_BitCast);
5729 return RHSType;
Douglas Gregor59e8b3b2010-08-06 10:14:59 +00005730 }
5731
Eli Friedman1408bc92011-06-23 18:10:35 +00005732 if (getLangOptions().LaxVectorConversions &&
Richard Trieu859d23f2011-09-06 21:01:04 +00005733 Context.getTypeSize(LHSType) == Context.getTypeSize(RHSType)) {
Eli Friedman1408bc92011-06-23 18:10:35 +00005734 // If we are allowing lax vector conversions, and LHS and RHS are both
5735 // vectors, the total size only needs to be the same. This is a
5736 // bitcast; no bits are changed but the result type is different.
5737 // FIXME: Should we really be allowing this?
Richard Trieu859d23f2011-09-06 21:01:04 +00005738 RHS = ImpCastExprToType(RHS.take(), LHSType, CK_BitCast);
5739 return LHSType;
Eli Friedman1408bc92011-06-23 18:10:35 +00005740 }
5741
Nate Begemanbd956c42009-06-28 02:36:38 +00005742 // Canonicalize the ExtVector to the LHS, remember if we swapped so we can
5743 // swap back (so that we don't reverse the inputs to a subtract, for instance.
5744 bool swapped = false;
Richard Trieuba63ce62011-09-09 01:45:06 +00005745 if (RHSType->isExtVectorType() && !IsCompAssign) {
Nate Begemanbd956c42009-06-28 02:36:38 +00005746 swapped = true;
Richard Trieu859d23f2011-09-06 21:01:04 +00005747 std::swap(RHS, LHS);
5748 std::swap(RHSType, LHSType);
Nate Begemanbd956c42009-06-28 02:36:38 +00005749 }
Mike Stump11289f42009-09-09 15:08:12 +00005750
Nate Begeman886448d2009-06-28 19:12:57 +00005751 // Handle the case of an ext vector and scalar.
Richard Trieu859d23f2011-09-06 21:01:04 +00005752 if (const ExtVectorType *LV = LHSType->getAs<ExtVectorType>()) {
Nate Begemanbd956c42009-06-28 02:36:38 +00005753 QualType EltTy = LV->getElementType();
Richard Trieu859d23f2011-09-06 21:01:04 +00005754 if (EltTy->isIntegralType(Context) && RHSType->isIntegralType(Context)) {
5755 int order = Context.getIntegerTypeOrder(EltTy, RHSType);
John McCall8cb679e2010-11-15 09:13:47 +00005756 if (order > 0)
Richard Trieu859d23f2011-09-06 21:01:04 +00005757 RHS = ImpCastExprToType(RHS.take(), EltTy, CK_IntegralCast);
John McCall8cb679e2010-11-15 09:13:47 +00005758 if (order >= 0) {
Richard Trieu859d23f2011-09-06 21:01:04 +00005759 RHS = ImpCastExprToType(RHS.take(), LHSType, CK_VectorSplat);
5760 if (swapped) std::swap(RHS, LHS);
5761 return LHSType;
Nate Begemanbd956c42009-06-28 02:36:38 +00005762 }
5763 }
Richard Trieu859d23f2011-09-06 21:01:04 +00005764 if (EltTy->isRealFloatingType() && RHSType->isScalarType() &&
5765 RHSType->isRealFloatingType()) {
5766 int order = Context.getFloatingTypeOrder(EltTy, RHSType);
John McCall8cb679e2010-11-15 09:13:47 +00005767 if (order > 0)
Richard Trieu859d23f2011-09-06 21:01:04 +00005768 RHS = ImpCastExprToType(RHS.take(), EltTy, CK_FloatingCast);
John McCall8cb679e2010-11-15 09:13:47 +00005769 if (order >= 0) {
Richard Trieu859d23f2011-09-06 21:01:04 +00005770 RHS = ImpCastExprToType(RHS.take(), LHSType, CK_VectorSplat);
5771 if (swapped) std::swap(RHS, LHS);
5772 return LHSType;
Nate Begemanbd956c42009-06-28 02:36:38 +00005773 }
Nate Begeman330aaa72007-12-30 02:59:45 +00005774 }
5775 }
Mike Stump11289f42009-09-09 15:08:12 +00005776
Nate Begeman886448d2009-06-28 19:12:57 +00005777 // Vectors of different size or scalar and non-ext-vector are errors.
Richard Trieu859d23f2011-09-06 21:01:04 +00005778 if (swapped) std::swap(RHS, LHS);
Chris Lattner377d1f82008-11-18 22:52:51 +00005779 Diag(Loc, diag::err_typecheck_vector_not_convertable)
Richard Trieu859d23f2011-09-06 21:01:04 +00005780 << LHS.get()->getType() << RHS.get()->getType()
5781 << LHS.get()->getSourceRange() << RHS.get()->getSourceRange();
Steve Naroff84ff4b42007-07-09 21:31:10 +00005782 return QualType();
Sebastian Redl112a97662009-02-07 00:15:38 +00005783}
5784
Richard Trieuf8916e12011-09-16 00:53:10 +00005785// checkArithmeticNull - Detect when a NULL constant is used improperly in an
5786// expression. These are mainly cases where the null pointer is used as an
5787// integer instead of a pointer.
5788static void checkArithmeticNull(Sema &S, ExprResult &LHS, ExprResult &RHS,
5789 SourceLocation Loc, bool IsCompare) {
5790 // The canonical way to check for a GNU null is with isNullPointerConstant,
5791 // but we use a bit of a hack here for speed; this is a relatively
5792 // hot path, and isNullPointerConstant is slow.
5793 bool LHSNull = isa<GNUNullExpr>(LHS.get()->IgnoreParenImpCasts());
5794 bool RHSNull = isa<GNUNullExpr>(RHS.get()->IgnoreParenImpCasts());
5795
5796 QualType NonNullType = LHSNull ? RHS.get()->getType() : LHS.get()->getType();
5797
5798 // Avoid analyzing cases where the result will either be invalid (and
5799 // diagnosed as such) or entirely valid and not something to warn about.
5800 if ((!LHSNull && !RHSNull) || NonNullType->isBlockPointerType() ||
5801 NonNullType->isMemberPointerType() || NonNullType->isFunctionType())
5802 return;
5803
5804 // Comparison operations would not make sense with a null pointer no matter
5805 // what the other expression is.
5806 if (!IsCompare) {
5807 S.Diag(Loc, diag::warn_null_in_arithmetic_operation)
5808 << (LHSNull ? LHS.get()->getSourceRange() : SourceRange())
5809 << (RHSNull ? RHS.get()->getSourceRange() : SourceRange());
5810 return;
5811 }
5812
5813 // The rest of the operations only make sense with a null pointer
5814 // if the other expression is a pointer.
5815 if (LHSNull == RHSNull || NonNullType->isAnyPointerType() ||
5816 NonNullType->canDecayToPointerType())
5817 return;
5818
5819 S.Diag(Loc, diag::warn_null_in_comparison_operation)
5820 << LHSNull /* LHS is NULL */ << NonNullType
5821 << LHS.get()->getSourceRange() << RHS.get()->getSourceRange();
5822}
5823
Richard Trieu859d23f2011-09-06 21:01:04 +00005824QualType Sema::CheckMultiplyDivideOperands(ExprResult &LHS, ExprResult &RHS,
Richard Trieucfc491d2011-08-02 04:35:43 +00005825 SourceLocation Loc,
Richard Trieuba63ce62011-09-09 01:45:06 +00005826 bool IsCompAssign, bool IsDiv) {
Richard Trieuf8916e12011-09-16 00:53:10 +00005827 checkArithmeticNull(*this, LHS, RHS, Loc, /*isCompare=*/false);
5828
Richard Trieu859d23f2011-09-06 21:01:04 +00005829 if (LHS.get()->getType()->isVectorType() ||
5830 RHS.get()->getType()->isVectorType())
Richard Trieuba63ce62011-09-09 01:45:06 +00005831 return CheckVectorOperands(LHS, RHS, Loc, IsCompAssign);
Mike Stump4e1f26a2009-02-19 03:04:26 +00005832
Richard Trieuba63ce62011-09-09 01:45:06 +00005833 QualType compType = UsualArithmeticConversions(LHS, RHS, IsCompAssign);
Richard Trieu859d23f2011-09-06 21:01:04 +00005834 if (LHS.isInvalid() || RHS.isInvalid())
John Wiegley01296292011-04-08 18:41:53 +00005835 return QualType();
Mike Stump4e1f26a2009-02-19 03:04:26 +00005836
David Chisnallfa35df62012-01-16 17:27:18 +00005837
Richard Trieu859d23f2011-09-06 21:01:04 +00005838 if (!LHS.get()->getType()->isArithmeticType() ||
David Chisnallfa35df62012-01-16 17:27:18 +00005839 !RHS.get()->getType()->isArithmeticType()) {
5840 if (IsCompAssign &&
5841 LHS.get()->getType()->isAtomicType() &&
5842 RHS.get()->getType()->isArithmeticType())
5843 return compType;
Richard Trieu859d23f2011-09-06 21:01:04 +00005844 return InvalidOperands(Loc, LHS, RHS);
David Chisnallfa35df62012-01-16 17:27:18 +00005845 }
Kovarththanan Rajaratnamba2c6522010-03-13 10:17:05 +00005846
Chris Lattnerfaa54172010-01-12 21:23:57 +00005847 // Check for division by zero.
Richard Trieuba63ce62011-09-09 01:45:06 +00005848 if (IsDiv &&
Richard Trieu859d23f2011-09-06 21:01:04 +00005849 RHS.get()->isNullPointerConstant(Context,
Richard Trieucfc491d2011-08-02 04:35:43 +00005850 Expr::NPC_ValueDependentIsNotNull))
Richard Trieu859d23f2011-09-06 21:01:04 +00005851 DiagRuntimeBehavior(Loc, RHS.get(), PDiag(diag::warn_division_by_zero)
5852 << RHS.get()->getSourceRange());
Kovarththanan Rajaratnamba2c6522010-03-13 10:17:05 +00005853
Chris Lattnerfaa54172010-01-12 21:23:57 +00005854 return compType;
Steve Naroff26c8ea52007-03-21 21:08:52 +00005855}
5856
Chris Lattnerfaa54172010-01-12 21:23:57 +00005857QualType Sema::CheckRemainderOperands(
Richard Trieuba63ce62011-09-09 01:45:06 +00005858 ExprResult &LHS, ExprResult &RHS, SourceLocation Loc, bool IsCompAssign) {
Richard Trieuf8916e12011-09-16 00:53:10 +00005859 checkArithmeticNull(*this, LHS, RHS, Loc, /*isCompare=*/false);
5860
Richard Trieu859d23f2011-09-06 21:01:04 +00005861 if (LHS.get()->getType()->isVectorType() ||
5862 RHS.get()->getType()->isVectorType()) {
5863 if (LHS.get()->getType()->hasIntegerRepresentation() &&
5864 RHS.get()->getType()->hasIntegerRepresentation())
Richard Trieuba63ce62011-09-09 01:45:06 +00005865 return CheckVectorOperands(LHS, RHS, Loc, IsCompAssign);
Richard Trieu859d23f2011-09-06 21:01:04 +00005866 return InvalidOperands(Loc, LHS, RHS);
Daniel Dunbar0d2bfec2009-01-05 22:55:36 +00005867 }
Steve Naroffb8ea4fb2007-07-13 23:32:42 +00005868
Richard Trieuba63ce62011-09-09 01:45:06 +00005869 QualType compType = UsualArithmeticConversions(LHS, RHS, IsCompAssign);
Richard Trieu859d23f2011-09-06 21:01:04 +00005870 if (LHS.isInvalid() || RHS.isInvalid())
John Wiegley01296292011-04-08 18:41:53 +00005871 return QualType();
Mike Stump4e1f26a2009-02-19 03:04:26 +00005872
Richard Trieu859d23f2011-09-06 21:01:04 +00005873 if (!LHS.get()->getType()->isIntegerType() ||
5874 !RHS.get()->getType()->isIntegerType())
5875 return InvalidOperands(Loc, LHS, RHS);
Kovarththanan Rajaratnamba2c6522010-03-13 10:17:05 +00005876
Chris Lattnerfaa54172010-01-12 21:23:57 +00005877 // Check for remainder by zero.
Richard Trieu859d23f2011-09-06 21:01:04 +00005878 if (RHS.get()->isNullPointerConstant(Context,
Richard Trieucfc491d2011-08-02 04:35:43 +00005879 Expr::NPC_ValueDependentIsNotNull))
Richard Trieu859d23f2011-09-06 21:01:04 +00005880 DiagRuntimeBehavior(Loc, RHS.get(), PDiag(diag::warn_remainder_by_zero)
5881 << RHS.get()->getSourceRange());
Kovarththanan Rajaratnamba2c6522010-03-13 10:17:05 +00005882
Chris Lattnerfaa54172010-01-12 21:23:57 +00005883 return compType;
Steve Naroff218bc2b2007-05-04 21:54:46 +00005884}
5885
Chandler Carruthc9332212011-06-27 08:02:19 +00005886/// \brief Diagnose invalid arithmetic on two void pointers.
5887static void diagnoseArithmeticOnTwoVoidPointers(Sema &S, SourceLocation Loc,
Richard Trieu4ae7e972011-09-06 21:13:51 +00005888 Expr *LHSExpr, Expr *RHSExpr) {
Chandler Carruthc9332212011-06-27 08:02:19 +00005889 S.Diag(Loc, S.getLangOptions().CPlusPlus
5890 ? diag::err_typecheck_pointer_arith_void_type
5891 : diag::ext_gnu_void_ptr)
Richard Trieu4ae7e972011-09-06 21:13:51 +00005892 << 1 /* two pointers */ << LHSExpr->getSourceRange()
5893 << RHSExpr->getSourceRange();
Chandler Carruthc9332212011-06-27 08:02:19 +00005894}
5895
5896/// \brief Diagnose invalid arithmetic on a void pointer.
5897static void diagnoseArithmeticOnVoidPointer(Sema &S, SourceLocation Loc,
5898 Expr *Pointer) {
5899 S.Diag(Loc, S.getLangOptions().CPlusPlus
5900 ? diag::err_typecheck_pointer_arith_void_type
5901 : diag::ext_gnu_void_ptr)
5902 << 0 /* one pointer */ << Pointer->getSourceRange();
5903}
5904
5905/// \brief Diagnose invalid arithmetic on two function pointers.
5906static void diagnoseArithmeticOnTwoFunctionPointers(Sema &S, SourceLocation Loc,
5907 Expr *LHS, Expr *RHS) {
5908 assert(LHS->getType()->isAnyPointerType());
5909 assert(RHS->getType()->isAnyPointerType());
5910 S.Diag(Loc, S.getLangOptions().CPlusPlus
5911 ? diag::err_typecheck_pointer_arith_function_type
5912 : diag::ext_gnu_ptr_func_arith)
5913 << 1 /* two pointers */ << LHS->getType()->getPointeeType()
5914 // We only show the second type if it differs from the first.
5915 << (unsigned)!S.Context.hasSameUnqualifiedType(LHS->getType(),
5916 RHS->getType())
5917 << RHS->getType()->getPointeeType()
5918 << LHS->getSourceRange() << RHS->getSourceRange();
5919}
5920
5921/// \brief Diagnose invalid arithmetic on a function pointer.
5922static void diagnoseArithmeticOnFunctionPointer(Sema &S, SourceLocation Loc,
5923 Expr *Pointer) {
5924 assert(Pointer->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 << 0 /* one pointer */ << Pointer->getType()->getPointeeType()
5929 << 0 /* one pointer, so only one type */
5930 << Pointer->getSourceRange();
5931}
5932
Richard Trieu993f3ab2011-09-12 18:08:02 +00005933/// \brief Emit error if Operand is incomplete pointer type
Richard Trieuaba22802011-09-02 02:15:37 +00005934///
5935/// \returns True if pointer has incomplete type
5936static bool checkArithmeticIncompletePointerType(Sema &S, SourceLocation Loc,
5937 Expr *Operand) {
5938 if ((Operand->getType()->isPointerType() &&
5939 !Operand->getType()->isDependentType()) ||
5940 Operand->getType()->isObjCObjectPointerType()) {
5941 QualType PointeeTy = Operand->getType()->getPointeeType();
5942 if (S.RequireCompleteType(
5943 Loc, PointeeTy,
5944 S.PDiag(diag::err_typecheck_arithmetic_incomplete_type)
5945 << PointeeTy << Operand->getSourceRange()))
5946 return true;
5947 }
5948 return false;
5949}
5950
Chandler Carruthc9332212011-06-27 08:02:19 +00005951/// \brief Check the validity of an arithmetic pointer operand.
5952///
5953/// If the operand has pointer type, this code will check for pointer types
5954/// which are invalid in arithmetic operations. These will be diagnosed
5955/// appropriately, including whether or not the use is supported as an
5956/// extension.
5957///
5958/// \returns True when the operand is valid to use (even if as an extension).
5959static bool checkArithmeticOpPointerOperand(Sema &S, SourceLocation Loc,
5960 Expr *Operand) {
5961 if (!Operand->getType()->isAnyPointerType()) return true;
5962
5963 QualType PointeeTy = Operand->getType()->getPointeeType();
5964 if (PointeeTy->isVoidType()) {
5965 diagnoseArithmeticOnVoidPointer(S, Loc, Operand);
5966 return !S.getLangOptions().CPlusPlus;
5967 }
5968 if (PointeeTy->isFunctionType()) {
5969 diagnoseArithmeticOnFunctionPointer(S, Loc, Operand);
5970 return !S.getLangOptions().CPlusPlus;
5971 }
5972
Richard Trieuaba22802011-09-02 02:15:37 +00005973 if (checkArithmeticIncompletePointerType(S, Loc, Operand)) return false;
Chandler Carruthc9332212011-06-27 08:02:19 +00005974
5975 return true;
5976}
5977
5978/// \brief Check the validity of a binary arithmetic operation w.r.t. pointer
5979/// operands.
5980///
5981/// This routine will diagnose any invalid arithmetic on pointer operands much
5982/// like \see checkArithmeticOpPointerOperand. However, it has special logic
5983/// for emitting a single diagnostic even for operations where both LHS and RHS
5984/// are (potentially problematic) pointers.
5985///
5986/// \returns True when the operand is valid to use (even if as an extension).
5987static bool checkArithmeticBinOpPointerOperands(Sema &S, SourceLocation Loc,
Richard Trieu4ae7e972011-09-06 21:13:51 +00005988 Expr *LHSExpr, Expr *RHSExpr) {
5989 bool isLHSPointer = LHSExpr->getType()->isAnyPointerType();
5990 bool isRHSPointer = RHSExpr->getType()->isAnyPointerType();
Chandler Carruthc9332212011-06-27 08:02:19 +00005991 if (!isLHSPointer && !isRHSPointer) return true;
5992
5993 QualType LHSPointeeTy, RHSPointeeTy;
Richard Trieu4ae7e972011-09-06 21:13:51 +00005994 if (isLHSPointer) LHSPointeeTy = LHSExpr->getType()->getPointeeType();
5995 if (isRHSPointer) RHSPointeeTy = RHSExpr->getType()->getPointeeType();
Chandler Carruthc9332212011-06-27 08:02:19 +00005996
5997 // Check for arithmetic on pointers to incomplete types.
5998 bool isLHSVoidPtr = isLHSPointer && LHSPointeeTy->isVoidType();
5999 bool isRHSVoidPtr = isRHSPointer && RHSPointeeTy->isVoidType();
6000 if (isLHSVoidPtr || isRHSVoidPtr) {
Richard Trieu4ae7e972011-09-06 21:13:51 +00006001 if (!isRHSVoidPtr) diagnoseArithmeticOnVoidPointer(S, Loc, LHSExpr);
6002 else if (!isLHSVoidPtr) diagnoseArithmeticOnVoidPointer(S, Loc, RHSExpr);
6003 else diagnoseArithmeticOnTwoVoidPointers(S, Loc, LHSExpr, RHSExpr);
Chandler Carruthc9332212011-06-27 08:02:19 +00006004
6005 return !S.getLangOptions().CPlusPlus;
6006 }
6007
6008 bool isLHSFuncPtr = isLHSPointer && LHSPointeeTy->isFunctionType();
6009 bool isRHSFuncPtr = isRHSPointer && RHSPointeeTy->isFunctionType();
6010 if (isLHSFuncPtr || isRHSFuncPtr) {
Richard Trieu4ae7e972011-09-06 21:13:51 +00006011 if (!isRHSFuncPtr) diagnoseArithmeticOnFunctionPointer(S, Loc, LHSExpr);
6012 else if (!isLHSFuncPtr) diagnoseArithmeticOnFunctionPointer(S, Loc,
6013 RHSExpr);
6014 else diagnoseArithmeticOnTwoFunctionPointers(S, Loc, LHSExpr, RHSExpr);
Chandler Carruthc9332212011-06-27 08:02:19 +00006015
6016 return !S.getLangOptions().CPlusPlus;
6017 }
6018
Richard Trieu4ae7e972011-09-06 21:13:51 +00006019 if (checkArithmeticIncompletePointerType(S, Loc, LHSExpr)) return false;
6020 if (checkArithmeticIncompletePointerType(S, Loc, RHSExpr)) return false;
Richard Trieuaba22802011-09-02 02:15:37 +00006021
Chandler Carruthc9332212011-06-27 08:02:19 +00006022 return true;
6023}
6024
Richard Trieub10c6312011-09-01 22:53:23 +00006025/// \brief Check bad cases where we step over interface counts.
6026static bool checkArithmethicPointerOnNonFragileABI(Sema &S,
6027 SourceLocation OpLoc,
6028 Expr *Op) {
6029 assert(Op->getType()->isAnyPointerType());
6030 QualType PointeeTy = Op->getType()->getPointeeType();
6031 if (!PointeeTy->isObjCObjectType() || !S.LangOpts.ObjCNonFragileABI)
6032 return true;
6033
6034 S.Diag(OpLoc, diag::err_arithmetic_nonfragile_interface)
6035 << PointeeTy << Op->getSourceRange();
6036 return false;
6037}
6038
Nico Weberccec40d2012-03-02 22:01:22 +00006039/// diagnoseStringPlusInt - Emit a warning when adding an integer to a string
6040/// literal.
6041static void diagnoseStringPlusInt(Sema &Self, SourceLocation OpLoc,
6042 Expr *LHSExpr, Expr *RHSExpr) {
6043 StringLiteral* StrExpr = dyn_cast<StringLiteral>(LHSExpr->IgnoreImpCasts());
6044 Expr* IndexExpr = RHSExpr;
6045 if (!StrExpr) {
6046 StrExpr = dyn_cast<StringLiteral>(RHSExpr->IgnoreImpCasts());
6047 IndexExpr = LHSExpr;
6048 }
6049
6050 bool IsStringPlusInt = StrExpr &&
6051 IndexExpr->getType()->isIntegralOrUnscopedEnumerationType();
6052 if (!IsStringPlusInt)
6053 return;
6054
6055 llvm::APSInt index;
6056 if (IndexExpr->EvaluateAsInt(index, Self.getASTContext())) {
6057 unsigned StrLenWithNull = StrExpr->getLength() + 1;
6058 if (index.isNonNegative() &&
6059 index <= llvm::APSInt(llvm::APInt(index.getBitWidth(), StrLenWithNull),
6060 index.isUnsigned()))
6061 return;
6062 }
6063
6064 SourceRange DiagRange(LHSExpr->getLocStart(), RHSExpr->getLocEnd());
6065 Self.Diag(OpLoc, diag::warn_string_plus_int)
6066 << DiagRange << IndexExpr->IgnoreImpCasts()->getType();
6067
6068 // Only print a fixit for "str" + int, not for int + "str".
6069 if (IndexExpr == RHSExpr) {
6070 SourceLocation EndLoc = Self.PP.getLocForEndOfToken(RHSExpr->getLocEnd());
6071 Self.Diag(OpLoc, diag::note_string_plus_int_silence)
6072 << FixItHint::CreateInsertion(LHSExpr->getLocStart(), "&")
6073 << FixItHint::CreateReplacement(SourceRange(OpLoc), "[")
6074 << FixItHint::CreateInsertion(EndLoc, "]");
6075 } else
6076 Self.Diag(OpLoc, diag::note_string_plus_int_silence);
6077}
6078
Richard Trieu993f3ab2011-09-12 18:08:02 +00006079/// \brief Emit error when two pointers are incompatible.
Richard Trieub10c6312011-09-01 22:53:23 +00006080static void diagnosePointerIncompatibility(Sema &S, SourceLocation Loc,
Richard Trieu4ae7e972011-09-06 21:13:51 +00006081 Expr *LHSExpr, Expr *RHSExpr) {
6082 assert(LHSExpr->getType()->isAnyPointerType());
6083 assert(RHSExpr->getType()->isAnyPointerType());
Richard Trieub10c6312011-09-01 22:53:23 +00006084 S.Diag(Loc, diag::err_typecheck_sub_ptr_compatible)
Richard Trieu4ae7e972011-09-06 21:13:51 +00006085 << LHSExpr->getType() << RHSExpr->getType() << LHSExpr->getSourceRange()
6086 << RHSExpr->getSourceRange();
Richard Trieub10c6312011-09-01 22:53:23 +00006087}
6088
Chris Lattnerfaa54172010-01-12 21:23:57 +00006089QualType Sema::CheckAdditionOperands( // C99 6.5.6
Nico Weberccec40d2012-03-02 22:01:22 +00006090 ExprResult &LHS, ExprResult &RHS, SourceLocation Loc, unsigned Opc,
6091 QualType* CompLHSTy) {
Richard Trieuf8916e12011-09-16 00:53:10 +00006092 checkArithmeticNull(*this, LHS, RHS, Loc, /*isCompare=*/false);
6093
Richard Trieu4ae7e972011-09-06 21:13:51 +00006094 if (LHS.get()->getType()->isVectorType() ||
6095 RHS.get()->getType()->isVectorType()) {
6096 QualType compType = CheckVectorOperands(LHS, RHS, Loc, CompLHSTy);
Eli Friedman8b7b1b12009-03-28 01:22:36 +00006097 if (CompLHSTy) *CompLHSTy = compType;
6098 return compType;
6099 }
Steve Naroff7a5af782007-07-13 16:58:59 +00006100
Richard Trieu4ae7e972011-09-06 21:13:51 +00006101 QualType compType = UsualArithmeticConversions(LHS, RHS, CompLHSTy);
6102 if (LHS.isInvalid() || RHS.isInvalid())
John Wiegley01296292011-04-08 18:41:53 +00006103 return QualType();
Eli Friedman8e122982008-05-18 18:08:51 +00006104
Nico Weberccec40d2012-03-02 22:01:22 +00006105 // Diagnose "string literal" '+' int.
6106 if (Opc == BO_Add)
6107 diagnoseStringPlusInt(*this, Loc, LHS.get(), RHS.get());
6108
Steve Naroffe4718892007-04-27 18:30:00 +00006109 // handle the common case first (both operands are arithmetic).
Richard Trieu4ae7e972011-09-06 21:13:51 +00006110 if (LHS.get()->getType()->isArithmeticType() &&
6111 RHS.get()->getType()->isArithmeticType()) {
Eli Friedman8b7b1b12009-03-28 01:22:36 +00006112 if (CompLHSTy) *CompLHSTy = compType;
Steve Naroffbe4c4d12007-08-24 19:07:16 +00006113 return compType;
Eli Friedman8b7b1b12009-03-28 01:22:36 +00006114 }
Steve Naroff218bc2b2007-05-04 21:54:46 +00006115
David Chisnallfa35df62012-01-16 17:27:18 +00006116 if (LHS.get()->getType()->isAtomicType() &&
6117 RHS.get()->getType()->isArithmeticType()) {
6118 *CompLHSTy = LHS.get()->getType();
6119 return compType;
6120 }
6121
Eli Friedman8e122982008-05-18 18:08:51 +00006122 // Put any potential pointer into PExp
Richard Trieu4ae7e972011-09-06 21:13:51 +00006123 Expr* PExp = LHS.get(), *IExp = RHS.get();
Steve Naroff6b712a72009-07-14 18:25:06 +00006124 if (IExp->getType()->isAnyPointerType())
Eli Friedman8e122982008-05-18 18:08:51 +00006125 std::swap(PExp, IExp);
6126
Richard Trieub420bca2011-09-12 18:37:54 +00006127 if (!PExp->getType()->isAnyPointerType())
6128 return InvalidOperands(Loc, LHS, RHS);
Chandler Carruthc9332212011-06-27 08:02:19 +00006129
Richard Trieub420bca2011-09-12 18:37:54 +00006130 if (!IExp->getType()->isIntegerType())
6131 return InvalidOperands(Loc, LHS, RHS);
Mike Stump11289f42009-09-09 15:08:12 +00006132
Richard Trieub420bca2011-09-12 18:37:54 +00006133 if (!checkArithmeticOpPointerOperand(*this, Loc, PExp))
6134 return QualType();
Kaelyn Uhrain2e7aa5a2011-08-05 23:18:04 +00006135
Richard Trieub420bca2011-09-12 18:37:54 +00006136 // Diagnose bad cases where we step over interface counts.
6137 if (!checkArithmethicPointerOnNonFragileABI(*this, Loc, PExp))
6138 return QualType();
6139
6140 // Check array bounds for pointer arithemtic
6141 CheckArrayAccess(PExp, IExp);
6142
6143 if (CompLHSTy) {
6144 QualType LHSTy = Context.isPromotableBitField(LHS.get());
6145 if (LHSTy.isNull()) {
6146 LHSTy = LHS.get()->getType();
6147 if (LHSTy->isPromotableIntegerType())
6148 LHSTy = Context.getPromotedIntegerType(LHSTy);
Eli Friedman8e122982008-05-18 18:08:51 +00006149 }
Richard Trieub420bca2011-09-12 18:37:54 +00006150 *CompLHSTy = LHSTy;
Eli Friedman8e122982008-05-18 18:08:51 +00006151 }
6152
Richard Trieub420bca2011-09-12 18:37:54 +00006153 return PExp->getType();
Steve Naroff26c8ea52007-03-21 21:08:52 +00006154}
6155
Chris Lattner2a3569b2008-04-07 05:30:13 +00006156// C99 6.5.6
Richard Trieu4ae7e972011-09-06 21:13:51 +00006157QualType Sema::CheckSubtractionOperands(ExprResult &LHS, ExprResult &RHS,
Richard Trieucfc491d2011-08-02 04:35:43 +00006158 SourceLocation Loc,
6159 QualType* CompLHSTy) {
Richard Trieuf8916e12011-09-16 00:53:10 +00006160 checkArithmeticNull(*this, LHS, RHS, Loc, /*isCompare=*/false);
6161
Richard Trieu4ae7e972011-09-06 21:13:51 +00006162 if (LHS.get()->getType()->isVectorType() ||
6163 RHS.get()->getType()->isVectorType()) {
6164 QualType compType = CheckVectorOperands(LHS, RHS, Loc, CompLHSTy);
Eli Friedman8b7b1b12009-03-28 01:22:36 +00006165 if (CompLHSTy) *CompLHSTy = compType;
6166 return compType;
6167 }
Mike Stump4e1f26a2009-02-19 03:04:26 +00006168
Richard Trieu4ae7e972011-09-06 21:13:51 +00006169 QualType compType = UsualArithmeticConversions(LHS, RHS, CompLHSTy);
6170 if (LHS.isInvalid() || RHS.isInvalid())
John Wiegley01296292011-04-08 18:41:53 +00006171 return QualType();
Mike Stump4e1f26a2009-02-19 03:04:26 +00006172
Chris Lattner4d62f422007-12-09 21:53:25 +00006173 // Enforce type constraints: C99 6.5.6p3.
Mike Stump4e1f26a2009-02-19 03:04:26 +00006174
Chris Lattner4d62f422007-12-09 21:53:25 +00006175 // Handle the common case first (both operands are arithmetic).
Richard Trieu4ae7e972011-09-06 21:13:51 +00006176 if (LHS.get()->getType()->isArithmeticType() &&
6177 RHS.get()->getType()->isArithmeticType()) {
Eli Friedman8b7b1b12009-03-28 01:22:36 +00006178 if (CompLHSTy) *CompLHSTy = compType;
Steve Naroffbe4c4d12007-08-24 19:07:16 +00006179 return compType;
Eli Friedman8b7b1b12009-03-28 01:22:36 +00006180 }
Mike Stump11289f42009-09-09 15:08:12 +00006181
David Chisnallfa35df62012-01-16 17:27:18 +00006182 if (LHS.get()->getType()->isAtomicType() &&
6183 RHS.get()->getType()->isArithmeticType()) {
6184 *CompLHSTy = LHS.get()->getType();
6185 return compType;
6186 }
6187
Chris Lattner4d62f422007-12-09 21:53:25 +00006188 // Either ptr - int or ptr - ptr.
Richard Trieu4ae7e972011-09-06 21:13:51 +00006189 if (LHS.get()->getType()->isAnyPointerType()) {
6190 QualType lpointee = LHS.get()->getType()->getPointeeType();
Mike Stump4e1f26a2009-02-19 03:04:26 +00006191
Chris Lattner12bdebb2009-04-24 23:50:08 +00006192 // Diagnose bad cases where we step over interface counts.
Richard Trieu4ae7e972011-09-06 21:13:51 +00006193 if (!checkArithmethicPointerOnNonFragileABI(*this, Loc, LHS.get()))
Chris Lattner12bdebb2009-04-24 23:50:08 +00006194 return QualType();
Mike Stump11289f42009-09-09 15:08:12 +00006195
Chris Lattner4d62f422007-12-09 21:53:25 +00006196 // The result type of a pointer-int computation is the pointer type.
Richard Trieu4ae7e972011-09-06 21:13:51 +00006197 if (RHS.get()->getType()->isIntegerType()) {
6198 if (!checkArithmeticOpPointerOperand(*this, Loc, LHS.get()))
Chandler Carruthc9332212011-06-27 08:02:19 +00006199 return QualType();
Douglas Gregorac1fb652009-03-24 19:52:54 +00006200
Kaelyn Uhrain2e7aa5a2011-08-05 23:18:04 +00006201 // Check array bounds for pointer arithemtic
Richard Smith13f67182011-12-16 19:31:14 +00006202 CheckArrayAccess(LHS.get(), RHS.get(), /*ArraySubscriptExpr*/0,
6203 /*AllowOnePastEnd*/true, /*IndexNegated*/true);
Kaelyn Uhrain2e7aa5a2011-08-05 23:18:04 +00006204
Richard Trieu4ae7e972011-09-06 21:13:51 +00006205 if (CompLHSTy) *CompLHSTy = LHS.get()->getType();
6206 return LHS.get()->getType();
Douglas Gregorac1fb652009-03-24 19:52:54 +00006207 }
Mike Stump4e1f26a2009-02-19 03:04:26 +00006208
Chris Lattner4d62f422007-12-09 21:53:25 +00006209 // Handle pointer-pointer subtractions.
Richard Trieucfc491d2011-08-02 04:35:43 +00006210 if (const PointerType *RHSPTy
Richard Trieu4ae7e972011-09-06 21:13:51 +00006211 = RHS.get()->getType()->getAs<PointerType>()) {
Eli Friedman1974e532008-02-08 01:19:44 +00006212 QualType rpointee = RHSPTy->getPointeeType();
Mike Stump4e1f26a2009-02-19 03:04:26 +00006213
Eli Friedman168fe152009-05-16 13:54:38 +00006214 if (getLangOptions().CPlusPlus) {
6215 // Pointee types must be the same: C++ [expr.add]
6216 if (!Context.hasSameUnqualifiedType(lpointee, rpointee)) {
Richard Trieu4ae7e972011-09-06 21:13:51 +00006217 diagnosePointerIncompatibility(*this, Loc, LHS.get(), RHS.get());
Eli Friedman168fe152009-05-16 13:54:38 +00006218 }
6219 } else {
6220 // Pointee types must be compatible C99 6.5.6p3
6221 if (!Context.typesAreCompatible(
6222 Context.getCanonicalType(lpointee).getUnqualifiedType(),
6223 Context.getCanonicalType(rpointee).getUnqualifiedType())) {
Richard Trieu4ae7e972011-09-06 21:13:51 +00006224 diagnosePointerIncompatibility(*this, Loc, LHS.get(), RHS.get());
Eli Friedman168fe152009-05-16 13:54:38 +00006225 return QualType();
6226 }
Chris Lattner4d62f422007-12-09 21:53:25 +00006227 }
Mike Stump4e1f26a2009-02-19 03:04:26 +00006228
Chandler Carruthc9332212011-06-27 08:02:19 +00006229 if (!checkArithmeticBinOpPointerOperands(*this, Loc,
Richard Trieu4ae7e972011-09-06 21:13:51 +00006230 LHS.get(), RHS.get()))
Chandler Carruthc9332212011-06-27 08:02:19 +00006231 return QualType();
Eli Friedman8b7b1b12009-03-28 01:22:36 +00006232
Richard Trieu4ae7e972011-09-06 21:13:51 +00006233 if (CompLHSTy) *CompLHSTy = LHS.get()->getType();
Chris Lattner4d62f422007-12-09 21:53:25 +00006234 return Context.getPointerDiffType();
6235 }
6236 }
Mike Stump4e1f26a2009-02-19 03:04:26 +00006237
Richard Trieu4ae7e972011-09-06 21:13:51 +00006238 return InvalidOperands(Loc, LHS, RHS);
Steve Naroff218bc2b2007-05-04 21:54:46 +00006239}
6240
Douglas Gregor0bf31402010-10-08 23:50:27 +00006241static bool isScopedEnumerationType(QualType T) {
6242 if (const EnumType *ET = dyn_cast<EnumType>(T))
6243 return ET->getDecl()->isScoped();
6244 return false;
6245}
6246
Richard Trieue4a19fb2011-09-06 21:21:28 +00006247static void DiagnoseBadShiftValues(Sema& S, ExprResult &LHS, ExprResult &RHS,
Chandler Carruth4c6fdca2011-02-23 23:34:11 +00006248 SourceLocation Loc, unsigned Opc,
Richard Trieue4a19fb2011-09-06 21:21:28 +00006249 QualType LHSType) {
Chandler Carruth4c6fdca2011-02-23 23:34:11 +00006250 llvm::APSInt Right;
6251 // Check right/shifter operand
Richard Trieue4a19fb2011-09-06 21:21:28 +00006252 if (RHS.get()->isValueDependent() ||
6253 !RHS.get()->isIntegerConstantExpr(Right, S.Context))
Chandler Carruth4c6fdca2011-02-23 23:34:11 +00006254 return;
6255
6256 if (Right.isNegative()) {
Richard Trieue4a19fb2011-09-06 21:21:28 +00006257 S.DiagRuntimeBehavior(Loc, RHS.get(),
Ted Kremenek63657fe2011-03-01 18:09:31 +00006258 S.PDiag(diag::warn_shift_negative)
Richard Trieue4a19fb2011-09-06 21:21:28 +00006259 << RHS.get()->getSourceRange());
Chandler Carruth4c6fdca2011-02-23 23:34:11 +00006260 return;
6261 }
6262 llvm::APInt LeftBits(Right.getBitWidth(),
Richard Trieue4a19fb2011-09-06 21:21:28 +00006263 S.Context.getTypeSize(LHS.get()->getType()));
Chandler Carruth4c6fdca2011-02-23 23:34:11 +00006264 if (Right.uge(LeftBits)) {
Richard Trieue4a19fb2011-09-06 21:21:28 +00006265 S.DiagRuntimeBehavior(Loc, RHS.get(),
Ted Kremenek26bbc3d2011-03-01 19:13:22 +00006266 S.PDiag(diag::warn_shift_gt_typewidth)
Richard Trieue4a19fb2011-09-06 21:21:28 +00006267 << RHS.get()->getSourceRange());
Chandler Carruth4c6fdca2011-02-23 23:34:11 +00006268 return;
6269 }
6270 if (Opc != BO_Shl)
6271 return;
6272
6273 // When left shifting an ICE which is signed, we can check for overflow which
6274 // according to C++ has undefined behavior ([expr.shift] 5.8/2). Unsigned
6275 // integers have defined behavior modulo one more than the maximum value
6276 // representable in the result type, so never warn for those.
6277 llvm::APSInt Left;
Richard Trieue4a19fb2011-09-06 21:21:28 +00006278 if (LHS.get()->isValueDependent() ||
6279 !LHS.get()->isIntegerConstantExpr(Left, S.Context) ||
6280 LHSType->hasUnsignedIntegerRepresentation())
Chandler Carruth4c6fdca2011-02-23 23:34:11 +00006281 return;
6282 llvm::APInt ResultBits =
6283 static_cast<llvm::APInt&>(Right) + Left.getMinSignedBits();
6284 if (LeftBits.uge(ResultBits))
6285 return;
6286 llvm::APSInt Result = Left.extend(ResultBits.getLimitedValue());
6287 Result = Result.shl(Right);
6288
Ted Kremenek70f05fd2011-06-15 00:54:52 +00006289 // Print the bit representation of the signed integer as an unsigned
6290 // hexadecimal number.
Dylan Noblesmith2c1dd272012-02-05 02:13:05 +00006291 SmallString<40> HexResult;
Ted Kremenek70f05fd2011-06-15 00:54:52 +00006292 Result.toString(HexResult, 16, /*Signed =*/false, /*Literal =*/true);
6293
Chandler Carruth4c6fdca2011-02-23 23:34:11 +00006294 // If we are only missing a sign bit, this is less likely to result in actual
6295 // bugs -- if the result is cast back to an unsigned type, it will have the
6296 // expected value. Thus we place this behind a different warning that can be
6297 // turned off separately if needed.
6298 if (LeftBits == ResultBits - 1) {
Ted Kremenek70f05fd2011-06-15 00:54:52 +00006299 S.Diag(Loc, diag::warn_shift_result_sets_sign_bit)
Richard Trieue4a19fb2011-09-06 21:21:28 +00006300 << HexResult.str() << LHSType
6301 << LHS.get()->getSourceRange() << RHS.get()->getSourceRange();
Chandler Carruth4c6fdca2011-02-23 23:34:11 +00006302 return;
6303 }
6304
6305 S.Diag(Loc, diag::warn_shift_result_gt_typewidth)
Richard Trieue4a19fb2011-09-06 21:21:28 +00006306 << HexResult.str() << Result.getMinSignedBits() << LHSType
6307 << Left.getBitWidth() << LHS.get()->getSourceRange()
6308 << RHS.get()->getSourceRange();
Chandler Carruth4c6fdca2011-02-23 23:34:11 +00006309}
6310
Chris Lattner2a3569b2008-04-07 05:30:13 +00006311// C99 6.5.7
Richard Trieue4a19fb2011-09-06 21:21:28 +00006312QualType Sema::CheckShiftOperands(ExprResult &LHS, ExprResult &RHS,
Richard Trieucfc491d2011-08-02 04:35:43 +00006313 SourceLocation Loc, unsigned Opc,
Richard Trieuba63ce62011-09-09 01:45:06 +00006314 bool IsCompAssign) {
Richard Trieuf8916e12011-09-16 00:53:10 +00006315 checkArithmeticNull(*this, LHS, RHS, Loc, /*isCompare=*/false);
6316
Chris Lattner5c11c412007-12-12 05:47:28 +00006317 // C99 6.5.7p2: Each of the operands shall have integer type.
Richard Trieue4a19fb2011-09-06 21:21:28 +00006318 if (!LHS.get()->getType()->hasIntegerRepresentation() ||
6319 !RHS.get()->getType()->hasIntegerRepresentation())
6320 return InvalidOperands(Loc, LHS, RHS);
Mike Stump4e1f26a2009-02-19 03:04:26 +00006321
Douglas Gregor0bf31402010-10-08 23:50:27 +00006322 // C++0x: Don't allow scoped enums. FIXME: Use something better than
6323 // hasIntegerRepresentation() above instead of this.
Richard Trieue4a19fb2011-09-06 21:21:28 +00006324 if (isScopedEnumerationType(LHS.get()->getType()) ||
6325 isScopedEnumerationType(RHS.get()->getType())) {
6326 return InvalidOperands(Loc, LHS, RHS);
Douglas Gregor0bf31402010-10-08 23:50:27 +00006327 }
6328
Nate Begemane46ee9a2009-10-25 02:26:48 +00006329 // Vector shifts promote their scalar inputs to vector type.
Richard Trieue4a19fb2011-09-06 21:21:28 +00006330 if (LHS.get()->getType()->isVectorType() ||
6331 RHS.get()->getType()->isVectorType())
Richard Trieuba63ce62011-09-09 01:45:06 +00006332 return CheckVectorOperands(LHS, RHS, Loc, IsCompAssign);
Nate Begemane46ee9a2009-10-25 02:26:48 +00006333
Chris Lattner5c11c412007-12-12 05:47:28 +00006334 // Shifts don't perform usual arithmetic conversions, they just do integer
6335 // promotions on each operand. C99 6.5.7p3
Eli Friedman8b7b1b12009-03-28 01:22:36 +00006336
John McCall57cdd882010-12-16 19:28:59 +00006337 // For the LHS, do usual unary conversions, but then reset them away
6338 // if this is a compound assignment.
Richard Trieue4a19fb2011-09-06 21:21:28 +00006339 ExprResult OldLHS = LHS;
6340 LHS = UsualUnaryConversions(LHS.take());
6341 if (LHS.isInvalid())
John Wiegley01296292011-04-08 18:41:53 +00006342 return QualType();
Richard Trieue4a19fb2011-09-06 21:21:28 +00006343 QualType LHSType = LHS.get()->getType();
Richard Trieuba63ce62011-09-09 01:45:06 +00006344 if (IsCompAssign) LHS = OldLHS;
John McCall57cdd882010-12-16 19:28:59 +00006345
6346 // The RHS is simpler.
Richard Trieue4a19fb2011-09-06 21:21:28 +00006347 RHS = UsualUnaryConversions(RHS.take());
6348 if (RHS.isInvalid())
John Wiegley01296292011-04-08 18:41:53 +00006349 return QualType();
Mike Stump4e1f26a2009-02-19 03:04:26 +00006350
Ryan Flynnf53fab82009-08-07 16:20:20 +00006351 // Sanity-check shift operands
Richard Trieue4a19fb2011-09-06 21:21:28 +00006352 DiagnoseBadShiftValues(*this, LHS, RHS, Loc, Opc, LHSType);
Ryan Flynnf53fab82009-08-07 16:20:20 +00006353
Chris Lattner5c11c412007-12-12 05:47:28 +00006354 // "The type of the result is that of the promoted left operand."
Richard Trieue4a19fb2011-09-06 21:21:28 +00006355 return LHSType;
Steve Naroff26c8ea52007-03-21 21:08:52 +00006356}
6357
Chandler Carruth17773fc2010-07-10 12:30:03 +00006358static bool IsWithinTemplateSpecialization(Decl *D) {
6359 if (DeclContext *DC = D->getDeclContext()) {
6360 if (isa<ClassTemplateSpecializationDecl>(DC))
6361 return true;
6362 if (FunctionDecl *FD = dyn_cast<FunctionDecl>(DC))
6363 return FD->isFunctionTemplateSpecialization();
6364 }
6365 return false;
6366}
6367
Richard Trieueea56f72011-09-02 03:48:46 +00006368/// If two different enums are compared, raise a warning.
Richard Trieu1762d7c2011-09-06 21:27:33 +00006369static void checkEnumComparison(Sema &S, SourceLocation Loc, ExprResult &LHS,
6370 ExprResult &RHS) {
6371 QualType LHSStrippedType = LHS.get()->IgnoreParenImpCasts()->getType();
6372 QualType RHSStrippedType = RHS.get()->IgnoreParenImpCasts()->getType();
Richard Trieueea56f72011-09-02 03:48:46 +00006373
6374 const EnumType *LHSEnumType = LHSStrippedType->getAs<EnumType>();
6375 if (!LHSEnumType)
6376 return;
6377 const EnumType *RHSEnumType = RHSStrippedType->getAs<EnumType>();
6378 if (!RHSEnumType)
6379 return;
6380
6381 // Ignore anonymous enums.
6382 if (!LHSEnumType->getDecl()->getIdentifier())
6383 return;
6384 if (!RHSEnumType->getDecl()->getIdentifier())
6385 return;
6386
6387 if (S.Context.hasSameUnqualifiedType(LHSStrippedType, RHSStrippedType))
6388 return;
6389
6390 S.Diag(Loc, diag::warn_comparison_of_mixed_enum_types)
6391 << LHSStrippedType << RHSStrippedType
Richard Trieu1762d7c2011-09-06 21:27:33 +00006392 << LHS.get()->getSourceRange() << RHS.get()->getSourceRange();
Richard Trieueea56f72011-09-02 03:48:46 +00006393}
6394
Richard Trieudd82a5c2011-09-02 02:55:45 +00006395/// \brief Diagnose bad pointer comparisons.
6396static void diagnoseDistinctPointerComparison(Sema &S, SourceLocation Loc,
Richard Trieu1762d7c2011-09-06 21:27:33 +00006397 ExprResult &LHS, ExprResult &RHS,
Richard Trieuba63ce62011-09-09 01:45:06 +00006398 bool IsError) {
6399 S.Diag(Loc, IsError ? diag::err_typecheck_comparison_of_distinct_pointers
Richard Trieudd82a5c2011-09-02 02:55:45 +00006400 : diag::ext_typecheck_comparison_of_distinct_pointers)
Richard Trieu1762d7c2011-09-06 21:27:33 +00006401 << LHS.get()->getType() << RHS.get()->getType()
6402 << LHS.get()->getSourceRange() << RHS.get()->getSourceRange();
Richard Trieudd82a5c2011-09-02 02:55:45 +00006403}
6404
6405/// \brief Returns false if the pointers are converted to a composite type,
6406/// true otherwise.
6407static bool convertPointersToCompositeType(Sema &S, SourceLocation Loc,
Richard Trieu1762d7c2011-09-06 21:27:33 +00006408 ExprResult &LHS, ExprResult &RHS) {
Richard Trieudd82a5c2011-09-02 02:55:45 +00006409 // C++ [expr.rel]p2:
6410 // [...] Pointer conversions (4.10) and qualification
6411 // conversions (4.4) are performed on pointer operands (or on
6412 // a pointer operand and a null pointer constant) to bring
6413 // them to their composite pointer type. [...]
6414 //
6415 // C++ [expr.eq]p1 uses the same notion for (in)equality
6416 // comparisons of pointers.
6417
6418 // C++ [expr.eq]p2:
6419 // In addition, pointers to members can be compared, or a pointer to
6420 // member and a null pointer constant. Pointer to member conversions
6421 // (4.11) and qualification conversions (4.4) are performed to bring
6422 // them to a common type. If one operand is a null pointer constant,
6423 // the common type is the type of the other operand. Otherwise, the
6424 // common type is a pointer to member type similar (4.4) to the type
6425 // of one of the operands, with a cv-qualification signature (4.4)
6426 // that is the union of the cv-qualification signatures of the operand
6427 // types.
6428
Richard Trieu1762d7c2011-09-06 21:27:33 +00006429 QualType LHSType = LHS.get()->getType();
6430 QualType RHSType = RHS.get()->getType();
6431 assert((LHSType->isPointerType() && RHSType->isPointerType()) ||
6432 (LHSType->isMemberPointerType() && RHSType->isMemberPointerType()));
Richard Trieudd82a5c2011-09-02 02:55:45 +00006433
6434 bool NonStandardCompositeType = false;
Richard Trieu48277e52011-09-02 21:44:27 +00006435 bool *BoolPtr = S.isSFINAEContext() ? 0 : &NonStandardCompositeType;
Richard Trieu1762d7c2011-09-06 21:27:33 +00006436 QualType T = S.FindCompositePointerType(Loc, LHS, RHS, BoolPtr);
Richard Trieudd82a5c2011-09-02 02:55:45 +00006437 if (T.isNull()) {
Richard Trieu1762d7c2011-09-06 21:27:33 +00006438 diagnoseDistinctPointerComparison(S, Loc, LHS, RHS, /*isError*/true);
Richard Trieudd82a5c2011-09-02 02:55:45 +00006439 return true;
6440 }
6441
6442 if (NonStandardCompositeType)
6443 S.Diag(Loc, diag::ext_typecheck_comparison_of_distinct_pointers_nonstandard)
Richard Trieu1762d7c2011-09-06 21:27:33 +00006444 << LHSType << RHSType << T << LHS.get()->getSourceRange()
6445 << RHS.get()->getSourceRange();
Richard Trieudd82a5c2011-09-02 02:55:45 +00006446
Richard Trieu1762d7c2011-09-06 21:27:33 +00006447 LHS = S.ImpCastExprToType(LHS.take(), T, CK_BitCast);
6448 RHS = S.ImpCastExprToType(RHS.take(), T, CK_BitCast);
Richard Trieudd82a5c2011-09-02 02:55:45 +00006449 return false;
6450}
6451
6452static void diagnoseFunctionPointerToVoidComparison(Sema &S, SourceLocation Loc,
Richard Trieu1762d7c2011-09-06 21:27:33 +00006453 ExprResult &LHS,
6454 ExprResult &RHS,
Richard Trieuba63ce62011-09-09 01:45:06 +00006455 bool IsError) {
6456 S.Diag(Loc, IsError ? diag::err_typecheck_comparison_of_fptr_to_void
6457 : diag::ext_typecheck_comparison_of_fptr_to_void)
Richard Trieu1762d7c2011-09-06 21:27:33 +00006458 << LHS.get()->getType() << RHS.get()->getType()
6459 << LHS.get()->getSourceRange() << RHS.get()->getSourceRange();
Richard Trieudd82a5c2011-09-02 02:55:45 +00006460}
6461
Douglas Gregor5b07c7e2009-05-04 06:07:12 +00006462// C99 6.5.8, C++ [expr.rel]
Richard Trieub80728f2011-09-06 21:43:51 +00006463QualType Sema::CheckCompareOperands(ExprResult &LHS, ExprResult &RHS,
Richard Trieucfc491d2011-08-02 04:35:43 +00006464 SourceLocation Loc, unsigned OpaqueOpc,
Richard Trieuba63ce62011-09-09 01:45:06 +00006465 bool IsRelational) {
Richard Trieuf8916e12011-09-16 00:53:10 +00006466 checkArithmeticNull(*this, LHS, RHS, Loc, /*isCompare=*/true);
6467
John McCalle3027922010-08-25 11:45:40 +00006468 BinaryOperatorKind Opc = (BinaryOperatorKind) OpaqueOpc;
Douglas Gregor7a5bc762009-04-06 18:45:53 +00006469
Chris Lattner9a152e22009-12-05 05:40:13 +00006470 // Handle vector comparisons separately.
Richard Trieub80728f2011-09-06 21:43:51 +00006471 if (LHS.get()->getType()->isVectorType() ||
6472 RHS.get()->getType()->isVectorType())
Richard Trieuba63ce62011-09-09 01:45:06 +00006473 return CheckVectorCompareOperands(LHS, RHS, Loc, IsRelational);
Mike Stump4e1f26a2009-02-19 03:04:26 +00006474
Richard Trieub80728f2011-09-06 21:43:51 +00006475 QualType LHSType = LHS.get()->getType();
6476 QualType RHSType = RHS.get()->getType();
Benjamin Kramera66aaa92011-09-03 08:46:20 +00006477
Richard Trieub80728f2011-09-06 21:43:51 +00006478 Expr *LHSStripped = LHS.get()->IgnoreParenImpCasts();
6479 Expr *RHSStripped = RHS.get()->IgnoreParenImpCasts();
Chandler Carruth712563b2011-02-17 08:37:06 +00006480
Richard Trieub80728f2011-09-06 21:43:51 +00006481 checkEnumComparison(*this, Loc, LHS, RHS);
Chandler Carruth712563b2011-02-17 08:37:06 +00006482
Richard Trieub80728f2011-09-06 21:43:51 +00006483 if (!LHSType->hasFloatingRepresentation() &&
Richard Trieuba63ce62011-09-09 01:45:06 +00006484 !(LHSType->isBlockPointerType() && IsRelational) &&
Richard Trieub80728f2011-09-06 21:43:51 +00006485 !LHS.get()->getLocStart().isMacroID() &&
6486 !RHS.get()->getLocStart().isMacroID()) {
Chris Lattner222b8bd2009-03-08 19:39:53 +00006487 // For non-floating point types, check for self-comparisons of the form
6488 // x == x, x != x, x < x, etc. These always evaluate to a constant, and
6489 // often indicate logic errors in the program.
Chandler Carruth65a38182010-07-12 06:23:38 +00006490 //
6491 // NOTE: Don't warn about comparison expressions resulting from macro
6492 // expansion. Also don't warn about comparisons which are only self
6493 // comparisons within a template specialization. The warnings should catch
6494 // obvious cases in the definition of the template anyways. The idea is to
6495 // warn when the typed comparison operator will always evaluate to the same
6496 // result.
Chandler Carruth17773fc2010-07-10 12:30:03 +00006497 if (DeclRefExpr* DRL = dyn_cast<DeclRefExpr>(LHSStripped)) {
Douglas Gregorec170db2010-06-08 19:50:34 +00006498 if (DeclRefExpr* DRR = dyn_cast<DeclRefExpr>(RHSStripped)) {
Ted Kremenek853734e2010-09-16 00:03:01 +00006499 if (DRL->getDecl() == DRR->getDecl() &&
Chandler Carruth17773fc2010-07-10 12:30:03 +00006500 !IsWithinTemplateSpecialization(DRL->getDecl())) {
Ted Kremenek3427fac2011-02-23 01:52:04 +00006501 DiagRuntimeBehavior(Loc, 0, PDiag(diag::warn_comparison_always)
Douglas Gregorec170db2010-06-08 19:50:34 +00006502 << 0 // self-
John McCalle3027922010-08-25 11:45:40 +00006503 << (Opc == BO_EQ
6504 || Opc == BO_LE
6505 || Opc == BO_GE));
Richard Trieub80728f2011-09-06 21:43:51 +00006506 } else if (LHSType->isArrayType() && RHSType->isArrayType() &&
Douglas Gregorec170db2010-06-08 19:50:34 +00006507 !DRL->getDecl()->getType()->isReferenceType() &&
6508 !DRR->getDecl()->getType()->isReferenceType()) {
6509 // what is it always going to eval to?
6510 char always_evals_to;
6511 switch(Opc) {
John McCalle3027922010-08-25 11:45:40 +00006512 case BO_EQ: // e.g. array1 == array2
Douglas Gregorec170db2010-06-08 19:50:34 +00006513 always_evals_to = 0; // false
6514 break;
John McCalle3027922010-08-25 11:45:40 +00006515 case BO_NE: // e.g. array1 != array2
Douglas Gregorec170db2010-06-08 19:50:34 +00006516 always_evals_to = 1; // true
6517 break;
6518 default:
6519 // best we can say is 'a constant'
6520 always_evals_to = 2; // e.g. array1 <= array2
6521 break;
6522 }
Ted Kremenek3427fac2011-02-23 01:52:04 +00006523 DiagRuntimeBehavior(Loc, 0, PDiag(diag::warn_comparison_always)
Douglas Gregorec170db2010-06-08 19:50:34 +00006524 << 1 // array
6525 << always_evals_to);
6526 }
6527 }
Chandler Carruth17773fc2010-07-10 12:30:03 +00006528 }
Mike Stump11289f42009-09-09 15:08:12 +00006529
Chris Lattner222b8bd2009-03-08 19:39:53 +00006530 if (isa<CastExpr>(LHSStripped))
6531 LHSStripped = LHSStripped->IgnoreParenCasts();
6532 if (isa<CastExpr>(RHSStripped))
6533 RHSStripped = RHSStripped->IgnoreParenCasts();
Mike Stump11289f42009-09-09 15:08:12 +00006534
Chris Lattner222b8bd2009-03-08 19:39:53 +00006535 // Warn about comparisons against a string constant (unless the other
6536 // operand is null), the user probably wants strcmp.
Douglas Gregor7a5bc762009-04-06 18:45:53 +00006537 Expr *literalString = 0;
6538 Expr *literalStringStripped = 0;
Chris Lattner222b8bd2009-03-08 19:39:53 +00006539 if ((isa<StringLiteral>(LHSStripped) || isa<ObjCEncodeExpr>(LHSStripped)) &&
Kovarththanan Rajaratnamba2c6522010-03-13 10:17:05 +00006540 !RHSStripped->isNullPointerConstant(Context,
Douglas Gregor56751b52009-09-25 04:25:58 +00006541 Expr::NPC_ValueDependentIsNull)) {
Richard Trieub80728f2011-09-06 21:43:51 +00006542 literalString = LHS.get();
Douglas Gregor7a5bc762009-04-06 18:45:53 +00006543 literalStringStripped = LHSStripped;
Mike Stump12b8ce12009-08-04 21:02:39 +00006544 } else if ((isa<StringLiteral>(RHSStripped) ||
6545 isa<ObjCEncodeExpr>(RHSStripped)) &&
Kovarththanan Rajaratnamba2c6522010-03-13 10:17:05 +00006546 !LHSStripped->isNullPointerConstant(Context,
Douglas Gregor56751b52009-09-25 04:25:58 +00006547 Expr::NPC_ValueDependentIsNull)) {
Richard Trieub80728f2011-09-06 21:43:51 +00006548 literalString = RHS.get();
Douglas Gregor7a5bc762009-04-06 18:45:53 +00006549 literalStringStripped = RHSStripped;
6550 }
6551
6552 if (literalString) {
6553 std::string resultComparison;
6554 switch (Opc) {
John McCalle3027922010-08-25 11:45:40 +00006555 case BO_LT: resultComparison = ") < 0"; break;
6556 case BO_GT: resultComparison = ") > 0"; break;
6557 case BO_LE: resultComparison = ") <= 0"; break;
6558 case BO_GE: resultComparison = ") >= 0"; break;
6559 case BO_EQ: resultComparison = ") == 0"; break;
6560 case BO_NE: resultComparison = ") != 0"; break;
David Blaikie83d382b2011-09-23 05:06:16 +00006561 default: llvm_unreachable("Invalid comparison operator");
Douglas Gregor7a5bc762009-04-06 18:45:53 +00006562 }
Kovarththanan Rajaratnamba2c6522010-03-13 10:17:05 +00006563
Ted Kremenek3427fac2011-02-23 01:52:04 +00006564 DiagRuntimeBehavior(Loc, 0,
Douglas Gregor49862b82010-01-12 23:18:54 +00006565 PDiag(diag::warn_stringcompare)
6566 << isa<ObjCEncodeExpr>(literalStringStripped)
Ted Kremenek800b66b2010-04-09 20:26:53 +00006567 << literalString->getSourceRange());
Douglas Gregor7a5bc762009-04-06 18:45:53 +00006568 }
Ted Kremeneke451eae2007-10-29 16:58:49 +00006569 }
Mike Stump4e1f26a2009-02-19 03:04:26 +00006570
Douglas Gregorec170db2010-06-08 19:50:34 +00006571 // C99 6.5.8p3 / C99 6.5.9p4
Richard Trieub80728f2011-09-06 21:43:51 +00006572 if (LHS.get()->getType()->isArithmeticType() &&
6573 RHS.get()->getType()->isArithmeticType()) {
6574 UsualArithmeticConversions(LHS, RHS);
6575 if (LHS.isInvalid() || RHS.isInvalid())
John Wiegley01296292011-04-08 18:41:53 +00006576 return QualType();
6577 }
Douglas Gregorec170db2010-06-08 19:50:34 +00006578 else {
Richard Trieub80728f2011-09-06 21:43:51 +00006579 LHS = UsualUnaryConversions(LHS.take());
6580 if (LHS.isInvalid())
John Wiegley01296292011-04-08 18:41:53 +00006581 return QualType();
6582
Richard Trieub80728f2011-09-06 21:43:51 +00006583 RHS = UsualUnaryConversions(RHS.take());
6584 if (RHS.isInvalid())
John Wiegley01296292011-04-08 18:41:53 +00006585 return QualType();
Douglas Gregorec170db2010-06-08 19:50:34 +00006586 }
6587
Richard Trieub80728f2011-09-06 21:43:51 +00006588 LHSType = LHS.get()->getType();
6589 RHSType = RHS.get()->getType();
Douglas Gregorec170db2010-06-08 19:50:34 +00006590
Douglas Gregorca63811b2008-11-19 03:25:36 +00006591 // The result of comparisons is 'bool' in C++, 'int' in C.
Argyrios Kyrtzidis1bdd6882011-02-18 20:55:15 +00006592 QualType ResultTy = Context.getLogicalOperationType();
Douglas Gregorca63811b2008-11-19 03:25:36 +00006593
Richard Trieuba63ce62011-09-09 01:45:06 +00006594 if (IsRelational) {
Richard Trieub80728f2011-09-06 21:43:51 +00006595 if (LHSType->isRealType() && RHSType->isRealType())
Douglas Gregorca63811b2008-11-19 03:25:36 +00006596 return ResultTy;
Chris Lattnerb620c342007-08-26 01:18:55 +00006597 } else {
Ted Kremeneke2763b02007-10-29 17:13:39 +00006598 // Check for comparisons of floating point operands using != and ==.
Richard Trieub80728f2011-09-06 21:43:51 +00006599 if (LHSType->hasFloatingRepresentation())
6600 CheckFloatComparison(Loc, LHS.get(), RHS.get());
Mike Stump4e1f26a2009-02-19 03:04:26 +00006601
Richard Trieub80728f2011-09-06 21:43:51 +00006602 if (LHSType->isArithmeticType() && RHSType->isArithmeticType())
Douglas Gregorca63811b2008-11-19 03:25:36 +00006603 return ResultTy;
Chris Lattnerb620c342007-08-26 01:18:55 +00006604 }
Mike Stump4e1f26a2009-02-19 03:04:26 +00006605
Richard Trieub80728f2011-09-06 21:43:51 +00006606 bool LHSIsNull = LHS.get()->isNullPointerConstant(Context,
Douglas Gregor56751b52009-09-25 04:25:58 +00006607 Expr::NPC_ValueDependentIsNull);
Richard Trieub80728f2011-09-06 21:43:51 +00006608 bool RHSIsNull = RHS.get()->isNullPointerConstant(Context,
Douglas Gregor56751b52009-09-25 04:25:58 +00006609 Expr::NPC_ValueDependentIsNull);
Mike Stump4e1f26a2009-02-19 03:04:26 +00006610
Douglas Gregorf267edd2010-06-15 21:38:40 +00006611 // All of the following pointer-related warnings are GCC extensions, except
6612 // when handling null pointer constants.
Richard Trieub80728f2011-09-06 21:43:51 +00006613 if (LHSType->isPointerType() && RHSType->isPointerType()) { // C99 6.5.8p2
Chris Lattner3a0702e2008-04-03 05:07:25 +00006614 QualType LCanPointeeTy =
John McCall9320b872011-09-09 05:25:32 +00006615 LHSType->castAs<PointerType>()->getPointeeType().getCanonicalType();
Chris Lattner3a0702e2008-04-03 05:07:25 +00006616 QualType RCanPointeeTy =
John McCall9320b872011-09-09 05:25:32 +00006617 RHSType->castAs<PointerType>()->getPointeeType().getCanonicalType();
Mike Stump4e1f26a2009-02-19 03:04:26 +00006618
Douglas Gregor5b07c7e2009-05-04 06:07:12 +00006619 if (getLangOptions().CPlusPlus) {
Eli Friedman16c209612009-08-23 00:27:47 +00006620 if (LCanPointeeTy == RCanPointeeTy)
6621 return ResultTy;
Richard Trieuba63ce62011-09-09 01:45:06 +00006622 if (!IsRelational &&
Fariborz Jahanianffc420c2009-12-21 18:19:17 +00006623 (LCanPointeeTy->isVoidType() || RCanPointeeTy->isVoidType())) {
6624 // Valid unless comparison between non-null pointer and function pointer
6625 // This is a gcc extension compatibility comparison.
Douglas Gregorf267edd2010-06-15 21:38:40 +00006626 // In a SFINAE context, we treat this as a hard error to maintain
6627 // conformance with the C++ standard.
Fariborz Jahanianffc420c2009-12-21 18:19:17 +00006628 if ((LCanPointeeTy->isFunctionType() || RCanPointeeTy->isFunctionType())
6629 && !LHSIsNull && !RHSIsNull) {
Richard Trieudd82a5c2011-09-02 02:55:45 +00006630 diagnoseFunctionPointerToVoidComparison(
Richard Trieub80728f2011-09-06 21:43:51 +00006631 *this, Loc, LHS, RHS, /*isError*/ isSFINAEContext());
Douglas Gregorf267edd2010-06-15 21:38:40 +00006632
6633 if (isSFINAEContext())
6634 return QualType();
6635
Richard Trieub80728f2011-09-06 21:43:51 +00006636 RHS = ImpCastExprToType(RHS.take(), LHSType, CK_BitCast);
Fariborz Jahanianffc420c2009-12-21 18:19:17 +00006637 return ResultTy;
6638 }
6639 }
Anders Carlssona95069c2010-11-04 03:17:43 +00006640
Richard Trieub80728f2011-09-06 21:43:51 +00006641 if (convertPointersToCompositeType(*this, Loc, LHS, RHS))
Douglas Gregor5b07c7e2009-05-04 06:07:12 +00006642 return QualType();
Richard Trieudd82a5c2011-09-02 02:55:45 +00006643 else
6644 return ResultTy;
Douglas Gregor5b07c7e2009-05-04 06:07:12 +00006645 }
Eli Friedman16c209612009-08-23 00:27:47 +00006646 // C99 6.5.9p2 and C99 6.5.8p2
6647 if (Context.typesAreCompatible(LCanPointeeTy.getUnqualifiedType(),
6648 RCanPointeeTy.getUnqualifiedType())) {
6649 // Valid unless a relational comparison of function pointers
Richard Trieuba63ce62011-09-09 01:45:06 +00006650 if (IsRelational && LCanPointeeTy->isFunctionType()) {
Eli Friedman16c209612009-08-23 00:27:47 +00006651 Diag(Loc, diag::ext_typecheck_ordered_comparison_of_function_pointers)
Richard Trieub80728f2011-09-06 21:43:51 +00006652 << LHSType << RHSType << LHS.get()->getSourceRange()
6653 << RHS.get()->getSourceRange();
Eli Friedman16c209612009-08-23 00:27:47 +00006654 }
Richard Trieuba63ce62011-09-09 01:45:06 +00006655 } else if (!IsRelational &&
Eli Friedman16c209612009-08-23 00:27:47 +00006656 (LCanPointeeTy->isVoidType() || RCanPointeeTy->isVoidType())) {
6657 // Valid unless comparison between non-null pointer and function pointer
6658 if ((LCanPointeeTy->isFunctionType() || RCanPointeeTy->isFunctionType())
Richard Trieudd82a5c2011-09-02 02:55:45 +00006659 && !LHSIsNull && !RHSIsNull)
Richard Trieub80728f2011-09-06 21:43:51 +00006660 diagnoseFunctionPointerToVoidComparison(*this, Loc, LHS, RHS,
Richard Trieudd82a5c2011-09-02 02:55:45 +00006661 /*isError*/false);
Eli Friedman16c209612009-08-23 00:27:47 +00006662 } else {
6663 // Invalid
Richard Trieub80728f2011-09-06 21:43:51 +00006664 diagnoseDistinctPointerComparison(*this, Loc, LHS, RHS, /*isError*/false);
Steve Naroff75c17232007-06-13 21:41:08 +00006665 }
John McCall7684dde2011-03-11 04:25:25 +00006666 if (LCanPointeeTy != RCanPointeeTy) {
6667 if (LHSIsNull && !RHSIsNull)
Richard Trieub80728f2011-09-06 21:43:51 +00006668 LHS = ImpCastExprToType(LHS.take(), RHSType, CK_BitCast);
John McCall7684dde2011-03-11 04:25:25 +00006669 else
Richard Trieub80728f2011-09-06 21:43:51 +00006670 RHS = ImpCastExprToType(RHS.take(), LHSType, CK_BitCast);
John McCall7684dde2011-03-11 04:25:25 +00006671 }
Douglas Gregorca63811b2008-11-19 03:25:36 +00006672 return ResultTy;
Steve Naroffcdee44c2007-08-16 21:48:38 +00006673 }
Mike Stump11289f42009-09-09 15:08:12 +00006674
Sebastian Redl576fd422009-05-10 18:38:11 +00006675 if (getLangOptions().CPlusPlus) {
Anders Carlssona95069c2010-11-04 03:17:43 +00006676 // Comparison of nullptr_t with itself.
Richard Trieub80728f2011-09-06 21:43:51 +00006677 if (LHSType->isNullPtrType() && RHSType->isNullPtrType())
Anders Carlssona95069c2010-11-04 03:17:43 +00006678 return ResultTy;
6679
Mike Stump11289f42009-09-09 15:08:12 +00006680 // Comparison of pointers with null pointer constants and equality
Douglas Gregorb00b10e2009-08-24 17:42:35 +00006681 // comparisons of member pointers to null pointer constants.
Mike Stump11289f42009-09-09 15:08:12 +00006682 if (RHSIsNull &&
Richard Trieub80728f2011-09-06 21:43:51 +00006683 ((LHSType->isAnyPointerType() || LHSType->isNullPtrType()) ||
Richard Trieuba63ce62011-09-09 01:45:06 +00006684 (!IsRelational &&
Richard Trieub80728f2011-09-06 21:43:51 +00006685 (LHSType->isMemberPointerType() || LHSType->isBlockPointerType())))) {
6686 RHS = ImpCastExprToType(RHS.take(), LHSType,
6687 LHSType->isMemberPointerType()
John McCalle3027922010-08-25 11:45:40 +00006688 ? CK_NullToMemberPointer
John McCalle84af4e2010-11-13 01:35:44 +00006689 : CK_NullToPointer);
Sebastian Redl576fd422009-05-10 18:38:11 +00006690 return ResultTy;
6691 }
Douglas Gregorb00b10e2009-08-24 17:42:35 +00006692 if (LHSIsNull &&
Richard Trieub80728f2011-09-06 21:43:51 +00006693 ((RHSType->isAnyPointerType() || RHSType->isNullPtrType()) ||
Richard Trieuba63ce62011-09-09 01:45:06 +00006694 (!IsRelational &&
Richard Trieub80728f2011-09-06 21:43:51 +00006695 (RHSType->isMemberPointerType() || RHSType->isBlockPointerType())))) {
6696 LHS = ImpCastExprToType(LHS.take(), RHSType,
6697 RHSType->isMemberPointerType()
John McCalle3027922010-08-25 11:45:40 +00006698 ? CK_NullToMemberPointer
John McCalle84af4e2010-11-13 01:35:44 +00006699 : CK_NullToPointer);
Sebastian Redl576fd422009-05-10 18:38:11 +00006700 return ResultTy;
6701 }
Douglas Gregorb00b10e2009-08-24 17:42:35 +00006702
6703 // Comparison of member pointers.
Richard Trieuba63ce62011-09-09 01:45:06 +00006704 if (!IsRelational &&
Richard Trieub80728f2011-09-06 21:43:51 +00006705 LHSType->isMemberPointerType() && RHSType->isMemberPointerType()) {
6706 if (convertPointersToCompositeType(*this, Loc, LHS, RHS))
Douglas Gregorb00b10e2009-08-24 17:42:35 +00006707 return QualType();
Richard Trieudd82a5c2011-09-02 02:55:45 +00006708 else
6709 return ResultTy;
Douglas Gregorb00b10e2009-08-24 17:42:35 +00006710 }
Douglas Gregor48e6bbf2011-03-01 17:16:20 +00006711
6712 // Handle scoped enumeration types specifically, since they don't promote
6713 // to integers.
Richard Trieub80728f2011-09-06 21:43:51 +00006714 if (LHS.get()->getType()->isEnumeralType() &&
6715 Context.hasSameUnqualifiedType(LHS.get()->getType(),
6716 RHS.get()->getType()))
Douglas Gregor48e6bbf2011-03-01 17:16:20 +00006717 return ResultTy;
Sebastian Redl576fd422009-05-10 18:38:11 +00006718 }
Mike Stump11289f42009-09-09 15:08:12 +00006719
Steve Naroff081c7422008-09-04 15:10:53 +00006720 // Handle block pointer types.
Richard Trieuba63ce62011-09-09 01:45:06 +00006721 if (!IsRelational && LHSType->isBlockPointerType() &&
Richard Trieub80728f2011-09-06 21:43:51 +00006722 RHSType->isBlockPointerType()) {
John McCall9320b872011-09-09 05:25:32 +00006723 QualType lpointee = LHSType->castAs<BlockPointerType>()->getPointeeType();
6724 QualType rpointee = RHSType->castAs<BlockPointerType>()->getPointeeType();
Mike Stump4e1f26a2009-02-19 03:04:26 +00006725
Steve Naroff081c7422008-09-04 15:10:53 +00006726 if (!LHSIsNull && !RHSIsNull &&
Eli Friedmana6638ca2009-06-08 05:08:54 +00006727 !Context.typesAreCompatible(lpointee, rpointee)) {
Chris Lattner377d1f82008-11-18 22:52:51 +00006728 Diag(Loc, diag::err_typecheck_comparison_of_distinct_blocks)
Richard Trieub80728f2011-09-06 21:43:51 +00006729 << LHSType << RHSType << LHS.get()->getSourceRange()
6730 << RHS.get()->getSourceRange();
Steve Naroff081c7422008-09-04 15:10:53 +00006731 }
Richard Trieub80728f2011-09-06 21:43:51 +00006732 RHS = ImpCastExprToType(RHS.take(), LHSType, CK_BitCast);
Douglas Gregorca63811b2008-11-19 03:25:36 +00006733 return ResultTy;
Steve Naroff081c7422008-09-04 15:10:53 +00006734 }
John Wiegley01296292011-04-08 18:41:53 +00006735
Steve Naroffe18f94c2008-09-28 01:11:11 +00006736 // Allow block pointers to be compared with null pointer constants.
Richard Trieuba63ce62011-09-09 01:45:06 +00006737 if (!IsRelational
Richard Trieub80728f2011-09-06 21:43:51 +00006738 && ((LHSType->isBlockPointerType() && RHSType->isPointerType())
6739 || (LHSType->isPointerType() && RHSType->isBlockPointerType()))) {
Steve Naroffe18f94c2008-09-28 01:11:11 +00006740 if (!LHSIsNull && !RHSIsNull) {
Richard Trieub80728f2011-09-06 21:43:51 +00006741 if (!((RHSType->isPointerType() && RHSType->castAs<PointerType>()
Mike Stump1b821b42009-05-07 03:14:14 +00006742 ->getPointeeType()->isVoidType())
Richard Trieub80728f2011-09-06 21:43:51 +00006743 || (LHSType->isPointerType() && LHSType->castAs<PointerType>()
Mike Stump1b821b42009-05-07 03:14:14 +00006744 ->getPointeeType()->isVoidType())))
6745 Diag(Loc, diag::err_typecheck_comparison_of_distinct_blocks)
Richard Trieub80728f2011-09-06 21:43:51 +00006746 << LHSType << RHSType << LHS.get()->getSourceRange()
6747 << RHS.get()->getSourceRange();
Steve Naroffe18f94c2008-09-28 01:11:11 +00006748 }
John McCall7684dde2011-03-11 04:25:25 +00006749 if (LHSIsNull && !RHSIsNull)
John McCall9320b872011-09-09 05:25:32 +00006750 LHS = ImpCastExprToType(LHS.take(), RHSType,
6751 RHSType->isPointerType() ? CK_BitCast
6752 : CK_AnyPointerToBlockPointerCast);
John McCall7684dde2011-03-11 04:25:25 +00006753 else
John McCall9320b872011-09-09 05:25:32 +00006754 RHS = ImpCastExprToType(RHS.take(), LHSType,
6755 LHSType->isPointerType() ? CK_BitCast
6756 : CK_AnyPointerToBlockPointerCast);
Douglas Gregorca63811b2008-11-19 03:25:36 +00006757 return ResultTy;
Steve Naroffe18f94c2008-09-28 01:11:11 +00006758 }
Steve Naroff081c7422008-09-04 15:10:53 +00006759
Richard Trieub80728f2011-09-06 21:43:51 +00006760 if (LHSType->isObjCObjectPointerType() ||
6761 RHSType->isObjCObjectPointerType()) {
6762 const PointerType *LPT = LHSType->getAs<PointerType>();
6763 const PointerType *RPT = RHSType->getAs<PointerType>();
John McCall7684dde2011-03-11 04:25:25 +00006764 if (LPT || RPT) {
6765 bool LPtrToVoid = LPT ? LPT->getPointeeType()->isVoidType() : false;
6766 bool RPtrToVoid = RPT ? RPT->getPointeeType()->isVoidType() : false;
Mike Stump4e1f26a2009-02-19 03:04:26 +00006767
Steve Naroff753567f2008-11-17 19:49:16 +00006768 if (!LPtrToVoid && !RPtrToVoid &&
Richard Trieub80728f2011-09-06 21:43:51 +00006769 !Context.typesAreCompatible(LHSType, RHSType)) {
6770 diagnoseDistinctPointerComparison(*this, Loc, LHS, RHS,
Richard Trieudd82a5c2011-09-02 02:55:45 +00006771 /*isError*/false);
Steve Naroff1d4a9a32008-10-27 10:33:19 +00006772 }
John McCall7684dde2011-03-11 04:25:25 +00006773 if (LHSIsNull && !RHSIsNull)
John McCall9320b872011-09-09 05:25:32 +00006774 LHS = ImpCastExprToType(LHS.take(), RHSType,
6775 RPT ? CK_BitCast :CK_CPointerToObjCPointerCast);
John McCall7684dde2011-03-11 04:25:25 +00006776 else
John McCall9320b872011-09-09 05:25:32 +00006777 RHS = ImpCastExprToType(RHS.take(), LHSType,
6778 LPT ? CK_BitCast :CK_CPointerToObjCPointerCast);
Douglas Gregorca63811b2008-11-19 03:25:36 +00006779 return ResultTy;
Steve Naroffea54d9e2008-10-20 18:19:10 +00006780 }
Richard Trieub80728f2011-09-06 21:43:51 +00006781 if (LHSType->isObjCObjectPointerType() &&
6782 RHSType->isObjCObjectPointerType()) {
6783 if (!Context.areComparableObjCPointerTypes(LHSType, RHSType))
6784 diagnoseDistinctPointerComparison(*this, Loc, LHS, RHS,
Richard Trieudd82a5c2011-09-02 02:55:45 +00006785 /*isError*/false);
John McCall7684dde2011-03-11 04:25:25 +00006786 if (LHSIsNull && !RHSIsNull)
Richard Trieub80728f2011-09-06 21:43:51 +00006787 LHS = ImpCastExprToType(LHS.take(), RHSType, CK_BitCast);
John McCall7684dde2011-03-11 04:25:25 +00006788 else
Richard Trieub80728f2011-09-06 21:43:51 +00006789 RHS = ImpCastExprToType(RHS.take(), LHSType, CK_BitCast);
Douglas Gregorca63811b2008-11-19 03:25:36 +00006790 return ResultTy;
Steve Naroffb788d9b2008-06-03 14:04:54 +00006791 }
Fariborz Jahanian134cbef2007-12-20 01:06:58 +00006792 }
Richard Trieub80728f2011-09-06 21:43:51 +00006793 if ((LHSType->isAnyPointerType() && RHSType->isIntegerType()) ||
6794 (LHSType->isIntegerType() && RHSType->isAnyPointerType())) {
Chris Lattnerd99bd522009-08-23 00:03:44 +00006795 unsigned DiagID = 0;
Douglas Gregorf267edd2010-06-15 21:38:40 +00006796 bool isError = false;
Richard Trieub80728f2011-09-06 21:43:51 +00006797 if ((LHSIsNull && LHSType->isIntegerType()) ||
6798 (RHSIsNull && RHSType->isIntegerType())) {
Richard Trieuba63ce62011-09-09 01:45:06 +00006799 if (IsRelational && !getLangOptions().CPlusPlus)
Chris Lattnerd99bd522009-08-23 00:03:44 +00006800 DiagID = diag::ext_typecheck_ordered_comparison_of_pointer_and_zero;
Richard Trieuba63ce62011-09-09 01:45:06 +00006801 } else if (IsRelational && !getLangOptions().CPlusPlus)
Chris Lattnerd99bd522009-08-23 00:03:44 +00006802 DiagID = diag::ext_typecheck_ordered_comparison_of_pointer_integer;
Douglas Gregorf267edd2010-06-15 21:38:40 +00006803 else if (getLangOptions().CPlusPlus) {
6804 DiagID = diag::err_typecheck_comparison_of_pointer_integer;
6805 isError = true;
6806 } else
Chris Lattnerd99bd522009-08-23 00:03:44 +00006807 DiagID = diag::ext_typecheck_comparison_of_pointer_integer;
Mike Stump11289f42009-09-09 15:08:12 +00006808
Chris Lattnerd99bd522009-08-23 00:03:44 +00006809 if (DiagID) {
Chris Lattnerf8344db2009-08-22 18:58:31 +00006810 Diag(Loc, DiagID)
Richard Trieub80728f2011-09-06 21:43:51 +00006811 << LHSType << RHSType << LHS.get()->getSourceRange()
6812 << RHS.get()->getSourceRange();
Douglas Gregorf267edd2010-06-15 21:38:40 +00006813 if (isError)
6814 return QualType();
Chris Lattnerf8344db2009-08-22 18:58:31 +00006815 }
Douglas Gregorf267edd2010-06-15 21:38:40 +00006816
Richard Trieub80728f2011-09-06 21:43:51 +00006817 if (LHSType->isIntegerType())
6818 LHS = ImpCastExprToType(LHS.take(), RHSType,
John McCalle84af4e2010-11-13 01:35:44 +00006819 LHSIsNull ? CK_NullToPointer : CK_IntegralToPointer);
Chris Lattnerd99bd522009-08-23 00:03:44 +00006820 else
Richard Trieub80728f2011-09-06 21:43:51 +00006821 RHS = ImpCastExprToType(RHS.take(), LHSType,
John McCalle84af4e2010-11-13 01:35:44 +00006822 RHSIsNull ? CK_NullToPointer : CK_IntegralToPointer);
Douglas Gregorca63811b2008-11-19 03:25:36 +00006823 return ResultTy;
Steve Naroff043d45d2007-05-15 02:32:35 +00006824 }
Douglas Gregorf267edd2010-06-15 21:38:40 +00006825
Steve Naroff4b191572008-09-04 16:56:14 +00006826 // Handle block pointers.
Richard Trieuba63ce62011-09-09 01:45:06 +00006827 if (!IsRelational && RHSIsNull
Richard Trieub80728f2011-09-06 21:43:51 +00006828 && LHSType->isBlockPointerType() && RHSType->isIntegerType()) {
6829 RHS = ImpCastExprToType(RHS.take(), LHSType, CK_NullToPointer);
Douglas Gregorca63811b2008-11-19 03:25:36 +00006830 return ResultTy;
Steve Naroff4b191572008-09-04 16:56:14 +00006831 }
Richard Trieuba63ce62011-09-09 01:45:06 +00006832 if (!IsRelational && LHSIsNull
Richard Trieub80728f2011-09-06 21:43:51 +00006833 && LHSType->isIntegerType() && RHSType->isBlockPointerType()) {
6834 LHS = ImpCastExprToType(LHS.take(), RHSType, CK_NullToPointer);
Douglas Gregorca63811b2008-11-19 03:25:36 +00006835 return ResultTy;
Steve Naroff4b191572008-09-04 16:56:14 +00006836 }
Douglas Gregor48e6bbf2011-03-01 17:16:20 +00006837
Richard Trieub80728f2011-09-06 21:43:51 +00006838 return InvalidOperands(Loc, LHS, RHS);
Steve Naroff26c8ea52007-03-21 21:08:52 +00006839}
6840
Tanya Lattner20248222012-01-16 21:02:28 +00006841
6842// Return a signed type that is of identical size and number of elements.
6843// For floating point vectors, return an integer type of identical size
6844// and number of elements.
6845QualType Sema::GetSignedVectorType(QualType V) {
6846 const VectorType *VTy = V->getAs<VectorType>();
6847 unsigned TypeSize = Context.getTypeSize(VTy->getElementType());
6848 if (TypeSize == Context.getTypeSize(Context.CharTy))
6849 return Context.getExtVectorType(Context.CharTy, VTy->getNumElements());
6850 else if (TypeSize == Context.getTypeSize(Context.ShortTy))
6851 return Context.getExtVectorType(Context.ShortTy, VTy->getNumElements());
6852 else if (TypeSize == Context.getTypeSize(Context.IntTy))
6853 return Context.getExtVectorType(Context.IntTy, VTy->getNumElements());
6854 else if (TypeSize == Context.getTypeSize(Context.LongTy))
6855 return Context.getExtVectorType(Context.LongTy, VTy->getNumElements());
6856 assert(TypeSize == Context.getTypeSize(Context.LongLongTy) &&
6857 "Unhandled vector element size in vector compare");
6858 return Context.getExtVectorType(Context.LongLongTy, VTy->getNumElements());
6859}
6860
Nate Begeman191a6b12008-07-14 18:02:46 +00006861/// CheckVectorCompareOperands - vector comparisons are a clang extension that
Mike Stump4e1f26a2009-02-19 03:04:26 +00006862/// operates on extended vector types. Instead of producing an IntTy result,
Nate Begeman191a6b12008-07-14 18:02:46 +00006863/// like a scalar comparison, a vector comparison produces a vector of integer
6864/// types.
Richard Trieubcce2f72011-09-07 01:19:57 +00006865QualType Sema::CheckVectorCompareOperands(ExprResult &LHS, ExprResult &RHS,
Chris Lattner326f7572008-11-18 01:30:42 +00006866 SourceLocation Loc,
Richard Trieuba63ce62011-09-09 01:45:06 +00006867 bool IsRelational) {
Nate Begeman191a6b12008-07-14 18:02:46 +00006868 // Check to make sure we're operating on vectors of the same type and width,
6869 // Allowing one side to be a scalar of element type.
Richard Trieubcce2f72011-09-07 01:19:57 +00006870 QualType vType = CheckVectorOperands(LHS, RHS, Loc, /*isCompAssign*/false);
Nate Begeman191a6b12008-07-14 18:02:46 +00006871 if (vType.isNull())
6872 return vType;
Mike Stump4e1f26a2009-02-19 03:04:26 +00006873
Richard Trieubcce2f72011-09-07 01:19:57 +00006874 QualType LHSType = LHS.get()->getType();
Mike Stump4e1f26a2009-02-19 03:04:26 +00006875
Anton Yartsev530deb92011-03-27 15:36:07 +00006876 // If AltiVec, the comparison results in a numeric type, i.e.
6877 // bool for C++, int for C
Anton Yartsev93900c72011-03-28 21:00:05 +00006878 if (vType->getAs<VectorType>()->getVectorKind() == VectorType::AltiVecVector)
Anton Yartsev530deb92011-03-27 15:36:07 +00006879 return Context.getLogicalOperationType();
6880
Nate Begeman191a6b12008-07-14 18:02:46 +00006881 // For non-floating point types, check for self-comparisons of the form
6882 // x == x, x != x, x < x, etc. These always evaluate to a constant, and
6883 // often indicate logic errors in the program.
Richard Trieubcce2f72011-09-07 01:19:57 +00006884 if (!LHSType->hasFloatingRepresentation()) {
Richard Smith508ebf32011-10-28 03:31:48 +00006885 if (DeclRefExpr* DRL
6886 = dyn_cast<DeclRefExpr>(LHS.get()->IgnoreParenImpCasts()))
6887 if (DeclRefExpr* DRR
6888 = dyn_cast<DeclRefExpr>(RHS.get()->IgnoreParenImpCasts()))
Nate Begeman191a6b12008-07-14 18:02:46 +00006889 if (DRL->getDecl() == DRR->getDecl())
Ted Kremenek3427fac2011-02-23 01:52:04 +00006890 DiagRuntimeBehavior(Loc, 0,
Douglas Gregorec170db2010-06-08 19:50:34 +00006891 PDiag(diag::warn_comparison_always)
6892 << 0 // self-
6893 << 2 // "a constant"
6894 );
Nate Begeman191a6b12008-07-14 18:02:46 +00006895 }
Mike Stump4e1f26a2009-02-19 03:04:26 +00006896
Nate Begeman191a6b12008-07-14 18:02:46 +00006897 // Check for comparisons of floating point operands using != and ==.
Richard Trieuba63ce62011-09-09 01:45:06 +00006898 if (!IsRelational && LHSType->hasFloatingRepresentation()) {
David Blaikieca043222012-01-16 05:16:03 +00006899 assert (RHS.get()->getType()->hasFloatingRepresentation());
Richard Trieubcce2f72011-09-07 01:19:57 +00006900 CheckFloatComparison(Loc, LHS.get(), RHS.get());
Nate Begeman191a6b12008-07-14 18:02:46 +00006901 }
Tanya Lattner20248222012-01-16 21:02:28 +00006902
6903 // Return a signed type for the vector.
6904 return GetSignedVectorType(LHSType);
6905}
Mike Stump4e1f26a2009-02-19 03:04:26 +00006906
Tanya Lattner3dd33b22012-01-19 01:16:16 +00006907QualType Sema::CheckVectorLogicalOperands(ExprResult &LHS, ExprResult &RHS,
6908 SourceLocation Loc) {
Tanya Lattner20248222012-01-16 21:02:28 +00006909 // Ensure that either both operands are of the same vector type, or
6910 // one operand is of a vector type and the other is of its element type.
6911 QualType vType = CheckVectorOperands(LHS, RHS, Loc, false);
6912 if (vType.isNull() || vType->isFloatingType())
6913 return InvalidOperands(Loc, LHS, RHS);
6914
6915 return GetSignedVectorType(LHS.get()->getType());
Nate Begeman191a6b12008-07-14 18:02:46 +00006916}
6917
Steve Naroff218bc2b2007-05-04 21:54:46 +00006918inline QualType Sema::CheckBitwiseOperands(
Richard Trieuba63ce62011-09-09 01:45:06 +00006919 ExprResult &LHS, ExprResult &RHS, SourceLocation Loc, bool IsCompAssign) {
Richard Trieuf8916e12011-09-16 00:53:10 +00006920 checkArithmeticNull(*this, LHS, RHS, Loc, /*isCompare=*/false);
6921
Richard Trieubcce2f72011-09-07 01:19:57 +00006922 if (LHS.get()->getType()->isVectorType() ||
6923 RHS.get()->getType()->isVectorType()) {
6924 if (LHS.get()->getType()->hasIntegerRepresentation() &&
6925 RHS.get()->getType()->hasIntegerRepresentation())
Richard Trieuba63ce62011-09-09 01:45:06 +00006926 return CheckVectorOperands(LHS, RHS, Loc, IsCompAssign);
Douglas Gregor5cc2c8b2010-07-23 15:58:24 +00006927
Richard Trieubcce2f72011-09-07 01:19:57 +00006928 return InvalidOperands(Loc, LHS, RHS);
Douglas Gregor5cc2c8b2010-07-23 15:58:24 +00006929 }
Steve Naroffb8ea4fb2007-07-13 23:32:42 +00006930
Richard Trieubcce2f72011-09-07 01:19:57 +00006931 ExprResult LHSResult = Owned(LHS), RHSResult = Owned(RHS);
6932 QualType compType = UsualArithmeticConversions(LHSResult, RHSResult,
Richard Trieuba63ce62011-09-09 01:45:06 +00006933 IsCompAssign);
Richard Trieubcce2f72011-09-07 01:19:57 +00006934 if (LHSResult.isInvalid() || RHSResult.isInvalid())
John Wiegley01296292011-04-08 18:41:53 +00006935 return QualType();
Richard Trieubcce2f72011-09-07 01:19:57 +00006936 LHS = LHSResult.take();
6937 RHS = RHSResult.take();
Mike Stump4e1f26a2009-02-19 03:04:26 +00006938
Richard Trieubcce2f72011-09-07 01:19:57 +00006939 if (LHS.get()->getType()->isIntegralOrUnscopedEnumerationType() &&
6940 RHS.get()->getType()->isIntegralOrUnscopedEnumerationType())
Steve Naroffbe4c4d12007-08-24 19:07:16 +00006941 return compType;
Richard Trieubcce2f72011-09-07 01:19:57 +00006942 return InvalidOperands(Loc, LHS, RHS);
Steve Naroff26c8ea52007-03-21 21:08:52 +00006943}
6944
Steve Naroff218bc2b2007-05-04 21:54:46 +00006945inline QualType Sema::CheckLogicalOperands( // C99 6.5.[13,14]
Richard Trieubcce2f72011-09-07 01:19:57 +00006946 ExprResult &LHS, ExprResult &RHS, SourceLocation Loc, unsigned Opc) {
Chris Lattner8406c512010-07-13 19:41:32 +00006947
Tanya Lattner20248222012-01-16 21:02:28 +00006948 // Check vector operands differently.
6949 if (LHS.get()->getType()->isVectorType() || RHS.get()->getType()->isVectorType())
6950 return CheckVectorLogicalOperands(LHS, RHS, Loc);
6951
Chris Lattner8406c512010-07-13 19:41:32 +00006952 // Diagnose cases where the user write a logical and/or but probably meant a
6953 // bitwise one. We do this when the LHS is a non-bool integer and the RHS
6954 // is a constant.
Richard Trieubcce2f72011-09-07 01:19:57 +00006955 if (LHS.get()->getType()->isIntegerType() &&
6956 !LHS.get()->getType()->isBooleanType() &&
6957 RHS.get()->getType()->isIntegerType() && !RHS.get()->isValueDependent() &&
Richard Trieucfe39262011-07-15 00:00:51 +00006958 // Don't warn in macros or template instantiations.
6959 !Loc.isMacroID() && ActiveTemplateInstantiations.empty()) {
Chris Lattner938533d2010-07-24 01:10:11 +00006960 // If the RHS can be constant folded, and if it constant folds to something
6961 // that isn't 0 or 1 (which indicate a potential logical operation that
6962 // happened to fold to true/false) then warn.
Chandler Carruthe54ff6c2011-05-31 05:41:42 +00006963 // Parens on the RHS are ignored.
Richard Smith00ab3ae2011-10-16 23:01:09 +00006964 llvm::APSInt Result;
6965 if (RHS.get()->EvaluateAsInt(Result, Context))
Richard Trieubcce2f72011-09-07 01:19:57 +00006966 if ((getLangOptions().Bool && !RHS.get()->getType()->isBooleanType()) ||
Richard Smith00ab3ae2011-10-16 23:01:09 +00006967 (Result != 0 && Result != 1)) {
Chandler Carruthe54ff6c2011-05-31 05:41:42 +00006968 Diag(Loc, diag::warn_logical_instead_of_bitwise)
Richard Trieubcce2f72011-09-07 01:19:57 +00006969 << RHS.get()->getSourceRange()
Matt Beaumont-Gay0a0ba9d2011-08-15 17:50:06 +00006970 << (Opc == BO_LAnd ? "&&" : "||");
6971 // Suggest replacing the logical operator with the bitwise version
6972 Diag(Loc, diag::note_logical_instead_of_bitwise_change_operator)
6973 << (Opc == BO_LAnd ? "&" : "|")
6974 << FixItHint::CreateReplacement(SourceRange(
6975 Loc, Lexer::getLocForEndOfToken(Loc, 0, getSourceManager(),
6976 getLangOptions())),
6977 Opc == BO_LAnd ? "&" : "|");
6978 if (Opc == BO_LAnd)
6979 // Suggest replacing "Foo() && kNonZero" with "Foo()"
6980 Diag(Loc, diag::note_logical_instead_of_bitwise_remove_constant)
6981 << FixItHint::CreateRemoval(
6982 SourceRange(
Richard Trieubcce2f72011-09-07 01:19:57 +00006983 Lexer::getLocForEndOfToken(LHS.get()->getLocEnd(),
Matt Beaumont-Gay0a0ba9d2011-08-15 17:50:06 +00006984 0, getSourceManager(),
6985 getLangOptions()),
Richard Trieubcce2f72011-09-07 01:19:57 +00006986 RHS.get()->getLocEnd()));
Matt Beaumont-Gay0a0ba9d2011-08-15 17:50:06 +00006987 }
Chris Lattner938533d2010-07-24 01:10:11 +00006988 }
Chris Lattner8406c512010-07-13 19:41:32 +00006989
Anders Carlsson2e7bc112009-11-23 21:47:44 +00006990 if (!Context.getLangOptions().CPlusPlus) {
Richard Trieubcce2f72011-09-07 01:19:57 +00006991 LHS = UsualUnaryConversions(LHS.take());
6992 if (LHS.isInvalid())
John Wiegley01296292011-04-08 18:41:53 +00006993 return QualType();
Mike Stump4e1f26a2009-02-19 03:04:26 +00006994
Richard Trieubcce2f72011-09-07 01:19:57 +00006995 RHS = UsualUnaryConversions(RHS.take());
6996 if (RHS.isInvalid())
John Wiegley01296292011-04-08 18:41:53 +00006997 return QualType();
6998
Richard Trieubcce2f72011-09-07 01:19:57 +00006999 if (!LHS.get()->getType()->isScalarType() ||
7000 !RHS.get()->getType()->isScalarType())
7001 return InvalidOperands(Loc, LHS, RHS);
Kovarththanan Rajaratnamba2c6522010-03-13 10:17:05 +00007002
Anders Carlsson2e7bc112009-11-23 21:47:44 +00007003 return Context.IntTy;
Anders Carlsson35a99d92009-10-16 01:44:21 +00007004 }
Kovarththanan Rajaratnamba2c6522010-03-13 10:17:05 +00007005
John McCall4a2429a2010-06-04 00:29:51 +00007006 // The following is safe because we only use this method for
7007 // non-overloadable operands.
7008
Anders Carlsson2e7bc112009-11-23 21:47:44 +00007009 // C++ [expr.log.and]p1
7010 // C++ [expr.log.or]p1
John McCall4a2429a2010-06-04 00:29:51 +00007011 // The operands are both contextually converted to type bool.
Richard Trieubcce2f72011-09-07 01:19:57 +00007012 ExprResult LHSRes = PerformContextuallyConvertToBool(LHS.get());
7013 if (LHSRes.isInvalid())
7014 return InvalidOperands(Loc, LHS, RHS);
7015 LHS = move(LHSRes);
John Wiegley01296292011-04-08 18:41:53 +00007016
Richard Trieubcce2f72011-09-07 01:19:57 +00007017 ExprResult RHSRes = PerformContextuallyConvertToBool(RHS.get());
7018 if (RHSRes.isInvalid())
7019 return InvalidOperands(Loc, LHS, RHS);
7020 RHS = move(RHSRes);
Kovarththanan Rajaratnamba2c6522010-03-13 10:17:05 +00007021
Anders Carlsson2e7bc112009-11-23 21:47:44 +00007022 // C++ [expr.log.and]p2
7023 // C++ [expr.log.or]p2
7024 // The result is a bool.
7025 return Context.BoolTy;
Steve Naroffae4143e2007-04-26 20:39:23 +00007026}
7027
Fariborz Jahanian8e1555c2009-01-12 19:55:42 +00007028/// IsReadonlyProperty - Verify that otherwise a valid l-value expression
7029/// is a read-only property; return true if so. A readonly property expression
7030/// depends on various declarations and thus must be treated specially.
7031///
Mike Stump11289f42009-09-09 15:08:12 +00007032static bool IsReadonlyProperty(Expr *E, Sema &S) {
John McCall526ab472011-10-25 17:37:35 +00007033 const ObjCPropertyRefExpr *PropExpr = dyn_cast<ObjCPropertyRefExpr>(E);
7034 if (!PropExpr) return false;
7035 if (PropExpr->isImplicitProperty()) return false;
John McCallb7bd14f2010-12-02 01:19:52 +00007036
John McCall526ab472011-10-25 17:37:35 +00007037 ObjCPropertyDecl *PDecl = PropExpr->getExplicitProperty();
7038 QualType BaseType = PropExpr->isSuperReceiver() ?
John McCallb7bd14f2010-12-02 01:19:52 +00007039 PropExpr->getSuperReceiverType() :
Fariborz Jahanian681c0752010-10-14 16:04:05 +00007040 PropExpr->getBase()->getType();
7041
John McCall526ab472011-10-25 17:37:35 +00007042 if (const ObjCObjectPointerType *OPT =
7043 BaseType->getAsObjCInterfacePointerType())
7044 if (ObjCInterfaceDecl *IFace = OPT->getInterfaceDecl())
7045 if (S.isPropertyReadonly(PDecl, IFace))
7046 return true;
Fariborz Jahanian8e1555c2009-01-12 19:55:42 +00007047 return false;
7048}
7049
Fariborz Jahanianb24b5682011-03-28 23:47:18 +00007050static bool IsConstProperty(Expr *E, Sema &S) {
John McCall526ab472011-10-25 17:37:35 +00007051 const ObjCPropertyRefExpr *PropExpr = dyn_cast<ObjCPropertyRefExpr>(E);
7052 if (!PropExpr) return false;
7053 if (PropExpr->isImplicitProperty()) return false;
Fariborz Jahanianb24b5682011-03-28 23:47:18 +00007054
John McCall526ab472011-10-25 17:37:35 +00007055 ObjCPropertyDecl *PDecl = PropExpr->getExplicitProperty();
7056 QualType T = PDecl->getType().getNonReferenceType();
7057 return T.isConstQualified();
Fariborz Jahanianb24b5682011-03-28 23:47:18 +00007058}
7059
Fariborz Jahanian071caef2011-03-26 19:48:30 +00007060static bool IsReadonlyMessage(Expr *E, Sema &S) {
John McCall526ab472011-10-25 17:37:35 +00007061 const MemberExpr *ME = dyn_cast<MemberExpr>(E);
7062 if (!ME) return false;
7063 if (!isa<FieldDecl>(ME->getMemberDecl())) return false;
7064 ObjCMessageExpr *Base =
7065 dyn_cast<ObjCMessageExpr>(ME->getBase()->IgnoreParenImpCasts());
7066 if (!Base) return false;
7067 return Base->getMethodDecl() != 0;
Fariborz Jahanian071caef2011-03-26 19:48:30 +00007068}
7069
Chris Lattner30bd3272008-11-18 01:22:49 +00007070/// CheckForModifiableLvalue - Verify that E is a modifiable lvalue. If not,
7071/// emit an error and return true. If so, return false.
7072static bool CheckForModifiableLvalue(Expr *E, SourceLocation Loc, Sema &S) {
Daniel Dunbarc2223ab2009-04-15 00:08:05 +00007073 SourceLocation OrigLoc = Loc;
Mike Stump11289f42009-09-09 15:08:12 +00007074 Expr::isModifiableLvalueResult IsLV = E->isModifiableLvalue(S.Context,
Daniel Dunbarc2223ab2009-04-15 00:08:05 +00007075 &Loc);
Fariborz Jahanian8e1555c2009-01-12 19:55:42 +00007076 if (IsLV == Expr::MLV_Valid && IsReadonlyProperty(E, S))
7077 IsLV = Expr::MLV_ReadonlyProperty;
Fariborz Jahanianb24b5682011-03-28 23:47:18 +00007078 else if (Expr::MLV_ConstQualified && IsConstProperty(E, S))
7079 IsLV = Expr::MLV_Valid;
Fariborz Jahanian071caef2011-03-26 19:48:30 +00007080 else if (IsLV == Expr::MLV_ClassTemporary && IsReadonlyMessage(E, S))
7081 IsLV = Expr::MLV_InvalidMessageExpression;
Chris Lattner30bd3272008-11-18 01:22:49 +00007082 if (IsLV == Expr::MLV_Valid)
7083 return false;
Mike Stump4e1f26a2009-02-19 03:04:26 +00007084
Chris Lattner30bd3272008-11-18 01:22:49 +00007085 unsigned Diag = 0;
7086 bool NeedType = false;
7087 switch (IsLV) { // C99 6.5.16p2
John McCall31168b02011-06-15 23:02:42 +00007088 case Expr::MLV_ConstQualified:
7089 Diag = diag::err_typecheck_assign_const;
7090
John McCalld4631322011-06-17 06:42:21 +00007091 // In ARC, use some specialized diagnostics for occasions where we
7092 // infer 'const'. These are always pseudo-strong variables.
John McCall31168b02011-06-15 23:02:42 +00007093 if (S.getLangOptions().ObjCAutoRefCount) {
7094 DeclRefExpr *declRef = dyn_cast<DeclRefExpr>(E->IgnoreParenCasts());
7095 if (declRef && isa<VarDecl>(declRef->getDecl())) {
7096 VarDecl *var = cast<VarDecl>(declRef->getDecl());
7097
John McCalld4631322011-06-17 06:42:21 +00007098 // Use the normal diagnostic if it's pseudo-__strong but the
7099 // user actually wrote 'const'.
7100 if (var->isARCPseudoStrong() &&
7101 (!var->getTypeSourceInfo() ||
7102 !var->getTypeSourceInfo()->getType().isConstQualified())) {
7103 // There are two pseudo-strong cases:
7104 // - self
John McCall31168b02011-06-15 23:02:42 +00007105 ObjCMethodDecl *method = S.getCurMethodDecl();
7106 if (method && var == method->getSelfDecl())
Ted Kremenek1fcdaa92011-11-14 21:59:25 +00007107 Diag = method->isClassMethod()
7108 ? diag::err_typecheck_arc_assign_self_class_method
7109 : diag::err_typecheck_arc_assign_self;
John McCalld4631322011-06-17 06:42:21 +00007110
7111 // - fast enumeration variables
7112 else
John McCall31168b02011-06-15 23:02:42 +00007113 Diag = diag::err_typecheck_arr_assign_enumeration;
John McCalld4631322011-06-17 06:42:21 +00007114
John McCall31168b02011-06-15 23:02:42 +00007115 SourceRange Assign;
7116 if (Loc != OrigLoc)
7117 Assign = SourceRange(OrigLoc, OrigLoc);
7118 S.Diag(Loc, Diag) << E->getSourceRange() << Assign;
7119 // We need to preserve the AST regardless, so migration tool
7120 // can do its job.
7121 return false;
7122 }
7123 }
7124 }
7125
7126 break;
Mike Stump4e1f26a2009-02-19 03:04:26 +00007127 case Expr::MLV_ArrayType:
Chris Lattner30bd3272008-11-18 01:22:49 +00007128 Diag = diag::err_typecheck_array_not_modifiable_lvalue;
7129 NeedType = true;
7130 break;
Mike Stump4e1f26a2009-02-19 03:04:26 +00007131 case Expr::MLV_NotObjectType:
Chris Lattner30bd3272008-11-18 01:22:49 +00007132 Diag = diag::err_typecheck_non_object_not_modifiable_lvalue;
7133 NeedType = true;
7134 break;
Chris Lattner9b3bbe92008-11-17 19:51:54 +00007135 case Expr::MLV_LValueCast:
Chris Lattner30bd3272008-11-18 01:22:49 +00007136 Diag = diag::err_typecheck_lvalue_casts_not_supported;
7137 break;
Douglas Gregorb154fdc2010-02-16 21:39:57 +00007138 case Expr::MLV_Valid:
7139 llvm_unreachable("did not take early return for MLV_Valid");
Chris Lattner9bad62c2008-01-04 18:04:52 +00007140 case Expr::MLV_InvalidExpression:
Douglas Gregorb154fdc2010-02-16 21:39:57 +00007141 case Expr::MLV_MemberFunction:
7142 case Expr::MLV_ClassTemporary:
Chris Lattner30bd3272008-11-18 01:22:49 +00007143 Diag = diag::err_typecheck_expression_not_modifiable_lvalue;
7144 break;
Chris Lattner9bad62c2008-01-04 18:04:52 +00007145 case Expr::MLV_IncompleteType:
7146 case Expr::MLV_IncompleteVoidType:
Douglas Gregored0cfbd2009-03-09 16:13:40 +00007147 return S.RequireCompleteType(Loc, E->getType(),
Douglas Gregor89336232010-03-29 23:34:08 +00007148 S.PDiag(diag::err_typecheck_incomplete_type_not_modifiable_lvalue)
Anders Carlssond624e162009-08-26 23:45:07 +00007149 << E->getSourceRange());
Chris Lattner9bad62c2008-01-04 18:04:52 +00007150 case Expr::MLV_DuplicateVectorComponents:
Chris Lattner30bd3272008-11-18 01:22:49 +00007151 Diag = diag::err_typecheck_duplicate_vector_components_not_mlvalue;
7152 break;
Steve Naroffba756cb2008-09-26 14:41:28 +00007153 case Expr::MLV_NotBlockQualified:
Chris Lattner30bd3272008-11-18 01:22:49 +00007154 Diag = diag::err_block_decl_ref_not_modifiable_lvalue;
7155 break;
Fariborz Jahanian8a1810f2008-11-22 18:39:36 +00007156 case Expr::MLV_ReadonlyProperty:
Fariborz Jahanian5118c412008-11-22 20:25:50 +00007157 case Expr::MLV_NoSetterProperty:
John McCall526ab472011-10-25 17:37:35 +00007158 llvm_unreachable("readonly properties should be processed differently");
Fariborz Jahanian071caef2011-03-26 19:48:30 +00007159 case Expr::MLV_InvalidMessageExpression:
7160 Diag = diag::error_readonly_message_assignment;
7161 break;
Fariborz Jahaniane8d28902009-12-15 23:59:41 +00007162 case Expr::MLV_SubObjCPropertySetting:
7163 Diag = diag::error_no_subobject_property_setting;
7164 break;
Steve Naroff218bc2b2007-05-04 21:54:46 +00007165 }
Steve Naroffad373bd2007-07-31 12:34:36 +00007166
Daniel Dunbarc2223ab2009-04-15 00:08:05 +00007167 SourceRange Assign;
7168 if (Loc != OrigLoc)
7169 Assign = SourceRange(OrigLoc, OrigLoc);
Chris Lattner30bd3272008-11-18 01:22:49 +00007170 if (NeedType)
Daniel Dunbarc2223ab2009-04-15 00:08:05 +00007171 S.Diag(Loc, Diag) << E->getType() << E->getSourceRange() << Assign;
Chris Lattner30bd3272008-11-18 01:22:49 +00007172 else
Mike Stump11289f42009-09-09 15:08:12 +00007173 S.Diag(Loc, Diag) << E->getSourceRange() << Assign;
Chris Lattner30bd3272008-11-18 01:22:49 +00007174 return true;
7175}
7176
7177
7178
7179// C99 6.5.16.1
Richard Trieuda4f43a62011-09-07 01:33:52 +00007180QualType Sema::CheckAssignmentOperands(Expr *LHSExpr, ExprResult &RHS,
Chris Lattner326f7572008-11-18 01:30:42 +00007181 SourceLocation Loc,
7182 QualType CompoundType) {
John McCall526ab472011-10-25 17:37:35 +00007183 assert(!LHSExpr->hasPlaceholderType(BuiltinType::PseudoObject));
7184
Chris Lattner326f7572008-11-18 01:30:42 +00007185 // Verify that LHS is a modifiable lvalue, and emit error if not.
Richard Trieuda4f43a62011-09-07 01:33:52 +00007186 if (CheckForModifiableLvalue(LHSExpr, Loc, *this))
Chris Lattner30bd3272008-11-18 01:22:49 +00007187 return QualType();
Chris Lattner326f7572008-11-18 01:30:42 +00007188
Richard Trieuda4f43a62011-09-07 01:33:52 +00007189 QualType LHSType = LHSExpr->getType();
Richard Trieucfc491d2011-08-02 04:35:43 +00007190 QualType RHSType = CompoundType.isNull() ? RHS.get()->getType() :
7191 CompoundType;
Chris Lattner9bad62c2008-01-04 18:04:52 +00007192 AssignConvertType ConvTy;
Chris Lattner326f7572008-11-18 01:30:42 +00007193 if (CompoundType.isNull()) {
Fariborz Jahanianbe21aa32010-06-07 22:02:01 +00007194 QualType LHSTy(LHSType);
Fariborz Jahanianbe21aa32010-06-07 22:02:01 +00007195 ConvTy = CheckSingleAssignmentConstraints(LHSTy, RHS);
John Wiegley01296292011-04-08 18:41:53 +00007196 if (RHS.isInvalid())
7197 return QualType();
Fariborz Jahanian255c0952009-01-13 23:34:40 +00007198 // Special case of NSObject attributes on c-style pointer types.
7199 if (ConvTy == IncompatiblePointer &&
7200 ((Context.isObjCNSObjectType(LHSType) &&
Steve Naroff79d12152009-07-16 15:41:00 +00007201 RHSType->isObjCObjectPointerType()) ||
Fariborz Jahanian255c0952009-01-13 23:34:40 +00007202 (Context.isObjCNSObjectType(RHSType) &&
Steve Naroff79d12152009-07-16 15:41:00 +00007203 LHSType->isObjCObjectPointerType())))
Fariborz Jahanian255c0952009-01-13 23:34:40 +00007204 ConvTy = Compatible;
Mike Stump4e1f26a2009-02-19 03:04:26 +00007205
John McCall7decc9e2010-11-18 06:31:45 +00007206 if (ConvTy == Compatible &&
Fariborz Jahaniane2a77762012-01-24 19:40:13 +00007207 LHSType->isObjCObjectType())
Fariborz Jahanian3c4225a2012-01-24 18:05:45 +00007208 Diag(Loc, diag::err_objc_object_assignment)
7209 << LHSType;
John McCall7decc9e2010-11-18 06:31:45 +00007210
Chris Lattnerea714382008-08-21 18:04:13 +00007211 // If the RHS is a unary plus or minus, check to see if they = and + are
7212 // right next to each other. If so, the user may have typo'd "x =+ 4"
7213 // instead of "x += 4".
John Wiegley01296292011-04-08 18:41:53 +00007214 Expr *RHSCheck = RHS.get();
Chris Lattnerea714382008-08-21 18:04:13 +00007215 if (ImplicitCastExpr *ICE = dyn_cast<ImplicitCastExpr>(RHSCheck))
7216 RHSCheck = ICE->getSubExpr();
7217 if (UnaryOperator *UO = dyn_cast<UnaryOperator>(RHSCheck)) {
John McCalle3027922010-08-25 11:45:40 +00007218 if ((UO->getOpcode() == UO_Plus ||
7219 UO->getOpcode() == UO_Minus) &&
Chris Lattner326f7572008-11-18 01:30:42 +00007220 Loc.isFileID() && UO->getOperatorLoc().isFileID() &&
Chris Lattnerea714382008-08-21 18:04:13 +00007221 // Only if the two operators are exactly adjacent.
Argyrios Kyrtzidise6e67de2011-09-19 20:40:19 +00007222 Loc.getLocWithOffset(1) == UO->getOperatorLoc() &&
Chris Lattner36c39c92009-03-08 06:51:10 +00007223 // And there is a space or other character before the subexpr of the
7224 // unary +/-. We don't want to warn on "x=-1".
Argyrios Kyrtzidise6e67de2011-09-19 20:40:19 +00007225 Loc.getLocWithOffset(2) != UO->getSubExpr()->getLocStart() &&
Chris Lattnered9f14c2009-03-09 07:11:10 +00007226 UO->getSubExpr()->getLocStart().isFileID()) {
Chris Lattner29e812b2008-11-20 06:06:08 +00007227 Diag(Loc, diag::warn_not_compound_assign)
John McCalle3027922010-08-25 11:45:40 +00007228 << (UO->getOpcode() == UO_Plus ? "+" : "-")
Chris Lattner29e812b2008-11-20 06:06:08 +00007229 << SourceRange(UO->getOperatorLoc(), UO->getOperatorLoc());
Chris Lattner36c39c92009-03-08 06:51:10 +00007230 }
Chris Lattnerea714382008-08-21 18:04:13 +00007231 }
John McCall31168b02011-06-15 23:02:42 +00007232
7233 if (ConvTy == Compatible) {
7234 if (LHSType.getObjCLifetime() == Qualifiers::OCL_Strong)
Richard Trieuda4f43a62011-09-07 01:33:52 +00007235 checkRetainCycles(LHSExpr, RHS.get());
Fariborz Jahanian5f98da02011-06-24 18:25:34 +00007236 else if (getLangOptions().ObjCAutoRefCount)
Richard Trieuda4f43a62011-09-07 01:33:52 +00007237 checkUnsafeExprAssigns(Loc, LHSExpr, RHS.get());
John McCall31168b02011-06-15 23:02:42 +00007238 }
Chris Lattnerea714382008-08-21 18:04:13 +00007239 } else {
7240 // Compound assignment "x += y"
Douglas Gregorc03a1082011-01-28 02:26:04 +00007241 ConvTy = CheckAssignmentConstraints(Loc, LHSType, RHSType);
Chris Lattnerea714382008-08-21 18:04:13 +00007242 }
Chris Lattner9bad62c2008-01-04 18:04:52 +00007243
Chris Lattner326f7572008-11-18 01:30:42 +00007244 if (DiagnoseAssignmentResult(ConvTy, Loc, LHSType, RHSType,
John Wiegley01296292011-04-08 18:41:53 +00007245 RHS.get(), AA_Assigning))
Chris Lattner9bad62c2008-01-04 18:04:52 +00007246 return QualType();
Mike Stump4e1f26a2009-02-19 03:04:26 +00007247
Richard Trieuda4f43a62011-09-07 01:33:52 +00007248 CheckForNullPointerDereference(*this, LHSExpr);
Kaelyn Uhrain2e7aa5a2011-08-05 23:18:04 +00007249
Steve Naroff98cf3e92007-06-06 18:38:38 +00007250 // C99 6.5.16p3: The type of an assignment expression is the type of the
7251 // left operand unless the left operand has qualified type, in which case
Mike Stump4e1f26a2009-02-19 03:04:26 +00007252 // it is the unqualified version of the type of the left operand.
Steve Naroff98cf3e92007-06-06 18:38:38 +00007253 // C99 6.5.16.1p2: In simple assignment, the value of the right operand
7254 // is converted to the type of the assignment expression (above).
Chris Lattnerf17bd422007-08-30 17:45:32 +00007255 // C++ 5.17p1: the type of the assignment expression is that of its left
Douglas Gregord2c2d172009-05-02 00:36:19 +00007256 // operand.
John McCall01cbf2d2010-10-12 02:19:57 +00007257 return (getLangOptions().CPlusPlus
7258 ? LHSType : LHSType.getUnqualifiedType());
Steve Naroffae4143e2007-04-26 20:39:23 +00007259}
7260
Chris Lattner326f7572008-11-18 01:30:42 +00007261// C99 6.5.17
John Wiegley01296292011-04-08 18:41:53 +00007262static QualType CheckCommaOperands(Sema &S, ExprResult &LHS, ExprResult &RHS,
John McCall4bc41ae2010-11-18 19:01:18 +00007263 SourceLocation Loc) {
John Wiegley01296292011-04-08 18:41:53 +00007264 S.DiagnoseUnusedExprResult(LHS.get());
Argyrios Kyrtzidis639ffb02010-06-30 10:53:14 +00007265
John McCall3aef3d82011-04-10 19:13:55 +00007266 LHS = S.CheckPlaceholderExpr(LHS.take());
7267 RHS = S.CheckPlaceholderExpr(RHS.take());
John Wiegley01296292011-04-08 18:41:53 +00007268 if (LHS.isInvalid() || RHS.isInvalid())
Douglas Gregor0124e9b2010-11-09 21:07:58 +00007269 return QualType();
7270
John McCall73d36182010-10-12 07:14:40 +00007271 // C's comma performs lvalue conversion (C99 6.3.2.1) on both its
7272 // operands, but not unary promotions.
7273 // C++'s comma does not do any conversions at all (C++ [expr.comma]p1).
Eli Friedmanba961a92009-03-23 00:24:07 +00007274
John McCall34376a62010-12-04 03:47:34 +00007275 // So we treat the LHS as a ignored value, and in C++ we allow the
7276 // containing site to determine what should be done with the RHS.
John Wiegley01296292011-04-08 18:41:53 +00007277 LHS = S.IgnoredValueConversions(LHS.take());
7278 if (LHS.isInvalid())
7279 return QualType();
John McCall34376a62010-12-04 03:47:34 +00007280
7281 if (!S.getLangOptions().CPlusPlus) {
John Wiegley01296292011-04-08 18:41:53 +00007282 RHS = S.DefaultFunctionArrayLvalueConversion(RHS.take());
7283 if (RHS.isInvalid())
7284 return QualType();
7285 if (!RHS.get()->getType()->isVoidType())
Richard Trieucfc491d2011-08-02 04:35:43 +00007286 S.RequireCompleteType(Loc, RHS.get()->getType(),
7287 diag::err_incomplete_type);
John McCall73d36182010-10-12 07:14:40 +00007288 }
Eli Friedmanba961a92009-03-23 00:24:07 +00007289
John Wiegley01296292011-04-08 18:41:53 +00007290 return RHS.get()->getType();
Steve Naroff95af0132007-03-30 23:47:58 +00007291}
7292
Steve Naroff7a5af782007-07-13 16:58:59 +00007293/// CheckIncrementDecrementOperand - unlike most "Check" methods, this routine
7294/// doesn't need to call UsualUnaryConversions or UsualArithmeticConversions.
John McCall4bc41ae2010-11-18 19:01:18 +00007295static QualType CheckIncrementDecrementOperand(Sema &S, Expr *Op,
7296 ExprValueKind &VK,
7297 SourceLocation OpLoc,
Richard Trieuba63ce62011-09-09 01:45:06 +00007298 bool IsInc, bool IsPrefix) {
Sebastian Redl8d2ccae2009-02-26 14:39:58 +00007299 if (Op->isTypeDependent())
John McCall4bc41ae2010-11-18 19:01:18 +00007300 return S.Context.DependentTy;
Sebastian Redl8d2ccae2009-02-26 14:39:58 +00007301
Chris Lattner6b0cf142008-11-21 07:05:48 +00007302 QualType ResType = Op->getType();
David Chisnallfa35df62012-01-16 17:27:18 +00007303 // Atomic types can be used for increment / decrement where the non-atomic
7304 // versions can, so ignore the _Atomic() specifier for the purpose of
7305 // checking.
7306 if (const AtomicType *ResAtomicType = ResType->getAs<AtomicType>())
7307 ResType = ResAtomicType->getValueType();
7308
Chris Lattner6b0cf142008-11-21 07:05:48 +00007309 assert(!ResType.isNull() && "no type for increment/decrement expression");
Steve Naroffd50c88e2007-04-05 21:15:20 +00007310
John McCall4bc41ae2010-11-18 19:01:18 +00007311 if (S.getLangOptions().CPlusPlus && ResType->isBooleanType()) {
Sebastian Redle10c2c32008-12-20 09:35:34 +00007312 // Decrement of bool is not allowed.
Richard Trieuba63ce62011-09-09 01:45:06 +00007313 if (!IsInc) {
John McCall4bc41ae2010-11-18 19:01:18 +00007314 S.Diag(OpLoc, diag::err_decrement_bool) << Op->getSourceRange();
Sebastian Redle10c2c32008-12-20 09:35:34 +00007315 return QualType();
7316 }
7317 // Increment of bool sets it to true, but is deprecated.
John McCall4bc41ae2010-11-18 19:01:18 +00007318 S.Diag(OpLoc, diag::warn_increment_bool) << Op->getSourceRange();
Sebastian Redle10c2c32008-12-20 09:35:34 +00007319 } else if (ResType->isRealType()) {
Chris Lattner6b0cf142008-11-21 07:05:48 +00007320 // OK!
Steve Naroff6b712a72009-07-14 18:25:06 +00007321 } else if (ResType->isAnyPointerType()) {
Chris Lattner6b0cf142008-11-21 07:05:48 +00007322 // C99 6.5.2.4p2, 6.5.6p2
Chandler Carruthc9332212011-06-27 08:02:19 +00007323 if (!checkArithmeticOpPointerOperand(S, OpLoc, Op))
Douglas Gregordd430f72009-01-19 19:26:10 +00007324 return QualType();
Chandler Carruthc9332212011-06-27 08:02:19 +00007325
Fariborz Jahanianca75db72009-07-16 17:59:14 +00007326 // Diagnose bad cases where we step over interface counts.
Richard Trieub10c6312011-09-01 22:53:23 +00007327 else if (!checkArithmethicPointerOnNonFragileABI(S, OpLoc, Op))
Fariborz Jahanianca75db72009-07-16 17:59:14 +00007328 return QualType();
Eli Friedman090addd2010-01-03 00:20:48 +00007329 } else if (ResType->isAnyComplexType()) {
Chris Lattner6b0cf142008-11-21 07:05:48 +00007330 // C99 does not support ++/-- on complex types, we allow as an extension.
John McCall4bc41ae2010-11-18 19:01:18 +00007331 S.Diag(OpLoc, diag::ext_integer_increment_complex)
Chris Lattner1e5665e2008-11-24 06:25:27 +00007332 << ResType << Op->getSourceRange();
John McCall36226622010-10-12 02:09:17 +00007333 } else if (ResType->isPlaceholderType()) {
John McCall3aef3d82011-04-10 19:13:55 +00007334 ExprResult PR = S.CheckPlaceholderExpr(Op);
John McCall36226622010-10-12 02:09:17 +00007335 if (PR.isInvalid()) return QualType();
John McCall4bc41ae2010-11-18 19:01:18 +00007336 return CheckIncrementDecrementOperand(S, PR.take(), VK, OpLoc,
Richard Trieuba63ce62011-09-09 01:45:06 +00007337 IsInc, IsPrefix);
Anton Yartsev85129b82011-02-07 02:17:30 +00007338 } else if (S.getLangOptions().AltiVec && ResType->isVectorType()) {
7339 // OK! ( C/C++ Language Extensions for CBEA(Version 2.6) 10.3 )
Chris Lattner6b0cf142008-11-21 07:05:48 +00007340 } else {
John McCall4bc41ae2010-11-18 19:01:18 +00007341 S.Diag(OpLoc, diag::err_typecheck_illegal_increment_decrement)
Richard Trieuba63ce62011-09-09 01:45:06 +00007342 << ResType << int(IsInc) << Op->getSourceRange();
Chris Lattner6b0cf142008-11-21 07:05:48 +00007343 return QualType();
Steve Naroff46ba1eb2007-04-03 23:13:13 +00007344 }
Mike Stump4e1f26a2009-02-19 03:04:26 +00007345 // At this point, we know we have a real, complex or pointer type.
Steve Naroff9e1e5512007-08-23 21:37:33 +00007346 // Now make sure the operand is a modifiable lvalue.
John McCall4bc41ae2010-11-18 19:01:18 +00007347 if (CheckForModifiableLvalue(Op, OpLoc, S))
Steve Naroff35d85152007-05-07 00:24:15 +00007348 return QualType();
Alexis Huntc46382e2010-04-28 23:02:27 +00007349 // In C++, a prefix increment is the same type as the operand. Otherwise
7350 // (in C or with postfix), the increment is the unqualified type of the
7351 // operand.
Richard Trieuba63ce62011-09-09 01:45:06 +00007352 if (IsPrefix && S.getLangOptions().CPlusPlus) {
John McCall4bc41ae2010-11-18 19:01:18 +00007353 VK = VK_LValue;
7354 return ResType;
7355 } else {
7356 VK = VK_RValue;
7357 return ResType.getUnqualifiedType();
7358 }
Steve Naroff26c8ea52007-03-21 21:08:52 +00007359}
Fariborz Jahanian805b74e2010-09-14 23:02:38 +00007360
7361
Anders Carlsson806700f2008-02-01 07:15:58 +00007362/// getPrimaryDecl - Helper function for CheckAddressOfOperand().
Steve Naroff47500512007-04-19 23:00:49 +00007363/// This routine allows us to typecheck complex/recursive expressions
Daniel Dunbarb692ef42008-08-04 20:02:37 +00007364/// where the declaration is needed for type checking. We only need to
7365/// handle cases when the expression references a function designator
7366/// or is an lvalue. Here are some examples:
7367/// - &(x) => x
7368/// - &*****f => f for f a function designator.
7369/// - &s.xx => s
7370/// - &s.zz[1].yy -> s, if zz is an array
7371/// - *(x + 1) -> x, if x is an array
7372/// - &"123"[2] -> 0
7373/// - & __real__ x -> x
John McCallf3a88602011-02-03 08:15:49 +00007374static ValueDecl *getPrimaryDecl(Expr *E) {
Chris Lattner24d5bfe2008-04-02 04:24:33 +00007375 switch (E->getStmtClass()) {
Steve Naroff47500512007-04-19 23:00:49 +00007376 case Stmt::DeclRefExprClass:
Chris Lattner24d5bfe2008-04-02 04:24:33 +00007377 return cast<DeclRefExpr>(E)->getDecl();
Steve Naroff47500512007-04-19 23:00:49 +00007378 case Stmt::MemberExprClass:
Eli Friedman3a1e6922009-04-20 08:23:18 +00007379 // If this is an arrow operator, the address is an offset from
7380 // the base's value, so the object the base refers to is
7381 // irrelevant.
Chris Lattner24d5bfe2008-04-02 04:24:33 +00007382 if (cast<MemberExpr>(E)->isArrow())
Chris Lattner48d52842007-11-16 17:46:48 +00007383 return 0;
Eli Friedman3a1e6922009-04-20 08:23:18 +00007384 // Otherwise, the expression refers to a part of the base
Chris Lattner24d5bfe2008-04-02 04:24:33 +00007385 return getPrimaryDecl(cast<MemberExpr>(E)->getBase());
Anders Carlsson806700f2008-02-01 07:15:58 +00007386 case Stmt::ArraySubscriptExprClass: {
Mike Stump87c57ac2009-05-16 07:39:55 +00007387 // FIXME: This code shouldn't be necessary! We should catch the implicit
7388 // promotion of register arrays earlier.
Eli Friedman3a1e6922009-04-20 08:23:18 +00007389 Expr* Base = cast<ArraySubscriptExpr>(E)->getBase();
7390 if (ImplicitCastExpr* ICE = dyn_cast<ImplicitCastExpr>(Base)) {
7391 if (ICE->getSubExpr()->getType()->isArrayType())
7392 return getPrimaryDecl(ICE->getSubExpr());
7393 }
7394 return 0;
Anders Carlsson806700f2008-02-01 07:15:58 +00007395 }
Daniel Dunbarb692ef42008-08-04 20:02:37 +00007396 case Stmt::UnaryOperatorClass: {
7397 UnaryOperator *UO = cast<UnaryOperator>(E);
Mike Stump4e1f26a2009-02-19 03:04:26 +00007398
Daniel Dunbarb692ef42008-08-04 20:02:37 +00007399 switch(UO->getOpcode()) {
John McCalle3027922010-08-25 11:45:40 +00007400 case UO_Real:
7401 case UO_Imag:
7402 case UO_Extension:
Daniel Dunbarb692ef42008-08-04 20:02:37 +00007403 return getPrimaryDecl(UO->getSubExpr());
7404 default:
7405 return 0;
7406 }
7407 }
Steve Naroff47500512007-04-19 23:00:49 +00007408 case Stmt::ParenExprClass:
Chris Lattner24d5bfe2008-04-02 04:24:33 +00007409 return getPrimaryDecl(cast<ParenExpr>(E)->getSubExpr());
Chris Lattner48d52842007-11-16 17:46:48 +00007410 case Stmt::ImplicitCastExprClass:
Eli Friedman3a1e6922009-04-20 08:23:18 +00007411 // If the result of an implicit cast is an l-value, we care about
7412 // the sub-expression; otherwise, the result here doesn't matter.
Chris Lattner24d5bfe2008-04-02 04:24:33 +00007413 return getPrimaryDecl(cast<ImplicitCastExpr>(E)->getSubExpr());
Steve Naroff47500512007-04-19 23:00:49 +00007414 default:
7415 return 0;
7416 }
7417}
7418
Richard Trieu5f376f62011-09-07 21:46:33 +00007419namespace {
7420 enum {
7421 AO_Bit_Field = 0,
7422 AO_Vector_Element = 1,
7423 AO_Property_Expansion = 2,
7424 AO_Register_Variable = 3,
7425 AO_No_Error = 4
7426 };
7427}
Richard Trieu3fd7bb82011-09-02 00:47:55 +00007428/// \brief Diagnose invalid operand for address of operations.
7429///
7430/// \param Type The type of operand which cannot have its address taken.
Richard Trieu3fd7bb82011-09-02 00:47:55 +00007431static void diagnoseAddressOfInvalidType(Sema &S, SourceLocation Loc,
7432 Expr *E, unsigned Type) {
7433 S.Diag(Loc, diag::err_typecheck_address_of) << Type << E->getSourceRange();
7434}
7435
Steve Naroff47500512007-04-19 23:00:49 +00007436/// CheckAddressOfOperand - The operand of & must be either a function
Mike Stump4e1f26a2009-02-19 03:04:26 +00007437/// designator or an lvalue designating an object. If it is an lvalue, the
Steve Naroff47500512007-04-19 23:00:49 +00007438/// object cannot be declared with storage class register or be a bit field.
Mike Stump4e1f26a2009-02-19 03:04:26 +00007439/// Note: The usual conversions are *not* applied to the operand of the &
Steve Naroffa78fe7e2007-05-16 19:47:19 +00007440/// operator (C99 6.3.2.1p[2-4]), and its result is never an lvalue.
Mike Stump4e1f26a2009-02-19 03:04:26 +00007441/// In C++, the operand might be an overloaded function name, in which case
Douglas Gregorcd695e52008-11-10 20:40:00 +00007442/// we allow the '&' but retain the overloaded-function type.
John McCall526ab472011-10-25 17:37:35 +00007443static QualType CheckAddressOfOperand(Sema &S, ExprResult &OrigOp,
John McCall4bc41ae2010-11-18 19:01:18 +00007444 SourceLocation OpLoc) {
John McCall526ab472011-10-25 17:37:35 +00007445 if (const BuiltinType *PTy = OrigOp.get()->getType()->getAsPlaceholderType()){
7446 if (PTy->getKind() == BuiltinType::Overload) {
7447 if (!isa<OverloadExpr>(OrigOp.get()->IgnoreParens())) {
7448 S.Diag(OpLoc, diag::err_typecheck_invalid_lvalue_addrof)
7449 << OrigOp.get()->getSourceRange();
7450 return QualType();
7451 }
7452
7453 return S.Context.OverloadTy;
7454 }
7455
7456 if (PTy->getKind() == BuiltinType::UnknownAny)
7457 return S.Context.UnknownAnyTy;
7458
7459 if (PTy->getKind() == BuiltinType::BoundMember) {
7460 S.Diag(OpLoc, diag::err_invalid_form_pointer_member_function)
7461 << OrigOp.get()->getSourceRange();
Douglas Gregor668d3622011-10-09 19:10:41 +00007462 return QualType();
7463 }
John McCall526ab472011-10-25 17:37:35 +00007464
7465 OrigOp = S.CheckPlaceholderExpr(OrigOp.take());
7466 if (OrigOp.isInvalid()) return QualType();
John McCall0009fcc2011-04-26 20:42:42 +00007467 }
John McCall8d08b9b2010-08-27 09:08:28 +00007468
John McCall526ab472011-10-25 17:37:35 +00007469 if (OrigOp.get()->isTypeDependent())
7470 return S.Context.DependentTy;
7471
7472 assert(!OrigOp.get()->getType()->isPlaceholderType());
John McCall36226622010-10-12 02:09:17 +00007473
John McCall8d08b9b2010-08-27 09:08:28 +00007474 // Make sure to ignore parentheses in subsequent checks
John McCall526ab472011-10-25 17:37:35 +00007475 Expr *op = OrigOp.get()->IgnoreParens();
Douglas Gregor19b8c4f2008-12-17 22:52:20 +00007476
John McCall4bc41ae2010-11-18 19:01:18 +00007477 if (S.getLangOptions().C99) {
Steve Naroff826e91a2008-01-13 17:10:08 +00007478 // Implement C99-only parts of addressof rules.
7479 if (UnaryOperator* uOp = dyn_cast<UnaryOperator>(op)) {
John McCalle3027922010-08-25 11:45:40 +00007480 if (uOp->getOpcode() == UO_Deref)
Steve Naroff826e91a2008-01-13 17:10:08 +00007481 // Per C99 6.5.3.2, the address of a deref always returns a valid result
7482 // (assuming the deref expression is valid).
7483 return uOp->getSubExpr()->getType();
7484 }
7485 // Technically, there should be a check for array subscript
7486 // expressions here, but the result of one is always an lvalue anyway.
7487 }
John McCallf3a88602011-02-03 08:15:49 +00007488 ValueDecl *dcl = getPrimaryDecl(op);
John McCall086a4642010-11-24 05:12:34 +00007489 Expr::LValueClassification lval = op->ClassifyLValue(S.Context);
Richard Trieu5f376f62011-09-07 21:46:33 +00007490 unsigned AddressOfError = AO_No_Error;
Nuno Lopes17f345f2008-12-16 22:59:47 +00007491
Fariborz Jahanian071caef2011-03-26 19:48:30 +00007492 if (lval == Expr::LV_ClassTemporary) {
John McCall4bc41ae2010-11-18 19:01:18 +00007493 bool sfinae = S.isSFINAEContext();
7494 S.Diag(OpLoc, sfinae ? diag::err_typecheck_addrof_class_temporary
7495 : diag::ext_typecheck_addrof_class_temporary)
Douglas Gregorb154fdc2010-02-16 21:39:57 +00007496 << op->getType() << op->getSourceRange();
John McCall4bc41ae2010-11-18 19:01:18 +00007497 if (sfinae)
Douglas Gregorb154fdc2010-02-16 21:39:57 +00007498 return QualType();
John McCall8d08b9b2010-08-27 09:08:28 +00007499 } else if (isa<ObjCSelectorExpr>(op)) {
John McCall4bc41ae2010-11-18 19:01:18 +00007500 return S.Context.getPointerType(op->getType());
John McCall8d08b9b2010-08-27 09:08:28 +00007501 } else if (lval == Expr::LV_MemberFunction) {
7502 // If it's an instance method, make a member pointer.
7503 // The expression must have exactly the form &A::foo.
7504
7505 // If the underlying expression isn't a decl ref, give up.
7506 if (!isa<DeclRefExpr>(op)) {
John McCall4bc41ae2010-11-18 19:01:18 +00007507 S.Diag(OpLoc, diag::err_invalid_form_pointer_member_function)
John McCall526ab472011-10-25 17:37:35 +00007508 << OrigOp.get()->getSourceRange();
John McCall8d08b9b2010-08-27 09:08:28 +00007509 return QualType();
7510 }
7511 DeclRefExpr *DRE = cast<DeclRefExpr>(op);
7512 CXXMethodDecl *MD = cast<CXXMethodDecl>(DRE->getDecl());
7513
7514 // The id-expression was parenthesized.
John McCall526ab472011-10-25 17:37:35 +00007515 if (OrigOp.get() != DRE) {
John McCall4bc41ae2010-11-18 19:01:18 +00007516 S.Diag(OpLoc, diag::err_parens_pointer_member_function)
John McCall526ab472011-10-25 17:37:35 +00007517 << OrigOp.get()->getSourceRange();
John McCall8d08b9b2010-08-27 09:08:28 +00007518
7519 // The method was named without a qualifier.
7520 } else if (!DRE->getQualifier()) {
John McCall4bc41ae2010-11-18 19:01:18 +00007521 S.Diag(OpLoc, diag::err_unqualified_pointer_member_function)
John McCall8d08b9b2010-08-27 09:08:28 +00007522 << op->getSourceRange();
7523 }
7524
John McCall4bc41ae2010-11-18 19:01:18 +00007525 return S.Context.getMemberPointerType(op->getType(),
7526 S.Context.getTypeDeclType(MD->getParent()).getTypePtr());
John McCall8d08b9b2010-08-27 09:08:28 +00007527 } else if (lval != Expr::LV_Valid && lval != Expr::LV_IncompleteVoidType) {
Eli Friedmance7f9002009-05-16 23:27:50 +00007528 // C99 6.5.3.2p1
Eli Friedman3a1e6922009-04-20 08:23:18 +00007529 // The operand must be either an l-value or a function designator
Eli Friedmance7f9002009-05-16 23:27:50 +00007530 if (!op->getType()->isFunctionType()) {
John McCall526ab472011-10-25 17:37:35 +00007531 // Use a special diagnostic for loads from property references.
John McCallfe96e0b2011-11-06 09:01:30 +00007532 if (isa<PseudoObjectExpr>(op)) {
John McCall526ab472011-10-25 17:37:35 +00007533 AddressOfError = AO_Property_Expansion;
7534 } else {
7535 // FIXME: emit more specific diag...
7536 S.Diag(OpLoc, diag::err_typecheck_invalid_lvalue_addrof)
7537 << op->getSourceRange();
7538 return QualType();
7539 }
Steve Naroff35d85152007-05-07 00:24:15 +00007540 }
John McCall086a4642010-11-24 05:12:34 +00007541 } else if (op->getObjectKind() == OK_BitField) { // C99 6.5.3.2p1
Eli Friedman3a1e6922009-04-20 08:23:18 +00007542 // The operand cannot be a bit-field
Richard Trieu5f376f62011-09-07 21:46:33 +00007543 AddressOfError = AO_Bit_Field;
John McCall086a4642010-11-24 05:12:34 +00007544 } else if (op->getObjectKind() == OK_VectorComponent) {
Eli Friedman3a1e6922009-04-20 08:23:18 +00007545 // The operand cannot be an element of a vector
Richard Trieu5f376f62011-09-07 21:46:33 +00007546 AddressOfError = AO_Vector_Element;
Steve Naroffb96e4ab62008-02-29 23:30:25 +00007547 } else if (dcl) { // C99 6.5.3.2p1
Mike Stump4e1f26a2009-02-19 03:04:26 +00007548 // We have an lvalue with a decl. Make sure the decl is not declared
Steve Naroff47500512007-04-19 23:00:49 +00007549 // with the register storage-class specifier.
7550 if (const VarDecl *vd = dyn_cast<VarDecl>(dcl)) {
Fariborz Jahaniane0fd5a92010-08-24 22:21:48 +00007551 // in C++ it is not error to take address of a register
7552 // variable (c++03 7.1.1P3)
John McCall8e7d6562010-08-26 03:08:43 +00007553 if (vd->getStorageClass() == SC_Register &&
John McCall4bc41ae2010-11-18 19:01:18 +00007554 !S.getLangOptions().CPlusPlus) {
Richard Trieu5f376f62011-09-07 21:46:33 +00007555 AddressOfError = AO_Register_Variable;
Steve Naroff35d85152007-05-07 00:24:15 +00007556 }
John McCalld14a8642009-11-21 08:51:07 +00007557 } else if (isa<FunctionTemplateDecl>(dcl)) {
John McCall4bc41ae2010-11-18 19:01:18 +00007558 return S.Context.OverloadTy;
John McCallf3a88602011-02-03 08:15:49 +00007559 } else if (isa<FieldDecl>(dcl) || isa<IndirectFieldDecl>(dcl)) {
Douglas Gregor9aa8b552008-12-10 21:26:49 +00007560 // Okay: we can take the address of a field.
Sebastian Redl3d3f75a2009-02-03 20:19:35 +00007561 // Could be a pointer to member, though, if there is an explicit
7562 // scope qualifier for the class.
Douglas Gregor4bd90e52009-10-23 18:54:35 +00007563 if (isa<DeclRefExpr>(op) && cast<DeclRefExpr>(op)->getQualifier()) {
Sebastian Redl3d3f75a2009-02-03 20:19:35 +00007564 DeclContext *Ctx = dcl->getDeclContext();
Anders Carlsson0b675f52009-07-08 21:45:58 +00007565 if (Ctx && Ctx->isRecord()) {
John McCallf3a88602011-02-03 08:15:49 +00007566 if (dcl->getType()->isReferenceType()) {
John McCall4bc41ae2010-11-18 19:01:18 +00007567 S.Diag(OpLoc,
7568 diag::err_cannot_form_pointer_to_member_of_reference_type)
John McCallf3a88602011-02-03 08:15:49 +00007569 << dcl->getDeclName() << dcl->getType();
Anders Carlsson0b675f52009-07-08 21:45:58 +00007570 return QualType();
7571 }
Mike Stump11289f42009-09-09 15:08:12 +00007572
Argyrios Kyrtzidis8322b422011-01-31 07:04:29 +00007573 while (cast<RecordDecl>(Ctx)->isAnonymousStructOrUnion())
7574 Ctx = Ctx->getParent();
John McCall4bc41ae2010-11-18 19:01:18 +00007575 return S.Context.getMemberPointerType(op->getType(),
7576 S.Context.getTypeDeclType(cast<RecordDecl>(Ctx)).getTypePtr());
Anders Carlsson0b675f52009-07-08 21:45:58 +00007577 }
Sebastian Redl3d3f75a2009-02-03 20:19:35 +00007578 }
Eli Friedman755c0c92011-08-26 20:28:17 +00007579 } else if (!isa<FunctionDecl>(dcl) && !isa<NonTypeTemplateParmDecl>(dcl))
David Blaikie83d382b2011-09-23 05:06:16 +00007580 llvm_unreachable("Unknown/unexpected decl type");
Steve Naroff47500512007-04-19 23:00:49 +00007581 }
Sebastian Redl18f8ff62009-02-04 21:23:32 +00007582
Richard Trieu5f376f62011-09-07 21:46:33 +00007583 if (AddressOfError != AO_No_Error) {
7584 diagnoseAddressOfInvalidType(S, OpLoc, op, AddressOfError);
7585 return QualType();
7586 }
7587
Eli Friedmance7f9002009-05-16 23:27:50 +00007588 if (lval == Expr::LV_IncompleteVoidType) {
7589 // Taking the address of a void variable is technically illegal, but we
7590 // allow it in cases which are otherwise valid.
7591 // Example: "extern void x; void* y = &x;".
John McCall4bc41ae2010-11-18 19:01:18 +00007592 S.Diag(OpLoc, diag::ext_typecheck_addrof_void) << op->getSourceRange();
Eli Friedmance7f9002009-05-16 23:27:50 +00007593 }
7594
Steve Naroff47500512007-04-19 23:00:49 +00007595 // If the operand has type "type", the result has type "pointer to type".
Douglas Gregor0bdcb8a2010-07-29 16:05:45 +00007596 if (op->getType()->isObjCObjectType())
John McCall4bc41ae2010-11-18 19:01:18 +00007597 return S.Context.getObjCObjectPointerType(op->getType());
7598 return S.Context.getPointerType(op->getType());
Steve Naroff47500512007-04-19 23:00:49 +00007599}
7600
Chris Lattner9156f1b2010-07-05 19:17:26 +00007601/// CheckIndirectionOperand - Type check unary indirection (prefix '*').
John McCall4bc41ae2010-11-18 19:01:18 +00007602static QualType CheckIndirectionOperand(Sema &S, Expr *Op, ExprValueKind &VK,
7603 SourceLocation OpLoc) {
Sebastian Redl8d2ccae2009-02-26 14:39:58 +00007604 if (Op->isTypeDependent())
John McCall4bc41ae2010-11-18 19:01:18 +00007605 return S.Context.DependentTy;
Sebastian Redl8d2ccae2009-02-26 14:39:58 +00007606
John Wiegley01296292011-04-08 18:41:53 +00007607 ExprResult ConvResult = S.UsualUnaryConversions(Op);
7608 if (ConvResult.isInvalid())
7609 return QualType();
7610 Op = ConvResult.take();
Chris Lattner9156f1b2010-07-05 19:17:26 +00007611 QualType OpTy = Op->getType();
7612 QualType Result;
Argyrios Kyrtzidis69a2c922011-05-02 18:21:19 +00007613
7614 if (isa<CXXReinterpretCastExpr>(Op)) {
7615 QualType OpOrigType = Op->IgnoreParenCasts()->getType();
7616 S.CheckCompatibleReinterpretCast(OpOrigType, OpTy, /*IsDereference*/true,
7617 Op->getSourceRange());
7618 }
7619
Chris Lattner9156f1b2010-07-05 19:17:26 +00007620 // Note that per both C89 and C99, indirection is always legal, even if OpTy
7621 // is an incomplete type or void. It would be possible to warn about
7622 // dereferencing a void pointer, but it's completely well-defined, and such a
7623 // warning is unlikely to catch any mistakes.
7624 if (const PointerType *PT = OpTy->getAs<PointerType>())
7625 Result = PT->getPointeeType();
7626 else if (const ObjCObjectPointerType *OPT =
7627 OpTy->getAs<ObjCObjectPointerType>())
7628 Result = OPT->getPointeeType();
John McCall36226622010-10-12 02:09:17 +00007629 else {
John McCall3aef3d82011-04-10 19:13:55 +00007630 ExprResult PR = S.CheckPlaceholderExpr(Op);
John McCall36226622010-10-12 02:09:17 +00007631 if (PR.isInvalid()) return QualType();
John McCall4bc41ae2010-11-18 19:01:18 +00007632 if (PR.take() != Op)
7633 return CheckIndirectionOperand(S, PR.take(), VK, OpLoc);
John McCall36226622010-10-12 02:09:17 +00007634 }
Mike Stump4e1f26a2009-02-19 03:04:26 +00007635
Chris Lattner9156f1b2010-07-05 19:17:26 +00007636 if (Result.isNull()) {
John McCall4bc41ae2010-11-18 19:01:18 +00007637 S.Diag(OpLoc, diag::err_typecheck_indirection_requires_pointer)
Chris Lattner9156f1b2010-07-05 19:17:26 +00007638 << OpTy << Op->getSourceRange();
7639 return QualType();
7640 }
John McCall4bc41ae2010-11-18 19:01:18 +00007641
7642 // Dereferences are usually l-values...
7643 VK = VK_LValue;
7644
7645 // ...except that certain expressions are never l-values in C.
Douglas Gregor5476205b2011-06-23 00:49:38 +00007646 if (!S.getLangOptions().CPlusPlus && Result.isCForbiddenLValueType())
John McCall4bc41ae2010-11-18 19:01:18 +00007647 VK = VK_RValue;
Chris Lattner9156f1b2010-07-05 19:17:26 +00007648
7649 return Result;
Steve Naroff1926c832007-04-24 00:23:05 +00007650}
Steve Naroff218bc2b2007-05-04 21:54:46 +00007651
John McCalle3027922010-08-25 11:45:40 +00007652static inline BinaryOperatorKind ConvertTokenKindToBinaryOpcode(
Steve Naroff218bc2b2007-05-04 21:54:46 +00007653 tok::TokenKind Kind) {
John McCalle3027922010-08-25 11:45:40 +00007654 BinaryOperatorKind Opc;
Steve Naroff218bc2b2007-05-04 21:54:46 +00007655 switch (Kind) {
David Blaikie83d382b2011-09-23 05:06:16 +00007656 default: llvm_unreachable("Unknown binop!");
John McCalle3027922010-08-25 11:45:40 +00007657 case tok::periodstar: Opc = BO_PtrMemD; break;
7658 case tok::arrowstar: Opc = BO_PtrMemI; break;
7659 case tok::star: Opc = BO_Mul; break;
7660 case tok::slash: Opc = BO_Div; break;
7661 case tok::percent: Opc = BO_Rem; break;
7662 case tok::plus: Opc = BO_Add; break;
7663 case tok::minus: Opc = BO_Sub; break;
7664 case tok::lessless: Opc = BO_Shl; break;
7665 case tok::greatergreater: Opc = BO_Shr; break;
7666 case tok::lessequal: Opc = BO_LE; break;
7667 case tok::less: Opc = BO_LT; break;
7668 case tok::greaterequal: Opc = BO_GE; break;
7669 case tok::greater: Opc = BO_GT; break;
7670 case tok::exclaimequal: Opc = BO_NE; break;
7671 case tok::equalequal: Opc = BO_EQ; break;
7672 case tok::amp: Opc = BO_And; break;
7673 case tok::caret: Opc = BO_Xor; break;
7674 case tok::pipe: Opc = BO_Or; break;
7675 case tok::ampamp: Opc = BO_LAnd; break;
7676 case tok::pipepipe: Opc = BO_LOr; break;
7677 case tok::equal: Opc = BO_Assign; break;
7678 case tok::starequal: Opc = BO_MulAssign; break;
7679 case tok::slashequal: Opc = BO_DivAssign; break;
7680 case tok::percentequal: Opc = BO_RemAssign; break;
7681 case tok::plusequal: Opc = BO_AddAssign; break;
7682 case tok::minusequal: Opc = BO_SubAssign; break;
7683 case tok::lesslessequal: Opc = BO_ShlAssign; break;
7684 case tok::greatergreaterequal: Opc = BO_ShrAssign; break;
7685 case tok::ampequal: Opc = BO_AndAssign; break;
7686 case tok::caretequal: Opc = BO_XorAssign; break;
7687 case tok::pipeequal: Opc = BO_OrAssign; break;
7688 case tok::comma: Opc = BO_Comma; break;
Steve Naroff218bc2b2007-05-04 21:54:46 +00007689 }
7690 return Opc;
7691}
7692
John McCalle3027922010-08-25 11:45:40 +00007693static inline UnaryOperatorKind ConvertTokenKindToUnaryOpcode(
Steve Naroff35d85152007-05-07 00:24:15 +00007694 tok::TokenKind Kind) {
John McCalle3027922010-08-25 11:45:40 +00007695 UnaryOperatorKind Opc;
Steve Naroff35d85152007-05-07 00:24:15 +00007696 switch (Kind) {
David Blaikie83d382b2011-09-23 05:06:16 +00007697 default: llvm_unreachable("Unknown unary op!");
John McCalle3027922010-08-25 11:45:40 +00007698 case tok::plusplus: Opc = UO_PreInc; break;
7699 case tok::minusminus: Opc = UO_PreDec; break;
7700 case tok::amp: Opc = UO_AddrOf; break;
7701 case tok::star: Opc = UO_Deref; break;
7702 case tok::plus: Opc = UO_Plus; break;
7703 case tok::minus: Opc = UO_Minus; break;
7704 case tok::tilde: Opc = UO_Not; break;
7705 case tok::exclaim: Opc = UO_LNot; break;
7706 case tok::kw___real: Opc = UO_Real; break;
7707 case tok::kw___imag: Opc = UO_Imag; break;
7708 case tok::kw___extension__: Opc = UO_Extension; break;
Steve Naroff35d85152007-05-07 00:24:15 +00007709 }
7710 return Opc;
7711}
7712
Chandler Carruthe0cee6a2011-01-04 06:52:15 +00007713/// DiagnoseSelfAssignment - Emits a warning if a value is assigned to itself.
7714/// This warning is only emitted for builtin assignment operations. It is also
7715/// suppressed in the event of macro expansions.
Richard Trieuda4f43a62011-09-07 01:33:52 +00007716static void DiagnoseSelfAssignment(Sema &S, Expr *LHSExpr, Expr *RHSExpr,
Chandler Carruthe0cee6a2011-01-04 06:52:15 +00007717 SourceLocation OpLoc) {
7718 if (!S.ActiveTemplateInstantiations.empty())
7719 return;
7720 if (OpLoc.isInvalid() || OpLoc.isMacroID())
7721 return;
Richard Trieuda4f43a62011-09-07 01:33:52 +00007722 LHSExpr = LHSExpr->IgnoreParenImpCasts();
7723 RHSExpr = RHSExpr->IgnoreParenImpCasts();
7724 const DeclRefExpr *LHSDeclRef = dyn_cast<DeclRefExpr>(LHSExpr);
7725 const DeclRefExpr *RHSDeclRef = dyn_cast<DeclRefExpr>(RHSExpr);
7726 if (!LHSDeclRef || !RHSDeclRef ||
7727 LHSDeclRef->getLocation().isMacroID() ||
7728 RHSDeclRef->getLocation().isMacroID())
Chandler Carruthe0cee6a2011-01-04 06:52:15 +00007729 return;
Richard Trieuda4f43a62011-09-07 01:33:52 +00007730 const ValueDecl *LHSDecl =
7731 cast<ValueDecl>(LHSDeclRef->getDecl()->getCanonicalDecl());
7732 const ValueDecl *RHSDecl =
7733 cast<ValueDecl>(RHSDeclRef->getDecl()->getCanonicalDecl());
7734 if (LHSDecl != RHSDecl)
Chandler Carruthe0cee6a2011-01-04 06:52:15 +00007735 return;
Richard Trieuda4f43a62011-09-07 01:33:52 +00007736 if (LHSDecl->getType().isVolatileQualified())
Chandler Carruthe0cee6a2011-01-04 06:52:15 +00007737 return;
Richard Trieuda4f43a62011-09-07 01:33:52 +00007738 if (const ReferenceType *RefTy = LHSDecl->getType()->getAs<ReferenceType>())
Chandler Carruthe0cee6a2011-01-04 06:52:15 +00007739 if (RefTy->getPointeeType().isVolatileQualified())
7740 return;
7741
7742 S.Diag(OpLoc, diag::warn_self_assignment)
Richard Trieuda4f43a62011-09-07 01:33:52 +00007743 << LHSDeclRef->getType()
7744 << LHSExpr->getSourceRange() << RHSExpr->getSourceRange();
Chandler Carruthe0cee6a2011-01-04 06:52:15 +00007745}
7746
Douglas Gregor7d5fc7e2008-11-06 23:29:22 +00007747/// CreateBuiltinBinOp - Creates a new built-in binary operation with
7748/// operator @p Opc at location @c TokLoc. This routine only supports
7749/// built-in operations; ActOnBinOp handles overloaded operators.
John McCalldadc5752010-08-24 06:29:42 +00007750ExprResult Sema::CreateBuiltinBinOp(SourceLocation OpLoc,
Argyrios Kyrtzidis7a808c02011-01-05 20:09:36 +00007751 BinaryOperatorKind Opc,
Richard Trieu4a287fb2011-09-07 01:49:20 +00007752 Expr *LHSExpr, Expr *RHSExpr) {
Sebastian Redl67766732012-02-27 20:34:02 +00007753 if (getLangOptions().CPlusPlus0x && isa<InitListExpr>(RHSExpr)) {
7754 // The syntax only allows initializer lists on the RHS of assignment,
7755 // so we don't need to worry about accepting invalid code for
7756 // non-assignment operators.
7757 // C++11 5.17p9:
7758 // The meaning of x = {v} [...] is that of x = T(v) [...]. The meaning
7759 // of x = {} is x = T().
7760 InitializationKind Kind =
7761 InitializationKind::CreateDirectList(RHSExpr->getLocStart());
7762 InitializedEntity Entity =
7763 InitializedEntity::InitializeTemporary(LHSExpr->getType());
7764 InitializationSequence InitSeq(*this, Entity, Kind, &RHSExpr, 1);
7765 ExprResult Init = InitSeq.Perform(*this, Entity, Kind,
7766 MultiExprArg(&RHSExpr, 1));
7767 if (Init.isInvalid())
7768 return Init;
7769 RHSExpr = Init.take();
7770 }
7771
Richard Trieu4a287fb2011-09-07 01:49:20 +00007772 ExprResult LHS = Owned(LHSExpr), RHS = Owned(RHSExpr);
Eli Friedman8b7b1b12009-03-28 01:22:36 +00007773 QualType ResultTy; // Result type of the binary operator.
Eli Friedman8b7b1b12009-03-28 01:22:36 +00007774 // The following two variables are used for compound assignment operators
7775 QualType CompLHSTy; // Type of LHS after promotions for computation
7776 QualType CompResultTy; // Type of computation result
John McCall7decc9e2010-11-18 06:31:45 +00007777 ExprValueKind VK = VK_RValue;
7778 ExprObjectKind OK = OK_Ordinary;
Douglas Gregor7d5fc7e2008-11-06 23:29:22 +00007779
7780 switch (Opc) {
John McCalle3027922010-08-25 11:45:40 +00007781 case BO_Assign:
Richard Trieu4a287fb2011-09-07 01:49:20 +00007782 ResultTy = CheckAssignmentOperands(LHS.get(), RHS, OpLoc, QualType());
John McCall34376a62010-12-04 03:47:34 +00007783 if (getLangOptions().CPlusPlus &&
Richard Trieu4a287fb2011-09-07 01:49:20 +00007784 LHS.get()->getObjectKind() != OK_ObjCProperty) {
7785 VK = LHS.get()->getValueKind();
7786 OK = LHS.get()->getObjectKind();
John McCall7decc9e2010-11-18 06:31:45 +00007787 }
Chandler Carruthe0cee6a2011-01-04 06:52:15 +00007788 if (!ResultTy.isNull())
Richard Trieu4a287fb2011-09-07 01:49:20 +00007789 DiagnoseSelfAssignment(*this, LHS.get(), RHS.get(), OpLoc);
Douglas Gregor7d5fc7e2008-11-06 23:29:22 +00007790 break;
John McCalle3027922010-08-25 11:45:40 +00007791 case BO_PtrMemD:
7792 case BO_PtrMemI:
Richard Trieu4a287fb2011-09-07 01:49:20 +00007793 ResultTy = CheckPointerToMemberOperands(LHS, RHS, VK, OpLoc,
John McCalle3027922010-08-25 11:45:40 +00007794 Opc == BO_PtrMemI);
Sebastian Redl112a97662009-02-07 00:15:38 +00007795 break;
John McCalle3027922010-08-25 11:45:40 +00007796 case BO_Mul:
7797 case BO_Div:
Richard Trieu4a287fb2011-09-07 01:49:20 +00007798 ResultTy = CheckMultiplyDivideOperands(LHS, RHS, OpLoc, false,
John McCalle3027922010-08-25 11:45:40 +00007799 Opc == BO_Div);
Douglas Gregor7d5fc7e2008-11-06 23:29:22 +00007800 break;
John McCalle3027922010-08-25 11:45:40 +00007801 case BO_Rem:
Richard Trieu4a287fb2011-09-07 01:49:20 +00007802 ResultTy = CheckRemainderOperands(LHS, RHS, OpLoc);
Douglas Gregor7d5fc7e2008-11-06 23:29:22 +00007803 break;
John McCalle3027922010-08-25 11:45:40 +00007804 case BO_Add:
Nico Weberccec40d2012-03-02 22:01:22 +00007805 ResultTy = CheckAdditionOperands(LHS, RHS, OpLoc, Opc);
Douglas Gregor7d5fc7e2008-11-06 23:29:22 +00007806 break;
John McCalle3027922010-08-25 11:45:40 +00007807 case BO_Sub:
Richard Trieu4a287fb2011-09-07 01:49:20 +00007808 ResultTy = CheckSubtractionOperands(LHS, RHS, OpLoc);
Douglas Gregor7d5fc7e2008-11-06 23:29:22 +00007809 break;
John McCalle3027922010-08-25 11:45:40 +00007810 case BO_Shl:
7811 case BO_Shr:
Richard Trieu4a287fb2011-09-07 01:49:20 +00007812 ResultTy = CheckShiftOperands(LHS, RHS, OpLoc, Opc);
Douglas Gregor7d5fc7e2008-11-06 23:29:22 +00007813 break;
John McCalle3027922010-08-25 11:45:40 +00007814 case BO_LE:
7815 case BO_LT:
7816 case BO_GE:
7817 case BO_GT:
Richard Trieu4a287fb2011-09-07 01:49:20 +00007818 ResultTy = CheckCompareOperands(LHS, RHS, OpLoc, Opc, true);
Douglas Gregor7d5fc7e2008-11-06 23:29:22 +00007819 break;
John McCalle3027922010-08-25 11:45:40 +00007820 case BO_EQ:
7821 case BO_NE:
Richard Trieu4a287fb2011-09-07 01:49:20 +00007822 ResultTy = CheckCompareOperands(LHS, RHS, OpLoc, Opc, false);
Douglas Gregor7d5fc7e2008-11-06 23:29:22 +00007823 break;
John McCalle3027922010-08-25 11:45:40 +00007824 case BO_And:
7825 case BO_Xor:
7826 case BO_Or:
Richard Trieu4a287fb2011-09-07 01:49:20 +00007827 ResultTy = CheckBitwiseOperands(LHS, RHS, OpLoc);
Douglas Gregor7d5fc7e2008-11-06 23:29:22 +00007828 break;
John McCalle3027922010-08-25 11:45:40 +00007829 case BO_LAnd:
7830 case BO_LOr:
Richard Trieu4a287fb2011-09-07 01:49:20 +00007831 ResultTy = CheckLogicalOperands(LHS, RHS, OpLoc, Opc);
Douglas Gregor7d5fc7e2008-11-06 23:29:22 +00007832 break;
John McCalle3027922010-08-25 11:45:40 +00007833 case BO_MulAssign:
7834 case BO_DivAssign:
Richard Trieu4a287fb2011-09-07 01:49:20 +00007835 CompResultTy = CheckMultiplyDivideOperands(LHS, RHS, OpLoc, true,
John McCall7decc9e2010-11-18 06:31:45 +00007836 Opc == BO_DivAssign);
Eli Friedman8b7b1b12009-03-28 01:22:36 +00007837 CompLHSTy = CompResultTy;
Richard Trieu4a287fb2011-09-07 01:49:20 +00007838 if (!CompResultTy.isNull() && !LHS.isInvalid() && !RHS.isInvalid())
7839 ResultTy = CheckAssignmentOperands(LHS.get(), RHS, OpLoc, CompResultTy);
Douglas Gregor7d5fc7e2008-11-06 23:29:22 +00007840 break;
John McCalle3027922010-08-25 11:45:40 +00007841 case BO_RemAssign:
Richard Trieu4a287fb2011-09-07 01:49:20 +00007842 CompResultTy = CheckRemainderOperands(LHS, RHS, OpLoc, true);
Eli Friedman8b7b1b12009-03-28 01:22:36 +00007843 CompLHSTy = CompResultTy;
Richard Trieu4a287fb2011-09-07 01:49:20 +00007844 if (!CompResultTy.isNull() && !LHS.isInvalid() && !RHS.isInvalid())
7845 ResultTy = CheckAssignmentOperands(LHS.get(), RHS, OpLoc, CompResultTy);
Douglas Gregor7d5fc7e2008-11-06 23:29:22 +00007846 break;
John McCalle3027922010-08-25 11:45:40 +00007847 case BO_AddAssign:
Nico Weberccec40d2012-03-02 22:01:22 +00007848 CompResultTy = CheckAdditionOperands(LHS, RHS, OpLoc, Opc, &CompLHSTy);
Richard Trieu4a287fb2011-09-07 01:49:20 +00007849 if (!CompResultTy.isNull() && !LHS.isInvalid() && !RHS.isInvalid())
7850 ResultTy = CheckAssignmentOperands(LHS.get(), RHS, OpLoc, CompResultTy);
Douglas Gregor7d5fc7e2008-11-06 23:29:22 +00007851 break;
John McCalle3027922010-08-25 11:45:40 +00007852 case BO_SubAssign:
Richard Trieu4a287fb2011-09-07 01:49:20 +00007853 CompResultTy = CheckSubtractionOperands(LHS, RHS, OpLoc, &CompLHSTy);
7854 if (!CompResultTy.isNull() && !LHS.isInvalid() && !RHS.isInvalid())
7855 ResultTy = CheckAssignmentOperands(LHS.get(), RHS, OpLoc, CompResultTy);
Douglas Gregor7d5fc7e2008-11-06 23:29:22 +00007856 break;
John McCalle3027922010-08-25 11:45:40 +00007857 case BO_ShlAssign:
7858 case BO_ShrAssign:
Richard Trieu4a287fb2011-09-07 01:49:20 +00007859 CompResultTy = CheckShiftOperands(LHS, RHS, OpLoc, Opc, true);
Eli Friedman8b7b1b12009-03-28 01:22:36 +00007860 CompLHSTy = CompResultTy;
Richard Trieu4a287fb2011-09-07 01:49:20 +00007861 if (!CompResultTy.isNull() && !LHS.isInvalid() && !RHS.isInvalid())
7862 ResultTy = CheckAssignmentOperands(LHS.get(), RHS, OpLoc, CompResultTy);
Douglas Gregor7d5fc7e2008-11-06 23:29:22 +00007863 break;
John McCalle3027922010-08-25 11:45:40 +00007864 case BO_AndAssign:
7865 case BO_XorAssign:
7866 case BO_OrAssign:
Richard Trieu4a287fb2011-09-07 01:49:20 +00007867 CompResultTy = CheckBitwiseOperands(LHS, RHS, OpLoc, true);
Eli Friedman8b7b1b12009-03-28 01:22:36 +00007868 CompLHSTy = CompResultTy;
Richard Trieu4a287fb2011-09-07 01:49:20 +00007869 if (!CompResultTy.isNull() && !LHS.isInvalid() && !RHS.isInvalid())
7870 ResultTy = CheckAssignmentOperands(LHS.get(), RHS, OpLoc, CompResultTy);
Douglas Gregor7d5fc7e2008-11-06 23:29:22 +00007871 break;
John McCalle3027922010-08-25 11:45:40 +00007872 case BO_Comma:
Richard Trieu4a287fb2011-09-07 01:49:20 +00007873 ResultTy = CheckCommaOperands(*this, LHS, RHS, OpLoc);
7874 if (getLangOptions().CPlusPlus && !RHS.isInvalid()) {
7875 VK = RHS.get()->getValueKind();
7876 OK = RHS.get()->getObjectKind();
John McCall7decc9e2010-11-18 06:31:45 +00007877 }
Douglas Gregor7d5fc7e2008-11-06 23:29:22 +00007878 break;
7879 }
Richard Trieu4a287fb2011-09-07 01:49:20 +00007880 if (ResultTy.isNull() || LHS.isInvalid() || RHS.isInvalid())
Sebastian Redlb5d49352009-01-19 22:31:54 +00007881 return ExprError();
Kaelyn Uhrain2e7aa5a2011-08-05 23:18:04 +00007882
7883 // Check for array bounds violations for both sides of the BinaryOperator
Richard Trieu4a287fb2011-09-07 01:49:20 +00007884 CheckArrayAccess(LHS.get());
7885 CheckArrayAccess(RHS.get());
Kaelyn Uhrain2e7aa5a2011-08-05 23:18:04 +00007886
Eli Friedman8b7b1b12009-03-28 01:22:36 +00007887 if (CompResultTy.isNull())
Richard Trieu4a287fb2011-09-07 01:49:20 +00007888 return Owned(new (Context) BinaryOperator(LHS.take(), RHS.take(), Opc,
John Wiegley01296292011-04-08 18:41:53 +00007889 ResultTy, VK, OK, OpLoc));
Richard Trieu4a287fb2011-09-07 01:49:20 +00007890 if (getLangOptions().CPlusPlus && LHS.get()->getObjectKind() !=
Richard Trieucfc491d2011-08-02 04:35:43 +00007891 OK_ObjCProperty) {
John McCall7decc9e2010-11-18 06:31:45 +00007892 VK = VK_LValue;
Richard Trieu4a287fb2011-09-07 01:49:20 +00007893 OK = LHS.get()->getObjectKind();
John McCall7decc9e2010-11-18 06:31:45 +00007894 }
Richard Trieu4a287fb2011-09-07 01:49:20 +00007895 return Owned(new (Context) CompoundAssignOperator(LHS.take(), RHS.take(), Opc,
John Wiegley01296292011-04-08 18:41:53 +00007896 ResultTy, VK, OK, CompLHSTy,
John McCall7decc9e2010-11-18 06:31:45 +00007897 CompResultTy, OpLoc));
Douglas Gregor7d5fc7e2008-11-06 23:29:22 +00007898}
7899
Sebastian Redl44615072009-10-27 12:10:02 +00007900/// DiagnoseBitwisePrecedence - Emit a warning when bitwise and comparison
7901/// operators are mixed in a way that suggests that the programmer forgot that
7902/// comparison operators have higher precedence. The most typical example of
7903/// such code is "flags & 0x0020 != 0", which is equivalent to "flags & 1".
John McCalle3027922010-08-25 11:45:40 +00007904static void DiagnoseBitwisePrecedence(Sema &Self, BinaryOperatorKind Opc,
Richard Trieu4a287fb2011-09-07 01:49:20 +00007905 SourceLocation OpLoc, Expr *LHSExpr,
7906 Expr *RHSExpr) {
Sebastian Redl44615072009-10-27 12:10:02 +00007907 typedef BinaryOperator BinOp;
Richard Trieu4a287fb2011-09-07 01:49:20 +00007908 BinOp::Opcode LHSopc = static_cast<BinOp::Opcode>(-1),
7909 RHSopc = static_cast<BinOp::Opcode>(-1);
7910 if (BinOp *BO = dyn_cast<BinOp>(LHSExpr))
7911 LHSopc = BO->getOpcode();
7912 if (BinOp *BO = dyn_cast<BinOp>(RHSExpr))
7913 RHSopc = BO->getOpcode();
Sebastian Redl43028242009-10-26 15:24:15 +00007914
7915 // Subs are not binary operators.
Richard Trieu4a287fb2011-09-07 01:49:20 +00007916 if (LHSopc == -1 && RHSopc == -1)
Sebastian Redl43028242009-10-26 15:24:15 +00007917 return;
7918
7919 // Bitwise operations are sometimes used as eager logical ops.
7920 // Don't diagnose this.
Richard Trieu4a287fb2011-09-07 01:49:20 +00007921 if ((BinOp::isComparisonOp(LHSopc) || BinOp::isBitwiseOp(LHSopc)) &&
7922 (BinOp::isComparisonOp(RHSopc) || BinOp::isBitwiseOp(RHSopc)))
Sebastian Redl43028242009-10-26 15:24:15 +00007923 return;
7924
Richard Trieu4a287fb2011-09-07 01:49:20 +00007925 bool isLeftComp = BinOp::isComparisonOp(LHSopc);
7926 bool isRightComp = BinOp::isComparisonOp(RHSopc);
Richard Trieu73088052011-08-10 22:41:34 +00007927 if (!isLeftComp && !isRightComp) return;
7928
Richard Trieu4a287fb2011-09-07 01:49:20 +00007929 SourceRange DiagRange = isLeftComp ? SourceRange(LHSExpr->getLocStart(),
7930 OpLoc)
7931 : SourceRange(OpLoc, RHSExpr->getLocEnd());
7932 std::string OpStr = isLeftComp ? BinOp::getOpcodeStr(LHSopc)
7933 : BinOp::getOpcodeStr(RHSopc);
Richard Trieu73088052011-08-10 22:41:34 +00007934 SourceRange ParensRange = isLeftComp ?
Richard Trieu4a287fb2011-09-07 01:49:20 +00007935 SourceRange(cast<BinOp>(LHSExpr)->getRHS()->getLocStart(),
7936 RHSExpr->getLocEnd())
7937 : SourceRange(LHSExpr->getLocStart(),
7938 cast<BinOp>(RHSExpr)->getLHS()->getLocStart());
Richard Trieu73088052011-08-10 22:41:34 +00007939
7940 Self.Diag(OpLoc, diag::warn_precedence_bitwise_rel)
7941 << DiagRange << BinOp::getOpcodeStr(Opc) << OpStr;
7942 SuggestParentheses(Self, OpLoc,
7943 Self.PDiag(diag::note_precedence_bitwise_silence) << OpStr,
Richard Trieu4a287fb2011-09-07 01:49:20 +00007944 RHSExpr->getSourceRange());
Richard Trieu73088052011-08-10 22:41:34 +00007945 SuggestParentheses(Self, OpLoc,
7946 Self.PDiag(diag::note_precedence_bitwise_first) << BinOp::getOpcodeStr(Opc),
7947 ParensRange);
Sebastian Redl43028242009-10-26 15:24:15 +00007948}
7949
Argyrios Kyrtzidis01bf7772011-06-20 18:41:26 +00007950/// \brief It accepts a '&' expr that is inside a '|' one.
7951/// Emit a diagnostic together with a fixit hint that wraps the '&' expression
7952/// in parentheses.
7953static void
7954EmitDiagnosticForBitwiseAndInBitwiseOr(Sema &Self, SourceLocation OpLoc,
7955 BinaryOperator *Bop) {
7956 assert(Bop->getOpcode() == BO_And);
7957 Self.Diag(Bop->getOperatorLoc(), diag::warn_bitwise_and_in_bitwise_or)
7958 << Bop->getSourceRange() << OpLoc;
7959 SuggestParentheses(Self, Bop->getOperatorLoc(),
7960 Self.PDiag(diag::note_bitwise_and_in_bitwise_or_silence),
7961 Bop->getSourceRange());
7962}
7963
Argyrios Kyrtzidis14a96622010-11-17 18:26:36 +00007964/// \brief It accepts a '&&' expr that is inside a '||' one.
7965/// Emit a diagnostic together with a fixit hint that wraps the '&&' expression
7966/// in parentheses.
7967static void
7968EmitDiagnosticForLogicalAndInLogicalOr(Sema &Self, SourceLocation OpLoc,
Argyrios Kyrtzidisad8b4d42011-04-22 19:16:27 +00007969 BinaryOperator *Bop) {
7970 assert(Bop->getOpcode() == BO_LAnd);
Chandler Carruthb00e8c02011-06-16 01:05:14 +00007971 Self.Diag(Bop->getOperatorLoc(), diag::warn_logical_and_in_logical_or)
7972 << Bop->getSourceRange() << OpLoc;
Argyrios Kyrtzidisad8b4d42011-04-22 19:16:27 +00007973 SuggestParentheses(Self, Bop->getOperatorLoc(),
Argyrios Kyrtzidis14a96622010-11-17 18:26:36 +00007974 Self.PDiag(diag::note_logical_and_in_logical_or_silence),
Chandler Carruthb00e8c02011-06-16 01:05:14 +00007975 Bop->getSourceRange());
Argyrios Kyrtzidis14a96622010-11-17 18:26:36 +00007976}
7977
7978/// \brief Returns true if the given expression can be evaluated as a constant
7979/// 'true'.
7980static bool EvaluatesAsTrue(Sema &S, Expr *E) {
7981 bool Res;
7982 return E->EvaluateAsBooleanCondition(Res, S.getASTContext()) && Res;
7983}
7984
Argyrios Kyrtzidis56e879d2010-11-17 19:18:19 +00007985/// \brief Returns true if the given expression can be evaluated as a constant
7986/// 'false'.
7987static bool EvaluatesAsFalse(Sema &S, Expr *E) {
7988 bool Res;
7989 return E->EvaluateAsBooleanCondition(Res, S.getASTContext()) && !Res;
7990}
7991
Argyrios Kyrtzidis14a96622010-11-17 18:26:36 +00007992/// \brief Look for '&&' in the left hand of a '||' expr.
7993static void DiagnoseLogicalAndInLogicalOrLHS(Sema &S, SourceLocation OpLoc,
Richard Trieuf9bd0f52011-09-07 02:02:10 +00007994 Expr *LHSExpr, Expr *RHSExpr) {
7995 if (BinaryOperator *Bop = dyn_cast<BinaryOperator>(LHSExpr)) {
Argyrios Kyrtzidisf89a56c2010-11-16 21:00:12 +00007996 if (Bop->getOpcode() == BO_LAnd) {
Argyrios Kyrtzidis56e879d2010-11-17 19:18:19 +00007997 // If it's "a && b || 0" don't warn since the precedence doesn't matter.
Richard Trieuf9bd0f52011-09-07 02:02:10 +00007998 if (EvaluatesAsFalse(S, RHSExpr))
Argyrios Kyrtzidis56e879d2010-11-17 19:18:19 +00007999 return;
Argyrios Kyrtzidis14a96622010-11-17 18:26:36 +00008000 // If it's "1 && a || b" don't warn since the precedence doesn't matter.
8001 if (!EvaluatesAsTrue(S, Bop->getLHS()))
8002 return EmitDiagnosticForLogicalAndInLogicalOr(S, OpLoc, Bop);
8003 } else if (Bop->getOpcode() == BO_LOr) {
8004 if (BinaryOperator *RBop = dyn_cast<BinaryOperator>(Bop->getRHS())) {
8005 // If it's "a || b && 1 || c" we didn't warn earlier for
8006 // "a || b && 1", but warn now.
8007 if (RBop->getOpcode() == BO_LAnd && EvaluatesAsTrue(S, RBop->getRHS()))
8008 return EmitDiagnosticForLogicalAndInLogicalOr(S, OpLoc, RBop);
8009 }
8010 }
8011 }
8012}
8013
8014/// \brief Look for '&&' in the right hand of a '||' expr.
8015static void DiagnoseLogicalAndInLogicalOrRHS(Sema &S, SourceLocation OpLoc,
Richard Trieuf9bd0f52011-09-07 02:02:10 +00008016 Expr *LHSExpr, Expr *RHSExpr) {
8017 if (BinaryOperator *Bop = dyn_cast<BinaryOperator>(RHSExpr)) {
Argyrios Kyrtzidis14a96622010-11-17 18:26:36 +00008018 if (Bop->getOpcode() == BO_LAnd) {
Argyrios Kyrtzidis56e879d2010-11-17 19:18:19 +00008019 // If it's "0 || a && b" don't warn since the precedence doesn't matter.
Richard Trieuf9bd0f52011-09-07 02:02:10 +00008020 if (EvaluatesAsFalse(S, LHSExpr))
Argyrios Kyrtzidis56e879d2010-11-17 19:18:19 +00008021 return;
Argyrios Kyrtzidis14a96622010-11-17 18:26:36 +00008022 // If it's "a || b && 1" don't warn since the precedence doesn't matter.
8023 if (!EvaluatesAsTrue(S, Bop->getRHS()))
8024 return EmitDiagnosticForLogicalAndInLogicalOr(S, OpLoc, Bop);
Argyrios Kyrtzidisf89a56c2010-11-16 21:00:12 +00008025 }
8026 }
8027}
8028
Argyrios Kyrtzidis01bf7772011-06-20 18:41:26 +00008029/// \brief Look for '&' in the left or right hand of a '|' expr.
8030static void DiagnoseBitwiseAndInBitwiseOr(Sema &S, SourceLocation OpLoc,
8031 Expr *OrArg) {
8032 if (BinaryOperator *Bop = dyn_cast<BinaryOperator>(OrArg)) {
8033 if (Bop->getOpcode() == BO_And)
8034 return EmitDiagnosticForBitwiseAndInBitwiseOr(S, OpLoc, Bop);
8035 }
8036}
8037
Sebastian Redl43028242009-10-26 15:24:15 +00008038/// DiagnoseBinOpPrecedence - Emit warnings for expressions with tricky
Argyrios Kyrtzidisf89a56c2010-11-16 21:00:12 +00008039/// precedence.
John McCalle3027922010-08-25 11:45:40 +00008040static void DiagnoseBinOpPrecedence(Sema &Self, BinaryOperatorKind Opc,
Richard Trieuf9bd0f52011-09-07 02:02:10 +00008041 SourceLocation OpLoc, Expr *LHSExpr,
8042 Expr *RHSExpr){
Argyrios Kyrtzidisf89a56c2010-11-16 21:00:12 +00008043 // Diagnose "arg1 'bitwise' arg2 'eq' arg3".
Sebastian Redl44615072009-10-27 12:10:02 +00008044 if (BinaryOperator::isBitwiseOp(Opc))
Richard Trieuf9bd0f52011-09-07 02:02:10 +00008045 DiagnoseBitwisePrecedence(Self, Opc, OpLoc, LHSExpr, RHSExpr);
Argyrios Kyrtzidis01bf7772011-06-20 18:41:26 +00008046
8047 // Diagnose "arg1 & arg2 | arg3"
8048 if (Opc == BO_Or && !OpLoc.isMacroID()/* Don't warn in macros. */) {
Richard Trieuf9bd0f52011-09-07 02:02:10 +00008049 DiagnoseBitwiseAndInBitwiseOr(Self, OpLoc, LHSExpr);
8050 DiagnoseBitwiseAndInBitwiseOr(Self, OpLoc, RHSExpr);
Argyrios Kyrtzidis01bf7772011-06-20 18:41:26 +00008051 }
Argyrios Kyrtzidisf89a56c2010-11-16 21:00:12 +00008052
Argyrios Kyrtzidis14a96622010-11-17 18:26:36 +00008053 // Warn about arg1 || arg2 && arg3, as GCC 4.3+ does.
8054 // We don't warn for 'assert(a || b && "bad")' since this is safe.
Argyrios Kyrtzidisb94e5a32010-11-17 18:54:22 +00008055 if (Opc == BO_LOr && !OpLoc.isMacroID()/* Don't warn in macros. */) {
Richard Trieuf9bd0f52011-09-07 02:02:10 +00008056 DiagnoseLogicalAndInLogicalOrLHS(Self, OpLoc, LHSExpr, RHSExpr);
8057 DiagnoseLogicalAndInLogicalOrRHS(Self, OpLoc, LHSExpr, RHSExpr);
Argyrios Kyrtzidisf89a56c2010-11-16 21:00:12 +00008058 }
Sebastian Redl43028242009-10-26 15:24:15 +00008059}
8060
Steve Naroff218bc2b2007-05-04 21:54:46 +00008061// Binary Operators. 'Tok' is the token for the operator.
John McCalldadc5752010-08-24 06:29:42 +00008062ExprResult Sema::ActOnBinOp(Scope *S, SourceLocation TokLoc,
John McCalle3027922010-08-25 11:45:40 +00008063 tok::TokenKind Kind,
Richard Trieuf9bd0f52011-09-07 02:02:10 +00008064 Expr *LHSExpr, Expr *RHSExpr) {
John McCalle3027922010-08-25 11:45:40 +00008065 BinaryOperatorKind Opc = ConvertTokenKindToBinaryOpcode(Kind);
Richard Trieuf9bd0f52011-09-07 02:02:10 +00008066 assert((LHSExpr != 0) && "ActOnBinOp(): missing left expression");
8067 assert((RHSExpr != 0) && "ActOnBinOp(): missing right expression");
Steve Naroff218bc2b2007-05-04 21:54:46 +00008068
Sebastian Redl43028242009-10-26 15:24:15 +00008069 // Emit warnings for tricky precedence issues, e.g. "bitfield & 0x4 == 0"
Richard Trieuf9bd0f52011-09-07 02:02:10 +00008070 DiagnoseBinOpPrecedence(*this, Opc, TokLoc, LHSExpr, RHSExpr);
Sebastian Redl43028242009-10-26 15:24:15 +00008071
Richard Trieuf9bd0f52011-09-07 02:02:10 +00008072 return BuildBinOp(S, TokLoc, Opc, LHSExpr, RHSExpr);
Douglas Gregor5287f092009-11-05 00:51:44 +00008073}
8074
John McCall526ab472011-10-25 17:37:35 +00008075/// Build an overloaded binary operator expression in the given scope.
8076static ExprResult BuildOverloadedBinOp(Sema &S, Scope *Sc, SourceLocation OpLoc,
8077 BinaryOperatorKind Opc,
8078 Expr *LHS, Expr *RHS) {
8079 // Find all of the overloaded operators visible from this
8080 // point. We perform both an operator-name lookup from the local
8081 // scope and an argument-dependent lookup based on the types of
8082 // the arguments.
8083 UnresolvedSet<16> Functions;
8084 OverloadedOperatorKind OverOp
8085 = BinaryOperator::getOverloadedOperator(Opc);
8086 if (Sc && OverOp != OO_None)
8087 S.LookupOverloadedOperatorName(OverOp, Sc, LHS->getType(),
8088 RHS->getType(), Functions);
8089
8090 // Build the (potentially-overloaded, potentially-dependent)
8091 // binary operation.
8092 return S.CreateOverloadedBinOp(OpLoc, Opc, Functions, LHS, RHS);
8093}
8094
John McCalldadc5752010-08-24 06:29:42 +00008095ExprResult Sema::BuildBinOp(Scope *S, SourceLocation OpLoc,
John McCalle3027922010-08-25 11:45:40 +00008096 BinaryOperatorKind Opc,
Richard Trieuf9bd0f52011-09-07 02:02:10 +00008097 Expr *LHSExpr, Expr *RHSExpr) {
John McCall9a43e122011-10-28 01:04:34 +00008098 // We want to end up calling one of checkPseudoObjectAssignment
8099 // (if the LHS is a pseudo-object), BuildOverloadedBinOp (if
8100 // both expressions are overloadable or either is type-dependent),
8101 // or CreateBuiltinBinOp (in any other case). We also want to get
8102 // any placeholder types out of the way.
8103
John McCall526ab472011-10-25 17:37:35 +00008104 // Handle pseudo-objects in the LHS.
8105 if (const BuiltinType *pty = LHSExpr->getType()->getAsPlaceholderType()) {
8106 // Assignments with a pseudo-object l-value need special analysis.
8107 if (pty->getKind() == BuiltinType::PseudoObject &&
8108 BinaryOperator::isAssignmentOp(Opc))
8109 return checkPseudoObjectAssignment(S, OpLoc, Opc, LHSExpr, RHSExpr);
8110
8111 // Don't resolve overloads if the other type is overloadable.
8112 if (pty->getKind() == BuiltinType::Overload) {
8113 // We can't actually test that if we still have a placeholder,
8114 // though. Fortunately, none of the exceptions we see in that
John McCall9a43e122011-10-28 01:04:34 +00008115 // code below are valid when the LHS is an overload set. Note
8116 // that an overload set can be dependently-typed, but it never
8117 // instantiates to having an overloadable type.
John McCall526ab472011-10-25 17:37:35 +00008118 ExprResult resolvedRHS = CheckPlaceholderExpr(RHSExpr);
8119 if (resolvedRHS.isInvalid()) return ExprError();
8120 RHSExpr = resolvedRHS.take();
8121
John McCall9a43e122011-10-28 01:04:34 +00008122 if (RHSExpr->isTypeDependent() ||
8123 RHSExpr->getType()->isOverloadableType())
John McCall526ab472011-10-25 17:37:35 +00008124 return BuildOverloadedBinOp(*this, S, OpLoc, Opc, LHSExpr, RHSExpr);
8125 }
8126
8127 ExprResult LHS = CheckPlaceholderExpr(LHSExpr);
8128 if (LHS.isInvalid()) return ExprError();
8129 LHSExpr = LHS.take();
8130 }
8131
8132 // Handle pseudo-objects in the RHS.
8133 if (const BuiltinType *pty = RHSExpr->getType()->getAsPlaceholderType()) {
8134 // An overload in the RHS can potentially be resolved by the type
8135 // being assigned to.
John McCall9a43e122011-10-28 01:04:34 +00008136 if (Opc == BO_Assign && pty->getKind() == BuiltinType::Overload) {
8137 if (LHSExpr->isTypeDependent() || RHSExpr->isTypeDependent())
8138 return BuildOverloadedBinOp(*this, S, OpLoc, Opc, LHSExpr, RHSExpr);
8139
Eli Friedman419b1ff2012-01-17 21:27:43 +00008140 if (LHSExpr->getType()->isOverloadableType())
8141 return BuildOverloadedBinOp(*this, S, OpLoc, Opc, LHSExpr, RHSExpr);
8142
John McCall526ab472011-10-25 17:37:35 +00008143 return CreateBuiltinBinOp(OpLoc, Opc, LHSExpr, RHSExpr);
John McCall9a43e122011-10-28 01:04:34 +00008144 }
John McCall526ab472011-10-25 17:37:35 +00008145
8146 // Don't resolve overloads if the other type is overloadable.
8147 if (pty->getKind() == BuiltinType::Overload &&
8148 LHSExpr->getType()->isOverloadableType())
8149 return BuildOverloadedBinOp(*this, S, OpLoc, Opc, LHSExpr, RHSExpr);
8150
8151 ExprResult resolvedRHS = CheckPlaceholderExpr(RHSExpr);
8152 if (!resolvedRHS.isUsable()) return ExprError();
8153 RHSExpr = resolvedRHS.take();
8154 }
8155
John McCall622114c2010-12-06 05:26:58 +00008156 if (getLangOptions().CPlusPlus) {
John McCall9a43e122011-10-28 01:04:34 +00008157 // If either expression is type-dependent, always build an
8158 // overloaded op.
8159 if (LHSExpr->isTypeDependent() || RHSExpr->isTypeDependent())
8160 return BuildOverloadedBinOp(*this, S, OpLoc, Opc, LHSExpr, RHSExpr);
Kovarththanan Rajaratnamba2c6522010-03-13 10:17:05 +00008161
John McCall9a43e122011-10-28 01:04:34 +00008162 // Otherwise, build an overloaded op if either expression has an
8163 // overloadable type.
8164 if (LHSExpr->getType()->isOverloadableType() ||
8165 RHSExpr->getType()->isOverloadableType())
John McCall526ab472011-10-25 17:37:35 +00008166 return BuildOverloadedBinOp(*this, S, OpLoc, Opc, LHSExpr, RHSExpr);
Sebastian Redlb5d49352009-01-19 22:31:54 +00008167 }
Kovarththanan Rajaratnamba2c6522010-03-13 10:17:05 +00008168
Douglas Gregor7d5fc7e2008-11-06 23:29:22 +00008169 // Build a built-in binary operation.
Richard Trieuf9bd0f52011-09-07 02:02:10 +00008170 return CreateBuiltinBinOp(OpLoc, Opc, LHSExpr, RHSExpr);
Steve Naroff218bc2b2007-05-04 21:54:46 +00008171}
8172
John McCalldadc5752010-08-24 06:29:42 +00008173ExprResult Sema::CreateBuiltinUnaryOp(SourceLocation OpLoc,
Argyrios Kyrtzidis7a808c02011-01-05 20:09:36 +00008174 UnaryOperatorKind Opc,
John Wiegley01296292011-04-08 18:41:53 +00008175 Expr *InputExpr) {
8176 ExprResult Input = Owned(InputExpr);
John McCall7decc9e2010-11-18 06:31:45 +00008177 ExprValueKind VK = VK_RValue;
8178 ExprObjectKind OK = OK_Ordinary;
Steve Naroff35d85152007-05-07 00:24:15 +00008179 QualType resultType;
8180 switch (Opc) {
John McCalle3027922010-08-25 11:45:40 +00008181 case UO_PreInc:
8182 case UO_PreDec:
8183 case UO_PostInc:
8184 case UO_PostDec:
John Wiegley01296292011-04-08 18:41:53 +00008185 resultType = CheckIncrementDecrementOperand(*this, Input.get(), VK, OpLoc,
John McCalle3027922010-08-25 11:45:40 +00008186 Opc == UO_PreInc ||
8187 Opc == UO_PostInc,
8188 Opc == UO_PreInc ||
8189 Opc == UO_PreDec);
Steve Naroff35d85152007-05-07 00:24:15 +00008190 break;
John McCalle3027922010-08-25 11:45:40 +00008191 case UO_AddrOf:
John McCall526ab472011-10-25 17:37:35 +00008192 resultType = CheckAddressOfOperand(*this, Input, OpLoc);
Steve Naroff35d85152007-05-07 00:24:15 +00008193 break;
John McCall31996342011-04-07 08:22:57 +00008194 case UO_Deref: {
John Wiegley01296292011-04-08 18:41:53 +00008195 Input = DefaultFunctionArrayLvalueConversion(Input.take());
8196 resultType = CheckIndirectionOperand(*this, Input.get(), VK, OpLoc);
Steve Naroff35d85152007-05-07 00:24:15 +00008197 break;
John McCall31996342011-04-07 08:22:57 +00008198 }
John McCalle3027922010-08-25 11:45:40 +00008199 case UO_Plus:
8200 case UO_Minus:
John Wiegley01296292011-04-08 18:41:53 +00008201 Input = UsualUnaryConversions(Input.take());
8202 if (Input.isInvalid()) return ExprError();
8203 resultType = Input.get()->getType();
Sebastian Redl8d2ccae2009-02-26 14:39:58 +00008204 if (resultType->isDependentType())
8205 break;
Douglas Gregora3208f92010-06-22 23:41:02 +00008206 if (resultType->isArithmeticType() || // C99 6.5.3.3p1
8207 resultType->isVectorType())
Douglas Gregord08452f2008-11-19 15:42:04 +00008208 break;
8209 else if (getLangOptions().CPlusPlus && // C++ [expr.unary.op]p6-7
8210 resultType->isEnumeralType())
8211 break;
8212 else if (getLangOptions().CPlusPlus && // C++ [expr.unary.op]p6
John McCalle3027922010-08-25 11:45:40 +00008213 Opc == UO_Plus &&
Douglas Gregord08452f2008-11-19 15:42:04 +00008214 resultType->isPointerType())
8215 break;
8216
Sebastian Redlc215cfc2009-01-19 00:08:26 +00008217 return ExprError(Diag(OpLoc, diag::err_typecheck_unary_expr)
John Wiegley01296292011-04-08 18:41:53 +00008218 << resultType << Input.get()->getSourceRange());
8219
John McCalle3027922010-08-25 11:45:40 +00008220 case UO_Not: // bitwise complement
John Wiegley01296292011-04-08 18:41:53 +00008221 Input = UsualUnaryConversions(Input.take());
8222 if (Input.isInvalid()) return ExprError();
8223 resultType = Input.get()->getType();
Sebastian Redl8d2ccae2009-02-26 14:39:58 +00008224 if (resultType->isDependentType())
8225 break;
Chris Lattner0d707612008-07-25 23:52:49 +00008226 // C99 6.5.3.3p1. We allow complex int and float as a GCC extension.
8227 if (resultType->isComplexType() || resultType->isComplexIntegerType())
8228 // C99 does not support '~' for complex conjugation.
Chris Lattner29e812b2008-11-20 06:06:08 +00008229 Diag(OpLoc, diag::ext_integer_complement_complex)
John Wiegley01296292011-04-08 18:41:53 +00008230 << resultType << Input.get()->getSourceRange();
John McCall36226622010-10-12 02:09:17 +00008231 else if (resultType->hasIntegerRepresentation())
8232 break;
John McCall526ab472011-10-25 17:37:35 +00008233 else {
Sebastian Redlc215cfc2009-01-19 00:08:26 +00008234 return ExprError(Diag(OpLoc, diag::err_typecheck_unary_expr)
John Wiegley01296292011-04-08 18:41:53 +00008235 << resultType << Input.get()->getSourceRange());
John McCall36226622010-10-12 02:09:17 +00008236 }
Steve Naroff35d85152007-05-07 00:24:15 +00008237 break;
John Wiegley01296292011-04-08 18:41:53 +00008238
John McCalle3027922010-08-25 11:45:40 +00008239 case UO_LNot: // logical negation
Steve Naroff71b59a92007-06-04 22:22:31 +00008240 // Unlike +/-/~, integer promotions aren't done here (C99 6.5.3.3p5).
John Wiegley01296292011-04-08 18:41:53 +00008241 Input = DefaultFunctionArrayLvalueConversion(Input.take());
8242 if (Input.isInvalid()) return ExprError();
8243 resultType = Input.get()->getType();
Anton Korobeynikovf0c267e2011-10-14 23:23:15 +00008244
8245 // Though we still have to promote half FP to float...
8246 if (resultType->isHalfType()) {
8247 Input = ImpCastExprToType(Input.take(), Context.FloatTy, CK_FloatingCast).take();
8248 resultType = Context.FloatTy;
8249 }
8250
Sebastian Redl8d2ccae2009-02-26 14:39:58 +00008251 if (resultType->isDependentType())
8252 break;
Abramo Bagnara7ccce982011-04-07 09:26:19 +00008253 if (resultType->isScalarType()) {
8254 // C99 6.5.3.3p1: ok, fallthrough;
8255 if (Context.getLangOptions().CPlusPlus) {
8256 // C++03 [expr.unary.op]p8, C++0x [expr.unary.op]p9:
8257 // operand contextually converted to bool.
John Wiegley01296292011-04-08 18:41:53 +00008258 Input = ImpCastExprToType(Input.take(), Context.BoolTy,
8259 ScalarTypeToBooleanCastKind(resultType));
Abramo Bagnara7ccce982011-04-07 09:26:19 +00008260 }
Tanya Lattner3dd33b22012-01-19 01:16:16 +00008261 } else if (resultType->isExtVectorType()) {
Tanya Lattner20248222012-01-16 21:02:28 +00008262 // Vector logical not returns the signed variant of the operand type.
8263 resultType = GetSignedVectorType(resultType);
8264 break;
John McCall36226622010-10-12 02:09:17 +00008265 } else {
Sebastian Redlc215cfc2009-01-19 00:08:26 +00008266 return ExprError(Diag(OpLoc, diag::err_typecheck_unary_expr)
John Wiegley01296292011-04-08 18:41:53 +00008267 << resultType << Input.get()->getSourceRange());
John McCall36226622010-10-12 02:09:17 +00008268 }
Douglas Gregordb8c6fd2010-09-20 17:13:33 +00008269
Chris Lattnerbe31ed82007-06-02 19:11:33 +00008270 // LNot always has type int. C99 6.5.3.3p5.
Sebastian Redlc215cfc2009-01-19 00:08:26 +00008271 // In C++, it's bool. C++ 5.3.1p8
Argyrios Kyrtzidis1bdd6882011-02-18 20:55:15 +00008272 resultType = Context.getLogicalOperationType();
Steve Naroff35d85152007-05-07 00:24:15 +00008273 break;
John McCalle3027922010-08-25 11:45:40 +00008274 case UO_Real:
8275 case UO_Imag:
John McCall4bc41ae2010-11-18 19:01:18 +00008276 resultType = CheckRealImagOperand(*this, Input, OpLoc, Opc == UO_Real);
Richard Smith0b6b8e42012-02-18 20:53:32 +00008277 // _Real maps ordinary l-values into ordinary l-values. _Imag maps ordinary
8278 // complex l-values to ordinary l-values and all other values to r-values.
John Wiegley01296292011-04-08 18:41:53 +00008279 if (Input.isInvalid()) return ExprError();
Richard Smith0b6b8e42012-02-18 20:53:32 +00008280 if (Opc == UO_Real || Input.get()->getType()->isAnyComplexType()) {
8281 if (Input.get()->getValueKind() != VK_RValue &&
8282 Input.get()->getObjectKind() == OK_Ordinary)
8283 VK = Input.get()->getValueKind();
8284 } else if (!getLangOptions().CPlusPlus) {
8285 // In C, a volatile scalar is read by __imag. In C++, it is not.
8286 Input = DefaultLvalueConversion(Input.take());
8287 }
Chris Lattner30b5dd02007-08-24 21:16:53 +00008288 break;
John McCalle3027922010-08-25 11:45:40 +00008289 case UO_Extension:
John Wiegley01296292011-04-08 18:41:53 +00008290 resultType = Input.get()->getType();
8291 VK = Input.get()->getValueKind();
8292 OK = Input.get()->getObjectKind();
Steve Naroff043d45d2007-05-15 02:32:35 +00008293 break;
Steve Naroff35d85152007-05-07 00:24:15 +00008294 }
John Wiegley01296292011-04-08 18:41:53 +00008295 if (resultType.isNull() || Input.isInvalid())
Sebastian Redlc215cfc2009-01-19 00:08:26 +00008296 return ExprError();
Douglas Gregor084d8552009-03-13 23:49:33 +00008297
Kaelyn Uhrain2e7aa5a2011-08-05 23:18:04 +00008298 // Check for array bounds violations in the operand of the UnaryOperator,
8299 // except for the '*' and '&' operators that have to be handled specially
8300 // by CheckArrayAccess (as there are special cases like &array[arraysize]
8301 // that are explicitly defined as valid by the standard).
8302 if (Opc != UO_AddrOf && Opc != UO_Deref)
8303 CheckArrayAccess(Input.get());
8304
John Wiegley01296292011-04-08 18:41:53 +00008305 return Owned(new (Context) UnaryOperator(Input.take(), Opc, resultType,
John McCall7decc9e2010-11-18 06:31:45 +00008306 VK, OK, OpLoc));
Steve Naroff35d85152007-05-07 00:24:15 +00008307}
Chris Lattnereefa10e2007-05-28 06:56:27 +00008308
Douglas Gregor72341032011-12-14 21:23:13 +00008309/// \brief Determine whether the given expression is a qualified member
8310/// access expression, of a form that could be turned into a pointer to member
8311/// with the address-of operator.
8312static bool isQualifiedMemberAccess(Expr *E) {
8313 if (DeclRefExpr *DRE = dyn_cast<DeclRefExpr>(E)) {
8314 if (!DRE->getQualifier())
8315 return false;
8316
8317 ValueDecl *VD = DRE->getDecl();
8318 if (!VD->isCXXClassMember())
8319 return false;
8320
8321 if (isa<FieldDecl>(VD) || isa<IndirectFieldDecl>(VD))
8322 return true;
8323 if (CXXMethodDecl *Method = dyn_cast<CXXMethodDecl>(VD))
8324 return Method->isInstance();
8325
8326 return false;
8327 }
8328
8329 if (UnresolvedLookupExpr *ULE = dyn_cast<UnresolvedLookupExpr>(E)) {
8330 if (!ULE->getQualifier())
8331 return false;
8332
8333 for (UnresolvedLookupExpr::decls_iterator D = ULE->decls_begin(),
8334 DEnd = ULE->decls_end();
8335 D != DEnd; ++D) {
8336 if (CXXMethodDecl *Method = dyn_cast<CXXMethodDecl>(*D)) {
8337 if (Method->isInstance())
8338 return true;
8339 } else {
8340 // Overload set does not contain methods.
8341 break;
8342 }
8343 }
8344
8345 return false;
8346 }
8347
8348 return false;
8349}
8350
John McCalldadc5752010-08-24 06:29:42 +00008351ExprResult Sema::BuildUnaryOp(Scope *S, SourceLocation OpLoc,
Richard Trieuba63ce62011-09-09 01:45:06 +00008352 UnaryOperatorKind Opc, Expr *Input) {
John McCall526ab472011-10-25 17:37:35 +00008353 // First things first: handle placeholders so that the
8354 // overloaded-operator check considers the right type.
8355 if (const BuiltinType *pty = Input->getType()->getAsPlaceholderType()) {
8356 // Increment and decrement of pseudo-object references.
8357 if (pty->getKind() == BuiltinType::PseudoObject &&
8358 UnaryOperator::isIncrementDecrementOp(Opc))
8359 return checkPseudoObjectIncDec(S, OpLoc, Opc, Input);
8360
8361 // extension is always a builtin operator.
8362 if (Opc == UO_Extension)
8363 return CreateBuiltinUnaryOp(OpLoc, Opc, Input);
8364
8365 // & gets special logic for several kinds of placeholder.
8366 // The builtin code knows what to do.
8367 if (Opc == UO_AddrOf &&
8368 (pty->getKind() == BuiltinType::Overload ||
8369 pty->getKind() == BuiltinType::UnknownAny ||
8370 pty->getKind() == BuiltinType::BoundMember))
8371 return CreateBuiltinUnaryOp(OpLoc, Opc, Input);
8372
8373 // Anything else needs to be handled now.
8374 ExprResult Result = CheckPlaceholderExpr(Input);
8375 if (Result.isInvalid()) return ExprError();
8376 Input = Result.take();
8377 }
8378
Anders Carlsson461a2c02009-11-14 21:26:41 +00008379 if (getLangOptions().CPlusPlus && Input->getType()->isOverloadableType() &&
Douglas Gregor72341032011-12-14 21:23:13 +00008380 UnaryOperator::getOverloadedOperator(Opc) != OO_None &&
8381 !(Opc == UO_AddrOf && isQualifiedMemberAccess(Input))) {
Douglas Gregor084d8552009-03-13 23:49:33 +00008382 // Find all of the overloaded operators visible from this
8383 // point. We perform both an operator-name lookup from the local
8384 // scope and an argument-dependent lookup based on the types of
8385 // the arguments.
John McCall4c4c1df2010-01-26 03:27:55 +00008386 UnresolvedSet<16> Functions;
Douglas Gregor084d8552009-03-13 23:49:33 +00008387 OverloadedOperatorKind OverOp = UnaryOperator::getOverloadedOperator(Opc);
John McCall4c4c1df2010-01-26 03:27:55 +00008388 if (S && OverOp != OO_None)
8389 LookupOverloadedOperatorName(OverOp, S, Input->getType(), QualType(),
8390 Functions);
Kovarththanan Rajaratnamba2c6522010-03-13 10:17:05 +00008391
John McCallb268a282010-08-23 23:25:46 +00008392 return CreateOverloadedUnaryOp(OpLoc, Opc, Functions, Input);
Douglas Gregor084d8552009-03-13 23:49:33 +00008393 }
Kovarththanan Rajaratnamba2c6522010-03-13 10:17:05 +00008394
John McCallb268a282010-08-23 23:25:46 +00008395 return CreateBuiltinUnaryOp(OpLoc, Opc, Input);
Douglas Gregor084d8552009-03-13 23:49:33 +00008396}
8397
Douglas Gregor5287f092009-11-05 00:51:44 +00008398// Unary Operators. 'Tok' is the token for the operator.
John McCalldadc5752010-08-24 06:29:42 +00008399ExprResult Sema::ActOnUnaryOp(Scope *S, SourceLocation OpLoc,
John McCall424cec92011-01-19 06:33:43 +00008400 tok::TokenKind Op, Expr *Input) {
John McCallb268a282010-08-23 23:25:46 +00008401 return BuildUnaryOp(S, OpLoc, ConvertTokenKindToUnaryOpcode(Op), Input);
Douglas Gregor5287f092009-11-05 00:51:44 +00008402}
8403
Steve Naroff66356bd2007-09-16 14:56:35 +00008404/// ActOnAddrLabel - Parse the GNU address of label extension: "&&foo".
Chris Lattnerc8e630e2011-02-17 07:39:24 +00008405ExprResult Sema::ActOnAddrLabel(SourceLocation OpLoc, SourceLocation LabLoc,
Chris Lattnercab02a62011-02-17 20:34:02 +00008406 LabelDecl *TheDecl) {
Chris Lattnerc8e630e2011-02-17 07:39:24 +00008407 TheDecl->setUsed();
Chris Lattnereefa10e2007-05-28 06:56:27 +00008408 // Create the AST node. The address of a label always has type 'void*'.
Chris Lattnerc8e630e2011-02-17 07:39:24 +00008409 return Owned(new (Context) AddrLabelExpr(OpLoc, LabLoc, TheDecl,
Sebastian Redl6d4256c2009-03-15 17:47:39 +00008410 Context.getPointerType(Context.VoidTy)));
Chris Lattnereefa10e2007-05-28 06:56:27 +00008411}
8412
John McCall31168b02011-06-15 23:02:42 +00008413/// Given the last statement in a statement-expression, check whether
8414/// the result is a producing expression (like a call to an
8415/// ns_returns_retained function) and, if so, rebuild it to hoist the
8416/// release out of the full-expression. Otherwise, return null.
8417/// Cannot fail.
Richard Trieuba63ce62011-09-09 01:45:06 +00008418static Expr *maybeRebuildARCConsumingStmt(Stmt *Statement) {
John McCall31168b02011-06-15 23:02:42 +00008419 // Should always be wrapped with one of these.
Richard Trieuba63ce62011-09-09 01:45:06 +00008420 ExprWithCleanups *cleanups = dyn_cast<ExprWithCleanups>(Statement);
John McCall31168b02011-06-15 23:02:42 +00008421 if (!cleanups) return 0;
8422
8423 ImplicitCastExpr *cast = dyn_cast<ImplicitCastExpr>(cleanups->getSubExpr());
John McCall2d637d22011-09-10 06:18:15 +00008424 if (!cast || cast->getCastKind() != CK_ARCConsumeObject)
John McCall31168b02011-06-15 23:02:42 +00008425 return 0;
8426
8427 // Splice out the cast. This shouldn't modify any interesting
8428 // features of the statement.
8429 Expr *producer = cast->getSubExpr();
8430 assert(producer->getType() == cast->getType());
8431 assert(producer->getValueKind() == cast->getValueKind());
8432 cleanups->setSubExpr(producer);
8433 return cleanups;
8434}
8435
John McCalldadc5752010-08-24 06:29:42 +00008436ExprResult
John McCallb268a282010-08-23 23:25:46 +00008437Sema::ActOnStmtExpr(SourceLocation LPLoc, Stmt *SubStmt,
Sebastian Redl6d4256c2009-03-15 17:47:39 +00008438 SourceLocation RPLoc) { // "({..})"
Chris Lattner366727f2007-07-24 16:58:17 +00008439 assert(SubStmt && isa<CompoundStmt>(SubStmt) && "Invalid action invocation!");
8440 CompoundStmt *Compound = cast<CompoundStmt>(SubStmt);
8441
Douglas Gregor6cf3f3c2010-03-10 04:54:39 +00008442 bool isFileScope
8443 = (getCurFunctionOrMethodDecl() == 0) && (getCurBlock() == 0);
Chris Lattnera69b0762009-04-25 19:11:05 +00008444 if (isFileScope)
Sebastian Redl6d4256c2009-03-15 17:47:39 +00008445 return ExprError(Diag(LPLoc, diag::err_stmtexpr_file_scope));
Eli Friedman52cc0162009-01-24 23:09:00 +00008446
Chris Lattner366727f2007-07-24 16:58:17 +00008447 // FIXME: there are a variety of strange constraints to enforce here, for
8448 // example, it is not possible to goto into a stmt expression apparently.
8449 // More semantic analysis is needed.
Mike Stump4e1f26a2009-02-19 03:04:26 +00008450
Chris Lattner366727f2007-07-24 16:58:17 +00008451 // If there are sub stmts in the compound stmt, take the type of the last one
8452 // as the type of the stmtexpr.
8453 QualType Ty = Context.VoidTy;
Fariborz Jahanian56143ae2010-10-25 23:27:26 +00008454 bool StmtExprMayBindToTemp = false;
Chris Lattner944d3062008-07-26 19:51:01 +00008455 if (!Compound->body_empty()) {
8456 Stmt *LastStmt = Compound->body_back();
Fariborz Jahanian56143ae2010-10-25 23:27:26 +00008457 LabelStmt *LastLabelStmt = 0;
Chris Lattner944d3062008-07-26 19:51:01 +00008458 // If LastStmt is a label, skip down through into the body.
Fariborz Jahanian56143ae2010-10-25 23:27:26 +00008459 while (LabelStmt *Label = dyn_cast<LabelStmt>(LastStmt)) {
8460 LastLabelStmt = Label;
Chris Lattner944d3062008-07-26 19:51:01 +00008461 LastStmt = Label->getSubStmt();
Fariborz Jahanian56143ae2010-10-25 23:27:26 +00008462 }
John McCall31168b02011-06-15 23:02:42 +00008463
John Wiegley01296292011-04-08 18:41:53 +00008464 if (Expr *LastE = dyn_cast<Expr>(LastStmt)) {
John McCall34376a62010-12-04 03:47:34 +00008465 // Do function/array conversion on the last expression, but not
8466 // lvalue-to-rvalue. However, initialize an unqualified type.
John Wiegley01296292011-04-08 18:41:53 +00008467 ExprResult LastExpr = DefaultFunctionArrayConversion(LastE);
8468 if (LastExpr.isInvalid())
8469 return ExprError();
8470 Ty = LastExpr.get()->getType().getUnqualifiedType();
John McCall34376a62010-12-04 03:47:34 +00008471
John Wiegley01296292011-04-08 18:41:53 +00008472 if (!Ty->isDependentType() && !LastExpr.get()->isTypeDependent()) {
John McCall31168b02011-06-15 23:02:42 +00008473 // In ARC, if the final expression ends in a consume, splice
8474 // the consume out and bind it later. In the alternate case
8475 // (when dealing with a retainable type), the result
8476 // initialization will create a produce. In both cases the
8477 // result will be +1, and we'll need to balance that out with
8478 // a bind.
8479 if (Expr *rebuiltLastStmt
8480 = maybeRebuildARCConsumingStmt(LastExpr.get())) {
8481 LastExpr = rebuiltLastStmt;
8482 } else {
8483 LastExpr = PerformCopyInitialization(
Fariborz Jahanian56143ae2010-10-25 23:27:26 +00008484 InitializedEntity::InitializeResult(LPLoc,
8485 Ty,
8486 false),
8487 SourceLocation(),
John McCall31168b02011-06-15 23:02:42 +00008488 LastExpr);
8489 }
8490
John Wiegley01296292011-04-08 18:41:53 +00008491 if (LastExpr.isInvalid())
Fariborz Jahanian56143ae2010-10-25 23:27:26 +00008492 return ExprError();
John Wiegley01296292011-04-08 18:41:53 +00008493 if (LastExpr.get() != 0) {
Fariborz Jahanian56143ae2010-10-25 23:27:26 +00008494 if (!LastLabelStmt)
John Wiegley01296292011-04-08 18:41:53 +00008495 Compound->setLastStmt(LastExpr.take());
Fariborz Jahanian56143ae2010-10-25 23:27:26 +00008496 else
John Wiegley01296292011-04-08 18:41:53 +00008497 LastLabelStmt->setSubStmt(LastExpr.take());
Fariborz Jahanian56143ae2010-10-25 23:27:26 +00008498 StmtExprMayBindToTemp = true;
8499 }
8500 }
8501 }
Chris Lattner944d3062008-07-26 19:51:01 +00008502 }
Mike Stump4e1f26a2009-02-19 03:04:26 +00008503
Eli Friedmanba961a92009-03-23 00:24:07 +00008504 // FIXME: Check that expression type is complete/non-abstract; statement
8505 // expressions are not lvalues.
Fariborz Jahanian56143ae2010-10-25 23:27:26 +00008506 Expr *ResStmtExpr = new (Context) StmtExpr(Compound, Ty, LPLoc, RPLoc);
8507 if (StmtExprMayBindToTemp)
8508 return MaybeBindToTemporary(ResStmtExpr);
8509 return Owned(ResStmtExpr);
Chris Lattner366727f2007-07-24 16:58:17 +00008510}
Steve Naroff78864672007-08-01 22:05:33 +00008511
John McCalldadc5752010-08-24 06:29:42 +00008512ExprResult Sema::BuildBuiltinOffsetOf(SourceLocation BuiltinLoc,
John McCall36226622010-10-12 02:09:17 +00008513 TypeSourceInfo *TInfo,
8514 OffsetOfComponent *CompPtr,
8515 unsigned NumComponents,
8516 SourceLocation RParenLoc) {
Douglas Gregor882211c2010-04-28 22:16:22 +00008517 QualType ArgTy = TInfo->getType();
Sebastian Redl8d2ccae2009-02-26 14:39:58 +00008518 bool Dependent = ArgTy->isDependentType();
Abramo Bagnara1108e7b2010-05-20 10:00:11 +00008519 SourceRange TypeRange = TInfo->getTypeLoc().getLocalSourceRange();
Douglas Gregor882211c2010-04-28 22:16:22 +00008520
Chris Lattnerf17bd422007-08-30 17:45:32 +00008521 // We must have at least one component that refers to the type, and the first
8522 // one is known to be a field designator. Verify that the ArgTy represents
8523 // a struct/union/class.
Sebastian Redl8d2ccae2009-02-26 14:39:58 +00008524 if (!Dependent && !ArgTy->isRecordType())
Douglas Gregor882211c2010-04-28 22:16:22 +00008525 return ExprError(Diag(BuiltinLoc, diag::err_offsetof_record_type)
8526 << ArgTy << TypeRange);
8527
8528 // Type must be complete per C99 7.17p3 because a declaring a variable
8529 // with an incomplete type would be ill-formed.
8530 if (!Dependent
8531 && RequireCompleteType(BuiltinLoc, ArgTy,
8532 PDiag(diag::err_offsetof_incomplete_type)
8533 << TypeRange))
8534 return ExprError();
8535
Chris Lattner78502cf2007-08-31 21:49:13 +00008536 // offsetof with non-identifier designators (e.g. "offsetof(x, a.b[c])") are a
8537 // GCC extension, diagnose them.
Eli Friedman988a16b2009-02-27 06:44:11 +00008538 // FIXME: This diagnostic isn't actually visible because the location is in
8539 // a system header!
Chris Lattner78502cf2007-08-31 21:49:13 +00008540 if (NumComponents != 1)
Chris Lattnerf490e152008-11-19 05:27:50 +00008541 Diag(BuiltinLoc, diag::ext_offsetof_extended_field_designator)
8542 << SourceRange(CompPtr[1].LocStart, CompPtr[NumComponents-1].LocEnd);
Douglas Gregor882211c2010-04-28 22:16:22 +00008543
8544 bool DidWarnAboutNonPOD = false;
8545 QualType CurrentType = ArgTy;
8546 typedef OffsetOfExpr::OffsetOfNode OffsetOfNode;
Chris Lattner0e62c1c2011-07-23 10:55:15 +00008547 SmallVector<OffsetOfNode, 4> Comps;
8548 SmallVector<Expr*, 4> Exprs;
Douglas Gregor882211c2010-04-28 22:16:22 +00008549 for (unsigned i = 0; i != NumComponents; ++i) {
8550 const OffsetOfComponent &OC = CompPtr[i];
8551 if (OC.isBrackets) {
8552 // Offset of an array sub-field. TODO: Should we allow vector elements?
8553 if (!CurrentType->isDependentType()) {
8554 const ArrayType *AT = Context.getAsArrayType(CurrentType);
8555 if(!AT)
8556 return ExprError(Diag(OC.LocEnd, diag::err_offsetof_array_type)
8557 << CurrentType);
8558 CurrentType = AT->getElementType();
8559 } else
8560 CurrentType = Context.DependentTy;
8561
Richard Smith9fcc5c32011-10-17 23:29:39 +00008562 ExprResult IdxRval = DefaultLvalueConversion(static_cast<Expr*>(OC.U.E));
8563 if (IdxRval.isInvalid())
8564 return ExprError();
8565 Expr *Idx = IdxRval.take();
8566
Douglas Gregor882211c2010-04-28 22:16:22 +00008567 // The expression must be an integral expression.
8568 // FIXME: An integral constant expression?
Douglas Gregor882211c2010-04-28 22:16:22 +00008569 if (!Idx->isTypeDependent() && !Idx->isValueDependent() &&
8570 !Idx->getType()->isIntegerType())
8571 return ExprError(Diag(Idx->getLocStart(),
8572 diag::err_typecheck_subscript_not_integer)
8573 << Idx->getSourceRange());
Richard Smitheda612882011-10-17 05:48:07 +00008574
Douglas Gregor882211c2010-04-28 22:16:22 +00008575 // Record this array index.
8576 Comps.push_back(OffsetOfNode(OC.LocStart, Exprs.size(), OC.LocEnd));
Richard Smith9fcc5c32011-10-17 23:29:39 +00008577 Exprs.push_back(Idx);
Douglas Gregor882211c2010-04-28 22:16:22 +00008578 continue;
8579 }
8580
8581 // Offset of a field.
8582 if (CurrentType->isDependentType()) {
8583 // We have the offset of a field, but we can't look into the dependent
8584 // type. Just record the identifier of the field.
8585 Comps.push_back(OffsetOfNode(OC.LocStart, OC.U.IdentInfo, OC.LocEnd));
8586 CurrentType = Context.DependentTy;
8587 continue;
8588 }
8589
8590 // We need to have a complete type to look into.
8591 if (RequireCompleteType(OC.LocStart, CurrentType,
8592 diag::err_offsetof_incomplete_type))
8593 return ExprError();
8594
8595 // Look for the designated field.
8596 const RecordType *RC = CurrentType->getAs<RecordType>();
8597 if (!RC)
8598 return ExprError(Diag(OC.LocEnd, diag::err_offsetof_record_type)
8599 << CurrentType);
8600 RecordDecl *RD = RC->getDecl();
8601
8602 // C++ [lib.support.types]p5:
8603 // The macro offsetof accepts a restricted set of type arguments in this
8604 // International Standard. type shall be a POD structure or a POD union
8605 // (clause 9).
8606 if (CXXRecordDecl *CRD = dyn_cast<CXXRecordDecl>(RD)) {
8607 if (!CRD->isPOD() && !DidWarnAboutNonPOD &&
Ted Kremenek55ae3192011-02-23 01:51:43 +00008608 DiagRuntimeBehavior(BuiltinLoc, 0,
Douglas Gregor882211c2010-04-28 22:16:22 +00008609 PDiag(diag::warn_offsetof_non_pod_type)
8610 << SourceRange(CompPtr[0].LocStart, OC.LocEnd)
8611 << CurrentType))
8612 DidWarnAboutNonPOD = true;
8613 }
8614
8615 // Look for the field.
8616 LookupResult R(*this, OC.U.IdentInfo, OC.LocStart, LookupMemberName);
8617 LookupQualifiedName(R, RD);
8618 FieldDecl *MemberDecl = R.getAsSingle<FieldDecl>();
Francois Pichet783dd6e2010-11-21 06:08:52 +00008619 IndirectFieldDecl *IndirectMemberDecl = 0;
8620 if (!MemberDecl) {
Benjamin Kramer39593702010-11-21 14:11:41 +00008621 if ((IndirectMemberDecl = R.getAsSingle<IndirectFieldDecl>()))
Francois Pichet783dd6e2010-11-21 06:08:52 +00008622 MemberDecl = IndirectMemberDecl->getAnonField();
8623 }
8624
Douglas Gregor882211c2010-04-28 22:16:22 +00008625 if (!MemberDecl)
8626 return ExprError(Diag(BuiltinLoc, diag::err_no_member)
8627 << OC.U.IdentInfo << RD << SourceRange(OC.LocStart,
8628 OC.LocEnd));
8629
Douglas Gregor10982ea2010-04-28 22:36:06 +00008630 // C99 7.17p3:
8631 // (If the specified member is a bit-field, the behavior is undefined.)
8632 //
8633 // We diagnose this as an error.
Richard Smithcaf33902011-10-10 18:28:20 +00008634 if (MemberDecl->isBitField()) {
Douglas Gregor10982ea2010-04-28 22:36:06 +00008635 Diag(OC.LocEnd, diag::err_offsetof_bitfield)
8636 << MemberDecl->getDeclName()
8637 << SourceRange(BuiltinLoc, RParenLoc);
8638 Diag(MemberDecl->getLocation(), diag::note_bitfield_decl);
8639 return ExprError();
8640 }
Eli Friedman74ef7cf2010-08-05 10:11:36 +00008641
8642 RecordDecl *Parent = MemberDecl->getParent();
Francois Pichet783dd6e2010-11-21 06:08:52 +00008643 if (IndirectMemberDecl)
8644 Parent = cast<RecordDecl>(IndirectMemberDecl->getDeclContext());
Eli Friedman74ef7cf2010-08-05 10:11:36 +00008645
Douglas Gregord1702062010-04-29 00:18:15 +00008646 // If the member was found in a base class, introduce OffsetOfNodes for
8647 // the base class indirections.
8648 CXXBasePaths Paths(/*FindAmbiguities=*/true, /*RecordPaths=*/true,
8649 /*DetectVirtual=*/false);
Eli Friedman74ef7cf2010-08-05 10:11:36 +00008650 if (IsDerivedFrom(CurrentType, Context.getTypeDeclType(Parent), Paths)) {
Douglas Gregord1702062010-04-29 00:18:15 +00008651 CXXBasePath &Path = Paths.front();
8652 for (CXXBasePath::iterator B = Path.begin(), BEnd = Path.end();
8653 B != BEnd; ++B)
8654 Comps.push_back(OffsetOfNode(B->Base));
8655 }
Eli Friedman74ef7cf2010-08-05 10:11:36 +00008656
Francois Pichet783dd6e2010-11-21 06:08:52 +00008657 if (IndirectMemberDecl) {
8658 for (IndirectFieldDecl::chain_iterator FI =
8659 IndirectMemberDecl->chain_begin(),
8660 FEnd = IndirectMemberDecl->chain_end(); FI != FEnd; FI++) {
8661 assert(isa<FieldDecl>(*FI));
8662 Comps.push_back(OffsetOfNode(OC.LocStart,
8663 cast<FieldDecl>(*FI), OC.LocEnd));
8664 }
8665 } else
Douglas Gregor882211c2010-04-28 22:16:22 +00008666 Comps.push_back(OffsetOfNode(OC.LocStart, MemberDecl, OC.LocEnd));
Francois Pichet783dd6e2010-11-21 06:08:52 +00008667
Douglas Gregor882211c2010-04-28 22:16:22 +00008668 CurrentType = MemberDecl->getType().getNonReferenceType();
8669 }
8670
8671 return Owned(OffsetOfExpr::Create(Context, Context.getSizeType(), BuiltinLoc,
8672 TInfo, Comps.data(), Comps.size(),
8673 Exprs.data(), Exprs.size(), RParenLoc));
8674}
Mike Stump4e1f26a2009-02-19 03:04:26 +00008675
John McCalldadc5752010-08-24 06:29:42 +00008676ExprResult Sema::ActOnBuiltinOffsetOf(Scope *S,
John McCall36226622010-10-12 02:09:17 +00008677 SourceLocation BuiltinLoc,
8678 SourceLocation TypeLoc,
Richard Trieuba63ce62011-09-09 01:45:06 +00008679 ParsedType ParsedArgTy,
John McCall36226622010-10-12 02:09:17 +00008680 OffsetOfComponent *CompPtr,
8681 unsigned NumComponents,
Richard Trieuba63ce62011-09-09 01:45:06 +00008682 SourceLocation RParenLoc) {
John McCall36226622010-10-12 02:09:17 +00008683
Douglas Gregor882211c2010-04-28 22:16:22 +00008684 TypeSourceInfo *ArgTInfo;
Richard Trieuba63ce62011-09-09 01:45:06 +00008685 QualType ArgTy = GetTypeFromParser(ParsedArgTy, &ArgTInfo);
Douglas Gregor882211c2010-04-28 22:16:22 +00008686 if (ArgTy.isNull())
8687 return ExprError();
8688
Eli Friedman06dcfd92010-08-05 10:15:45 +00008689 if (!ArgTInfo)
8690 ArgTInfo = Context.getTrivialTypeSourceInfo(ArgTy, TypeLoc);
8691
8692 return BuildBuiltinOffsetOf(BuiltinLoc, ArgTInfo, CompPtr, NumComponents,
Richard Trieuba63ce62011-09-09 01:45:06 +00008693 RParenLoc);
Chris Lattnerf17bd422007-08-30 17:45:32 +00008694}
8695
8696
John McCalldadc5752010-08-24 06:29:42 +00008697ExprResult Sema::ActOnChooseExpr(SourceLocation BuiltinLoc,
John McCall36226622010-10-12 02:09:17 +00008698 Expr *CondExpr,
8699 Expr *LHSExpr, Expr *RHSExpr,
8700 SourceLocation RPLoc) {
Steve Naroff9efdabc2007-08-03 21:21:27 +00008701 assert((CondExpr && LHSExpr && RHSExpr) && "Missing type argument(s)");
8702
John McCall7decc9e2010-11-18 06:31:45 +00008703 ExprValueKind VK = VK_RValue;
8704 ExprObjectKind OK = OK_Ordinary;
Sebastian Redl8d2ccae2009-02-26 14:39:58 +00008705 QualType resType;
Douglas Gregor56751b52009-09-25 04:25:58 +00008706 bool ValueDependent = false;
Douglas Gregor0df91122009-05-19 22:43:30 +00008707 if (CondExpr->isTypeDependent() || CondExpr->isValueDependent()) {
Sebastian Redl8d2ccae2009-02-26 14:39:58 +00008708 resType = Context.DependentTy;
Douglas Gregor56751b52009-09-25 04:25:58 +00008709 ValueDependent = true;
Sebastian Redl8d2ccae2009-02-26 14:39:58 +00008710 } else {
8711 // The conditional expression is required to be a constant expression.
8712 llvm::APSInt condEval(32);
Richard Smithf4c51d92012-02-04 09:53:13 +00008713 ExprResult CondICE = VerifyIntegerConstantExpression(CondExpr, &condEval,
8714 PDiag(diag::err_typecheck_choose_expr_requires_constant), false);
8715 if (CondICE.isInvalid())
8716 return ExprError();
8717 CondExpr = CondICE.take();
Steve Naroff9efdabc2007-08-03 21:21:27 +00008718
Sebastian Redl8d2ccae2009-02-26 14:39:58 +00008719 // If the condition is > zero, then the AST type is the same as the LSHExpr.
John McCall7decc9e2010-11-18 06:31:45 +00008720 Expr *ActiveExpr = condEval.getZExtValue() ? LHSExpr : RHSExpr;
8721
8722 resType = ActiveExpr->getType();
8723 ValueDependent = ActiveExpr->isValueDependent();
8724 VK = ActiveExpr->getValueKind();
8725 OK = ActiveExpr->getObjectKind();
Sebastian Redl8d2ccae2009-02-26 14:39:58 +00008726 }
8727
Sebastian Redl6d4256c2009-03-15 17:47:39 +00008728 return Owned(new (Context) ChooseExpr(BuiltinLoc, CondExpr, LHSExpr, RHSExpr,
John McCall7decc9e2010-11-18 06:31:45 +00008729 resType, VK, OK, RPLoc,
Douglas Gregor56751b52009-09-25 04:25:58 +00008730 resType->isDependentType(),
8731 ValueDependent));
Steve Naroff9efdabc2007-08-03 21:21:27 +00008732}
8733
Steve Naroffc540d662008-09-03 18:15:37 +00008734//===----------------------------------------------------------------------===//
8735// Clang Extensions.
8736//===----------------------------------------------------------------------===//
8737
8738/// ActOnBlockStart - This callback is invoked when a block literal is started.
Richard Trieuba63ce62011-09-09 01:45:06 +00008739void Sema::ActOnBlockStart(SourceLocation CaretLoc, Scope *CurScope) {
Douglas Gregor9a28e842010-03-01 23:15:13 +00008740 BlockDecl *Block = BlockDecl::Create(Context, CurContext, CaretLoc);
Richard Trieuba63ce62011-09-09 01:45:06 +00008741 PushBlockScope(CurScope, Block);
Douglas Gregor9a28e842010-03-01 23:15:13 +00008742 CurContext->addDecl(Block);
Richard Trieuba63ce62011-09-09 01:45:06 +00008743 if (CurScope)
8744 PushDeclContext(CurScope, Block);
Fariborz Jahanian1babe772010-07-09 18:44:02 +00008745 else
8746 CurContext = Block;
John McCallf1a3c2a2011-11-11 03:19:12 +00008747
Eli Friedman34b49062012-01-26 03:00:14 +00008748 getCurBlock()->HasImplicitReturnType = true;
8749
John McCallf1a3c2a2011-11-11 03:19:12 +00008750 // Enter a new evaluation context to insulate the block from any
8751 // cleanups from the enclosing full-expression.
8752 PushExpressionEvaluationContext(PotentiallyEvaluated);
Steve Naroff1d95e5a2008-10-10 01:28:17 +00008753}
8754
Mike Stump82f071f2009-02-04 22:31:32 +00008755void Sema::ActOnBlockArguments(Declarator &ParamInfo, Scope *CurScope) {
Mike Stumpf70bcf72009-05-07 18:43:07 +00008756 assert(ParamInfo.getIdentifier()==0 && "block-id should have no identifier!");
John McCall3882ace2011-01-05 12:14:39 +00008757 assert(ParamInfo.getContext() == Declarator::BlockLiteralContext);
Douglas Gregor9a28e842010-03-01 23:15:13 +00008758 BlockScopeInfo *CurBlock = getCurBlock();
Kovarththanan Rajaratnamba2c6522010-03-13 10:17:05 +00008759
John McCall8cb7bdf2010-06-04 23:28:52 +00008760 TypeSourceInfo *Sig = GetTypeForDeclarator(ParamInfo, CurScope);
John McCall8cb7bdf2010-06-04 23:28:52 +00008761 QualType T = Sig->getType();
Mike Stump82f071f2009-02-04 22:31:32 +00008762
John McCall3882ace2011-01-05 12:14:39 +00008763 // GetTypeForDeclarator always produces a function type for a block
8764 // literal signature. Furthermore, it is always a FunctionProtoType
8765 // unless the function was written with a typedef.
8766 assert(T->isFunctionType() &&
8767 "GetTypeForDeclarator made a non-function block signature");
8768
8769 // Look for an explicit signature in that function type.
8770 FunctionProtoTypeLoc ExplicitSignature;
8771
8772 TypeLoc tmp = Sig->getTypeLoc().IgnoreParens();
8773 if (isa<FunctionProtoTypeLoc>(tmp)) {
8774 ExplicitSignature = cast<FunctionProtoTypeLoc>(tmp);
8775
8776 // Check whether that explicit signature was synthesized by
8777 // GetTypeForDeclarator. If so, don't save that as part of the
8778 // written signature.
Abramo Bagnaraf2a79d92011-03-12 11:17:06 +00008779 if (ExplicitSignature.getLocalRangeBegin() ==
8780 ExplicitSignature.getLocalRangeEnd()) {
John McCall3882ace2011-01-05 12:14:39 +00008781 // This would be much cheaper if we stored TypeLocs instead of
8782 // TypeSourceInfos.
8783 TypeLoc Result = ExplicitSignature.getResultLoc();
8784 unsigned Size = Result.getFullDataSize();
8785 Sig = Context.CreateTypeSourceInfo(Result.getType(), Size);
8786 Sig->getTypeLoc().initializeFullCopy(Result, Size);
8787
8788 ExplicitSignature = FunctionProtoTypeLoc();
8789 }
John McCalla3ccba02010-06-04 11:21:44 +00008790 }
Mike Stump11289f42009-09-09 15:08:12 +00008791
John McCall3882ace2011-01-05 12:14:39 +00008792 CurBlock->TheDecl->setSignatureAsWritten(Sig);
8793 CurBlock->FunctionType = T;
8794
8795 const FunctionType *Fn = T->getAs<FunctionType>();
8796 QualType RetTy = Fn->getResultType();
8797 bool isVariadic =
8798 (isa<FunctionProtoType>(Fn) && cast<FunctionProtoType>(Fn)->isVariadic());
8799
John McCall8e346702010-06-04 19:02:56 +00008800 CurBlock->TheDecl->setIsVariadic(isVariadic);
Douglas Gregorb92a1562010-02-03 00:27:59 +00008801
John McCalla3ccba02010-06-04 11:21:44 +00008802 // Don't allow returning a objc interface by value.
8803 if (RetTy->isObjCObjectType()) {
8804 Diag(ParamInfo.getSourceRange().getBegin(),
8805 diag::err_object_cannot_be_passed_returned_by_value) << 0 << RetTy;
8806 return;
8807 }
Mike Stump4e1f26a2009-02-19 03:04:26 +00008808
John McCalla3ccba02010-06-04 11:21:44 +00008809 // Context.DependentTy is used as a placeholder for a missing block
John McCall8e346702010-06-04 19:02:56 +00008810 // return type. TODO: what should we do with declarators like:
8811 // ^ * { ... }
8812 // If the answer is "apply template argument deduction"....
Fariborz Jahaniandd5eb9d2011-12-03 17:47:53 +00008813 if (RetTy != Context.DependentTy) {
John McCalla3ccba02010-06-04 11:21:44 +00008814 CurBlock->ReturnType = RetTy;
Fariborz Jahaniandd5eb9d2011-12-03 17:47:53 +00008815 CurBlock->TheDecl->setBlockMissingReturnType(false);
Eli Friedman34b49062012-01-26 03:00:14 +00008816 CurBlock->HasImplicitReturnType = false;
Fariborz Jahaniandd5eb9d2011-12-03 17:47:53 +00008817 }
Mike Stump4e1f26a2009-02-19 03:04:26 +00008818
John McCalla3ccba02010-06-04 11:21:44 +00008819 // Push block parameters from the declarator if we had them.
Chris Lattner0e62c1c2011-07-23 10:55:15 +00008820 SmallVector<ParmVarDecl*, 8> Params;
John McCall3882ace2011-01-05 12:14:39 +00008821 if (ExplicitSignature) {
8822 for (unsigned I = 0, E = ExplicitSignature.getNumArgs(); I != E; ++I) {
8823 ParmVarDecl *Param = ExplicitSignature.getArg(I);
Fariborz Jahanian5ec502e2010-02-12 21:53:14 +00008824 if (Param->getIdentifier() == 0 &&
8825 !Param->isImplicit() &&
8826 !Param->isInvalidDecl() &&
8827 !getLangOptions().CPlusPlus)
8828 Diag(Param->getLocation(), diag::err_parameter_name_omitted);
John McCall8e346702010-06-04 19:02:56 +00008829 Params.push_back(Param);
Fariborz Jahanian5ec502e2010-02-12 21:53:14 +00008830 }
John McCalla3ccba02010-06-04 11:21:44 +00008831
8832 // Fake up parameter variables if we have a typedef, like
8833 // ^ fntype { ... }
8834 } else if (const FunctionProtoType *Fn = T->getAs<FunctionProtoType>()) {
8835 for (FunctionProtoType::arg_type_iterator
8836 I = Fn->arg_type_begin(), E = Fn->arg_type_end(); I != E; ++I) {
8837 ParmVarDecl *Param =
8838 BuildParmVarDeclForTypedef(CurBlock->TheDecl,
8839 ParamInfo.getSourceRange().getBegin(),
8840 *I);
John McCall8e346702010-06-04 19:02:56 +00008841 Params.push_back(Param);
John McCalla3ccba02010-06-04 11:21:44 +00008842 }
Steve Naroffc540d662008-09-03 18:15:37 +00008843 }
John McCalla3ccba02010-06-04 11:21:44 +00008844
John McCall8e346702010-06-04 19:02:56 +00008845 // Set the parameters on the block decl.
Douglas Gregorb524d902010-11-01 18:37:59 +00008846 if (!Params.empty()) {
David Blaikie9c70e042011-09-21 18:16:56 +00008847 CurBlock->TheDecl->setParams(Params);
Douglas Gregorb524d902010-11-01 18:37:59 +00008848 CheckParmsForFunctionDef(CurBlock->TheDecl->param_begin(),
8849 CurBlock->TheDecl->param_end(),
8850 /*CheckParameterNames=*/false);
8851 }
8852
John McCalla3ccba02010-06-04 11:21:44 +00008853 // Finally we can process decl attributes.
Douglas Gregor758a8692009-06-17 21:51:59 +00008854 ProcessDeclAttributes(CurScope, CurBlock->TheDecl, ParamInfo);
John McCalldf8b37c2010-03-22 09:20:08 +00008855
John McCalla3ccba02010-06-04 11:21:44 +00008856 // Put the parameter variables in scope. We can bail out immediately
8857 // if we don't have any.
John McCall8e346702010-06-04 19:02:56 +00008858 if (Params.empty())
John McCalla3ccba02010-06-04 11:21:44 +00008859 return;
8860
Steve Naroff1d95e5a2008-10-10 01:28:17 +00008861 for (BlockDecl::param_iterator AI = CurBlock->TheDecl->param_begin(),
John McCallf7b2fb52010-01-22 00:28:27 +00008862 E = CurBlock->TheDecl->param_end(); AI != E; ++AI) {
8863 (*AI)->setOwningFunction(CurBlock->TheDecl);
8864
Steve Naroff1d95e5a2008-10-10 01:28:17 +00008865 // If this has an identifier, add it to the scope stack.
John McCalldf8b37c2010-03-22 09:20:08 +00008866 if ((*AI)->getIdentifier()) {
Argyrios Kyrtzidis1cb0de12010-12-15 18:44:22 +00008867 CheckShadow(CurBlock->TheScope, *AI);
John McCalldf8b37c2010-03-22 09:20:08 +00008868
Steve Naroff1d95e5a2008-10-10 01:28:17 +00008869 PushOnScopeChains(*AI, CurBlock->TheScope);
John McCalldf8b37c2010-03-22 09:20:08 +00008870 }
John McCallf7b2fb52010-01-22 00:28:27 +00008871 }
Steve Naroffc540d662008-09-03 18:15:37 +00008872}
8873
8874/// ActOnBlockError - If there is an error parsing a block, this callback
8875/// is invoked to pop the information about the block from the action impl.
8876void Sema::ActOnBlockError(SourceLocation CaretLoc, Scope *CurScope) {
John McCallf1a3c2a2011-11-11 03:19:12 +00008877 // Leave the expression-evaluation context.
8878 DiscardCleanupsInEvaluationContext();
8879 PopExpressionEvaluationContext();
8880
Steve Naroffc540d662008-09-03 18:15:37 +00008881 // Pop off CurBlock, handle nested blocks.
Chris Lattner41b86942009-04-21 22:38:46 +00008882 PopDeclContext();
Eli Friedman71c80552012-01-05 03:35:19 +00008883 PopFunctionScopeInfo();
Steve Naroffc540d662008-09-03 18:15:37 +00008884}
8885
8886/// ActOnBlockStmtExpr - This is called when the body of a block statement
8887/// literal was successfully completed. ^(int x){...}
John McCalldadc5752010-08-24 06:29:42 +00008888ExprResult Sema::ActOnBlockStmtExpr(SourceLocation CaretLoc,
Chris Lattner60f84492011-02-17 23:58:47 +00008889 Stmt *Body, Scope *CurScope) {
Chris Lattner9eac9312009-03-27 04:18:06 +00008890 // If blocks are disabled, emit an error.
8891 if (!LangOpts.Blocks)
8892 Diag(CaretLoc, diag::err_blocks_disable);
Mike Stump11289f42009-09-09 15:08:12 +00008893
John McCallf1a3c2a2011-11-11 03:19:12 +00008894 // Leave the expression-evaluation context.
John McCall85110b42012-03-08 22:00:17 +00008895 if (hasAnyUnrecoverableErrorsInThisFunction())
8896 DiscardCleanupsInEvaluationContext();
John McCallf1a3c2a2011-11-11 03:19:12 +00008897 assert(!ExprNeedsCleanups && "cleanups within block not correctly bound!");
8898 PopExpressionEvaluationContext();
8899
Douglas Gregor9a28e842010-03-01 23:15:13 +00008900 BlockScopeInfo *BSI = cast<BlockScopeInfo>(FunctionScopes.back());
Fariborz Jahanian1babe772010-07-09 18:44:02 +00008901
Steve Naroff1d95e5a2008-10-10 01:28:17 +00008902 PopDeclContext();
8903
Steve Naroffc540d662008-09-03 18:15:37 +00008904 QualType RetTy = Context.VoidTy;
Fariborz Jahanian3fd73102009-06-19 23:37:08 +00008905 if (!BSI->ReturnType.isNull())
8906 RetTy = BSI->ReturnType;
Mike Stump4e1f26a2009-02-19 03:04:26 +00008907
Mike Stump3bf1ab42009-07-28 22:04:01 +00008908 bool NoReturn = BSI->TheDecl->getAttr<NoReturnAttr>();
Steve Naroffc540d662008-09-03 18:15:37 +00008909 QualType BlockTy;
John McCall8e346702010-06-04 19:02:56 +00008910
John McCallc63de662011-02-02 13:00:07 +00008911 // Set the captured variables on the block.
Eli Friedman20139d32012-01-11 02:36:31 +00008912 // FIXME: Share capture structure between BlockDecl and CapturingScopeInfo!
8913 SmallVector<BlockDecl::Capture, 4> Captures;
8914 for (unsigned i = 0, e = BSI->Captures.size(); i != e; i++) {
8915 CapturingScopeInfo::Capture &Cap = BSI->Captures[i];
8916 if (Cap.isThisCapture())
8917 continue;
Eli Friedman24af8502012-02-03 22:47:37 +00008918 BlockDecl::Capture NewCap(Cap.getVariable(), Cap.isBlockCapture(),
Eli Friedman20139d32012-01-11 02:36:31 +00008919 Cap.isNested(), Cap.getCopyExpr());
8920 Captures.push_back(NewCap);
8921 }
8922 BSI->TheDecl->setCaptures(Context, Captures.begin(), Captures.end(),
8923 BSI->CXXThisCaptureIndex != 0);
John McCallc63de662011-02-02 13:00:07 +00008924
John McCall8e346702010-06-04 19:02:56 +00008925 // If the user wrote a function type in some form, try to use that.
8926 if (!BSI->FunctionType.isNull()) {
8927 const FunctionType *FTy = BSI->FunctionType->getAs<FunctionType>();
8928
8929 FunctionType::ExtInfo Ext = FTy->getExtInfo();
8930 if (NoReturn && !Ext.getNoReturn()) Ext = Ext.withNoReturn(true);
8931
8932 // Turn protoless block types into nullary block types.
8933 if (isa<FunctionNoProtoType>(FTy)) {
John McCalldb40c7f2010-12-14 08:05:40 +00008934 FunctionProtoType::ExtProtoInfo EPI;
8935 EPI.ExtInfo = Ext;
8936 BlockTy = Context.getFunctionType(RetTy, 0, 0, EPI);
John McCall8e346702010-06-04 19:02:56 +00008937
8938 // Otherwise, if we don't need to change anything about the function type,
8939 // preserve its sugar structure.
8940 } else if (FTy->getResultType() == RetTy &&
8941 (!NoReturn || FTy->getNoReturnAttr())) {
8942 BlockTy = BSI->FunctionType;
8943
8944 // Otherwise, make the minimal modifications to the function type.
8945 } else {
8946 const FunctionProtoType *FPT = cast<FunctionProtoType>(FTy);
John McCalldb40c7f2010-12-14 08:05:40 +00008947 FunctionProtoType::ExtProtoInfo EPI = FPT->getExtProtoInfo();
8948 EPI.TypeQuals = 0; // FIXME: silently?
8949 EPI.ExtInfo = Ext;
John McCall8e346702010-06-04 19:02:56 +00008950 BlockTy = Context.getFunctionType(RetTy,
8951 FPT->arg_type_begin(),
8952 FPT->getNumArgs(),
John McCalldb40c7f2010-12-14 08:05:40 +00008953 EPI);
John McCall8e346702010-06-04 19:02:56 +00008954 }
8955
8956 // If we don't have a function type, just build one from nothing.
8957 } else {
John McCalldb40c7f2010-12-14 08:05:40 +00008958 FunctionProtoType::ExtProtoInfo EPI;
John McCall31168b02011-06-15 23:02:42 +00008959 EPI.ExtInfo = FunctionType::ExtInfo().withNoReturn(NoReturn);
John McCalldb40c7f2010-12-14 08:05:40 +00008960 BlockTy = Context.getFunctionType(RetTy, 0, 0, EPI);
John McCall8e346702010-06-04 19:02:56 +00008961 }
Mike Stump4e1f26a2009-02-19 03:04:26 +00008962
John McCall8e346702010-06-04 19:02:56 +00008963 DiagnoseUnusedParameters(BSI->TheDecl->param_begin(),
8964 BSI->TheDecl->param_end());
Steve Naroffc540d662008-09-03 18:15:37 +00008965 BlockTy = Context.getBlockPointerType(BlockTy);
Mike Stump4e1f26a2009-02-19 03:04:26 +00008966
Chris Lattner45542ea2009-04-19 05:28:12 +00008967 // If needed, diagnose invalid gotos and switches in the block.
John McCall31168b02011-06-15 23:02:42 +00008968 if (getCurFunction()->NeedsScopeChecking() &&
8969 !hasAnyUnrecoverableErrorsInThisFunction())
John McCallb268a282010-08-23 23:25:46 +00008970 DiagnoseInvalidJumps(cast<CompoundStmt>(Body));
Mike Stump11289f42009-09-09 15:08:12 +00008971
Chris Lattner60f84492011-02-17 23:58:47 +00008972 BSI->TheDecl->setBody(cast<CompoundStmt>(Body));
Kovarththanan Rajaratnamba2c6522010-03-13 10:17:05 +00008973
Fariborz Jahanian256d39d2011-07-11 18:04:54 +00008974 for (BlockDecl::capture_const_iterator ci = BSI->TheDecl->capture_begin(),
8975 ce = BSI->TheDecl->capture_end(); ci != ce; ++ci) {
8976 const VarDecl *variable = ci->getVariable();
8977 QualType T = variable->getType();
8978 QualType::DestructionKind destructKind = T.isDestructedType();
8979 if (destructKind != QualType::DK_none)
8980 getCurFunction()->setHasBranchProtectedScope();
8981 }
8982
Douglas Gregor49695f02011-09-06 20:46:03 +00008983 computeNRVO(Body, getCurBlock());
8984
Benjamin Kramera4fb8362011-07-12 14:11:05 +00008985 BlockExpr *Result = new (Context) BlockExpr(BSI->TheDecl, BlockTy);
8986 const AnalysisBasedWarnings::Policy &WP = AnalysisWarnings.getDefaultPolicy();
Eli Friedman71c80552012-01-05 03:35:19 +00008987 PopFunctionScopeInfo(&WP, Result->getBlockDecl(), Result);
Benjamin Kramera4fb8362011-07-12 14:11:05 +00008988
John McCall28fc7092011-11-10 05:35:25 +00008989 // If the block isn't obviously global, i.e. it captures anything at
8990 // all, mark this full-expression as needing a cleanup.
8991 if (Result->getBlockDecl()->hasCaptures()) {
8992 ExprCleanupObjects.push_back(Result->getBlockDecl());
8993 ExprNeedsCleanups = true;
8994 }
Fariborz Jahanian197c68c2012-03-06 18:41:35 +00008995
Douglas Gregor9a28e842010-03-01 23:15:13 +00008996 return Owned(Result);
Steve Naroffc540d662008-09-03 18:15:37 +00008997}
8998
John McCalldadc5752010-08-24 06:29:42 +00008999ExprResult Sema::ActOnVAArg(SourceLocation BuiltinLoc,
Richard Trieuba63ce62011-09-09 01:45:06 +00009000 Expr *E, ParsedType Ty,
Sebastian Redl6d4256c2009-03-15 17:47:39 +00009001 SourceLocation RPLoc) {
Abramo Bagnara27db2392010-08-10 10:06:15 +00009002 TypeSourceInfo *TInfo;
Richard Trieuba63ce62011-09-09 01:45:06 +00009003 GetTypeFromParser(Ty, &TInfo);
9004 return BuildVAArgExpr(BuiltinLoc, E, TInfo, RPLoc);
Abramo Bagnara27db2392010-08-10 10:06:15 +00009005}
9006
John McCalldadc5752010-08-24 06:29:42 +00009007ExprResult Sema::BuildVAArgExpr(SourceLocation BuiltinLoc,
John McCall7decc9e2010-11-18 06:31:45 +00009008 Expr *E, TypeSourceInfo *TInfo,
9009 SourceLocation RPLoc) {
Chris Lattner56382aa2009-04-05 15:49:53 +00009010 Expr *OrigExpr = E;
Mike Stump11289f42009-09-09 15:08:12 +00009011
Eli Friedman121ba0c2008-08-09 23:32:40 +00009012 // Get the va_list type
9013 QualType VaListType = Context.getBuiltinVaListType();
Eli Friedmane2cad652009-05-16 12:46:54 +00009014 if (VaListType->isArrayType()) {
9015 // Deal with implicit array decay; for example, on x86-64,
9016 // va_list is an array, but it's supposed to decay to
9017 // a pointer for va_arg.
Eli Friedman121ba0c2008-08-09 23:32:40 +00009018 VaListType = Context.getArrayDecayedType(VaListType);
Eli Friedmane2cad652009-05-16 12:46:54 +00009019 // Make sure the input expression also decays appropriately.
John Wiegley01296292011-04-08 18:41:53 +00009020 ExprResult Result = UsualUnaryConversions(E);
9021 if (Result.isInvalid())
9022 return ExprError();
9023 E = Result.take();
Eli Friedmane2cad652009-05-16 12:46:54 +00009024 } else {
9025 // Otherwise, the va_list argument must be an l-value because
9026 // it is modified by va_arg.
Mike Stump11289f42009-09-09 15:08:12 +00009027 if (!E->isTypeDependent() &&
Douglas Gregorad3150c2009-05-19 23:10:31 +00009028 CheckForModifiableLvalue(E, BuiltinLoc, *this))
Eli Friedmane2cad652009-05-16 12:46:54 +00009029 return ExprError();
9030 }
Eli Friedman121ba0c2008-08-09 23:32:40 +00009031
Douglas Gregorad3150c2009-05-19 23:10:31 +00009032 if (!E->isTypeDependent() &&
9033 !Context.hasSameType(VaListType, E->getType())) {
Sebastian Redl6d4256c2009-03-15 17:47:39 +00009034 return ExprError(Diag(E->getLocStart(),
9035 diag::err_first_argument_to_va_arg_not_of_type_va_list)
Chris Lattner56382aa2009-04-05 15:49:53 +00009036 << OrigExpr->getType() << E->getSourceRange());
Chris Lattner3f5cd772009-04-05 00:59:53 +00009037 }
Mike Stump4e1f26a2009-02-19 03:04:26 +00009038
David Majnemerc75d1a12011-06-14 05:17:32 +00009039 if (!TInfo->getType()->isDependentType()) {
9040 if (RequireCompleteType(TInfo->getTypeLoc().getBeginLoc(), TInfo->getType(),
9041 PDiag(diag::err_second_parameter_to_va_arg_incomplete)
9042 << TInfo->getTypeLoc().getSourceRange()))
9043 return ExprError();
David Majnemer254a5c02011-06-13 06:37:03 +00009044
David Majnemerc75d1a12011-06-14 05:17:32 +00009045 if (RequireNonAbstractType(TInfo->getTypeLoc().getBeginLoc(),
9046 TInfo->getType(),
9047 PDiag(diag::err_second_parameter_to_va_arg_abstract)
9048 << TInfo->getTypeLoc().getSourceRange()))
9049 return ExprError();
9050
Douglas Gregor7e1eb932011-07-30 06:45:27 +00009051 if (!TInfo->getType().isPODType(Context)) {
David Majnemerc75d1a12011-06-14 05:17:32 +00009052 Diag(TInfo->getTypeLoc().getBeginLoc(),
Douglas Gregor7e1eb932011-07-30 06:45:27 +00009053 TInfo->getType()->isObjCLifetimeType()
9054 ? diag::warn_second_parameter_to_va_arg_ownership_qualified
9055 : diag::warn_second_parameter_to_va_arg_not_pod)
David Majnemerc75d1a12011-06-14 05:17:32 +00009056 << TInfo->getType()
9057 << TInfo->getTypeLoc().getSourceRange();
Douglas Gregor7e1eb932011-07-30 06:45:27 +00009058 }
Eli Friedman6290ae42011-07-11 21:45:59 +00009059
9060 // Check for va_arg where arguments of the given type will be promoted
9061 // (i.e. this va_arg is guaranteed to have undefined behavior).
9062 QualType PromoteType;
9063 if (TInfo->getType()->isPromotableIntegerType()) {
9064 PromoteType = Context.getPromotedIntegerType(TInfo->getType());
9065 if (Context.typesAreCompatible(PromoteType, TInfo->getType()))
9066 PromoteType = QualType();
9067 }
9068 if (TInfo->getType()->isSpecificBuiltinType(BuiltinType::Float))
9069 PromoteType = Context.DoubleTy;
9070 if (!PromoteType.isNull())
9071 Diag(TInfo->getTypeLoc().getBeginLoc(),
9072 diag::warn_second_parameter_to_va_arg_never_compatible)
9073 << TInfo->getType()
9074 << PromoteType
9075 << TInfo->getTypeLoc().getSourceRange();
David Majnemerc75d1a12011-06-14 05:17:32 +00009076 }
Mike Stump4e1f26a2009-02-19 03:04:26 +00009077
Abramo Bagnara27db2392010-08-10 10:06:15 +00009078 QualType T = TInfo->getType().getNonLValueExprType(Context);
9079 return Owned(new (Context) VAArgExpr(BuiltinLoc, E, TInfo, RPLoc, T));
Anders Carlsson7e13ab82007-10-15 20:28:48 +00009080}
9081
John McCalldadc5752010-08-24 06:29:42 +00009082ExprResult Sema::ActOnGNUNullExpr(SourceLocation TokenLoc) {
Douglas Gregor3be4b122008-11-29 04:51:27 +00009083 // The type of __null will be int or long, depending on the size of
9084 // pointers on the target.
9085 QualType Ty;
Douglas Gregore8bbc122011-09-02 00:18:52 +00009086 unsigned pw = Context.getTargetInfo().getPointerWidth(0);
9087 if (pw == Context.getTargetInfo().getIntWidth())
Douglas Gregor3be4b122008-11-29 04:51:27 +00009088 Ty = Context.IntTy;
Douglas Gregore8bbc122011-09-02 00:18:52 +00009089 else if (pw == Context.getTargetInfo().getLongWidth())
Douglas Gregor3be4b122008-11-29 04:51:27 +00009090 Ty = Context.LongTy;
Douglas Gregore8bbc122011-09-02 00:18:52 +00009091 else if (pw == Context.getTargetInfo().getLongLongWidth())
NAKAMURA Takumi0d13fd32011-01-19 00:11:41 +00009092 Ty = Context.LongLongTy;
9093 else {
David Blaikie83d382b2011-09-23 05:06:16 +00009094 llvm_unreachable("I don't know size of pointer!");
NAKAMURA Takumi0d13fd32011-01-19 00:11:41 +00009095 }
Douglas Gregor3be4b122008-11-29 04:51:27 +00009096
Sebastian Redl6d4256c2009-03-15 17:47:39 +00009097 return Owned(new (Context) GNUNullExpr(Ty, TokenLoc));
Douglas Gregor3be4b122008-11-29 04:51:27 +00009098}
9099
Alexis Huntc46382e2010-04-28 23:02:27 +00009100static void MakeObjCStringLiteralFixItHint(Sema& SemaRef, QualType DstType,
Douglas Gregora771f462010-03-31 17:46:05 +00009101 Expr *SrcExpr, FixItHint &Hint) {
Anders Carlssonace5d072009-11-10 04:46:30 +00009102 if (!SemaRef.getLangOptions().ObjC1)
9103 return;
Kovarththanan Rajaratnamba2c6522010-03-13 10:17:05 +00009104
Anders Carlssonace5d072009-11-10 04:46:30 +00009105 const ObjCObjectPointerType *PT = DstType->getAs<ObjCObjectPointerType>();
9106 if (!PT)
9107 return;
9108
9109 // Check if the destination is of type 'id'.
9110 if (!PT->isObjCIdType()) {
9111 // Check if the destination is the 'NSString' interface.
9112 const ObjCInterfaceDecl *ID = PT->getInterfaceDecl();
9113 if (!ID || !ID->getIdentifier()->isStr("NSString"))
9114 return;
9115 }
Kovarththanan Rajaratnamba2c6522010-03-13 10:17:05 +00009116
John McCallfe96e0b2011-11-06 09:01:30 +00009117 // Ignore any parens, implicit casts (should only be
9118 // array-to-pointer decays), and not-so-opaque values. The last is
9119 // important for making this trigger for property assignments.
9120 SrcExpr = SrcExpr->IgnoreParenImpCasts();
9121 if (OpaqueValueExpr *OV = dyn_cast<OpaqueValueExpr>(SrcExpr))
9122 if (OV->getSourceExpr())
9123 SrcExpr = OV->getSourceExpr()->IgnoreParenImpCasts();
9124
9125 StringLiteral *SL = dyn_cast<StringLiteral>(SrcExpr);
Douglas Gregorfb65e592011-07-27 05:40:30 +00009126 if (!SL || !SL->isAscii())
Anders Carlssonace5d072009-11-10 04:46:30 +00009127 return;
Kovarththanan Rajaratnamba2c6522010-03-13 10:17:05 +00009128
Douglas Gregora771f462010-03-31 17:46:05 +00009129 Hint = FixItHint::CreateInsertion(SL->getLocStart(), "@");
Anders Carlssonace5d072009-11-10 04:46:30 +00009130}
9131
Chris Lattner9bad62c2008-01-04 18:04:52 +00009132bool Sema::DiagnoseAssignmentResult(AssignConvertType ConvTy,
9133 SourceLocation Loc,
9134 QualType DstType, QualType SrcType,
Douglas Gregor4f4946a2010-04-22 00:20:18 +00009135 Expr *SrcExpr, AssignmentAction Action,
9136 bool *Complained) {
9137 if (Complained)
9138 *Complained = false;
9139
Chris Lattner9bad62c2008-01-04 18:04:52 +00009140 // Decode the result (notice that AST's are still created for extensions).
Douglas Gregor33823722011-06-11 01:09:30 +00009141 bool CheckInferredResultType = false;
Chris Lattner9bad62c2008-01-04 18:04:52 +00009142 bool isInvalid = false;
Eli Friedman381f4312012-02-29 20:59:56 +00009143 unsigned DiagKind = 0;
Douglas Gregora771f462010-03-31 17:46:05 +00009144 FixItHint Hint;
Anna Zaks3b402712011-07-28 19:51:27 +00009145 ConversionFixItGenerator ConvHints;
9146 bool MayHaveConvFixit = false;
Richard Trieucaff2472011-11-23 22:32:32 +00009147 bool MayHaveFunctionDiff = false;
Kovarththanan Rajaratnamba2c6522010-03-13 10:17:05 +00009148
Chris Lattner9bad62c2008-01-04 18:04:52 +00009149 switch (ConvTy) {
Chris Lattner9bad62c2008-01-04 18:04:52 +00009150 case Compatible: return false;
Chris Lattner940cfeb2008-01-04 18:22:42 +00009151 case PointerToInt:
Chris Lattner9bad62c2008-01-04 18:04:52 +00009152 DiagKind = diag::ext_typecheck_convert_pointer_int;
Anna Zaks3b402712011-07-28 19:51:27 +00009153 ConvHints.tryToFixConversion(SrcExpr, SrcType, DstType, *this);
9154 MayHaveConvFixit = true;
Chris Lattner9bad62c2008-01-04 18:04:52 +00009155 break;
Chris Lattner940cfeb2008-01-04 18:22:42 +00009156 case IntToPointer:
9157 DiagKind = diag::ext_typecheck_convert_int_pointer;
Anna Zaks3b402712011-07-28 19:51:27 +00009158 ConvHints.tryToFixConversion(SrcExpr, SrcType, DstType, *this);
9159 MayHaveConvFixit = true;
Chris Lattner940cfeb2008-01-04 18:22:42 +00009160 break;
Chris Lattner9bad62c2008-01-04 18:04:52 +00009161 case IncompatiblePointer:
Douglas Gregora771f462010-03-31 17:46:05 +00009162 MakeObjCStringLiteralFixItHint(*this, DstType, SrcExpr, Hint);
Chris Lattner9bad62c2008-01-04 18:04:52 +00009163 DiagKind = diag::ext_typecheck_convert_incompatible_pointer;
Douglas Gregor33823722011-06-11 01:09:30 +00009164 CheckInferredResultType = DstType->isObjCObjectPointerType() &&
9165 SrcType->isObjCObjectPointerType();
Anna Zaks3b402712011-07-28 19:51:27 +00009166 if (Hint.isNull() && !CheckInferredResultType) {
9167 ConvHints.tryToFixConversion(SrcExpr, SrcType, DstType, *this);
9168 }
9169 MayHaveConvFixit = true;
Chris Lattner9bad62c2008-01-04 18:04:52 +00009170 break;
Eli Friedman80160bd2009-03-22 23:59:44 +00009171 case IncompatiblePointerSign:
9172 DiagKind = diag::ext_typecheck_convert_incompatible_pointer_sign;
9173 break;
Chris Lattner9bad62c2008-01-04 18:04:52 +00009174 case FunctionVoidPointer:
9175 DiagKind = diag::ext_typecheck_convert_pointer_void_func;
9176 break;
John McCall4fff8f62011-02-01 00:10:29 +00009177 case IncompatiblePointerDiscardsQualifiers: {
John McCall71de91c2011-02-01 23:28:01 +00009178 // Perform array-to-pointer decay if necessary.
9179 if (SrcType->isArrayType()) SrcType = Context.getArrayDecayedType(SrcType);
9180
John McCall4fff8f62011-02-01 00:10:29 +00009181 Qualifiers lhq = SrcType->getPointeeType().getQualifiers();
9182 Qualifiers rhq = DstType->getPointeeType().getQualifiers();
9183 if (lhq.getAddressSpace() != rhq.getAddressSpace()) {
9184 DiagKind = diag::err_typecheck_incompatible_address_space;
9185 break;
John McCall31168b02011-06-15 23:02:42 +00009186
9187
9188 } else if (lhq.getObjCLifetime() != rhq.getObjCLifetime()) {
Argyrios Kyrtzidiscff00d92011-06-24 00:08:59 +00009189 DiagKind = diag::err_typecheck_incompatible_ownership;
John McCall31168b02011-06-15 23:02:42 +00009190 break;
John McCall4fff8f62011-02-01 00:10:29 +00009191 }
9192
9193 llvm_unreachable("unknown error case for discarding qualifiers!");
9194 // fallthrough
9195 }
Chris Lattner9bad62c2008-01-04 18:04:52 +00009196 case CompatiblePointerDiscardsQualifiers:
Douglas Gregoraa1e21d2008-09-12 00:47:35 +00009197 // If the qualifiers lost were because we were applying the
9198 // (deprecated) C++ conversion from a string literal to a char*
9199 // (or wchar_t*), then there was no error (C++ 4.2p2). FIXME:
9200 // Ideally, this check would be performed in
John McCallaba90822011-01-31 23:13:11 +00009201 // checkPointerTypesForAssignment. However, that would require a
Douglas Gregoraa1e21d2008-09-12 00:47:35 +00009202 // bit of refactoring (so that the second argument is an
9203 // expression, rather than a type), which should be done as part
John McCallaba90822011-01-31 23:13:11 +00009204 // of a larger effort to fix checkPointerTypesForAssignment for
Douglas Gregoraa1e21d2008-09-12 00:47:35 +00009205 // C++ semantics.
9206 if (getLangOptions().CPlusPlus &&
9207 IsStringLiteralToNonConstPointerConversion(SrcExpr, DstType))
9208 return false;
Chris Lattner9bad62c2008-01-04 18:04:52 +00009209 DiagKind = diag::ext_typecheck_convert_discards_qualifiers;
9210 break;
Alexis Hunt6f3de502009-11-08 07:46:34 +00009211 case IncompatibleNestedPointerQualifiers:
Fariborz Jahanianb98dade2009-11-09 22:16:37 +00009212 DiagKind = diag::ext_nested_pointer_qualifier_mismatch;
Fariborz Jahaniand7aa9d82009-11-07 20:20:40 +00009213 break;
Steve Naroff081c7422008-09-04 15:10:53 +00009214 case IntToBlockPointer:
9215 DiagKind = diag::err_int_to_block_pointer;
9216 break;
9217 case IncompatibleBlockPointer:
Mike Stumpd79b5a82009-04-21 22:51:42 +00009218 DiagKind = diag::err_typecheck_convert_incompatible_block_pointer;
Steve Naroff081c7422008-09-04 15:10:53 +00009219 break;
Steve Naroff8afa9892008-10-14 22:18:38 +00009220 case IncompatibleObjCQualifiedId:
Mike Stump4e1f26a2009-02-19 03:04:26 +00009221 // FIXME: Diagnose the problem in ObjCQualifiedIdTypesAreCompatible, since
Steve Naroff8afa9892008-10-14 22:18:38 +00009222 // it can give a more specific diagnostic.
9223 DiagKind = diag::warn_incompatible_qualified_id;
9224 break;
Anders Carlssondb5a9b62009-01-30 23:17:46 +00009225 case IncompatibleVectors:
9226 DiagKind = diag::warn_incompatible_vectors;
9227 break;
Fariborz Jahanian6f472e82011-07-07 18:55:47 +00009228 case IncompatibleObjCWeakRef:
9229 DiagKind = diag::err_arc_weak_unavailable_assign;
9230 break;
Chris Lattner9bad62c2008-01-04 18:04:52 +00009231 case Incompatible:
9232 DiagKind = diag::err_typecheck_convert_incompatible;
Anna Zaks3b402712011-07-28 19:51:27 +00009233 ConvHints.tryToFixConversion(SrcExpr, SrcType, DstType, *this);
9234 MayHaveConvFixit = true;
Chris Lattner9bad62c2008-01-04 18:04:52 +00009235 isInvalid = true;
Richard Trieucaff2472011-11-23 22:32:32 +00009236 MayHaveFunctionDiff = true;
Chris Lattner9bad62c2008-01-04 18:04:52 +00009237 break;
9238 }
Mike Stump4e1f26a2009-02-19 03:04:26 +00009239
Douglas Gregorc68e1402010-04-09 00:35:39 +00009240 QualType FirstType, SecondType;
9241 switch (Action) {
9242 case AA_Assigning:
9243 case AA_Initializing:
9244 // The destination type comes first.
9245 FirstType = DstType;
9246 SecondType = SrcType;
9247 break;
Alexis Huntc46382e2010-04-28 23:02:27 +00009248
Douglas Gregorc68e1402010-04-09 00:35:39 +00009249 case AA_Returning:
9250 case AA_Passing:
9251 case AA_Converting:
9252 case AA_Sending:
9253 case AA_Casting:
9254 // The source type comes first.
9255 FirstType = SrcType;
9256 SecondType = DstType;
9257 break;
9258 }
Alexis Huntc46382e2010-04-28 23:02:27 +00009259
Anna Zaks3b402712011-07-28 19:51:27 +00009260 PartialDiagnostic FDiag = PDiag(DiagKind);
9261 FDiag << FirstType << SecondType << Action << SrcExpr->getSourceRange();
9262
9263 // If we can fix the conversion, suggest the FixIts.
9264 assert(ConvHints.isNull() || Hint.isNull());
9265 if (!ConvHints.isNull()) {
Benjamin Kramer490afa62012-01-14 21:05:10 +00009266 for (std::vector<FixItHint>::iterator HI = ConvHints.Hints.begin(),
9267 HE = ConvHints.Hints.end(); HI != HE; ++HI)
Anna Zaks3b402712011-07-28 19:51:27 +00009268 FDiag << *HI;
9269 } else {
9270 FDiag << Hint;
9271 }
9272 if (MayHaveConvFixit) { FDiag << (unsigned) (ConvHints.Kind); }
9273
Richard Trieucaff2472011-11-23 22:32:32 +00009274 if (MayHaveFunctionDiff)
9275 HandleFunctionTypeMismatch(FDiag, SecondType, FirstType);
9276
Anna Zaks3b402712011-07-28 19:51:27 +00009277 Diag(Loc, FDiag);
9278
Richard Trieucaff2472011-11-23 22:32:32 +00009279 if (SecondType == Context.OverloadTy)
9280 NoteAllOverloadCandidates(OverloadExpr::find(SrcExpr).Expression,
9281 FirstType);
9282
Douglas Gregor33823722011-06-11 01:09:30 +00009283 if (CheckInferredResultType)
9284 EmitRelatedResultTypeNote(SrcExpr);
9285
Douglas Gregor4f4946a2010-04-22 00:20:18 +00009286 if (Complained)
9287 *Complained = true;
Chris Lattner9bad62c2008-01-04 18:04:52 +00009288 return isInvalid;
9289}
Anders Carlssone54e8a12008-11-30 19:50:32 +00009290
Richard Smithf4c51d92012-02-04 09:53:13 +00009291ExprResult Sema::VerifyIntegerConstantExpression(Expr *E,
9292 llvm::APSInt *Result) {
9293 return VerifyIntegerConstantExpression(E, Result,
9294 PDiag(diag::err_expr_not_ice) << LangOpts.CPlusPlus);
9295}
9296
9297ExprResult Sema::VerifyIntegerConstantExpression(Expr *E, llvm::APSInt *Result,
9298 PartialDiagnostic NotIceDiag,
9299 bool AllowFold,
9300 PartialDiagnostic FoldDiag) {
9301 SourceLocation DiagLoc = E->getSourceRange().getBegin();
9302
9303 if (getLangOptions().CPlusPlus0x) {
9304 // C++11 [expr.const]p5:
9305 // If an expression of literal class type is used in a context where an
9306 // integral constant expression is required, then that class type shall
9307 // have a single non-explicit conversion function to an integral or
9308 // unscoped enumeration type
9309 ExprResult Converted;
9310 if (NotIceDiag.getDiagID()) {
9311 Converted = ConvertToIntegralOrEnumerationType(
9312 DiagLoc, E,
9313 PDiag(diag::err_ice_not_integral),
9314 PDiag(diag::err_ice_incomplete_type),
9315 PDiag(diag::err_ice_explicit_conversion),
9316 PDiag(diag::note_ice_conversion_here),
9317 PDiag(diag::err_ice_ambiguous_conversion),
9318 PDiag(diag::note_ice_conversion_here),
9319 PDiag(0),
9320 /*AllowScopedEnumerations*/ false);
9321 } else {
9322 // The caller wants to silently enquire whether this is an ICE. Don't
9323 // produce any diagnostics if it isn't.
9324 Converted = ConvertToIntegralOrEnumerationType(
9325 DiagLoc, E, PDiag(), PDiag(), PDiag(), PDiag(),
9326 PDiag(), PDiag(), PDiag(), false);
9327 }
9328 if (Converted.isInvalid())
9329 return Converted;
9330 E = Converted.take();
9331 if (!E->getType()->isIntegralOrUnscopedEnumerationType())
9332 return ExprError();
9333 } else if (!E->getType()->isIntegralOrUnscopedEnumerationType()) {
9334 // An ICE must be of integral or unscoped enumeration type.
9335 if (NotIceDiag.getDiagID())
9336 Diag(DiagLoc, NotIceDiag) << E->getSourceRange();
9337 return ExprError();
9338 }
9339
Richard Smith902ca212011-12-14 23:32:26 +00009340 // Circumvent ICE checking in C++11 to avoid evaluating the expression twice
9341 // in the non-ICE case.
Richard Smithf4c51d92012-02-04 09:53:13 +00009342 if (!getLangOptions().CPlusPlus0x && E->isIntegerConstantExpr(Context)) {
9343 if (Result)
9344 *Result = E->EvaluateKnownConstInt(Context);
9345 return Owned(E);
Eli Friedmanbb967cc2009-04-25 22:26:58 +00009346 }
9347
Anders Carlssone54e8a12008-11-30 19:50:32 +00009348 Expr::EvalResult EvalResult;
Richard Smith92b1ce02011-12-12 09:28:41 +00009349 llvm::SmallVector<PartialDiagnosticAt, 8> Notes;
9350 EvalResult.Diag = &Notes;
Anders Carlssone54e8a12008-11-30 19:50:32 +00009351
Richard Smith902ca212011-12-14 23:32:26 +00009352 // Try to evaluate the expression, and produce diagnostics explaining why it's
9353 // not a constant expression as a side-effect.
9354 bool Folded = E->EvaluateAsRValue(EvalResult, Context) &&
9355 EvalResult.Val.isInt() && !EvalResult.HasSideEffects;
9356
9357 // In C++11, we can rely on diagnostics being produced for any expression
9358 // which is not a constant expression. If no diagnostics were produced, then
9359 // this is a constant expression.
9360 if (Folded && getLangOptions().CPlusPlus0x && Notes.empty()) {
9361 if (Result)
9362 *Result = EvalResult.Val.getInt();
Richard Smithf4c51d92012-02-04 09:53:13 +00009363 return Owned(E);
9364 }
9365
9366 // If our only note is the usual "invalid subexpression" note, just point
9367 // the caret at its location rather than producing an essentially
9368 // redundant note.
9369 if (Notes.size() == 1 && Notes[0].second.getDiagID() ==
9370 diag::note_invalid_subexpr_in_const_expr) {
9371 DiagLoc = Notes[0].first;
9372 Notes.clear();
Richard Smith902ca212011-12-14 23:32:26 +00009373 }
9374
9375 if (!Folded || !AllowFold) {
Richard Smithf4c51d92012-02-04 09:53:13 +00009376 if (NotIceDiag.getDiagID()) {
9377 Diag(DiagLoc, NotIceDiag) << E->getSourceRange();
Richard Smith92b1ce02011-12-12 09:28:41 +00009378 for (unsigned I = 0, N = Notes.size(); I != N; ++I)
9379 Diag(Notes[I].first, Notes[I].second);
Anders Carlssone54e8a12008-11-30 19:50:32 +00009380 }
Mike Stump4e1f26a2009-02-19 03:04:26 +00009381
Richard Smithf4c51d92012-02-04 09:53:13 +00009382 return ExprError();
Anders Carlssone54e8a12008-11-30 19:50:32 +00009383 }
9384
Richard Smithf4c51d92012-02-04 09:53:13 +00009385 if (FoldDiag.getDiagID())
9386 Diag(DiagLoc, FoldDiag) << E->getSourceRange();
9387 else
9388 Diag(DiagLoc, diag::ext_expr_not_ice)
9389 << E->getSourceRange() << LangOpts.CPlusPlus;
Richard Smith2ec40612012-01-15 03:51:30 +00009390 for (unsigned I = 0, N = Notes.size(); I != N; ++I)
9391 Diag(Notes[I].first, Notes[I].second);
Mike Stump4e1f26a2009-02-19 03:04:26 +00009392
Anders Carlssone54e8a12008-11-30 19:50:32 +00009393 if (Result)
9394 *Result = EvalResult.Val.getInt();
Richard Smithf4c51d92012-02-04 09:53:13 +00009395 return Owned(E);
Anders Carlssone54e8a12008-11-30 19:50:32 +00009396}
Douglas Gregorc9c02ed2009-06-19 23:52:42 +00009397
Eli Friedman456f0182012-01-20 01:26:23 +00009398namespace {
9399 // Handle the case where we conclude a expression which we speculatively
9400 // considered to be unevaluated is actually evaluated.
9401 class TransformToPE : public TreeTransform<TransformToPE> {
9402 typedef TreeTransform<TransformToPE> BaseTransform;
9403
9404 public:
9405 TransformToPE(Sema &SemaRef) : BaseTransform(SemaRef) { }
9406
9407 // Make sure we redo semantic analysis
9408 bool AlwaysRebuild() { return true; }
9409
Eli Friedman5f0ca242012-02-06 23:29:57 +00009410 // Make sure we handle LabelStmts correctly.
9411 // FIXME: This does the right thing, but maybe we need a more general
9412 // fix to TreeTransform?
9413 StmtResult TransformLabelStmt(LabelStmt *S) {
9414 S->getDecl()->setStmt(0);
9415 return BaseTransform::TransformLabelStmt(S);
9416 }
9417
Eli Friedman456f0182012-01-20 01:26:23 +00009418 // We need to special-case DeclRefExprs referring to FieldDecls which
9419 // are not part of a member pointer formation; normal TreeTransforming
9420 // doesn't catch this case because of the way we represent them in the AST.
9421 // FIXME: This is a bit ugly; is it really the best way to handle this
9422 // case?
9423 //
9424 // Error on DeclRefExprs referring to FieldDecls.
9425 ExprResult TransformDeclRefExpr(DeclRefExpr *E) {
9426 if (isa<FieldDecl>(E->getDecl()) &&
9427 SemaRef.ExprEvalContexts.back().Context != Sema::Unevaluated)
9428 return SemaRef.Diag(E->getLocation(),
9429 diag::err_invalid_non_static_member_use)
9430 << E->getDecl() << E->getSourceRange();
9431
9432 return BaseTransform::TransformDeclRefExpr(E);
9433 }
9434
9435 // Exception: filter out member pointer formation
9436 ExprResult TransformUnaryOperator(UnaryOperator *E) {
9437 if (E->getOpcode() == UO_AddrOf && E->getType()->isMemberPointerType())
9438 return E;
9439
9440 return BaseTransform::TransformUnaryOperator(E);
9441 }
9442
Douglas Gregor89625492012-02-09 08:14:43 +00009443 ExprResult TransformLambdaExpr(LambdaExpr *E) {
9444 // Lambdas never need to be transformed.
9445 return E;
9446 }
Eli Friedman456f0182012-01-20 01:26:23 +00009447 };
Eli Friedmanfbc0dff2012-01-18 01:05:54 +00009448}
9449
Eli Friedman456f0182012-01-20 01:26:23 +00009450ExprResult Sema::TranformToPotentiallyEvaluated(Expr *E) {
Eli Friedmane4f22df2012-02-29 04:03:55 +00009451 assert(ExprEvalContexts.back().Context == Unevaluated &&
9452 "Should only transform unevaluated expressions");
Eli Friedman456f0182012-01-20 01:26:23 +00009453 ExprEvalContexts.back().Context =
9454 ExprEvalContexts[ExprEvalContexts.size()-2].Context;
9455 if (ExprEvalContexts.back().Context == Unevaluated)
9456 return E;
9457 return TransformToPE(*this).TransformExpr(E);
Eli Friedmanfbc0dff2012-01-18 01:05:54 +00009458}
9459
Douglas Gregorff790f12009-11-26 00:44:06 +00009460void
Douglas Gregor7fcbd902012-02-21 00:37:24 +00009461Sema::PushExpressionEvaluationContext(ExpressionEvaluationContext NewContext,
Richard Smithfd555f62012-02-22 02:04:18 +00009462 Decl *LambdaContextDecl,
9463 bool IsDecltype) {
Douglas Gregorff790f12009-11-26 00:44:06 +00009464 ExprEvalContexts.push_back(
John McCall31168b02011-06-15 23:02:42 +00009465 ExpressionEvaluationContextRecord(NewContext,
John McCall28fc7092011-11-10 05:35:25 +00009466 ExprCleanupObjects.size(),
Douglas Gregor7fcbd902012-02-21 00:37:24 +00009467 ExprNeedsCleanups,
Richard Smithfd555f62012-02-22 02:04:18 +00009468 LambdaContextDecl,
9469 IsDecltype));
John McCall31168b02011-06-15 23:02:42 +00009470 ExprNeedsCleanups = false;
Eli Friedman3bda6b12012-02-02 23:15:15 +00009471 if (!MaybeODRUseExprs.empty())
9472 std::swap(MaybeODRUseExprs, ExprEvalContexts.back().SavedMaybeODRUseExprs);
Douglas Gregor0b6a6242009-06-22 20:57:11 +00009473}
9474
Richard Trieucfc491d2011-08-02 04:35:43 +00009475void Sema::PopExpressionEvaluationContext() {
Eli Friedmanfa0df832012-02-02 03:46:19 +00009476 ExpressionEvaluationContextRecord& Rec = ExprEvalContexts.back();
Douglas Gregor0b6a6242009-06-22 20:57:11 +00009477
Douglas Gregor89625492012-02-09 08:14:43 +00009478 if (!Rec.Lambdas.empty()) {
9479 if (Rec.Context == Unevaluated) {
9480 // C++11 [expr.prim.lambda]p2:
9481 // A lambda-expression shall not appear in an unevaluated operand
9482 // (Clause 5).
9483 for (unsigned I = 0, N = Rec.Lambdas.size(); I != N; ++I)
9484 Diag(Rec.Lambdas[I]->getLocStart(),
9485 diag::err_lambda_unevaluated_operand);
9486 } else {
9487 // Mark the capture expressions odr-used. This was deferred
9488 // during lambda expression creation.
9489 for (unsigned I = 0, N = Rec.Lambdas.size(); I != N; ++I) {
9490 LambdaExpr *Lambda = Rec.Lambdas[I];
9491 for (LambdaExpr::capture_init_iterator
9492 C = Lambda->capture_init_begin(),
9493 CEnd = Lambda->capture_init_end();
9494 C != CEnd; ++C) {
9495 MarkDeclarationsReferencedInExpr(*C);
9496 }
9497 }
9498 }
9499 }
9500
Douglas Gregorff790f12009-11-26 00:44:06 +00009501 // When are coming out of an unevaluated context, clear out any
9502 // temporaries that we may have created as part of the evaluation of
9503 // the expression in that context: they aren't relevant because they
9504 // will never be constructed.
Richard Smith764d2fe2011-12-20 02:08:33 +00009505 if (Rec.Context == Unevaluated || Rec.Context == ConstantEvaluated) {
John McCall28fc7092011-11-10 05:35:25 +00009506 ExprCleanupObjects.erase(ExprCleanupObjects.begin() + Rec.NumCleanupObjects,
9507 ExprCleanupObjects.end());
John McCall31168b02011-06-15 23:02:42 +00009508 ExprNeedsCleanups = Rec.ParentNeedsCleanups;
Eli Friedman3bda6b12012-02-02 23:15:15 +00009509 CleanupVarDeclMarking();
9510 std::swap(MaybeODRUseExprs, Rec.SavedMaybeODRUseExprs);
John McCall31168b02011-06-15 23:02:42 +00009511 // Otherwise, merge the contexts together.
9512 } else {
9513 ExprNeedsCleanups |= Rec.ParentNeedsCleanups;
Eli Friedman3bda6b12012-02-02 23:15:15 +00009514 MaybeODRUseExprs.insert(Rec.SavedMaybeODRUseExprs.begin(),
9515 Rec.SavedMaybeODRUseExprs.end());
John McCall31168b02011-06-15 23:02:42 +00009516 }
Eli Friedmanfa0df832012-02-02 03:46:19 +00009517
9518 // Pop the current expression evaluation context off the stack.
9519 ExprEvalContexts.pop_back();
Douglas Gregor0b6a6242009-06-22 20:57:11 +00009520}
Douglas Gregorc9c02ed2009-06-19 23:52:42 +00009521
John McCall31168b02011-06-15 23:02:42 +00009522void Sema::DiscardCleanupsInEvaluationContext() {
John McCall28fc7092011-11-10 05:35:25 +00009523 ExprCleanupObjects.erase(
9524 ExprCleanupObjects.begin() + ExprEvalContexts.back().NumCleanupObjects,
9525 ExprCleanupObjects.end());
John McCall31168b02011-06-15 23:02:42 +00009526 ExprNeedsCleanups = false;
Eli Friedman3bda6b12012-02-02 23:15:15 +00009527 MaybeODRUseExprs.clear();
John McCall31168b02011-06-15 23:02:42 +00009528}
9529
Eli Friedmane0afc982012-01-21 01:01:51 +00009530ExprResult Sema::HandleExprEvaluationContextForTypeof(Expr *E) {
9531 if (!E->getType()->isVariablyModifiedType())
9532 return E;
9533 return TranformToPotentiallyEvaluated(E);
9534}
9535
Benjamin Kramerbf8da9d2012-02-06 11:13:08 +00009536static bool IsPotentiallyEvaluatedContext(Sema &SemaRef) {
Douglas Gregorc9c02ed2009-06-19 23:52:42 +00009537 // Do not mark anything as "used" within a dependent context; wait for
9538 // an instantiation.
Eli Friedmanfa0df832012-02-02 03:46:19 +00009539 if (SemaRef.CurContext->isDependentContext())
9540 return false;
Mike Stump11289f42009-09-09 15:08:12 +00009541
Eli Friedmanfa0df832012-02-02 03:46:19 +00009542 switch (SemaRef.ExprEvalContexts.back().Context) {
9543 case Sema::Unevaluated:
Douglas Gregor0b6a6242009-06-22 20:57:11 +00009544 // We are in an expression that is not potentially evaluated; do nothing.
Eli Friedman02b58512012-01-21 04:44:06 +00009545 // (Depending on how you read the standard, we actually do need to do
9546 // something here for null pointer constants, but the standard's
9547 // definition of a null pointer constant is completely crazy.)
Eli Friedmanfa0df832012-02-02 03:46:19 +00009548 return false;
Mike Stump11289f42009-09-09 15:08:12 +00009549
Eli Friedmanfa0df832012-02-02 03:46:19 +00009550 case Sema::ConstantEvaluated:
9551 case Sema::PotentiallyEvaluated:
Eli Friedman02b58512012-01-21 04:44:06 +00009552 // We are in a potentially evaluated expression (or a constant-expression
9553 // in C++03); we need to do implicit template instantiation, implicitly
9554 // define class members, and mark most declarations as used.
Eli Friedmanfa0df832012-02-02 03:46:19 +00009555 return true;
Mike Stump11289f42009-09-09 15:08:12 +00009556
Eli Friedmanfa0df832012-02-02 03:46:19 +00009557 case Sema::PotentiallyEvaluatedIfUsed:
Douglas Gregor8a01b2a2010-09-11 20:24:53 +00009558 // Referenced declarations will only be used if the construct in the
9559 // containing expression is used.
Eli Friedmanfa0df832012-02-02 03:46:19 +00009560 return false;
Douglas Gregor0b6a6242009-06-22 20:57:11 +00009561 }
Matt Beaumont-Gay248bc722012-02-02 18:35:35 +00009562 llvm_unreachable("Invalid context");
Eli Friedmanfa0df832012-02-02 03:46:19 +00009563}
9564
9565/// \brief Mark a function referenced, and check whether it is odr-used
9566/// (C++ [basic.def.odr]p2, C99 6.9p3)
9567void Sema::MarkFunctionReferenced(SourceLocation Loc, FunctionDecl *Func) {
9568 assert(Func && "No function?");
9569
9570 Func->setReferenced();
9571
Richard Smith4a941e22012-02-14 22:25:15 +00009572 // Don't mark this function as used multiple times, unless it's a constexpr
9573 // function which we need to instantiate.
9574 if (Func->isUsed(false) &&
9575 !(Func->isConstexpr() && !Func->getBody() &&
9576 Func->isImplicitlyInstantiable()))
Eli Friedmanfa0df832012-02-02 03:46:19 +00009577 return;
9578
9579 if (!IsPotentiallyEvaluatedContext(*this))
9580 return;
Mike Stump11289f42009-09-09 15:08:12 +00009581
Douglas Gregorc9c02ed2009-06-19 23:52:42 +00009582 // Note that this declaration has been used.
Eli Friedmanfa0df832012-02-02 03:46:19 +00009583 if (CXXConstructorDecl *Constructor = dyn_cast<CXXConstructorDecl>(Func)) {
Richard Smith273c4e92012-02-26 07:51:39 +00009584 if (Constructor->isDefaulted() && !Constructor->isDeleted()) {
Sebastian Redl22653ba2011-08-30 19:58:05 +00009585 if (Constructor->isDefaultConstructor()) {
9586 if (Constructor->isTrivial())
9587 return;
9588 if (!Constructor->isUsed(false))
9589 DefineImplicitDefaultConstructor(Loc, Constructor);
9590 } else if (Constructor->isCopyConstructor()) {
9591 if (!Constructor->isUsed(false))
9592 DefineImplicitCopyConstructor(Loc, Constructor);
9593 } else if (Constructor->isMoveConstructor()) {
9594 if (!Constructor->isUsed(false))
9595 DefineImplicitMoveConstructor(Loc, Constructor);
9596 }
Fariborz Jahanian477d2422009-06-22 23:34:40 +00009597 }
Kovarththanan Rajaratnamba2c6522010-03-13 10:17:05 +00009598
Douglas Gregor88d292c2010-05-13 16:44:06 +00009599 MarkVTableUsed(Loc, Constructor->getParent());
Eli Friedmanfa0df832012-02-02 03:46:19 +00009600 } else if (CXXDestructorDecl *Destructor =
9601 dyn_cast<CXXDestructorDecl>(Func)) {
Richard Smith273c4e92012-02-26 07:51:39 +00009602 if (Destructor->isDefaulted() && !Destructor->isDeleted() &&
9603 !Destructor->isUsed(false))
Fariborz Jahanian24a175b2009-06-26 23:49:16 +00009604 DefineImplicitDestructor(Loc, Destructor);
Douglas Gregor88d292c2010-05-13 16:44:06 +00009605 if (Destructor->isVirtual())
9606 MarkVTableUsed(Loc, Destructor->getParent());
Eli Friedmanfa0df832012-02-02 03:46:19 +00009607 } else if (CXXMethodDecl *MethodDecl = dyn_cast<CXXMethodDecl>(Func)) {
Richard Smith273c4e92012-02-26 07:51:39 +00009608 if (MethodDecl->isDefaulted() && !MethodDecl->isDeleted() &&
9609 MethodDecl->isOverloadedOperator() &&
Fariborz Jahanian41f79272009-06-25 21:45:19 +00009610 MethodDecl->getOverloadedOperator() == OO_Equal) {
Sebastian Redl22653ba2011-08-30 19:58:05 +00009611 if (!MethodDecl->isUsed(false)) {
9612 if (MethodDecl->isCopyAssignmentOperator())
9613 DefineImplicitCopyAssignment(Loc, MethodDecl);
9614 else
9615 DefineImplicitMoveAssignment(Loc, MethodDecl);
9616 }
Douglas Gregord3b672c2012-02-16 01:06:16 +00009617 } else if (isa<CXXConversionDecl>(MethodDecl) &&
9618 MethodDecl->getParent()->isLambda()) {
9619 CXXConversionDecl *Conversion = cast<CXXConversionDecl>(MethodDecl);
9620 if (Conversion->isLambdaToBlockPointerConversion())
9621 DefineImplicitLambdaToBlockPointerConversion(Loc, Conversion);
9622 else
9623 DefineImplicitLambdaToFunctionPointerConversion(Loc, Conversion);
Douglas Gregor88d292c2010-05-13 16:44:06 +00009624 } else if (MethodDecl->isVirtual())
9625 MarkVTableUsed(Loc, MethodDecl->getParent());
Fariborz Jahanian41f79272009-06-25 21:45:19 +00009626 }
John McCall83779672011-02-19 02:53:41 +00009627
Eli Friedmanfa0df832012-02-02 03:46:19 +00009628 // Recursive functions should be marked when used from another function.
9629 // FIXME: Is this really right?
9630 if (CurContext == Func) return;
Kovarththanan Rajaratnamba2c6522010-03-13 10:17:05 +00009631
Eli Friedmanfa0df832012-02-02 03:46:19 +00009632 // Implicit instantiation of function templates and member functions of
9633 // class templates.
9634 if (Func->isImplicitlyInstantiable()) {
9635 bool AlreadyInstantiated = false;
Richard Smith4a941e22012-02-14 22:25:15 +00009636 SourceLocation PointOfInstantiation = Loc;
Eli Friedmanfa0df832012-02-02 03:46:19 +00009637 if (FunctionTemplateSpecializationInfo *SpecInfo
9638 = Func->getTemplateSpecializationInfo()) {
9639 if (SpecInfo->getPointOfInstantiation().isInvalid())
9640 SpecInfo->setPointOfInstantiation(Loc);
9641 else if (SpecInfo->getTemplateSpecializationKind()
Richard Smith4a941e22012-02-14 22:25:15 +00009642 == TSK_ImplicitInstantiation) {
Eli Friedmanfa0df832012-02-02 03:46:19 +00009643 AlreadyInstantiated = true;
Richard Smith4a941e22012-02-14 22:25:15 +00009644 PointOfInstantiation = SpecInfo->getPointOfInstantiation();
9645 }
Eli Friedmanfa0df832012-02-02 03:46:19 +00009646 } else if (MemberSpecializationInfo *MSInfo
9647 = Func->getMemberSpecializationInfo()) {
9648 if (MSInfo->getPointOfInstantiation().isInvalid())
Douglas Gregor06db9f52009-10-12 20:18:28 +00009649 MSInfo->setPointOfInstantiation(Loc);
Eli Friedmanfa0df832012-02-02 03:46:19 +00009650 else if (MSInfo->getTemplateSpecializationKind()
Richard Smith4a941e22012-02-14 22:25:15 +00009651 == TSK_ImplicitInstantiation) {
Eli Friedmanfa0df832012-02-02 03:46:19 +00009652 AlreadyInstantiated = true;
Richard Smith4a941e22012-02-14 22:25:15 +00009653 PointOfInstantiation = MSInfo->getPointOfInstantiation();
9654 }
Douglas Gregor06db9f52009-10-12 20:18:28 +00009655 }
Mike Stump11289f42009-09-09 15:08:12 +00009656
Richard Smith4a941e22012-02-14 22:25:15 +00009657 if (!AlreadyInstantiated || Func->isConstexpr()) {
Eli Friedmanfa0df832012-02-02 03:46:19 +00009658 if (isa<CXXRecordDecl>(Func->getDeclContext()) &&
9659 cast<CXXRecordDecl>(Func->getDeclContext())->isLocalClass())
Richard Smith4a941e22012-02-14 22:25:15 +00009660 PendingLocalImplicitInstantiations.push_back(
9661 std::make_pair(Func, PointOfInstantiation));
9662 else if (Func->isConstexpr())
Eli Friedmanfa0df832012-02-02 03:46:19 +00009663 // Do not defer instantiations of constexpr functions, to avoid the
9664 // expression evaluator needing to call back into Sema if it sees a
9665 // call to such a function.
Richard Smith4a941e22012-02-14 22:25:15 +00009666 InstantiateFunctionDefinition(PointOfInstantiation, Func);
Argyrios Kyrtzidise5dc5b32012-02-10 20:10:44 +00009667 else {
Richard Smith4a941e22012-02-14 22:25:15 +00009668 PendingInstantiations.push_back(std::make_pair(Func,
9669 PointOfInstantiation));
Argyrios Kyrtzidise5dc5b32012-02-10 20:10:44 +00009670 // Notify the consumer that a function was implicitly instantiated.
9671 Consumer.HandleCXXImplicitFunctionInstantiation(Func);
9672 }
John McCall83779672011-02-19 02:53:41 +00009673 }
Eli Friedmanfa0df832012-02-02 03:46:19 +00009674 } else {
9675 // Walk redefinitions, as some of them may be instantiable.
9676 for (FunctionDecl::redecl_iterator i(Func->redecls_begin()),
9677 e(Func->redecls_end()); i != e; ++i) {
9678 if (!i->isUsed(false) && i->isImplicitlyInstantiable())
9679 MarkFunctionReferenced(Loc, *i);
9680 }
Sam Weinigbae69142009-09-11 03:29:30 +00009681 }
Eli Friedmanfa0df832012-02-02 03:46:19 +00009682
9683 // Keep track of used but undefined functions.
9684 if (!Func->isPure() && !Func->hasBody() &&
9685 Func->getLinkage() != ExternalLinkage) {
9686 SourceLocation &old = UndefinedInternals[Func->getCanonicalDecl()];
9687 if (old.isInvalid()) old = Loc;
9688 }
9689
9690 Func->setUsed(true);
9691}
9692
Eli Friedman9bb33f52012-02-03 02:04:35 +00009693static void
9694diagnoseUncapturableValueReference(Sema &S, SourceLocation loc,
9695 VarDecl *var, DeclContext *DC) {
Eli Friedmandd053f62012-02-07 00:15:00 +00009696 DeclContext *VarDC = var->getDeclContext();
9697
Eli Friedman9bb33f52012-02-03 02:04:35 +00009698 // If the parameter still belongs to the translation unit, then
9699 // we're actually just using one parameter in the declaration of
9700 // the next.
9701 if (isa<ParmVarDecl>(var) &&
Eli Friedmandd053f62012-02-07 00:15:00 +00009702 isa<TranslationUnitDecl>(VarDC))
Eli Friedman9bb33f52012-02-03 02:04:35 +00009703 return;
9704
Eli Friedmandd053f62012-02-07 00:15:00 +00009705 // For C code, don't diagnose about capture if we're not actually in code
9706 // right now; it's impossible to write a non-constant expression outside of
9707 // function context, so we'll get other (more useful) diagnostics later.
9708 //
9709 // For C++, things get a bit more nasty... it would be nice to suppress this
9710 // diagnostic for certain cases like using a local variable in an array bound
9711 // for a member of a local class, but the correct predicate is not obvious.
9712 if (!S.getLangOptions().CPlusPlus && !S.CurContext->isFunctionOrMethod())
Eli Friedman9bb33f52012-02-03 02:04:35 +00009713 return;
9714
Eli Friedmandd053f62012-02-07 00:15:00 +00009715 if (isa<CXXMethodDecl>(VarDC) &&
9716 cast<CXXRecordDecl>(VarDC->getParent())->isLambda()) {
9717 S.Diag(loc, diag::err_reference_to_local_var_in_enclosing_lambda)
9718 << var->getIdentifier();
9719 } else if (FunctionDecl *fn = dyn_cast<FunctionDecl>(VarDC)) {
9720 S.Diag(loc, diag::err_reference_to_local_var_in_enclosing_function)
9721 << var->getIdentifier() << fn->getDeclName();
9722 } else if (isa<BlockDecl>(VarDC)) {
9723 S.Diag(loc, diag::err_reference_to_local_var_in_enclosing_block)
9724 << var->getIdentifier();
9725 } else {
9726 // FIXME: Is there any other context where a local variable can be
9727 // declared?
9728 S.Diag(loc, diag::err_reference_to_local_var_in_enclosing_context)
9729 << var->getIdentifier();
9730 }
Eli Friedman9bb33f52012-02-03 02:04:35 +00009731
Eli Friedman9bb33f52012-02-03 02:04:35 +00009732 S.Diag(var->getLocation(), diag::note_local_variable_declared_here)
9733 << var->getIdentifier();
Eli Friedmandd053f62012-02-07 00:15:00 +00009734
9735 // FIXME: Add additional diagnostic info about class etc. which prevents
9736 // capture.
Eli Friedman9bb33f52012-02-03 02:04:35 +00009737}
9738
Douglas Gregor81495f32012-02-12 18:42:33 +00009739/// \brief Capture the given variable in the given lambda expression.
9740static ExprResult captureInLambda(Sema &S, LambdaScopeInfo *LSI,
Douglas Gregorfdf598e2012-02-18 09:37:24 +00009741 VarDecl *Var, QualType FieldType,
9742 QualType DeclRefType,
9743 SourceLocation Loc) {
Douglas Gregor81495f32012-02-12 18:42:33 +00009744 CXXRecordDecl *Lambda = LSI->Lambda;
Douglas Gregor81495f32012-02-12 18:42:33 +00009745
Douglas Gregorabecb9c2012-02-09 01:56:40 +00009746 // Build the non-static data member.
9747 FieldDecl *Field
9748 = FieldDecl::Create(S.Context, Lambda, Loc, Loc, 0, FieldType,
9749 S.Context.getTrivialTypeSourceInfo(FieldType, Loc),
9750 0, false, false);
9751 Field->setImplicit(true);
9752 Field->setAccess(AS_private);
Douglas Gregor3d23f7882012-02-09 02:12:34 +00009753 Lambda->addDecl(Field);
Douglas Gregorabecb9c2012-02-09 01:56:40 +00009754
9755 // C++11 [expr.prim.lambda]p21:
9756 // When the lambda-expression is evaluated, the entities that
9757 // are captured by copy are used to direct-initialize each
9758 // corresponding non-static data member of the resulting closure
9759 // object. (For array members, the array elements are
9760 // direct-initialized in increasing subscript order.) These
9761 // initializations are performed in the (unspecified) order in
9762 // which the non-static data members are declared.
Douglas Gregorabecb9c2012-02-09 01:56:40 +00009763
Douglas Gregor89625492012-02-09 08:14:43 +00009764 // Introduce a new evaluation context for the initialization, so
9765 // that temporaries introduced as part of the capture are retained
9766 // to be re-"exported" from the lambda expression itself.
Douglas Gregorabecb9c2012-02-09 01:56:40 +00009767 S.PushExpressionEvaluationContext(Sema::PotentiallyEvaluated);
9768
Douglas Gregorf02455e2012-02-10 09:26:04 +00009769 // C++ [expr.prim.labda]p12:
9770 // An entity captured by a lambda-expression is odr-used (3.2) in
9771 // the scope containing the lambda-expression.
Douglas Gregorfdf598e2012-02-18 09:37:24 +00009772 Expr *Ref = new (S.Context) DeclRefExpr(Var, DeclRefType, VK_LValue, Loc);
Eli Friedman23b1be92012-03-01 21:32:56 +00009773 Var->setReferenced(true);
Douglas Gregorf02455e2012-02-10 09:26:04 +00009774 Var->setUsed(true);
Douglas Gregor199cec72012-02-09 02:45:47 +00009775
9776 // When the field has array type, create index variables for each
9777 // dimension of the array. We use these index variables to subscript
9778 // the source array, and other clients (e.g., CodeGen) will perform
9779 // the necessary iteration with these index variables.
9780 SmallVector<VarDecl *, 4> IndexVariables;
Douglas Gregor199cec72012-02-09 02:45:47 +00009781 QualType BaseType = FieldType;
9782 QualType SizeType = S.Context.getSizeType();
Douglas Gregor54fcea62012-02-13 16:35:30 +00009783 LSI->ArrayIndexStarts.push_back(LSI->ArrayIndexVars.size());
Douglas Gregor199cec72012-02-09 02:45:47 +00009784 while (const ConstantArrayType *Array
9785 = S.Context.getAsConstantArrayType(BaseType)) {
Douglas Gregor199cec72012-02-09 02:45:47 +00009786 // Create the iteration variable for this array index.
9787 IdentifierInfo *IterationVarName = 0;
9788 {
9789 SmallString<8> Str;
9790 llvm::raw_svector_ostream OS(Str);
9791 OS << "__i" << IndexVariables.size();
9792 IterationVarName = &S.Context.Idents.get(OS.str());
9793 }
9794 VarDecl *IterationVar
9795 = VarDecl::Create(S.Context, S.CurContext, Loc, Loc,
9796 IterationVarName, SizeType,
9797 S.Context.getTrivialTypeSourceInfo(SizeType, Loc),
9798 SC_None, SC_None);
9799 IndexVariables.push_back(IterationVar);
Douglas Gregor54fcea62012-02-13 16:35:30 +00009800 LSI->ArrayIndexVars.push_back(IterationVar);
9801
Douglas Gregor199cec72012-02-09 02:45:47 +00009802 // Create a reference to the iteration variable.
9803 ExprResult IterationVarRef
9804 = S.BuildDeclRefExpr(IterationVar, SizeType, VK_LValue, Loc);
9805 assert(!IterationVarRef.isInvalid() &&
9806 "Reference to invented variable cannot fail!");
9807 IterationVarRef = S.DefaultLvalueConversion(IterationVarRef.take());
9808 assert(!IterationVarRef.isInvalid() &&
9809 "Conversion of invented variable cannot fail!");
9810
9811 // Subscript the array with this iteration variable.
9812 ExprResult Subscript = S.CreateBuiltinArraySubscriptExpr(
9813 Ref, Loc, IterationVarRef.take(), Loc);
9814 if (Subscript.isInvalid()) {
9815 S.CleanupVarDeclMarking();
9816 S.DiscardCleanupsInEvaluationContext();
9817 S.PopExpressionEvaluationContext();
9818 return ExprError();
9819 }
9820
9821 Ref = Subscript.take();
9822 BaseType = Array->getElementType();
9823 }
9824
9825 // Construct the entity that we will be initializing. For an array, this
9826 // will be first element in the array, which may require several levels
9827 // of array-subscript entities.
9828 SmallVector<InitializedEntity, 4> Entities;
9829 Entities.reserve(1 + IndexVariables.size());
Douglas Gregor19666fb2012-02-15 16:57:26 +00009830 Entities.push_back(
9831 InitializedEntity::InitializeLambdaCapture(Var, Field, Loc));
Douglas Gregor199cec72012-02-09 02:45:47 +00009832 for (unsigned I = 0, N = IndexVariables.size(); I != N; ++I)
9833 Entities.push_back(InitializedEntity::InitializeElement(S.Context,
9834 0,
9835 Entities.back()));
9836
Douglas Gregorabecb9c2012-02-09 01:56:40 +00009837 InitializationKind InitKind
9838 = InitializationKind::CreateDirect(Loc, Loc, Loc);
Douglas Gregor199cec72012-02-09 02:45:47 +00009839 InitializationSequence Init(S, Entities.back(), InitKind, &Ref, 1);
Douglas Gregorabecb9c2012-02-09 01:56:40 +00009840 ExprResult Result(true);
Douglas Gregor199cec72012-02-09 02:45:47 +00009841 if (!Init.Diagnose(S, Entities.back(), InitKind, &Ref, 1))
9842 Result = Init.Perform(S, Entities.back(), InitKind,
Douglas Gregorabecb9c2012-02-09 01:56:40 +00009843 MultiExprArg(S, &Ref, 1));
9844
9845 // If this initialization requires any cleanups (e.g., due to a
9846 // default argument to a copy constructor), note that for the
9847 // lambda.
9848 if (S.ExprNeedsCleanups)
9849 LSI->ExprNeedsCleanups = true;
9850
9851 // Exit the expression evaluation context used for the capture.
9852 S.CleanupVarDeclMarking();
9853 S.DiscardCleanupsInEvaluationContext();
9854 S.PopExpressionEvaluationContext();
9855 return Result;
Douglas Gregor199cec72012-02-09 02:45:47 +00009856}
Douglas Gregorabecb9c2012-02-09 01:56:40 +00009857
Douglas Gregorfdf598e2012-02-18 09:37:24 +00009858bool Sema::tryCaptureVariable(VarDecl *Var, SourceLocation Loc,
9859 TryCaptureKind Kind, SourceLocation EllipsisLoc,
9860 bool BuildAndDiagnose,
9861 QualType &CaptureType,
9862 QualType &DeclRefType) {
9863 bool Nested = false;
Douglas Gregor81495f32012-02-12 18:42:33 +00009864
Eli Friedman24af8502012-02-03 22:47:37 +00009865 DeclContext *DC = CurContext;
Douglas Gregorfdf598e2012-02-18 09:37:24 +00009866 if (Var->getDeclContext() == DC) return true;
9867 if (!Var->hasLocalStorage()) return true;
Eli Friedman9bb33f52012-02-03 02:04:35 +00009868
Douglas Gregor81495f32012-02-12 18:42:33 +00009869 bool HasBlocksAttr = Var->hasAttr<BlocksAttr>();
Eli Friedman9bb33f52012-02-03 02:04:35 +00009870
Douglas Gregorfdf598e2012-02-18 09:37:24 +00009871 // Walk up the stack to determine whether we can capture the variable,
9872 // performing the "simple" checks that don't depend on type. We stop when
9873 // we've either hit the declared scope of the variable or find an existing
9874 // capture of that variable.
9875 CaptureType = Var->getType();
9876 DeclRefType = CaptureType.getNonReferenceType();
9877 bool Explicit = (Kind != TryCapture_Implicit);
9878 unsigned FunctionScopesIndex = FunctionScopes.size() - 1;
Eli Friedman9bb33f52012-02-03 02:04:35 +00009879 do {
Eli Friedman24af8502012-02-03 22:47:37 +00009880 // Only block literals and lambda expressions can capture; other
Eli Friedman9bb33f52012-02-03 02:04:35 +00009881 // scopes don't work.
Eli Friedman24af8502012-02-03 22:47:37 +00009882 DeclContext *ParentDC;
9883 if (isa<BlockDecl>(DC))
9884 ParentDC = DC->getParent();
9885 else if (isa<CXXMethodDecl>(DC) &&
Douglas Gregor81495f32012-02-12 18:42:33 +00009886 cast<CXXMethodDecl>(DC)->getOverloadedOperator() == OO_Call &&
Eli Friedman24af8502012-02-03 22:47:37 +00009887 cast<CXXRecordDecl>(DC->getParent())->isLambda())
9888 ParentDC = DC->getParent()->getParent();
Douglas Gregor81495f32012-02-12 18:42:33 +00009889 else {
Douglas Gregorfdf598e2012-02-18 09:37:24 +00009890 if (BuildAndDiagnose)
Douglas Gregor81495f32012-02-12 18:42:33 +00009891 diagnoseUncapturableValueReference(*this, Loc, Var, DC);
Douglas Gregorfdf598e2012-02-18 09:37:24 +00009892 return true;
Douglas Gregor81495f32012-02-12 18:42:33 +00009893 }
Eli Friedman9bb33f52012-02-03 02:04:35 +00009894
Eli Friedman24af8502012-02-03 22:47:37 +00009895 CapturingScopeInfo *CSI =
Douglas Gregor81495f32012-02-12 18:42:33 +00009896 cast<CapturingScopeInfo>(FunctionScopes[FunctionScopesIndex]);
Eli Friedman9bb33f52012-02-03 02:04:35 +00009897
Eli Friedman24af8502012-02-03 22:47:37 +00009898 // Check whether we've already captured it.
Douglas Gregor81495f32012-02-12 18:42:33 +00009899 if (CSI->CaptureMap.count(Var)) {
Douglas Gregorfdf598e2012-02-18 09:37:24 +00009900 // If we found a capture, any subcaptures are nested.
Eli Friedman9bb33f52012-02-03 02:04:35 +00009901 Nested = true;
Douglas Gregorfdf598e2012-02-18 09:37:24 +00009902
9903 // Retrieve the capture type for this variable.
9904 CaptureType = CSI->getCapture(Var).getCaptureType();
9905
9906 // Compute the type of an expression that refers to this variable.
9907 DeclRefType = CaptureType.getNonReferenceType();
9908
9909 const CapturingScopeInfo::Capture &Cap = CSI->getCapture(Var);
9910 if (Cap.isCopyCapture() &&
9911 !(isa<LambdaScopeInfo>(CSI) && cast<LambdaScopeInfo>(CSI)->Mutable))
9912 DeclRefType.addConst();
Eli Friedman9bb33f52012-02-03 02:04:35 +00009913 break;
9914 }
9915
Douglas Gregor81495f32012-02-12 18:42:33 +00009916 bool IsBlock = isa<BlockScopeInfo>(CSI);
Douglas Gregorfdf598e2012-02-18 09:37:24 +00009917 bool IsLambda = !IsBlock;
Eli Friedman24af8502012-02-03 22:47:37 +00009918
9919 // Lambdas are not allowed to capture unnamed variables
9920 // (e.g. anonymous unions).
9921 // FIXME: The C++11 rule don't actually state this explicitly, but I'm
9922 // assuming that's the intent.
Douglas Gregor81495f32012-02-12 18:42:33 +00009923 if (IsLambda && !Var->getDeclName()) {
Douglas Gregorfdf598e2012-02-18 09:37:24 +00009924 if (BuildAndDiagnose) {
Douglas Gregor81495f32012-02-12 18:42:33 +00009925 Diag(Loc, diag::err_lambda_capture_anonymous_var);
9926 Diag(Var->getLocation(), diag::note_declared_at);
9927 }
Douglas Gregorfdf598e2012-02-18 09:37:24 +00009928 return true;
Eli Friedman24af8502012-02-03 22:47:37 +00009929 }
9930
9931 // Prohibit variably-modified types; they're difficult to deal with.
Douglas Gregorfdf598e2012-02-18 09:37:24 +00009932 if (Var->getType()->isVariablyModifiedType()) {
9933 if (BuildAndDiagnose) {
Douglas Gregor81495f32012-02-12 18:42:33 +00009934 if (IsBlock)
9935 Diag(Loc, diag::err_ref_vm_type);
9936 else
9937 Diag(Loc, diag::err_lambda_capture_vm_type) << Var->getDeclName();
9938 Diag(Var->getLocation(), diag::note_previous_decl)
9939 << Var->getDeclName();
9940 }
Douglas Gregorfdf598e2012-02-18 09:37:24 +00009941 return true;
Eli Friedman9bb33f52012-02-03 02:04:35 +00009942 }
9943
Eli Friedman24af8502012-02-03 22:47:37 +00009944 // Lambdas are not allowed to capture __block variables; they don't
9945 // support the expected semantics.
Douglas Gregor81495f32012-02-12 18:42:33 +00009946 if (IsLambda && HasBlocksAttr) {
Douglas Gregorfdf598e2012-02-18 09:37:24 +00009947 if (BuildAndDiagnose) {
Douglas Gregor81495f32012-02-12 18:42:33 +00009948 Diag(Loc, diag::err_lambda_capture_block)
9949 << Var->getDeclName();
9950 Diag(Var->getLocation(), diag::note_previous_decl)
9951 << Var->getDeclName();
9952 }
Douglas Gregorfdf598e2012-02-18 09:37:24 +00009953 return true;
Eli Friedman24af8502012-02-03 22:47:37 +00009954 }
9955
Douglas Gregor81495f32012-02-12 18:42:33 +00009956 if (CSI->ImpCaptureStyle == CapturingScopeInfo::ImpCap_None && !Explicit) {
9957 // No capture-default
Douglas Gregorfdf598e2012-02-18 09:37:24 +00009958 if (BuildAndDiagnose) {
Douglas Gregor81495f32012-02-12 18:42:33 +00009959 Diag(Loc, diag::err_lambda_impcap) << Var->getDeclName();
9960 Diag(Var->getLocation(), diag::note_previous_decl)
9961 << Var->getDeclName();
9962 Diag(cast<LambdaScopeInfo>(CSI)->Lambda->getLocStart(),
9963 diag::note_lambda_decl);
9964 }
Douglas Gregorfdf598e2012-02-18 09:37:24 +00009965 return true;
Douglas Gregor81495f32012-02-12 18:42:33 +00009966 }
9967
9968 FunctionScopesIndex--;
9969 DC = ParentDC;
9970 Explicit = false;
9971 } while (!Var->getDeclContext()->Equals(DC));
9972
Douglas Gregorfdf598e2012-02-18 09:37:24 +00009973 // Walk back down the scope stack, computing the type of the capture at
9974 // each step, checking type-specific requirements, and adding captures if
9975 // requested.
9976 for (unsigned I = ++FunctionScopesIndex, N = FunctionScopes.size(); I != N;
9977 ++I) {
9978 CapturingScopeInfo *CSI = cast<CapturingScopeInfo>(FunctionScopes[I]);
Douglas Gregor812d8f62012-02-18 05:51:20 +00009979
Douglas Gregorfdf598e2012-02-18 09:37:24 +00009980 // Compute the type of the capture and of a reference to the capture within
9981 // this scope.
9982 if (isa<BlockScopeInfo>(CSI)) {
9983 Expr *CopyExpr = 0;
9984 bool ByRef = false;
9985
9986 // Blocks are not allowed to capture arrays.
9987 if (CaptureType->isArrayType()) {
9988 if (BuildAndDiagnose) {
9989 Diag(Loc, diag::err_ref_array_type);
9990 Diag(Var->getLocation(), diag::note_previous_decl)
9991 << Var->getDeclName();
9992 }
9993 return true;
9994 }
9995
9996 if (HasBlocksAttr || CaptureType->isReferenceType()) {
9997 // Block capture by reference does not change the capture or
9998 // declaration reference types.
9999 ByRef = true;
10000 } else {
10001 // Block capture by copy introduces 'const'.
10002 CaptureType = CaptureType.getNonReferenceType().withConst();
10003 DeclRefType = CaptureType;
10004
10005 if (getLangOptions().CPlusPlus && BuildAndDiagnose) {
10006 if (const RecordType *Record = DeclRefType->getAs<RecordType>()) {
10007 // The capture logic needs the destructor, so make sure we mark it.
10008 // Usually this is unnecessary because most local variables have
10009 // their destructors marked at declaration time, but parameters are
10010 // an exception because it's technically only the call site that
10011 // actually requires the destructor.
10012 if (isa<ParmVarDecl>(Var))
10013 FinalizeVarWithDestructor(Var, Record);
10014
10015 // According to the blocks spec, the capture of a variable from
10016 // the stack requires a const copy constructor. This is not true
10017 // of the copy/move done to move a __block variable to the heap.
10018 Expr *DeclRef = new (Context) DeclRefExpr(Var,
10019 DeclRefType.withConst(),
10020 VK_LValue, Loc);
10021 ExprResult Result
10022 = PerformCopyInitialization(
10023 InitializedEntity::InitializeBlock(Var->getLocation(),
10024 CaptureType, false),
10025 Loc, Owned(DeclRef));
10026
10027 // Build a full-expression copy expression if initialization
10028 // succeeded and used a non-trivial constructor. Recover from
10029 // errors by pretending that the copy isn't necessary.
10030 if (!Result.isInvalid() &&
10031 !cast<CXXConstructExpr>(Result.get())->getConstructor()
10032 ->isTrivial()) {
10033 Result = MaybeCreateExprWithCleanups(Result);
10034 CopyExpr = Result.take();
10035 }
10036 }
10037 }
10038 }
10039
10040 // Actually capture the variable.
10041 if (BuildAndDiagnose)
10042 CSI->addCapture(Var, HasBlocksAttr, ByRef, Nested, Loc,
10043 SourceLocation(), CaptureType, CopyExpr);
10044 Nested = true;
10045 continue;
10046 }
Douglas Gregor812d8f62012-02-18 05:51:20 +000010047
Douglas Gregorfdf598e2012-02-18 09:37:24 +000010048 LambdaScopeInfo *LSI = cast<LambdaScopeInfo>(CSI);
10049
10050 // Determine whether we are capturing by reference or by value.
10051 bool ByRef = false;
10052 if (I == N - 1 && Kind != TryCapture_Implicit) {
10053 ByRef = (Kind == TryCapture_ExplicitByRef);
Eli Friedman24af8502012-02-03 22:47:37 +000010054 } else {
Douglas Gregorfdf598e2012-02-18 09:37:24 +000010055 ByRef = (LSI->ImpCaptureStyle == LambdaScopeInfo::ImpCap_LambdaByref);
Eli Friedman24af8502012-02-03 22:47:37 +000010056 }
Douglas Gregorfdf598e2012-02-18 09:37:24 +000010057
10058 // Compute the type of the field that will capture this variable.
10059 if (ByRef) {
10060 // C++11 [expr.prim.lambda]p15:
10061 // An entity is captured by reference if it is implicitly or
10062 // explicitly captured but not captured by copy. It is
10063 // unspecified whether additional unnamed non-static data
10064 // members are declared in the closure type for entities
10065 // captured by reference.
10066 //
10067 // FIXME: It is not clear whether we want to build an lvalue reference
10068 // to the DeclRefType or to CaptureType.getNonReferenceType(). GCC appears
10069 // to do the former, while EDG does the latter. Core issue 1249 will
10070 // clarify, but for now we follow GCC because it's a more permissive and
10071 // easily defensible position.
10072 CaptureType = Context.getLValueReferenceType(DeclRefType);
10073 } else {
10074 // C++11 [expr.prim.lambda]p14:
10075 // For each entity captured by copy, an unnamed non-static
10076 // data member is declared in the closure type. The
10077 // declaration order of these members is unspecified. The type
10078 // of such a data member is the type of the corresponding
10079 // captured entity if the entity is not a reference to an
10080 // object, or the referenced type otherwise. [Note: If the
10081 // captured entity is a reference to a function, the
10082 // corresponding data member is also a reference to a
10083 // function. - end note ]
10084 if (const ReferenceType *RefType = CaptureType->getAs<ReferenceType>()){
10085 if (!RefType->getPointeeType()->isFunctionType())
10086 CaptureType = RefType->getPointeeType();
Eli Friedman9bb33f52012-02-03 02:04:35 +000010087 }
10088 }
10089
Douglas Gregorfdf598e2012-02-18 09:37:24 +000010090 // Capture this variable in the lambda.
10091 Expr *CopyExpr = 0;
10092 if (BuildAndDiagnose) {
10093 ExprResult Result = captureInLambda(*this, LSI, Var, CaptureType,
10094 DeclRefType, Loc);
10095 if (!Result.isInvalid())
10096 CopyExpr = Result.take();
10097 }
10098
10099 // Compute the type of a reference to this captured variable.
10100 if (ByRef)
10101 DeclRefType = CaptureType.getNonReferenceType();
10102 else {
10103 // C++ [expr.prim.lambda]p5:
10104 // The closure type for a lambda-expression has a public inline
10105 // function call operator [...]. This function call operator is
10106 // declared const (9.3.1) if and only if the lambda-expression’s
10107 // parameter-declaration-clause is not followed by mutable.
10108 DeclRefType = CaptureType.getNonReferenceType();
10109 if (!LSI->Mutable && !CaptureType->isReferenceType())
10110 DeclRefType.addConst();
10111 }
10112
10113 // Add the capture.
10114 if (BuildAndDiagnose)
10115 CSI->addCapture(Var, /*IsBlock=*/false, ByRef, Nested, Loc,
10116 EllipsisLoc, CaptureType, CopyExpr);
Eli Friedman9bb33f52012-02-03 02:04:35 +000010117 Nested = true;
10118 }
Douglas Gregorfdf598e2012-02-18 09:37:24 +000010119
10120 return false;
10121}
10122
10123bool Sema::tryCaptureVariable(VarDecl *Var, SourceLocation Loc,
10124 TryCaptureKind Kind, SourceLocation EllipsisLoc) {
10125 QualType CaptureType;
10126 QualType DeclRefType;
10127 return tryCaptureVariable(Var, Loc, Kind, EllipsisLoc,
10128 /*BuildAndDiagnose=*/true, CaptureType,
10129 DeclRefType);
10130}
10131
10132QualType Sema::getCapturedDeclRefType(VarDecl *Var, SourceLocation Loc) {
10133 QualType CaptureType;
10134 QualType DeclRefType;
10135
10136 // Determine whether we can capture this variable.
10137 if (tryCaptureVariable(Var, Loc, TryCapture_Implicit, SourceLocation(),
10138 /*BuildAndDiagnose=*/false, CaptureType, DeclRefType))
10139 return QualType();
10140
10141 return DeclRefType;
Eli Friedman9bb33f52012-02-03 02:04:35 +000010142}
10143
Eli Friedman3bda6b12012-02-02 23:15:15 +000010144static void MarkVarDeclODRUsed(Sema &SemaRef, VarDecl *Var,
10145 SourceLocation Loc) {
10146 // Keep track of used but undefined variables.
Eli Friedman130bbd02012-02-04 00:54:05 +000010147 // FIXME: We shouldn't suppress this warning for static data members.
Daniel Dunbar9d355812012-03-09 01:51:51 +000010148 if (Var->hasDefinition(SemaRef.Context) == VarDecl::DeclarationOnly &&
Eli Friedman130bbd02012-02-04 00:54:05 +000010149 Var->getLinkage() != ExternalLinkage &&
10150 !(Var->isStaticDataMember() && Var->hasInit())) {
Eli Friedman3bda6b12012-02-02 23:15:15 +000010151 SourceLocation &old = SemaRef.UndefinedInternals[Var->getCanonicalDecl()];
10152 if (old.isInvalid()) old = Loc;
10153 }
10154
Douglas Gregorfdf598e2012-02-18 09:37:24 +000010155 SemaRef.tryCaptureVariable(Var, Loc);
Eli Friedman9bb33f52012-02-03 02:04:35 +000010156
Eli Friedman3bda6b12012-02-02 23:15:15 +000010157 Var->setUsed(true);
10158}
10159
10160void Sema::UpdateMarkingForLValueToRValue(Expr *E) {
10161 // Per C++11 [basic.def.odr], a variable is odr-used "unless it is
10162 // an object that satisfies the requirements for appearing in a
10163 // constant expression (5.19) and the lvalue-to-rvalue conversion (4.1)
10164 // is immediately applied." This function handles the lvalue-to-rvalue
10165 // conversion part.
10166 MaybeODRUseExprs.erase(E->IgnoreParens());
10167}
10168
Eli Friedmanc6237c62012-02-29 03:16:56 +000010169ExprResult Sema::ActOnConstantExpression(ExprResult Res) {
10170 if (!Res.isUsable())
10171 return Res;
10172
10173 // If a constant-expression is a reference to a variable where we delay
10174 // deciding whether it is an odr-use, just assume we will apply the
10175 // lvalue-to-rvalue conversion. In the one case where this doesn't happen
10176 // (a non-type template argument), we have special handling anyway.
10177 UpdateMarkingForLValueToRValue(Res.get());
10178 return Res;
10179}
10180
Eli Friedman3bda6b12012-02-02 23:15:15 +000010181void Sema::CleanupVarDeclMarking() {
10182 for (llvm::SmallPtrSetIterator<Expr*> i = MaybeODRUseExprs.begin(),
10183 e = MaybeODRUseExprs.end();
10184 i != e; ++i) {
10185 VarDecl *Var;
10186 SourceLocation Loc;
10187 if (BlockDeclRefExpr *BDRE = dyn_cast<BlockDeclRefExpr>(*i)) {
10188 Var = BDRE->getDecl();
10189 Loc = BDRE->getLocation();
10190 } else if (DeclRefExpr *DRE = dyn_cast<DeclRefExpr>(*i)) {
10191 Var = cast<VarDecl>(DRE->getDecl());
10192 Loc = DRE->getLocation();
10193 } else if (MemberExpr *ME = dyn_cast<MemberExpr>(*i)) {
10194 Var = cast<VarDecl>(ME->getMemberDecl());
10195 Loc = ME->getMemberLoc();
10196 } else {
10197 llvm_unreachable("Unexpcted expression");
10198 }
10199
10200 MarkVarDeclODRUsed(*this, Var, Loc);
10201 }
10202
10203 MaybeODRUseExprs.clear();
10204}
10205
10206// Mark a VarDecl referenced, and perform the necessary handling to compute
10207// odr-uses.
10208static void DoMarkVarDeclReferenced(Sema &SemaRef, SourceLocation Loc,
10209 VarDecl *Var, Expr *E) {
Eli Friedmanfa0df832012-02-02 03:46:19 +000010210 Var->setReferenced();
10211
Eli Friedman3bda6b12012-02-02 23:15:15 +000010212 if (!IsPotentiallyEvaluatedContext(SemaRef))
Eli Friedmanfa0df832012-02-02 03:46:19 +000010213 return;
10214
10215 // Implicit instantiation of static data members of class templates.
Richard Smithd3cf2382012-02-15 02:42:50 +000010216 if (Var->isStaticDataMember() && Var->getInstantiatedFromStaticDataMember()) {
Eli Friedmanfa0df832012-02-02 03:46:19 +000010217 MemberSpecializationInfo *MSInfo = Var->getMemberSpecializationInfo();
10218 assert(MSInfo && "Missing member specialization information?");
Richard Smithd3cf2382012-02-15 02:42:50 +000010219 bool AlreadyInstantiated = !MSInfo->getPointOfInstantiation().isInvalid();
10220 if (MSInfo->getTemplateSpecializationKind() == TSK_ImplicitInstantiation &&
Daniel Dunbar9d355812012-03-09 01:51:51 +000010221 (!AlreadyInstantiated ||
10222 Var->isUsableInConstantExpressions(SemaRef.Context))) {
Richard Smithd3cf2382012-02-15 02:42:50 +000010223 if (!AlreadyInstantiated) {
10224 // This is a modification of an existing AST node. Notify listeners.
10225 if (ASTMutationListener *L = SemaRef.getASTMutationListener())
10226 L->StaticDataMemberInstantiated(Var);
10227 MSInfo->setPointOfInstantiation(Loc);
10228 }
10229 SourceLocation PointOfInstantiation = MSInfo->getPointOfInstantiation();
Daniel Dunbar9d355812012-03-09 01:51:51 +000010230 if (Var->isUsableInConstantExpressions(SemaRef.Context))
Eli Friedmanfa0df832012-02-02 03:46:19 +000010231 // Do not defer instantiations of variables which could be used in a
10232 // constant expression.
Richard Smithd3cf2382012-02-15 02:42:50 +000010233 SemaRef.InstantiateStaticDataMemberDefinition(PointOfInstantiation,Var);
Eli Friedmanfa0df832012-02-02 03:46:19 +000010234 else
Richard Smithd3cf2382012-02-15 02:42:50 +000010235 SemaRef.PendingInstantiations.push_back(
10236 std::make_pair(Var, PointOfInstantiation));
Eli Friedmanfa0df832012-02-02 03:46:19 +000010237 }
10238 }
10239
Eli Friedman3bda6b12012-02-02 23:15:15 +000010240 // Per C++11 [basic.def.odr], a variable is odr-used "unless it is
10241 // an object that satisfies the requirements for appearing in a
10242 // constant expression (5.19) and the lvalue-to-rvalue conversion (4.1)
10243 // is immediately applied." We check the first part here, and
10244 // Sema::UpdateMarkingForLValueToRValue deals with the second part.
10245 // Note that we use the C++11 definition everywhere because nothing in
Richard Smith35ecb362012-03-02 04:14:40 +000010246 // C++03 depends on whether we get the C++03 version correct. This does not
10247 // apply to references, since they are not objects.
Eli Friedman3bda6b12012-02-02 23:15:15 +000010248 const VarDecl *DefVD;
Richard Smith35ecb362012-03-02 04:14:40 +000010249 if (E && !isa<ParmVarDecl>(Var) && !Var->getType()->isReferenceType() &&
Daniel Dunbar9d355812012-03-09 01:51:51 +000010250 Var->isUsableInConstantExpressions(SemaRef.Context) &&
Eli Friedman3bda6b12012-02-02 23:15:15 +000010251 Var->getAnyInitializer(DefVD) && DefVD->checkInitIsICE())
10252 SemaRef.MaybeODRUseExprs.insert(E);
10253 else
10254 MarkVarDeclODRUsed(SemaRef, Var, Loc);
10255}
Eli Friedmanfa0df832012-02-02 03:46:19 +000010256
Eli Friedman3bda6b12012-02-02 23:15:15 +000010257/// \brief Mark a variable referenced, and check whether it is odr-used
10258/// (C++ [basic.def.odr]p2, C99 6.9p3). Note that this should not be
10259/// used directly for normal expressions referring to VarDecl.
10260void Sema::MarkVariableReferenced(SourceLocation Loc, VarDecl *Var) {
10261 DoMarkVarDeclReferenced(*this, Loc, Var, 0);
Eli Friedmanfa0df832012-02-02 03:46:19 +000010262}
10263
10264static void MarkExprReferenced(Sema &SemaRef, SourceLocation Loc,
10265 Decl *D, Expr *E) {
Eli Friedman3bda6b12012-02-02 23:15:15 +000010266 if (VarDecl *Var = dyn_cast<VarDecl>(D)) {
10267 DoMarkVarDeclReferenced(SemaRef, Loc, Var, E);
10268 return;
10269 }
10270
Eli Friedmanfa0df832012-02-02 03:46:19 +000010271 SemaRef.MarkAnyDeclReferenced(Loc, D);
Douglas Gregord3b672c2012-02-16 01:06:16 +000010272}
Eli Friedmanfa0df832012-02-02 03:46:19 +000010273
10274/// \brief Perform reference-marking and odr-use handling for a
10275/// BlockDeclRefExpr.
10276void Sema::MarkBlockDeclRefReferenced(BlockDeclRefExpr *E) {
10277 MarkExprReferenced(*this, E->getLocation(), E->getDecl(), E);
10278}
10279
10280/// \brief Perform reference-marking and odr-use handling for a DeclRefExpr.
10281void Sema::MarkDeclRefReferenced(DeclRefExpr *E) {
10282 MarkExprReferenced(*this, E->getLocation(), E->getDecl(), E);
10283}
10284
10285/// \brief Perform reference-marking and odr-use handling for a MemberExpr.
10286void Sema::MarkMemberReferenced(MemberExpr *E) {
10287 MarkExprReferenced(*this, E->getMemberLoc(), E->getMemberDecl(), E);
10288}
10289
Douglas Gregorf02455e2012-02-10 09:26:04 +000010290/// \brief Perform marking for a reference to an arbitrary declaration. It
Eli Friedmanfa0df832012-02-02 03:46:19 +000010291/// marks the declaration referenced, and performs odr-use checking for functions
10292/// and variables. This method should not be used when building an normal
10293/// expression which refers to a variable.
10294void Sema::MarkAnyDeclReferenced(SourceLocation Loc, Decl *D) {
10295 if (VarDecl *VD = dyn_cast<VarDecl>(D))
10296 MarkVariableReferenced(Loc, VD);
10297 else if (FunctionDecl *FD = dyn_cast<FunctionDecl>(D))
10298 MarkFunctionReferenced(Loc, FD);
10299 else
10300 D->setReferenced();
Douglas Gregorc9c02ed2009-06-19 23:52:42 +000010301}
Anders Carlsson7f84ed92009-10-09 23:51:55 +000010302
Douglas Gregor5597ab42010-05-07 23:12:07 +000010303namespace {
Chandler Carruthaf80f662010-06-09 08:17:30 +000010304 // Mark all of the declarations referenced
Douglas Gregor5597ab42010-05-07 23:12:07 +000010305 // FIXME: Not fully implemented yet! We need to have a better understanding
Chandler Carruthaf80f662010-06-09 08:17:30 +000010306 // of when we're entering
Douglas Gregor5597ab42010-05-07 23:12:07 +000010307 class MarkReferencedDecls : public RecursiveASTVisitor<MarkReferencedDecls> {
10308 Sema &S;
10309 SourceLocation Loc;
Chandler Carruthaf80f662010-06-09 08:17:30 +000010310
Douglas Gregor5597ab42010-05-07 23:12:07 +000010311 public:
10312 typedef RecursiveASTVisitor<MarkReferencedDecls> Inherited;
Chandler Carruthaf80f662010-06-09 08:17:30 +000010313
Douglas Gregor5597ab42010-05-07 23:12:07 +000010314 MarkReferencedDecls(Sema &S, SourceLocation Loc) : S(S), Loc(Loc) { }
Chandler Carruthaf80f662010-06-09 08:17:30 +000010315
10316 bool TraverseTemplateArgument(const TemplateArgument &Arg);
10317 bool TraverseRecordType(RecordType *T);
Douglas Gregor5597ab42010-05-07 23:12:07 +000010318 };
10319}
10320
Chandler Carruthaf80f662010-06-09 08:17:30 +000010321bool MarkReferencedDecls::TraverseTemplateArgument(
10322 const TemplateArgument &Arg) {
Douglas Gregor5597ab42010-05-07 23:12:07 +000010323 if (Arg.getKind() == TemplateArgument::Declaration) {
Eli Friedmanfa0df832012-02-02 03:46:19 +000010324 S.MarkAnyDeclReferenced(Loc, Arg.getAsDecl());
Douglas Gregor5597ab42010-05-07 23:12:07 +000010325 }
Chandler Carruthaf80f662010-06-09 08:17:30 +000010326
10327 return Inherited::TraverseTemplateArgument(Arg);
Douglas Gregor5597ab42010-05-07 23:12:07 +000010328}
10329
Chandler Carruthaf80f662010-06-09 08:17:30 +000010330bool MarkReferencedDecls::TraverseRecordType(RecordType *T) {
Douglas Gregor5597ab42010-05-07 23:12:07 +000010331 if (ClassTemplateSpecializationDecl *Spec
10332 = dyn_cast<ClassTemplateSpecializationDecl>(T->getDecl())) {
10333 const TemplateArgumentList &Args = Spec->getTemplateArgs();
Douglas Gregor1ccc8412010-11-07 23:05:16 +000010334 return TraverseTemplateArguments(Args.data(), Args.size());
Douglas Gregor5597ab42010-05-07 23:12:07 +000010335 }
10336
Chandler Carruthc65667c2010-06-10 10:31:57 +000010337 return true;
Douglas Gregor5597ab42010-05-07 23:12:07 +000010338}
10339
10340void Sema::MarkDeclarationsReferencedInType(SourceLocation Loc, QualType T) {
10341 MarkReferencedDecls Marker(*this, Loc);
Chandler Carruthaf80f662010-06-09 08:17:30 +000010342 Marker.TraverseType(Context.getCanonicalType(T));
Douglas Gregor5597ab42010-05-07 23:12:07 +000010343}
10344
Douglas Gregor8a01b2a2010-09-11 20:24:53 +000010345namespace {
10346 /// \brief Helper class that marks all of the declarations referenced by
10347 /// potentially-evaluated subexpressions as "referenced".
10348 class EvaluatedExprMarker : public EvaluatedExprVisitor<EvaluatedExprMarker> {
10349 Sema &S;
Douglas Gregor680e9e02012-02-21 19:11:17 +000010350 bool SkipLocalVariables;
Douglas Gregor8a01b2a2010-09-11 20:24:53 +000010351
10352 public:
10353 typedef EvaluatedExprVisitor<EvaluatedExprMarker> Inherited;
10354
Douglas Gregor680e9e02012-02-21 19:11:17 +000010355 EvaluatedExprMarker(Sema &S, bool SkipLocalVariables)
10356 : Inherited(S.Context), S(S), SkipLocalVariables(SkipLocalVariables) { }
Douglas Gregor8a01b2a2010-09-11 20:24:53 +000010357
10358 void VisitDeclRefExpr(DeclRefExpr *E) {
Douglas Gregor680e9e02012-02-21 19:11:17 +000010359 // If we were asked not to visit local variables, don't.
10360 if (SkipLocalVariables) {
10361 if (VarDecl *VD = dyn_cast<VarDecl>(E->getDecl()))
10362 if (VD->hasLocalStorage())
10363 return;
10364 }
10365
Eli Friedmanfa0df832012-02-02 03:46:19 +000010366 S.MarkDeclRefReferenced(E);
Douglas Gregor8a01b2a2010-09-11 20:24:53 +000010367 }
10368
10369 void VisitMemberExpr(MemberExpr *E) {
Eli Friedmanfa0df832012-02-02 03:46:19 +000010370 S.MarkMemberReferenced(E);
Douglas Gregor32b3de52010-09-11 23:32:50 +000010371 Inherited::VisitMemberExpr(E);
Douglas Gregor8a01b2a2010-09-11 20:24:53 +000010372 }
10373
John McCall28fc7092011-11-10 05:35:25 +000010374 void VisitCXXBindTemporaryExpr(CXXBindTemporaryExpr *E) {
Eli Friedmanfa0df832012-02-02 03:46:19 +000010375 S.MarkFunctionReferenced(E->getLocStart(),
John McCall28fc7092011-11-10 05:35:25 +000010376 const_cast<CXXDestructorDecl*>(E->getTemporary()->getDestructor()));
10377 Visit(E->getSubExpr());
10378 }
10379
Douglas Gregor8a01b2a2010-09-11 20:24:53 +000010380 void VisitCXXNewExpr(CXXNewExpr *E) {
Douglas Gregor8a01b2a2010-09-11 20:24:53 +000010381 if (E->getOperatorNew())
Eli Friedmanfa0df832012-02-02 03:46:19 +000010382 S.MarkFunctionReferenced(E->getLocStart(), E->getOperatorNew());
Douglas Gregor8a01b2a2010-09-11 20:24:53 +000010383 if (E->getOperatorDelete())
Eli Friedmanfa0df832012-02-02 03:46:19 +000010384 S.MarkFunctionReferenced(E->getLocStart(), E->getOperatorDelete());
Douglas Gregor32b3de52010-09-11 23:32:50 +000010385 Inherited::VisitCXXNewExpr(E);
Douglas Gregor8a01b2a2010-09-11 20:24:53 +000010386 }
Sebastian Redl6047f072012-02-16 12:22:20 +000010387
Douglas Gregor8a01b2a2010-09-11 20:24:53 +000010388 void VisitCXXDeleteExpr(CXXDeleteExpr *E) {
10389 if (E->getOperatorDelete())
Eli Friedmanfa0df832012-02-02 03:46:19 +000010390 S.MarkFunctionReferenced(E->getLocStart(), E->getOperatorDelete());
Douglas Gregor6ed2fee2010-09-14 22:55:20 +000010391 QualType Destroyed = S.Context.getBaseElementType(E->getDestroyedType());
10392 if (const RecordType *DestroyedRec = Destroyed->getAs<RecordType>()) {
10393 CXXRecordDecl *Record = cast<CXXRecordDecl>(DestroyedRec->getDecl());
Eli Friedmanfa0df832012-02-02 03:46:19 +000010394 S.MarkFunctionReferenced(E->getLocStart(),
Douglas Gregor6ed2fee2010-09-14 22:55:20 +000010395 S.LookupDestructor(Record));
10396 }
10397
Douglas Gregor32b3de52010-09-11 23:32:50 +000010398 Inherited::VisitCXXDeleteExpr(E);
Douglas Gregor8a01b2a2010-09-11 20:24:53 +000010399 }
10400
10401 void VisitCXXConstructExpr(CXXConstructExpr *E) {
Eli Friedmanfa0df832012-02-02 03:46:19 +000010402 S.MarkFunctionReferenced(E->getLocStart(), E->getConstructor());
Douglas Gregor32b3de52010-09-11 23:32:50 +000010403 Inherited::VisitCXXConstructExpr(E);
Douglas Gregor8a01b2a2010-09-11 20:24:53 +000010404 }
10405
10406 void VisitBlockDeclRefExpr(BlockDeclRefExpr *E) {
Douglas Gregor680e9e02012-02-21 19:11:17 +000010407 // If we were asked not to visit local variables, don't.
10408 if (SkipLocalVariables && E->getDecl()->hasLocalStorage())
10409 return;
10410
Eli Friedmanfa0df832012-02-02 03:46:19 +000010411 S.MarkBlockDeclRefReferenced(E);
Douglas Gregor8a01b2a2010-09-11 20:24:53 +000010412 }
Douglas Gregorf0873f42010-10-19 17:17:35 +000010413
10414 void VisitCXXDefaultArgExpr(CXXDefaultArgExpr *E) {
10415 Visit(E->getExpr());
10416 }
Eli Friedman3bda6b12012-02-02 23:15:15 +000010417
10418 void VisitImplicitCastExpr(ImplicitCastExpr *E) {
10419 Inherited::VisitImplicitCastExpr(E);
10420
10421 if (E->getCastKind() == CK_LValueToRValue)
10422 S.UpdateMarkingForLValueToRValue(E->getSubExpr());
10423 }
Douglas Gregor8a01b2a2010-09-11 20:24:53 +000010424 };
10425}
10426
10427/// \brief Mark any declarations that appear within this expression or any
10428/// potentially-evaluated subexpressions as "referenced".
Douglas Gregor680e9e02012-02-21 19:11:17 +000010429///
10430/// \param SkipLocalVariables If true, don't mark local variables as
10431/// 'referenced'.
10432void Sema::MarkDeclarationsReferencedInExpr(Expr *E,
10433 bool SkipLocalVariables) {
10434 EvaluatedExprMarker(*this, SkipLocalVariables).Visit(E);
Douglas Gregor8a01b2a2010-09-11 20:24:53 +000010435}
10436
Douglas Gregorda8cdbc2009-12-22 01:01:55 +000010437/// \brief Emit a diagnostic that describes an effect on the run-time behavior
10438/// of the program being compiled.
10439///
10440/// This routine emits the given diagnostic when the code currently being
Kovarththanan Rajaratnamba2c6522010-03-13 10:17:05 +000010441/// type-checked is "potentially evaluated", meaning that there is a
Douglas Gregorda8cdbc2009-12-22 01:01:55 +000010442/// possibility that the code will actually be executable. Code in sizeof()
10443/// expressions, code used only during overload resolution, etc., are not
10444/// potentially evaluated. This routine will suppress such diagnostics or,
10445/// in the absolutely nutty case of potentially potentially evaluated
Kovarththanan Rajaratnamba2c6522010-03-13 10:17:05 +000010446/// expressions (C++ typeid), queue the diagnostic to potentially emit it
Douglas Gregorda8cdbc2009-12-22 01:01:55 +000010447/// later.
Kovarththanan Rajaratnamba2c6522010-03-13 10:17:05 +000010448///
Douglas Gregorda8cdbc2009-12-22 01:01:55 +000010449/// This routine should be used for all diagnostics that describe the run-time
10450/// behavior of a program, such as passing a non-POD value through an ellipsis.
10451/// Failure to do so will likely result in spurious diagnostics or failures
10452/// during overload resolution or within sizeof/alignof/typeof/typeid.
Richard Trieuba63ce62011-09-09 01:45:06 +000010453bool Sema::DiagRuntimeBehavior(SourceLocation Loc, const Stmt *Statement,
Douglas Gregorda8cdbc2009-12-22 01:01:55 +000010454 const PartialDiagnostic &PD) {
John McCall31168b02011-06-15 23:02:42 +000010455 switch (ExprEvalContexts.back().Context) {
Douglas Gregorda8cdbc2009-12-22 01:01:55 +000010456 case Unevaluated:
10457 // The argument will never be evaluated, so don't complain.
10458 break;
Kovarththanan Rajaratnamba2c6522010-03-13 10:17:05 +000010459
Richard Smith764d2fe2011-12-20 02:08:33 +000010460 case ConstantEvaluated:
10461 // Relevant diagnostics should be produced by constant evaluation.
10462 break;
10463
Douglas Gregorda8cdbc2009-12-22 01:01:55 +000010464 case PotentiallyEvaluated:
Douglas Gregor8a01b2a2010-09-11 20:24:53 +000010465 case PotentiallyEvaluatedIfUsed:
Richard Trieuba63ce62011-09-09 01:45:06 +000010466 if (Statement && getCurFunctionOrMethodDecl()) {
Ted Kremenek3427fac2011-02-23 01:52:04 +000010467 FunctionScopes.back()->PossiblyUnreachableDiags.
Richard Trieuba63ce62011-09-09 01:45:06 +000010468 push_back(sema::PossiblyUnreachableDiag(PD, Loc, Statement));
Ted Kremenek3427fac2011-02-23 01:52:04 +000010469 }
10470 else
10471 Diag(Loc, PD);
10472
Douglas Gregorda8cdbc2009-12-22 01:01:55 +000010473 return true;
Douglas Gregorda8cdbc2009-12-22 01:01:55 +000010474 }
10475
10476 return false;
10477}
10478
Anders Carlsson7f84ed92009-10-09 23:51:55 +000010479bool Sema::CheckCallReturnType(QualType ReturnType, SourceLocation Loc,
10480 CallExpr *CE, FunctionDecl *FD) {
10481 if (ReturnType->isVoidType() || !ReturnType->isIncompleteType())
10482 return false;
10483
Richard Smithfd555f62012-02-22 02:04:18 +000010484 // If we're inside a decltype's expression, don't check for a valid return
10485 // type or construct temporaries until we know whether this is the last call.
10486 if (ExprEvalContexts.back().IsDecltype) {
10487 ExprEvalContexts.back().DelayedDecltypeCalls.push_back(CE);
10488 return false;
10489 }
10490
Anders Carlsson7f84ed92009-10-09 23:51:55 +000010491 PartialDiagnostic Note =
10492 FD ? PDiag(diag::note_function_with_incomplete_return_type_declared_here)
10493 << FD->getDeclName() : PDiag();
10494 SourceLocation NoteLoc = FD ? FD->getLocation() : SourceLocation();
Kovarththanan Rajaratnamba2c6522010-03-13 10:17:05 +000010495
Anders Carlsson7f84ed92009-10-09 23:51:55 +000010496 if (RequireCompleteType(Loc, ReturnType,
Kovarththanan Rajaratnamba2c6522010-03-13 10:17:05 +000010497 FD ?
Anders Carlsson7f84ed92009-10-09 23:51:55 +000010498 PDiag(diag::err_call_function_incomplete_return)
10499 << CE->getSourceRange() << FD->getDeclName() :
Kovarththanan Rajaratnamba2c6522010-03-13 10:17:05 +000010500 PDiag(diag::err_call_incomplete_return)
Anders Carlsson7f84ed92009-10-09 23:51:55 +000010501 << CE->getSourceRange(),
10502 std::make_pair(NoteLoc, Note)))
10503 return true;
10504
10505 return false;
10506}
10507
Douglas Gregor2d4f64f2011-01-19 16:50:08 +000010508// Diagnose the s/=/==/ and s/\|=/!=/ typos. Note that adding parentheses
John McCalld5707ab2009-10-12 21:59:07 +000010509// will prevent this condition from triggering, which is what we want.
10510void Sema::DiagnoseAssignmentAsCondition(Expr *E) {
10511 SourceLocation Loc;
10512
John McCall0506e4a2009-11-11 02:41:58 +000010513 unsigned diagnostic = diag::warn_condition_is_assignment;
Douglas Gregor2d4f64f2011-01-19 16:50:08 +000010514 bool IsOrAssign = false;
John McCall0506e4a2009-11-11 02:41:58 +000010515
Chandler Carruthf87d6c02011-08-16 22:30:10 +000010516 if (BinaryOperator *Op = dyn_cast<BinaryOperator>(E)) {
Douglas Gregor2d4f64f2011-01-19 16:50:08 +000010517 if (Op->getOpcode() != BO_Assign && Op->getOpcode() != BO_OrAssign)
John McCalld5707ab2009-10-12 21:59:07 +000010518 return;
10519
Douglas Gregor2d4f64f2011-01-19 16:50:08 +000010520 IsOrAssign = Op->getOpcode() == BO_OrAssign;
10521
John McCallb0e419e2009-11-12 00:06:05 +000010522 // Greylist some idioms by putting them into a warning subcategory.
10523 if (ObjCMessageExpr *ME
10524 = dyn_cast<ObjCMessageExpr>(Op->getRHS()->IgnoreParenCasts())) {
10525 Selector Sel = ME->getSelector();
10526
John McCallb0e419e2009-11-12 00:06:05 +000010527 // self = [<foo> init...]
Douglas Gregor486b74e2011-09-27 16:10:05 +000010528 if (isSelfExpr(Op->getLHS()) && Sel.getNameForSlot(0).startswith("init"))
John McCallb0e419e2009-11-12 00:06:05 +000010529 diagnostic = diag::warn_condition_is_idiomatic_assignment;
10530
10531 // <foo> = [<bar> nextObject]
Douglas Gregoraf2a6ae2011-02-18 22:29:55 +000010532 else if (Sel.isUnarySelector() && Sel.getNameForSlot(0) == "nextObject")
John McCallb0e419e2009-11-12 00:06:05 +000010533 diagnostic = diag::warn_condition_is_idiomatic_assignment;
10534 }
John McCall0506e4a2009-11-11 02:41:58 +000010535
John McCalld5707ab2009-10-12 21:59:07 +000010536 Loc = Op->getOperatorLoc();
Chandler Carruthf87d6c02011-08-16 22:30:10 +000010537 } else if (CXXOperatorCallExpr *Op = dyn_cast<CXXOperatorCallExpr>(E)) {
Douglas Gregor2d4f64f2011-01-19 16:50:08 +000010538 if (Op->getOperator() != OO_Equal && Op->getOperator() != OO_PipeEqual)
John McCalld5707ab2009-10-12 21:59:07 +000010539 return;
10540
Douglas Gregor2d4f64f2011-01-19 16:50:08 +000010541 IsOrAssign = Op->getOperator() == OO_PipeEqual;
John McCalld5707ab2009-10-12 21:59:07 +000010542 Loc = Op->getOperatorLoc();
10543 } else {
10544 // Not an assignment.
10545 return;
10546 }
10547
Douglas Gregor2bf2d3d2010-04-14 16:09:52 +000010548 Diag(Loc, diagnostic) << E->getSourceRange();
Douglas Gregor2d4f64f2011-01-19 16:50:08 +000010549
Argyrios Kyrtzidise1b97c42011-04-25 23:01:29 +000010550 SourceLocation Open = E->getSourceRange().getBegin();
10551 SourceLocation Close = PP.getLocForEndOfToken(E->getSourceRange().getEnd());
10552 Diag(Loc, diag::note_condition_assign_silence)
10553 << FixItHint::CreateInsertion(Open, "(")
10554 << FixItHint::CreateInsertion(Close, ")");
10555
Douglas Gregor2d4f64f2011-01-19 16:50:08 +000010556 if (IsOrAssign)
10557 Diag(Loc, diag::note_condition_or_assign_to_comparison)
10558 << FixItHint::CreateReplacement(Loc, "!=");
10559 else
10560 Diag(Loc, diag::note_condition_assign_to_comparison)
10561 << FixItHint::CreateReplacement(Loc, "==");
John McCalld5707ab2009-10-12 21:59:07 +000010562}
10563
Argyrios Kyrtzidis8b6ec682011-02-01 18:24:22 +000010564/// \brief Redundant parentheses over an equality comparison can indicate
10565/// that the user intended an assignment used as condition.
Richard Trieuba63ce62011-09-09 01:45:06 +000010566void Sema::DiagnoseEqualityWithExtraParens(ParenExpr *ParenE) {
Argyrios Kyrtzidisf4f82782011-02-01 22:23:56 +000010567 // Don't warn if the parens came from a macro.
Richard Trieuba63ce62011-09-09 01:45:06 +000010568 SourceLocation parenLoc = ParenE->getLocStart();
Argyrios Kyrtzidisf4f82782011-02-01 22:23:56 +000010569 if (parenLoc.isInvalid() || parenLoc.isMacroID())
10570 return;
Argyrios Kyrtzidisba699d62011-03-28 23:52:04 +000010571 // Don't warn for dependent expressions.
Richard Trieuba63ce62011-09-09 01:45:06 +000010572 if (ParenE->isTypeDependent())
Argyrios Kyrtzidisba699d62011-03-28 23:52:04 +000010573 return;
Argyrios Kyrtzidisf4f82782011-02-01 22:23:56 +000010574
Richard Trieuba63ce62011-09-09 01:45:06 +000010575 Expr *E = ParenE->IgnoreParens();
Argyrios Kyrtzidis8b6ec682011-02-01 18:24:22 +000010576
10577 if (BinaryOperator *opE = dyn_cast<BinaryOperator>(E))
Argyrios Kyrtzidis582dd682011-02-01 19:32:59 +000010578 if (opE->getOpcode() == BO_EQ &&
10579 opE->getLHS()->IgnoreParenImpCasts()->isModifiableLvalue(Context)
10580 == Expr::MLV_Valid) {
Argyrios Kyrtzidis8b6ec682011-02-01 18:24:22 +000010581 SourceLocation Loc = opE->getOperatorLoc();
Ted Kremenekc358d9f2011-02-01 22:36:09 +000010582
Ted Kremenekae022092011-02-02 02:20:30 +000010583 Diag(Loc, diag::warn_equality_with_extra_parens) << E->getSourceRange();
Ted Kremenekae022092011-02-02 02:20:30 +000010584 Diag(Loc, diag::note_equality_comparison_silence)
Richard Trieuba63ce62011-09-09 01:45:06 +000010585 << FixItHint::CreateRemoval(ParenE->getSourceRange().getBegin())
10586 << FixItHint::CreateRemoval(ParenE->getSourceRange().getEnd());
Argyrios Kyrtzidise1b97c42011-04-25 23:01:29 +000010587 Diag(Loc, diag::note_equality_comparison_to_assign)
10588 << FixItHint::CreateReplacement(Loc, "=");
Argyrios Kyrtzidis8b6ec682011-02-01 18:24:22 +000010589 }
10590}
10591
John Wiegley01296292011-04-08 18:41:53 +000010592ExprResult Sema::CheckBooleanCondition(Expr *E, SourceLocation Loc) {
John McCalld5707ab2009-10-12 21:59:07 +000010593 DiagnoseAssignmentAsCondition(E);
Argyrios Kyrtzidis8b6ec682011-02-01 18:24:22 +000010594 if (ParenExpr *parenE = dyn_cast<ParenExpr>(E))
10595 DiagnoseEqualityWithExtraParens(parenE);
John McCalld5707ab2009-10-12 21:59:07 +000010596
John McCall0009fcc2011-04-26 20:42:42 +000010597 ExprResult result = CheckPlaceholderExpr(E);
10598 if (result.isInvalid()) return ExprError();
10599 E = result.take();
Argyrios Kyrtzidisca766292010-11-01 18:49:26 +000010600
John McCall0009fcc2011-04-26 20:42:42 +000010601 if (!E->isTypeDependent()) {
John McCall34376a62010-12-04 03:47:34 +000010602 if (getLangOptions().CPlusPlus)
10603 return CheckCXXBooleanCondition(E); // C++ 6.4p4
10604
John Wiegley01296292011-04-08 18:41:53 +000010605 ExprResult ERes = DefaultFunctionArrayLvalueConversion(E);
10606 if (ERes.isInvalid())
10607 return ExprError();
10608 E = ERes.take();
John McCall29cb2fd2010-12-04 06:09:13 +000010609
10610 QualType T = E->getType();
John Wiegley01296292011-04-08 18:41:53 +000010611 if (!T->isScalarType()) { // C99 6.8.4.1p1
10612 Diag(Loc, diag::err_typecheck_statement_requires_scalar)
10613 << T << E->getSourceRange();
10614 return ExprError();
10615 }
John McCalld5707ab2009-10-12 21:59:07 +000010616 }
10617
John Wiegley01296292011-04-08 18:41:53 +000010618 return Owned(E);
John McCalld5707ab2009-10-12 21:59:07 +000010619}
Douglas Gregore60e41a2010-05-06 17:25:47 +000010620
John McCalldadc5752010-08-24 06:29:42 +000010621ExprResult Sema::ActOnBooleanCondition(Scope *S, SourceLocation Loc,
Richard Trieuba63ce62011-09-09 01:45:06 +000010622 Expr *SubExpr) {
10623 if (!SubExpr)
Douglas Gregore60e41a2010-05-06 17:25:47 +000010624 return ExprError();
John Wiegley01296292011-04-08 18:41:53 +000010625
Richard Trieuba63ce62011-09-09 01:45:06 +000010626 return CheckBooleanCondition(SubExpr, Loc);
Douglas Gregore60e41a2010-05-06 17:25:47 +000010627}
John McCall36e7fe32010-10-12 00:20:44 +000010628
John McCall31996342011-04-07 08:22:57 +000010629namespace {
John McCall2979fe02011-04-12 00:42:48 +000010630 /// A visitor for rebuilding a call to an __unknown_any expression
10631 /// to have an appropriate type.
10632 struct RebuildUnknownAnyFunction
10633 : StmtVisitor<RebuildUnknownAnyFunction, ExprResult> {
10634
10635 Sema &S;
10636
10637 RebuildUnknownAnyFunction(Sema &S) : S(S) {}
10638
10639 ExprResult VisitStmt(Stmt *S) {
10640 llvm_unreachable("unexpected statement!");
John McCall2979fe02011-04-12 00:42:48 +000010641 }
10642
Richard Trieu10162ab2011-09-09 03:59:41 +000010643 ExprResult VisitExpr(Expr *E) {
10644 S.Diag(E->getExprLoc(), diag::err_unsupported_unknown_any_call)
10645 << E->getSourceRange();
John McCall2979fe02011-04-12 00:42:48 +000010646 return ExprError();
10647 }
10648
10649 /// Rebuild an expression which simply semantically wraps another
10650 /// expression which it shares the type and value kind of.
Richard Trieu10162ab2011-09-09 03:59:41 +000010651 template <class T> ExprResult rebuildSugarExpr(T *E) {
10652 ExprResult SubResult = Visit(E->getSubExpr());
10653 if (SubResult.isInvalid()) return ExprError();
John McCall2979fe02011-04-12 00:42:48 +000010654
Richard Trieu10162ab2011-09-09 03:59:41 +000010655 Expr *SubExpr = SubResult.take();
10656 E->setSubExpr(SubExpr);
10657 E->setType(SubExpr->getType());
10658 E->setValueKind(SubExpr->getValueKind());
10659 assert(E->getObjectKind() == OK_Ordinary);
10660 return E;
John McCall2979fe02011-04-12 00:42:48 +000010661 }
10662
Richard Trieu10162ab2011-09-09 03:59:41 +000010663 ExprResult VisitParenExpr(ParenExpr *E) {
10664 return rebuildSugarExpr(E);
John McCall2979fe02011-04-12 00:42:48 +000010665 }
10666
Richard Trieu10162ab2011-09-09 03:59:41 +000010667 ExprResult VisitUnaryExtension(UnaryOperator *E) {
10668 return rebuildSugarExpr(E);
John McCall2979fe02011-04-12 00:42:48 +000010669 }
10670
Richard Trieu10162ab2011-09-09 03:59:41 +000010671 ExprResult VisitUnaryAddrOf(UnaryOperator *E) {
10672 ExprResult SubResult = Visit(E->getSubExpr());
10673 if (SubResult.isInvalid()) return ExprError();
John McCall2979fe02011-04-12 00:42:48 +000010674
Richard Trieu10162ab2011-09-09 03:59:41 +000010675 Expr *SubExpr = SubResult.take();
10676 E->setSubExpr(SubExpr);
10677 E->setType(S.Context.getPointerType(SubExpr->getType()));
10678 assert(E->getValueKind() == VK_RValue);
10679 assert(E->getObjectKind() == OK_Ordinary);
10680 return E;
John McCall2979fe02011-04-12 00:42:48 +000010681 }
10682
Richard Trieu10162ab2011-09-09 03:59:41 +000010683 ExprResult resolveDecl(Expr *E, ValueDecl *VD) {
10684 if (!isa<FunctionDecl>(VD)) return VisitExpr(E);
John McCall2979fe02011-04-12 00:42:48 +000010685
Richard Trieu10162ab2011-09-09 03:59:41 +000010686 E->setType(VD->getType());
John McCall2979fe02011-04-12 00:42:48 +000010687
Richard Trieu10162ab2011-09-09 03:59:41 +000010688 assert(E->getValueKind() == VK_RValue);
John McCall2979fe02011-04-12 00:42:48 +000010689 if (S.getLangOptions().CPlusPlus &&
Richard Trieu10162ab2011-09-09 03:59:41 +000010690 !(isa<CXXMethodDecl>(VD) &&
10691 cast<CXXMethodDecl>(VD)->isInstance()))
10692 E->setValueKind(VK_LValue);
John McCall2979fe02011-04-12 00:42:48 +000010693
Richard Trieu10162ab2011-09-09 03:59:41 +000010694 return E;
John McCall2979fe02011-04-12 00:42:48 +000010695 }
10696
Richard Trieu10162ab2011-09-09 03:59:41 +000010697 ExprResult VisitMemberExpr(MemberExpr *E) {
10698 return resolveDecl(E, E->getMemberDecl());
John McCall2979fe02011-04-12 00:42:48 +000010699 }
10700
Richard Trieu10162ab2011-09-09 03:59:41 +000010701 ExprResult VisitDeclRefExpr(DeclRefExpr *E) {
10702 return resolveDecl(E, E->getDecl());
John McCall2979fe02011-04-12 00:42:48 +000010703 }
10704 };
10705}
10706
10707/// Given a function expression of unknown-any type, try to rebuild it
10708/// to have a function type.
Richard Trieu10162ab2011-09-09 03:59:41 +000010709static ExprResult rebuildUnknownAnyFunction(Sema &S, Expr *FunctionExpr) {
10710 ExprResult Result = RebuildUnknownAnyFunction(S).Visit(FunctionExpr);
10711 if (Result.isInvalid()) return ExprError();
10712 return S.DefaultFunctionArrayConversion(Result.take());
John McCall2979fe02011-04-12 00:42:48 +000010713}
10714
10715namespace {
John McCall2d2e8702011-04-11 07:02:50 +000010716 /// A visitor for rebuilding an expression of type __unknown_anytype
10717 /// into one which resolves the type directly on the referring
10718 /// expression. Strict preservation of the original source
10719 /// structure is not a goal.
John McCall31996342011-04-07 08:22:57 +000010720 struct RebuildUnknownAnyExpr
John McCall39439732011-04-09 22:50:59 +000010721 : StmtVisitor<RebuildUnknownAnyExpr, ExprResult> {
John McCall31996342011-04-07 08:22:57 +000010722
10723 Sema &S;
10724
10725 /// The current destination type.
10726 QualType DestType;
10727
Richard Trieu10162ab2011-09-09 03:59:41 +000010728 RebuildUnknownAnyExpr(Sema &S, QualType CastType)
10729 : S(S), DestType(CastType) {}
John McCall31996342011-04-07 08:22:57 +000010730
John McCall39439732011-04-09 22:50:59 +000010731 ExprResult VisitStmt(Stmt *S) {
John McCall2d2e8702011-04-11 07:02:50 +000010732 llvm_unreachable("unexpected statement!");
John McCall31996342011-04-07 08:22:57 +000010733 }
10734
Richard Trieu10162ab2011-09-09 03:59:41 +000010735 ExprResult VisitExpr(Expr *E) {
10736 S.Diag(E->getExprLoc(), diag::err_unsupported_unknown_any_expr)
10737 << E->getSourceRange();
John McCall2d2e8702011-04-11 07:02:50 +000010738 return ExprError();
John McCall31996342011-04-07 08:22:57 +000010739 }
10740
Richard Trieu10162ab2011-09-09 03:59:41 +000010741 ExprResult VisitCallExpr(CallExpr *E);
10742 ExprResult VisitObjCMessageExpr(ObjCMessageExpr *E);
John McCall2d2e8702011-04-11 07:02:50 +000010743
John McCall39439732011-04-09 22:50:59 +000010744 /// Rebuild an expression which simply semantically wraps another
10745 /// expression which it shares the type and value kind of.
Richard Trieu10162ab2011-09-09 03:59:41 +000010746 template <class T> ExprResult rebuildSugarExpr(T *E) {
10747 ExprResult SubResult = Visit(E->getSubExpr());
10748 if (SubResult.isInvalid()) return ExprError();
10749 Expr *SubExpr = SubResult.take();
10750 E->setSubExpr(SubExpr);
10751 E->setType(SubExpr->getType());
10752 E->setValueKind(SubExpr->getValueKind());
10753 assert(E->getObjectKind() == OK_Ordinary);
10754 return E;
John McCall39439732011-04-09 22:50:59 +000010755 }
John McCall31996342011-04-07 08:22:57 +000010756
Richard Trieu10162ab2011-09-09 03:59:41 +000010757 ExprResult VisitParenExpr(ParenExpr *E) {
10758 return rebuildSugarExpr(E);
John McCall39439732011-04-09 22:50:59 +000010759 }
10760
Richard Trieu10162ab2011-09-09 03:59:41 +000010761 ExprResult VisitUnaryExtension(UnaryOperator *E) {
10762 return rebuildSugarExpr(E);
John McCall39439732011-04-09 22:50:59 +000010763 }
10764
Richard Trieu10162ab2011-09-09 03:59:41 +000010765 ExprResult VisitUnaryAddrOf(UnaryOperator *E) {
10766 const PointerType *Ptr = DestType->getAs<PointerType>();
10767 if (!Ptr) {
10768 S.Diag(E->getOperatorLoc(), diag::err_unknown_any_addrof)
10769 << E->getSourceRange();
John McCall2979fe02011-04-12 00:42:48 +000010770 return ExprError();
10771 }
Richard Trieu10162ab2011-09-09 03:59:41 +000010772 assert(E->getValueKind() == VK_RValue);
10773 assert(E->getObjectKind() == OK_Ordinary);
10774 E->setType(DestType);
John McCall2979fe02011-04-12 00:42:48 +000010775
10776 // Build the sub-expression as if it were an object of the pointee type.
Richard Trieu10162ab2011-09-09 03:59:41 +000010777 DestType = Ptr->getPointeeType();
10778 ExprResult SubResult = Visit(E->getSubExpr());
10779 if (SubResult.isInvalid()) return ExprError();
10780 E->setSubExpr(SubResult.take());
10781 return E;
John McCall2979fe02011-04-12 00:42:48 +000010782 }
10783
Richard Trieu10162ab2011-09-09 03:59:41 +000010784 ExprResult VisitImplicitCastExpr(ImplicitCastExpr *E);
John McCall39439732011-04-09 22:50:59 +000010785
Richard Trieu10162ab2011-09-09 03:59:41 +000010786 ExprResult resolveDecl(Expr *E, ValueDecl *VD);
John McCall39439732011-04-09 22:50:59 +000010787
Richard Trieu10162ab2011-09-09 03:59:41 +000010788 ExprResult VisitMemberExpr(MemberExpr *E) {
10789 return resolveDecl(E, E->getMemberDecl());
John McCall2979fe02011-04-12 00:42:48 +000010790 }
John McCall39439732011-04-09 22:50:59 +000010791
Richard Trieu10162ab2011-09-09 03:59:41 +000010792 ExprResult VisitDeclRefExpr(DeclRefExpr *E) {
10793 return resolveDecl(E, E->getDecl());
John McCall31996342011-04-07 08:22:57 +000010794 }
10795 };
10796}
10797
John McCall2d2e8702011-04-11 07:02:50 +000010798/// Rebuilds a call expression which yielded __unknown_anytype.
Richard Trieu10162ab2011-09-09 03:59:41 +000010799ExprResult RebuildUnknownAnyExpr::VisitCallExpr(CallExpr *E) {
10800 Expr *CalleeExpr = E->getCallee();
John McCall2d2e8702011-04-11 07:02:50 +000010801
10802 enum FnKind {
John McCall4adb38c2011-04-27 00:36:17 +000010803 FK_MemberFunction,
John McCall2d2e8702011-04-11 07:02:50 +000010804 FK_FunctionPointer,
10805 FK_BlockPointer
10806 };
10807
Richard Trieu10162ab2011-09-09 03:59:41 +000010808 FnKind Kind;
10809 QualType CalleeType = CalleeExpr->getType();
10810 if (CalleeType == S.Context.BoundMemberTy) {
10811 assert(isa<CXXMemberCallExpr>(E) || isa<CXXOperatorCallExpr>(E));
10812 Kind = FK_MemberFunction;
10813 CalleeType = Expr::findBoundMemberType(CalleeExpr);
10814 } else if (const PointerType *Ptr = CalleeType->getAs<PointerType>()) {
10815 CalleeType = Ptr->getPointeeType();
10816 Kind = FK_FunctionPointer;
John McCall2d2e8702011-04-11 07:02:50 +000010817 } else {
Richard Trieu10162ab2011-09-09 03:59:41 +000010818 CalleeType = CalleeType->castAs<BlockPointerType>()->getPointeeType();
10819 Kind = FK_BlockPointer;
John McCall2d2e8702011-04-11 07:02:50 +000010820 }
Richard Trieu10162ab2011-09-09 03:59:41 +000010821 const FunctionType *FnType = CalleeType->castAs<FunctionType>();
John McCall2d2e8702011-04-11 07:02:50 +000010822
10823 // Verify that this is a legal result type of a function.
10824 if (DestType->isArrayType() || DestType->isFunctionType()) {
10825 unsigned diagID = diag::err_func_returning_array_function;
Richard Trieu10162ab2011-09-09 03:59:41 +000010826 if (Kind == FK_BlockPointer)
John McCall2d2e8702011-04-11 07:02:50 +000010827 diagID = diag::err_block_returning_array_function;
10828
Richard Trieu10162ab2011-09-09 03:59:41 +000010829 S.Diag(E->getExprLoc(), diagID)
John McCall2d2e8702011-04-11 07:02:50 +000010830 << DestType->isFunctionType() << DestType;
10831 return ExprError();
10832 }
10833
10834 // Otherwise, go ahead and set DestType as the call's result.
Richard Trieu10162ab2011-09-09 03:59:41 +000010835 E->setType(DestType.getNonLValueExprType(S.Context));
10836 E->setValueKind(Expr::getValueKindForType(DestType));
10837 assert(E->getObjectKind() == OK_Ordinary);
John McCall2d2e8702011-04-11 07:02:50 +000010838
10839 // Rebuild the function type, replacing the result type with DestType.
Richard Trieu10162ab2011-09-09 03:59:41 +000010840 if (const FunctionProtoType *Proto = dyn_cast<FunctionProtoType>(FnType))
John McCall2d2e8702011-04-11 07:02:50 +000010841 DestType = S.Context.getFunctionType(DestType,
Richard Trieu10162ab2011-09-09 03:59:41 +000010842 Proto->arg_type_begin(),
10843 Proto->getNumArgs(),
10844 Proto->getExtProtoInfo());
John McCall2d2e8702011-04-11 07:02:50 +000010845 else
10846 DestType = S.Context.getFunctionNoProtoType(DestType,
Richard Trieu10162ab2011-09-09 03:59:41 +000010847 FnType->getExtInfo());
John McCall2d2e8702011-04-11 07:02:50 +000010848
10849 // Rebuild the appropriate pointer-to-function type.
Richard Trieu10162ab2011-09-09 03:59:41 +000010850 switch (Kind) {
John McCall4adb38c2011-04-27 00:36:17 +000010851 case FK_MemberFunction:
John McCall2d2e8702011-04-11 07:02:50 +000010852 // Nothing to do.
10853 break;
10854
10855 case FK_FunctionPointer:
10856 DestType = S.Context.getPointerType(DestType);
10857 break;
10858
10859 case FK_BlockPointer:
10860 DestType = S.Context.getBlockPointerType(DestType);
10861 break;
10862 }
10863
10864 // Finally, we can recurse.
Richard Trieu10162ab2011-09-09 03:59:41 +000010865 ExprResult CalleeResult = Visit(CalleeExpr);
10866 if (!CalleeResult.isUsable()) return ExprError();
10867 E->setCallee(CalleeResult.take());
John McCall2d2e8702011-04-11 07:02:50 +000010868
10869 // Bind a temporary if necessary.
Richard Trieu10162ab2011-09-09 03:59:41 +000010870 return S.MaybeBindToTemporary(E);
John McCall2d2e8702011-04-11 07:02:50 +000010871}
10872
Richard Trieu10162ab2011-09-09 03:59:41 +000010873ExprResult RebuildUnknownAnyExpr::VisitObjCMessageExpr(ObjCMessageExpr *E) {
John McCall2979fe02011-04-12 00:42:48 +000010874 // Verify that this is a legal result type of a call.
10875 if (DestType->isArrayType() || DestType->isFunctionType()) {
Richard Trieu10162ab2011-09-09 03:59:41 +000010876 S.Diag(E->getExprLoc(), diag::err_func_returning_array_function)
John McCall2979fe02011-04-12 00:42:48 +000010877 << DestType->isFunctionType() << DestType;
10878 return ExprError();
John McCall2d2e8702011-04-11 07:02:50 +000010879 }
10880
John McCall3f4138c2011-07-13 17:56:40 +000010881 // Rewrite the method result type if available.
Richard Trieu10162ab2011-09-09 03:59:41 +000010882 if (ObjCMethodDecl *Method = E->getMethodDecl()) {
10883 assert(Method->getResultType() == S.Context.UnknownAnyTy);
10884 Method->setResultType(DestType);
John McCall3f4138c2011-07-13 17:56:40 +000010885 }
John McCall2979fe02011-04-12 00:42:48 +000010886
John McCall2d2e8702011-04-11 07:02:50 +000010887 // Change the type of the message.
Richard Trieu10162ab2011-09-09 03:59:41 +000010888 E->setType(DestType.getNonReferenceType());
10889 E->setValueKind(Expr::getValueKindForType(DestType));
John McCall2d2e8702011-04-11 07:02:50 +000010890
Richard Trieu10162ab2011-09-09 03:59:41 +000010891 return S.MaybeBindToTemporary(E);
John McCall2d2e8702011-04-11 07:02:50 +000010892}
10893
Richard Trieu10162ab2011-09-09 03:59:41 +000010894ExprResult RebuildUnknownAnyExpr::VisitImplicitCastExpr(ImplicitCastExpr *E) {
John McCall2979fe02011-04-12 00:42:48 +000010895 // The only case we should ever see here is a function-to-pointer decay.
Sean Callanan2db103c2012-03-06 23:12:57 +000010896 if (E->getCastKind() == CK_FunctionToPointerDecay) {
Sean Callanan12495112012-03-06 21:34:12 +000010897 assert(E->getValueKind() == VK_RValue);
10898 assert(E->getObjectKind() == OK_Ordinary);
10899
10900 E->setType(DestType);
10901
10902 // Rebuild the sub-expression as the pointee (function) type.
10903 DestType = DestType->castAs<PointerType>()->getPointeeType();
10904
10905 ExprResult Result = Visit(E->getSubExpr());
10906 if (!Result.isUsable()) return ExprError();
10907
10908 E->setSubExpr(Result.take());
10909 return S.Owned(E);
Sean Callanan2db103c2012-03-06 23:12:57 +000010910 } else if (E->getCastKind() == CK_LValueToRValue) {
Sean Callanan12495112012-03-06 21:34:12 +000010911 assert(E->getValueKind() == VK_RValue);
10912 assert(E->getObjectKind() == OK_Ordinary);
John McCall2d2e8702011-04-11 07:02:50 +000010913
Sean Callanan12495112012-03-06 21:34:12 +000010914 assert(isa<BlockPointerType>(E->getType()));
John McCall2979fe02011-04-12 00:42:48 +000010915
Sean Callanan12495112012-03-06 21:34:12 +000010916 E->setType(DestType);
John McCall2d2e8702011-04-11 07:02:50 +000010917
Sean Callanan12495112012-03-06 21:34:12 +000010918 // The sub-expression has to be a lvalue reference, so rebuild it as such.
10919 DestType = S.Context.getLValueReferenceType(DestType);
John McCall2d2e8702011-04-11 07:02:50 +000010920
Sean Callanan12495112012-03-06 21:34:12 +000010921 ExprResult Result = Visit(E->getSubExpr());
10922 if (!Result.isUsable()) return ExprError();
10923
10924 E->setSubExpr(Result.take());
10925 return S.Owned(E);
Sean Callanan2db103c2012-03-06 23:12:57 +000010926 } else {
Sean Callanan12495112012-03-06 21:34:12 +000010927 llvm_unreachable("Unhandled cast type!");
10928 }
John McCall2d2e8702011-04-11 07:02:50 +000010929}
10930
Richard Trieu10162ab2011-09-09 03:59:41 +000010931ExprResult RebuildUnknownAnyExpr::resolveDecl(Expr *E, ValueDecl *VD) {
10932 ExprValueKind ValueKind = VK_LValue;
10933 QualType Type = DestType;
John McCall2d2e8702011-04-11 07:02:50 +000010934
10935 // We know how to make this work for certain kinds of decls:
10936
10937 // - functions
Richard Trieu10162ab2011-09-09 03:59:41 +000010938 if (FunctionDecl *FD = dyn_cast<FunctionDecl>(VD)) {
10939 if (const PointerType *Ptr = Type->getAs<PointerType>()) {
10940 DestType = Ptr->getPointeeType();
10941 ExprResult Result = resolveDecl(E, VD);
10942 if (Result.isInvalid()) return ExprError();
10943 return S.ImpCastExprToType(Result.take(), Type,
John McCall9a877fe2011-08-10 04:12:23 +000010944 CK_FunctionToPointerDecay, VK_RValue);
10945 }
10946
Richard Trieu10162ab2011-09-09 03:59:41 +000010947 if (!Type->isFunctionType()) {
10948 S.Diag(E->getExprLoc(), diag::err_unknown_any_function)
10949 << VD << E->getSourceRange();
John McCall9a877fe2011-08-10 04:12:23 +000010950 return ExprError();
10951 }
John McCall2d2e8702011-04-11 07:02:50 +000010952
Richard Trieu10162ab2011-09-09 03:59:41 +000010953 if (CXXMethodDecl *MD = dyn_cast<CXXMethodDecl>(FD))
10954 if (MD->isInstance()) {
10955 ValueKind = VK_RValue;
10956 Type = S.Context.BoundMemberTy;
John McCall4adb38c2011-04-27 00:36:17 +000010957 }
10958
John McCall2d2e8702011-04-11 07:02:50 +000010959 // Function references aren't l-values in C.
10960 if (!S.getLangOptions().CPlusPlus)
Richard Trieu10162ab2011-09-09 03:59:41 +000010961 ValueKind = VK_RValue;
John McCall2d2e8702011-04-11 07:02:50 +000010962
10963 // - variables
Richard Trieu10162ab2011-09-09 03:59:41 +000010964 } else if (isa<VarDecl>(VD)) {
10965 if (const ReferenceType *RefTy = Type->getAs<ReferenceType>()) {
10966 Type = RefTy->getPointeeType();
10967 } else if (Type->isFunctionType()) {
10968 S.Diag(E->getExprLoc(), diag::err_unknown_any_var_function_type)
10969 << VD << E->getSourceRange();
John McCall2979fe02011-04-12 00:42:48 +000010970 return ExprError();
John McCall2d2e8702011-04-11 07:02:50 +000010971 }
10972
10973 // - nothing else
10974 } else {
Richard Trieu10162ab2011-09-09 03:59:41 +000010975 S.Diag(E->getExprLoc(), diag::err_unsupported_unknown_any_decl)
10976 << VD << E->getSourceRange();
John McCall2d2e8702011-04-11 07:02:50 +000010977 return ExprError();
10978 }
10979
Richard Trieu10162ab2011-09-09 03:59:41 +000010980 VD->setType(DestType);
10981 E->setType(Type);
10982 E->setValueKind(ValueKind);
10983 return S.Owned(E);
John McCall2d2e8702011-04-11 07:02:50 +000010984}
10985
John McCall31996342011-04-07 08:22:57 +000010986/// Check a cast of an unknown-any type. We intentionally only
10987/// trigger this for C-style casts.
Richard Trieuba63ce62011-09-09 01:45:06 +000010988ExprResult Sema::checkUnknownAnyCast(SourceRange TypeRange, QualType CastType,
10989 Expr *CastExpr, CastKind &CastKind,
10990 ExprValueKind &VK, CXXCastPath &Path) {
John McCall31996342011-04-07 08:22:57 +000010991 // Rewrite the casted expression from scratch.
Richard Trieuba63ce62011-09-09 01:45:06 +000010992 ExprResult result = RebuildUnknownAnyExpr(*this, CastType).Visit(CastExpr);
John McCall39439732011-04-09 22:50:59 +000010993 if (!result.isUsable()) return ExprError();
John McCall31996342011-04-07 08:22:57 +000010994
Richard Trieuba63ce62011-09-09 01:45:06 +000010995 CastExpr = result.take();
10996 VK = CastExpr->getValueKind();
10997 CastKind = CK_NoOp;
John McCall39439732011-04-09 22:50:59 +000010998
Richard Trieuba63ce62011-09-09 01:45:06 +000010999 return CastExpr;
John McCall31996342011-04-07 08:22:57 +000011000}
11001
Douglas Gregord8fb1e32011-12-01 01:37:36 +000011002ExprResult Sema::forceUnknownAnyToType(Expr *E, QualType ToType) {
11003 return RebuildUnknownAnyExpr(*this, ToType).Visit(E);
11004}
11005
Richard Trieuba63ce62011-09-09 01:45:06 +000011006static ExprResult diagnoseUnknownAnyExpr(Sema &S, Expr *E) {
11007 Expr *orig = E;
John McCall2d2e8702011-04-11 07:02:50 +000011008 unsigned diagID = diag::err_uncasted_use_of_unknown_any;
John McCall31996342011-04-07 08:22:57 +000011009 while (true) {
Richard Trieuba63ce62011-09-09 01:45:06 +000011010 E = E->IgnoreParenImpCasts();
11011 if (CallExpr *call = dyn_cast<CallExpr>(E)) {
11012 E = call->getCallee();
John McCall2d2e8702011-04-11 07:02:50 +000011013 diagID = diag::err_uncasted_call_of_unknown_any;
11014 } else {
John McCall31996342011-04-07 08:22:57 +000011015 break;
John McCall2d2e8702011-04-11 07:02:50 +000011016 }
John McCall31996342011-04-07 08:22:57 +000011017 }
11018
John McCall2d2e8702011-04-11 07:02:50 +000011019 SourceLocation loc;
11020 NamedDecl *d;
Richard Trieuba63ce62011-09-09 01:45:06 +000011021 if (DeclRefExpr *ref = dyn_cast<DeclRefExpr>(E)) {
John McCall2d2e8702011-04-11 07:02:50 +000011022 loc = ref->getLocation();
11023 d = ref->getDecl();
Richard Trieuba63ce62011-09-09 01:45:06 +000011024 } else if (MemberExpr *mem = dyn_cast<MemberExpr>(E)) {
John McCall2d2e8702011-04-11 07:02:50 +000011025 loc = mem->getMemberLoc();
11026 d = mem->getMemberDecl();
Richard Trieuba63ce62011-09-09 01:45:06 +000011027 } else if (ObjCMessageExpr *msg = dyn_cast<ObjCMessageExpr>(E)) {
John McCall2d2e8702011-04-11 07:02:50 +000011028 diagID = diag::err_uncasted_call_of_unknown_any;
Argyrios Kyrtzidisa6011e22011-10-03 06:36:51 +000011029 loc = msg->getSelectorStartLoc();
John McCall2d2e8702011-04-11 07:02:50 +000011030 d = msg->getMethodDecl();
John McCallfa6f5d62011-08-31 20:57:36 +000011031 if (!d) {
11032 S.Diag(loc, diag::err_uncasted_send_to_unknown_any_method)
11033 << static_cast<unsigned>(msg->isClassMessage()) << msg->getSelector()
11034 << orig->getSourceRange();
11035 return ExprError();
11036 }
John McCall2d2e8702011-04-11 07:02:50 +000011037 } else {
Richard Trieuba63ce62011-09-09 01:45:06 +000011038 S.Diag(E->getExprLoc(), diag::err_unsupported_unknown_any_expr)
11039 << E->getSourceRange();
John McCall2d2e8702011-04-11 07:02:50 +000011040 return ExprError();
11041 }
11042
11043 S.Diag(loc, diagID) << d << orig->getSourceRange();
John McCall31996342011-04-07 08:22:57 +000011044
11045 // Never recoverable.
11046 return ExprError();
11047}
11048
John McCall36e7fe32010-10-12 00:20:44 +000011049/// Check for operands with placeholder types and complain if found.
11050/// Returns true if there was an error and no recovery was possible.
John McCall3aef3d82011-04-10 19:13:55 +000011051ExprResult Sema::CheckPlaceholderExpr(Expr *E) {
John McCall4124c492011-10-17 18:40:02 +000011052 const BuiltinType *placeholderType = E->getType()->getAsPlaceholderType();
11053 if (!placeholderType) return Owned(E);
11054
11055 switch (placeholderType->getKind()) {
John McCall36e7fe32010-10-12 00:20:44 +000011056
John McCall31996342011-04-07 08:22:57 +000011057 // Overloaded expressions.
John McCall4124c492011-10-17 18:40:02 +000011058 case BuiltinType::Overload: {
John McCall50a2c2c2011-10-11 23:14:30 +000011059 // Try to resolve a single function template specialization.
11060 // This is obligatory.
11061 ExprResult result = Owned(E);
11062 if (ResolveAndFixSingleFunctionTemplateSpecialization(result, false)) {
11063 return result;
11064
11065 // If that failed, try to recover with a call.
11066 } else {
11067 tryToRecoverWithCall(result, PDiag(diag::err_ovl_unresolvable),
11068 /*complain*/ true);
11069 return result;
11070 }
11071 }
John McCall31996342011-04-07 08:22:57 +000011072
John McCall0009fcc2011-04-26 20:42:42 +000011073 // Bound member functions.
John McCall4124c492011-10-17 18:40:02 +000011074 case BuiltinType::BoundMember: {
John McCall50a2c2c2011-10-11 23:14:30 +000011075 ExprResult result = Owned(E);
11076 tryToRecoverWithCall(result, PDiag(diag::err_bound_member_function),
11077 /*complain*/ true);
11078 return result;
John McCall4124c492011-10-17 18:40:02 +000011079 }
11080
11081 // ARC unbridged casts.
11082 case BuiltinType::ARCUnbridgedCast: {
11083 Expr *realCast = stripARCUnbridgedCast(E);
11084 diagnoseARCUnbridgedCast(realCast);
11085 return Owned(realCast);
11086 }
John McCall0009fcc2011-04-26 20:42:42 +000011087
John McCall31996342011-04-07 08:22:57 +000011088 // Expressions of unknown type.
John McCall4124c492011-10-17 18:40:02 +000011089 case BuiltinType::UnknownAny:
John McCall31996342011-04-07 08:22:57 +000011090 return diagnoseUnknownAnyExpr(*this, E);
11091
John McCall526ab472011-10-25 17:37:35 +000011092 // Pseudo-objects.
11093 case BuiltinType::PseudoObject:
11094 return checkPseudoObjectRValue(E);
11095
John McCalle314e272011-10-18 21:02:43 +000011096 // Everything else should be impossible.
11097#define BUILTIN_TYPE(Id, SingletonId) \
11098 case BuiltinType::Id:
11099#define PLACEHOLDER_TYPE(Id, SingletonId)
11100#include "clang/AST/BuiltinTypes.def"
John McCall4124c492011-10-17 18:40:02 +000011101 break;
11102 }
11103
11104 llvm_unreachable("invalid placeholder type!");
John McCall36e7fe32010-10-12 00:20:44 +000011105}
Richard Trieu2c850c02011-04-21 21:44:26 +000011106
Richard Trieuba63ce62011-09-09 01:45:06 +000011107bool Sema::CheckCaseExpression(Expr *E) {
11108 if (E->isTypeDependent())
Richard Trieu2c850c02011-04-21 21:44:26 +000011109 return true;
Richard Trieuba63ce62011-09-09 01:45:06 +000011110 if (E->isValueDependent() || E->isIntegerConstantExpr(Context))
11111 return E->getType()->isIntegralOrEnumerationType();
Richard Trieu2c850c02011-04-21 21:44:26 +000011112 return false;
11113}
Ted Kremeneke65b0862012-03-06 20:05:56 +000011114
11115/// ActOnObjCBoolLiteral - Parse {__objc_yes,__objc_no} literals.
11116ExprResult
11117Sema::ActOnObjCBoolLiteral(SourceLocation OpLoc, tok::TokenKind Kind) {
11118 assert((Kind == tok::kw___objc_yes || Kind == tok::kw___objc_no) &&
11119 "Unknown Objective-C Boolean value!");
11120 return Owned(new (Context) ObjCBoolLiteralExpr(Kind == tok::kw___objc_yes,
11121 Context.ObjCBuiltinBoolTy, OpLoc));
11122}