blob: 0f9793d8394fa1a99b84f86517092ebd3579b197 [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
Richard Smith852265f2012-03-30 20:53:28 +0000111/// \brief Emit a note explaining that this function is deleted or unavailable.
112void Sema::NoteDeletedFunction(FunctionDecl *Decl) {
113 CXXMethodDecl *Method = dyn_cast<CXXMethodDecl>(Decl);
114
Richard Smith6f1e2c62012-04-02 20:59:25 +0000115 if (Method && Method->isDeleted() && !Method->isDeletedAsWritten()) {
116 // If the method was explicitly defaulted, point at that declaration.
117 if (!Method->isImplicit())
118 Diag(Decl->getLocation(), diag::note_implicitly_deleted);
119
120 // Try to diagnose why this special member function was implicitly
121 // deleted. This might fail, if that reason no longer applies.
Richard Smith852265f2012-03-30 20:53:28 +0000122 CXXSpecialMember CSM = getSpecialMember(Method);
Richard Smith6f1e2c62012-04-02 20:59:25 +0000123 if (CSM != CXXInvalid)
124 ShouldDeleteSpecialMember(Method, CSM, /*Diagnose=*/true);
125
126 return;
Richard Smith852265f2012-03-30 20:53:28 +0000127 }
128
129 Diag(Decl->getLocation(), diag::note_unavailable_here)
130 << 1 << Decl->isDeleted();
131}
132
Douglas Gregor171c45a2009-02-18 21:56:37 +0000133/// \brief Determine whether the use of this declaration is valid, and
134/// emit any corresponding diagnostics.
135///
136/// This routine diagnoses various problems with referencing
137/// declarations that can occur when using a declaration. For example,
138/// it might warn if a deprecated or unavailable declaration is being
139/// used, or produce an error (and return true) if a C++0x deleted
140/// function is being used.
141///
142/// \returns true if there was an error (this declaration cannot be
143/// referenced), false otherwise.
Chris Lattnerb7df3c62009-10-25 22:31:57 +0000144///
Fariborz Jahanian7d6e11a2010-12-21 00:44:01 +0000145bool Sema::DiagnoseUseOfDecl(NamedDecl *D, SourceLocation Loc,
Fariborz Jahanian6b854c52011-09-29 22:45:21 +0000146 const ObjCInterfaceDecl *UnknownObjCClass) {
David Blaikiebbafb8a2012-03-11 07:00:24 +0000147 if (getLangOpts().CPlusPlus && isa<FunctionDecl>(D)) {
Douglas Gregor5bb5e4a2010-10-12 23:32:35 +0000148 // If there were any diagnostics suppressed by template argument deduction,
149 // emit them now.
Chris Lattner0e62c1c2011-07-23 10:55:15 +0000150 llvm::DenseMap<Decl *, SmallVector<PartialDiagnosticAt, 1> >::iterator
Douglas Gregor5bb5e4a2010-10-12 23:32:35 +0000151 Pos = SuppressedDiagnostics.find(D->getCanonicalDecl());
152 if (Pos != SuppressedDiagnostics.end()) {
Chris Lattner0e62c1c2011-07-23 10:55:15 +0000153 SmallVectorImpl<PartialDiagnosticAt> &Suppressed = Pos->second;
Douglas Gregor5bb5e4a2010-10-12 23:32:35 +0000154 for (unsigned I = 0, N = Suppressed.size(); I != N; ++I)
155 Diag(Suppressed[I].first, Suppressed[I].second);
156
157 // Clear out the list of suppressed diagnostics, so that we don't emit
Douglas Gregor20b2ebd2011-03-23 00:50:03 +0000158 // them again for this specialization. However, we don't obsolete this
Douglas Gregor5bb5e4a2010-10-12 23:32:35 +0000159 // entry from the table, because we want to avoid ever emitting these
160 // diagnostics again.
161 Suppressed.clear();
162 }
163 }
164
Richard Smith30482bc2011-02-20 03:19:35 +0000165 // See if this is an auto-typed variable whose initializer we are parsing.
Richard Smithb2bc2e62011-02-21 20:05:19 +0000166 if (ParsingInitForAutoVars.count(D)) {
167 Diag(Loc, diag::err_auto_variable_cannot_appear_in_own_initializer)
168 << D->getDeclName();
169 return true;
Richard Smith30482bc2011-02-20 03:19:35 +0000170 }
171
Douglas Gregor171c45a2009-02-18 21:56:37 +0000172 // See if this is a deleted function.
Douglas Gregorde681d42009-02-24 04:26:15 +0000173 if (FunctionDecl *FD = dyn_cast<FunctionDecl>(D)) {
Douglas Gregor171c45a2009-02-18 21:56:37 +0000174 if (FD->isDeleted()) {
175 Diag(Loc, diag::err_deleted_function_use);
Richard Smith852265f2012-03-30 20:53:28 +0000176 NoteDeletedFunction(FD);
Douglas Gregor171c45a2009-02-18 21:56:37 +0000177 return true;
178 }
Douglas Gregorde681d42009-02-24 04:26:15 +0000179 }
Ted Kremenek6eb25622012-02-10 02:45:47 +0000180 DiagnoseAvailabilityOfDecl(*this, D, Loc, UnknownObjCClass);
Douglas Gregor20b2ebd2011-03-23 00:50:03 +0000181
Anders Carlsson73067a02010-10-22 23:37:08 +0000182 // Warn if this is used but marked unused.
Fariborz Jahanian6b854c52011-09-29 22:45:21 +0000183 if (D->hasAttr<UnusedAttr>())
Anders Carlsson73067a02010-10-22 23:37:08 +0000184 Diag(Loc, diag::warn_used_but_marked_unused) << D->getDeclName();
Douglas Gregor171c45a2009-02-18 21:56:37 +0000185 return false;
Chris Lattner4bf74fd2009-02-15 22:43:40 +0000186}
187
Douglas Gregor20b2ebd2011-03-23 00:50:03 +0000188/// \brief Retrieve the message suffix that should be added to a
189/// diagnostic complaining about the given function being deleted or
190/// unavailable.
191std::string Sema::getDeletedOrUnavailableSuffix(const FunctionDecl *FD) {
192 // FIXME: C++0x implicitly-deleted special member functions could be
193 // detected here so that we could improve diagnostics to say, e.g.,
194 // "base class 'A' had a deleted copy constructor".
195 if (FD->isDeleted())
196 return std::string();
197
198 std::string Message;
199 if (FD->getAvailability(&Message))
200 return ": " + Message;
201
202 return std::string();
203}
204
John McCallb46f2872011-09-09 07:56:05 +0000205/// DiagnoseSentinelCalls - This routine checks whether a call or
206/// message-send is to a declaration with the sentinel attribute, and
207/// if so, it checks that the requirements of the sentinel are
208/// satisfied.
Fariborz Jahanian027b8862009-05-13 18:09:35 +0000209void Sema::DiagnoseSentinelCalls(NamedDecl *D, SourceLocation Loc,
John McCallb46f2872011-09-09 07:56:05 +0000210 Expr **args, unsigned numArgs) {
Argyrios Kyrtzidisb4b64ca2009-06-30 02:34:44 +0000211 const SentinelAttr *attr = D->getAttr<SentinelAttr>();
Mike Stump11289f42009-09-09 15:08:12 +0000212 if (!attr)
Fariborz Jahanian9e877212009-05-13 23:20:50 +0000213 return;
Douglas Gregorc298ffc2010-04-22 16:44:27 +0000214
John McCallb46f2872011-09-09 07:56:05 +0000215 // The number of formal parameters of the declaration.
216 unsigned numFormalParams;
Mike Stump11289f42009-09-09 15:08:12 +0000217
John McCallb46f2872011-09-09 07:56:05 +0000218 // The kind of declaration. This is also an index into a %select in
219 // the diagnostic.
220 enum CalleeType { CT_Function, CT_Method, CT_Block } calleeType;
221
Fariborz Jahanian4a528032009-05-14 18:00:00 +0000222 if (ObjCMethodDecl *MD = dyn_cast<ObjCMethodDecl>(D)) {
John McCallb46f2872011-09-09 07:56:05 +0000223 numFormalParams = MD->param_size();
224 calleeType = CT_Method;
Mike Stump12b8ce12009-08-04 21:02:39 +0000225 } else if (FunctionDecl *FD = dyn_cast<FunctionDecl>(D)) {
John McCallb46f2872011-09-09 07:56:05 +0000226 numFormalParams = FD->param_size();
227 calleeType = CT_Function;
228 } else if (isa<VarDecl>(D)) {
229 QualType type = cast<ValueDecl>(D)->getType();
230 const FunctionType *fn = 0;
231 if (const PointerType *ptr = type->getAs<PointerType>()) {
232 fn = ptr->getPointeeType()->getAs<FunctionType>();
233 if (!fn) return;
234 calleeType = CT_Function;
235 } else if (const BlockPointerType *ptr = type->getAs<BlockPointerType>()) {
236 fn = ptr->getPointeeType()->castAs<FunctionType>();
237 calleeType = CT_Block;
238 } else {
Fariborz Jahanian0aa5c452009-05-15 20:33:25 +0000239 return;
John McCallb46f2872011-09-09 07:56:05 +0000240 }
Fariborz Jahanian4a528032009-05-14 18:00:00 +0000241
John McCallb46f2872011-09-09 07:56:05 +0000242 if (const FunctionProtoType *proto = dyn_cast<FunctionProtoType>(fn)) {
243 numFormalParams = proto->getNumArgs();
244 } else {
245 numFormalParams = 0;
246 }
247 } else {
Fariborz Jahanian9e877212009-05-13 23:20:50 +0000248 return;
249 }
John McCallb46f2872011-09-09 07:56:05 +0000250
251 // "nullPos" is the number of formal parameters at the end which
252 // effectively count as part of the variadic arguments. This is
253 // useful if you would prefer to not have *any* formal parameters,
254 // but the language forces you to have at least one.
255 unsigned nullPos = attr->getNullPos();
256 assert((nullPos == 0 || nullPos == 1) && "invalid null position on sentinel");
257 numFormalParams = (nullPos > numFormalParams ? 0 : numFormalParams - nullPos);
258
259 // The number of arguments which should follow the sentinel.
260 unsigned numArgsAfterSentinel = attr->getSentinel();
261
262 // If there aren't enough arguments for all the formal parameters,
263 // the sentinel, and the args after the sentinel, complain.
264 if (numArgs < numFormalParams + numArgsAfterSentinel + 1) {
Fariborz Jahanian9e877212009-05-13 23:20:50 +0000265 Diag(Loc, diag::warn_not_enough_argument) << D->getDeclName();
John McCallb46f2872011-09-09 07:56:05 +0000266 Diag(D->getLocation(), diag::note_sentinel_here) << calleeType;
Fariborz Jahanian9e877212009-05-13 23:20:50 +0000267 return;
268 }
John McCallb46f2872011-09-09 07:56:05 +0000269
270 // Otherwise, find the sentinel expression.
271 Expr *sentinelExpr = args[numArgs - numArgsAfterSentinel - 1];
John McCall7ddbcf42010-05-06 23:53:00 +0000272 if (!sentinelExpr) return;
John McCall7ddbcf42010-05-06 23:53:00 +0000273 if (sentinelExpr->isValueDependent()) return;
Argyrios Kyrtzidis2e809ce2012-02-03 05:58:16 +0000274 if (Context.isSentinelNullExpr(sentinelExpr)) return;
John McCall7ddbcf42010-05-06 23:53:00 +0000275
John McCallb46f2872011-09-09 07:56:05 +0000276 // Pick a reasonable string to insert. Optimistically use 'nil' or
277 // 'NULL' if those are actually defined in the context. Only use
278 // 'nil' for ObjC methods, where it's much more likely that the
279 // variadic arguments form a list of object pointers.
280 SourceLocation MissingNilLoc
Douglas Gregor5ff4e982011-07-30 08:57:03 +0000281 = PP.getLocForEndOfToken(sentinelExpr->getLocEnd());
282 std::string NullValue;
John McCallb46f2872011-09-09 07:56:05 +0000283 if (calleeType == CT_Method &&
284 PP.getIdentifierInfo("nil")->hasMacroDefinition())
Douglas Gregor5ff4e982011-07-30 08:57:03 +0000285 NullValue = "nil";
286 else if (PP.getIdentifierInfo("NULL")->hasMacroDefinition())
287 NullValue = "NULL";
Douglas Gregor5ff4e982011-07-30 08:57:03 +0000288 else
John McCallb46f2872011-09-09 07:56:05 +0000289 NullValue = "(void*) 0";
Eli Friedman9ab36372011-09-27 23:46:37 +0000290
291 if (MissingNilLoc.isInvalid())
292 Diag(Loc, diag::warn_missing_sentinel) << calleeType;
293 else
294 Diag(MissingNilLoc, diag::warn_missing_sentinel)
295 << calleeType
296 << FixItHint::CreateInsertion(MissingNilLoc, ", " + NullValue);
John McCallb46f2872011-09-09 07:56:05 +0000297 Diag(D->getLocation(), diag::note_sentinel_here) << calleeType;
Fariborz Jahanian027b8862009-05-13 18:09:35 +0000298}
299
Richard Trieuba63ce62011-09-09 01:45:06 +0000300SourceRange Sema::getExprRange(Expr *E) const {
301 return E ? E->getSourceRange() : SourceRange();
Douglas Gregor87f95b02009-02-26 21:00:50 +0000302}
303
Chris Lattner513165e2008-07-25 21:10:04 +0000304//===----------------------------------------------------------------------===//
305// Standard Promotions and Conversions
306//===----------------------------------------------------------------------===//
307
Chris Lattner513165e2008-07-25 21:10:04 +0000308/// DefaultFunctionArrayConversion (C99 6.3.2.1p3, C99 6.3.2.1p4).
John Wiegley01296292011-04-08 18:41:53 +0000309ExprResult Sema::DefaultFunctionArrayConversion(Expr *E) {
John McCall50a2c2c2011-10-11 23:14:30 +0000310 // Handle any placeholder expressions which made it here.
311 if (E->getType()->isPlaceholderType()) {
312 ExprResult result = CheckPlaceholderExpr(E);
313 if (result.isInvalid()) return ExprError();
314 E = result.take();
315 }
316
Chris Lattner513165e2008-07-25 21:10:04 +0000317 QualType Ty = E->getType();
318 assert(!Ty.isNull() && "DefaultFunctionArrayConversion - missing type");
319
Chris Lattner513165e2008-07-25 21:10:04 +0000320 if (Ty->isFunctionType())
John Wiegley01296292011-04-08 18:41:53 +0000321 E = ImpCastExprToType(E, Context.getPointerType(Ty),
322 CK_FunctionToPointerDecay).take();
Chris Lattner61f60a02008-07-25 21:33:13 +0000323 else if (Ty->isArrayType()) {
324 // In C90 mode, arrays only promote to pointers if the array expression is
325 // an lvalue. The relevant legalese is C90 6.2.2.1p3: "an lvalue that has
326 // type 'array of type' is converted to an expression that has type 'pointer
327 // to type'...". In C99 this was changed to: C99 6.3.2.1p3: "an expression
328 // that has type 'array of type' ...". The relevant change is "an lvalue"
329 // (C90) to "an expression" (C99).
Argyrios Kyrtzidis9321c742008-09-11 04:25:59 +0000330 //
331 // C++ 4.2p1:
332 // An lvalue or rvalue of type "array of N T" or "array of unknown bound of
333 // T" can be converted to an rvalue of type "pointer to T".
334 //
David Blaikiebbafb8a2012-03-11 07:00:24 +0000335 if (getLangOpts().C99 || getLangOpts().CPlusPlus || E->isLValue())
John Wiegley01296292011-04-08 18:41:53 +0000336 E = ImpCastExprToType(E, Context.getArrayDecayedType(Ty),
337 CK_ArrayToPointerDecay).take();
Chris Lattner61f60a02008-07-25 21:33:13 +0000338 }
John Wiegley01296292011-04-08 18:41:53 +0000339 return Owned(E);
Chris Lattner513165e2008-07-25 21:10:04 +0000340}
341
Argyrios Kyrtzidisa9b630e2011-04-26 17:41:22 +0000342static void CheckForNullPointerDereference(Sema &S, Expr *E) {
343 // Check to see if we are dereferencing a null pointer. If so,
344 // and if not volatile-qualified, this is undefined behavior that the
345 // optimizer will delete, so warn about it. People sometimes try to use this
346 // to get a deterministic trap and are surprised by clang's behavior. This
347 // only handles the pattern "*null", which is a very syntactic check.
348 if (UnaryOperator *UO = dyn_cast<UnaryOperator>(E->IgnoreParenCasts()))
349 if (UO->getOpcode() == UO_Deref &&
350 UO->getSubExpr()->IgnoreParenCasts()->
351 isNullPointerConstant(S.Context, Expr::NPC_ValueDependentIsNotNull) &&
352 !UO->getType().isVolatileQualified()) {
353 S.DiagRuntimeBehavior(UO->getOperatorLoc(), UO,
354 S.PDiag(diag::warn_indirection_through_null)
355 << UO->getSubExpr()->getSourceRange());
356 S.DiagRuntimeBehavior(UO->getOperatorLoc(), UO,
357 S.PDiag(diag::note_indirection_through_null));
358 }
359}
360
John Wiegley01296292011-04-08 18:41:53 +0000361ExprResult Sema::DefaultLvalueConversion(Expr *E) {
John McCall50a2c2c2011-10-11 23:14:30 +0000362 // Handle any placeholder expressions which made it here.
363 if (E->getType()->isPlaceholderType()) {
364 ExprResult result = CheckPlaceholderExpr(E);
365 if (result.isInvalid()) return ExprError();
366 E = result.take();
367 }
368
John McCallf3735e02010-12-01 04:43:34 +0000369 // C++ [conv.lval]p1:
370 // A glvalue of a non-function, non-array type T can be
371 // converted to a prvalue.
John Wiegley01296292011-04-08 18:41:53 +0000372 if (!E->isGLValue()) return Owned(E);
Kaelyn Uhrain2e7aa5a2011-08-05 23:18:04 +0000373
John McCall27584242010-12-06 20:48:59 +0000374 QualType T = E->getType();
375 assert(!T.isNull() && "r-value conversion on typeless expression?");
John McCall34376a62010-12-04 03:47:34 +0000376
John McCall27584242010-12-06 20:48:59 +0000377 // We don't want to throw lvalue-to-rvalue casts on top of
378 // expressions of certain types in C++.
David Blaikiebbafb8a2012-03-11 07:00:24 +0000379 if (getLangOpts().CPlusPlus &&
John McCall27584242010-12-06 20:48:59 +0000380 (E->getType() == Context.OverloadTy ||
381 T->isDependentType() ||
382 T->isRecordType()))
John Wiegley01296292011-04-08 18:41:53 +0000383 return Owned(E);
John McCall27584242010-12-06 20:48:59 +0000384
385 // The C standard is actually really unclear on this point, and
386 // DR106 tells us what the result should be but not why. It's
387 // generally best to say that void types just doesn't undergo
388 // lvalue-to-rvalue at all. Note that expressions of unqualified
389 // 'void' type are never l-values, but qualified void can be.
390 if (T->isVoidType())
John Wiegley01296292011-04-08 18:41:53 +0000391 return Owned(E);
John McCall27584242010-12-06 20:48:59 +0000392
Argyrios Kyrtzidisa9b630e2011-04-26 17:41:22 +0000393 CheckForNullPointerDereference(*this, E);
394
John McCall27584242010-12-06 20:48:59 +0000395 // C++ [conv.lval]p1:
396 // [...] If T is a non-class type, the type of the prvalue is the
397 // cv-unqualified version of T. Otherwise, the type of the
398 // rvalue is T.
399 //
400 // C99 6.3.2.1p2:
401 // If the lvalue has qualified type, the value has the unqualified
402 // version of the type of the lvalue; otherwise, the value has the
Anton Korobeynikovf0c267e2011-10-14 23:23:15 +0000403 // type of the lvalue.
John McCall27584242010-12-06 20:48:59 +0000404 if (T.hasQualifiers())
405 T = T.getUnqualifiedType();
Anton Korobeynikovf0c267e2011-10-14 23:23:15 +0000406
Eli Friedman3bda6b12012-02-02 23:15:15 +0000407 UpdateMarkingForLValueToRValue(E);
408
Anton Korobeynikovf0c267e2011-10-14 23:23:15 +0000409 ExprResult Res = Owned(ImplicitCastExpr::Create(Context, T, CK_LValueToRValue,
410 E, 0, VK_RValue));
411
Douglas Gregorc79862f2012-04-12 17:51:55 +0000412 // C11 6.3.2.1p2:
413 // ... if the lvalue has atomic type, the value has the non-atomic version
414 // of the type of the lvalue ...
415 if (const AtomicType *Atomic = T->getAs<AtomicType>()) {
416 T = Atomic->getValueType().getUnqualifiedType();
417 Res = Owned(ImplicitCastExpr::Create(Context, T, CK_AtomicToNonAtomic,
418 Res.get(), 0, VK_RValue));
419 }
420
Anton Korobeynikovf0c267e2011-10-14 23:23:15 +0000421 return Res;
John McCall27584242010-12-06 20:48:59 +0000422}
423
John Wiegley01296292011-04-08 18:41:53 +0000424ExprResult Sema::DefaultFunctionArrayLvalueConversion(Expr *E) {
425 ExprResult Res = DefaultFunctionArrayConversion(E);
426 if (Res.isInvalid())
427 return ExprError();
428 Res = DefaultLvalueConversion(Res.take());
429 if (Res.isInvalid())
430 return ExprError();
431 return move(Res);
Douglas Gregorb92a1562010-02-03 00:27:59 +0000432}
433
434
Chris Lattner513165e2008-07-25 21:10:04 +0000435/// UsualUnaryConversions - Performs various conversions that are common to most
Mike Stump11289f42009-09-09 15:08:12 +0000436/// operators (C99 6.3). The conversions of array and function types are
Chris Lattner57540c52011-04-15 05:22:18 +0000437/// sometimes suppressed. For example, the array->pointer conversion doesn't
Chris Lattner513165e2008-07-25 21:10:04 +0000438/// apply if the array is an argument to the sizeof or address (&) operators.
439/// In these instances, this routine should *not* be called.
John Wiegley01296292011-04-08 18:41:53 +0000440ExprResult Sema::UsualUnaryConversions(Expr *E) {
John McCallf3735e02010-12-01 04:43:34 +0000441 // First, convert to an r-value.
John Wiegley01296292011-04-08 18:41:53 +0000442 ExprResult Res = DefaultFunctionArrayLvalueConversion(E);
443 if (Res.isInvalid())
444 return Owned(E);
445 E = Res.take();
Anton Korobeynikovf0c267e2011-10-14 23:23:15 +0000446
John McCallf3735e02010-12-01 04:43:34 +0000447 QualType Ty = E->getType();
Chris Lattner513165e2008-07-25 21:10:04 +0000448 assert(!Ty.isNull() && "UsualUnaryConversions - missing type");
Anton Korobeynikovf0c267e2011-10-14 23:23:15 +0000449
450 // Half FP is a bit different: it's a storage-only type, meaning that any
451 // "use" of it should be promoted to float.
452 if (Ty->isHalfType())
453 return ImpCastExprToType(Res.take(), Context.FloatTy, CK_FloatingCast);
454
John McCallf3735e02010-12-01 04:43:34 +0000455 // Try to perform integral promotions if the object has a theoretically
456 // promotable type.
457 if (Ty->isIntegralOrUnscopedEnumerationType()) {
458 // C99 6.3.1.1p2:
459 //
460 // The following may be used in an expression wherever an int or
461 // unsigned int may be used:
462 // - an object or expression with an integer type whose integer
463 // conversion rank is less than or equal to the rank of int
464 // and unsigned int.
465 // - A bit-field of type _Bool, int, signed int, or unsigned int.
466 //
467 // If an int can represent all values of the original type, the
468 // value is converted to an int; otherwise, it is converted to an
469 // unsigned int. These are called the integer promotions. All
470 // other types are unchanged by the integer promotions.
Anton Korobeynikovf0c267e2011-10-14 23:23:15 +0000471
John McCallf3735e02010-12-01 04:43:34 +0000472 QualType PTy = Context.isPromotableBitField(E);
473 if (!PTy.isNull()) {
John Wiegley01296292011-04-08 18:41:53 +0000474 E = ImpCastExprToType(E, PTy, CK_IntegralCast).take();
475 return Owned(E);
John McCallf3735e02010-12-01 04:43:34 +0000476 }
477 if (Ty->isPromotableIntegerType()) {
478 QualType PT = Context.getPromotedIntegerType(Ty);
John Wiegley01296292011-04-08 18:41:53 +0000479 E = ImpCastExprToType(E, PT, CK_IntegralCast).take();
480 return Owned(E);
John McCallf3735e02010-12-01 04:43:34 +0000481 }
Eli Friedman629ffb92009-08-20 04:21:42 +0000482 }
John Wiegley01296292011-04-08 18:41:53 +0000483 return Owned(E);
Chris Lattner513165e2008-07-25 21:10:04 +0000484}
485
Chris Lattner2ce500f2008-07-25 22:25:12 +0000486/// DefaultArgumentPromotion (C99 6.5.2.2p6). Used for function calls that
Mike Stump11289f42009-09-09 15:08:12 +0000487/// do not have a prototype. Arguments that have type float are promoted to
Chris Lattner2ce500f2008-07-25 22:25:12 +0000488/// double. All other argument types are converted by UsualUnaryConversions().
John Wiegley01296292011-04-08 18:41:53 +0000489ExprResult Sema::DefaultArgumentPromotion(Expr *E) {
490 QualType Ty = E->getType();
Chris Lattner2ce500f2008-07-25 22:25:12 +0000491 assert(!Ty.isNull() && "DefaultArgumentPromotion - missing type");
Mike Stump11289f42009-09-09 15:08:12 +0000492
John Wiegley01296292011-04-08 18:41:53 +0000493 ExprResult Res = UsualUnaryConversions(E);
494 if (Res.isInvalid())
495 return Owned(E);
496 E = Res.take();
John McCall9bc26772010-12-06 18:36:11 +0000497
Chris Lattner2ce500f2008-07-25 22:25:12 +0000498 // If this is a 'float' (CVR qualified or typedef) promote to double.
Chris Lattnerbb53efb2010-05-16 04:01:30 +0000499 if (Ty->isSpecificBuiltinType(BuiltinType::Float))
John Wiegley01296292011-04-08 18:41:53 +0000500 E = ImpCastExprToType(E, Context.DoubleTy, CK_FloatingCast).take();
501
John McCall4bb057d2011-08-27 22:06:17 +0000502 // C++ performs lvalue-to-rvalue conversion as a default argument
John McCall0562caa2011-08-29 23:55:37 +0000503 // promotion, even on class types, but note:
504 // C++11 [conv.lval]p2:
505 // When an lvalue-to-rvalue conversion occurs in an unevaluated
506 // operand or a subexpression thereof the value contained in the
507 // referenced object is not accessed. Otherwise, if the glvalue
508 // has a class type, the conversion copy-initializes a temporary
509 // of type T from the glvalue and the result of the conversion
510 // is a prvalue for the temporary.
Eli Friedman05e28012012-01-17 02:13:45 +0000511 // FIXME: add some way to gate this entire thing for correctness in
512 // potentially potentially evaluated contexts.
David Blaikiebbafb8a2012-03-11 07:00:24 +0000513 if (getLangOpts().CPlusPlus && E->isGLValue() &&
Eli Friedman05e28012012-01-17 02:13:45 +0000514 ExprEvalContexts.back().Context != Unevaluated) {
515 ExprResult Temp = PerformCopyInitialization(
516 InitializedEntity::InitializeTemporary(E->getType()),
517 E->getExprLoc(),
518 Owned(E));
519 if (Temp.isInvalid())
520 return ExprError();
521 E = Temp.get();
John McCall29ad95b2011-08-27 01:09:30 +0000522 }
523
John Wiegley01296292011-04-08 18:41:53 +0000524 return Owned(E);
Chris Lattner2ce500f2008-07-25 22:25:12 +0000525}
526
Chris Lattnera8a7d0f2009-04-12 08:11:20 +0000527/// DefaultVariadicArgumentPromotion - Like DefaultArgumentPromotion, but
528/// will warn if the resulting type is not a POD type, and rejects ObjC
John Wiegley01296292011-04-08 18:41:53 +0000529/// interfaces passed by value.
530ExprResult Sema::DefaultVariadicArgumentPromotion(Expr *E, VariadicCallType CT,
John McCall31168b02011-06-15 23:02:42 +0000531 FunctionDecl *FDecl) {
John McCall4124c492011-10-17 18:40:02 +0000532 if (const BuiltinType *PlaceholderTy = E->getType()->getAsPlaceholderType()) {
533 // Strip the unbridged-cast placeholder expression off, if applicable.
534 if (PlaceholderTy->getKind() == BuiltinType::ARCUnbridgedCast &&
535 (CT == VariadicMethod ||
536 (FDecl && FDecl->hasAttr<CFAuditedTransferAttr>()))) {
537 E = stripARCUnbridgedCast(E);
538
539 // Otherwise, do normal placeholder checking.
540 } else {
541 ExprResult ExprRes = CheckPlaceholderExpr(E);
542 if (ExprRes.isInvalid())
543 return ExprError();
544 E = ExprRes.take();
545 }
546 }
Douglas Gregorcbd446d2011-06-17 00:15:10 +0000547
John McCall4124c492011-10-17 18:40:02 +0000548 ExprResult ExprRes = DefaultArgumentPromotion(E);
John Wiegley01296292011-04-08 18:41:53 +0000549 if (ExprRes.isInvalid())
550 return ExprError();
551 E = ExprRes.take();
Mike Stump11289f42009-09-09 15:08:12 +0000552
Douglas Gregor347e0f22011-05-21 19:26:31 +0000553 // Don't allow one to pass an Objective-C interface to a vararg.
John Wiegley01296292011-04-08 18:41:53 +0000554 if (E->getType()->isObjCObjectType() &&
Douglas Gregor347e0f22011-05-21 19:26:31 +0000555 DiagRuntimeBehavior(E->getLocStart(), 0,
556 PDiag(diag::err_cannot_pass_objc_interface_to_vararg)
557 << E->getType() << CT))
John Wiegley01296292011-04-08 18:41:53 +0000558 return ExprError();
John McCall29ad95b2011-08-27 01:09:30 +0000559
Douglas Gregor7e1aa5b2011-10-14 20:34:19 +0000560 // Complain about passing non-POD types through varargs. However, don't
561 // perform this check for incomplete types, which we can get here when we're
562 // in an unevaluated context.
Benjamin Kramer6a0a2112012-04-28 10:00:42 +0000563 if (!E->getType()->isIncompleteType() &&
564 !E->getType().isCXX98PODType(Context)) {
Douglas Gregor253cadf2011-05-21 16:27:21 +0000565 // C++0x [expr.call]p7:
566 // Passing a potentially-evaluated argument of class type (Clause 9)
567 // having a non-trivial copy constructor, a non-trivial move constructor,
568 // or a non-trivial destructor, with no corresponding parameter,
569 // is conditionally-supported with implementation-defined semantics.
570 bool TrivialEnough = false;
David Blaikiebbafb8a2012-03-11 07:00:24 +0000571 if (getLangOpts().CPlusPlus0x && !E->getType()->isDependentType()) {
Douglas Gregor253cadf2011-05-21 16:27:21 +0000572 if (CXXRecordDecl *Record = E->getType()->getAsCXXRecordDecl()) {
573 if (Record->hasTrivialCopyConstructor() &&
574 Record->hasTrivialMoveConstructor() &&
Richard Smith0bf8a4922011-10-18 20:49:44 +0000575 Record->hasTrivialDestructor()) {
576 DiagRuntimeBehavior(E->getLocStart(), 0,
577 PDiag(diag::warn_cxx98_compat_pass_non_pod_arg_to_vararg)
578 << E->getType() << CT);
Douglas Gregor253cadf2011-05-21 16:27:21 +0000579 TrivialEnough = true;
Richard Smith0bf8a4922011-10-18 20:49:44 +0000580 }
Douglas Gregor253cadf2011-05-21 16:27:21 +0000581 }
582 }
John McCall31168b02011-06-15 23:02:42 +0000583
584 if (!TrivialEnough &&
David Blaikiebbafb8a2012-03-11 07:00:24 +0000585 getLangOpts().ObjCAutoRefCount &&
John McCall31168b02011-06-15 23:02:42 +0000586 E->getType()->isObjCLifetimeType())
587 TrivialEnough = true;
Douglas Gregor253cadf2011-05-21 16:27:21 +0000588
589 if (TrivialEnough) {
590 // Nothing to diagnose. This is okay.
591 } else if (DiagRuntimeBehavior(E->getLocStart(), 0,
Douglas Gregorda8cdbc2009-12-22 01:01:55 +0000592 PDiag(diag::warn_cannot_pass_non_pod_arg_to_vararg)
David Blaikiebbafb8a2012-03-11 07:00:24 +0000593 << getLangOpts().CPlusPlus0x << E->getType()
Douglas Gregor347e0f22011-05-21 19:26:31 +0000594 << CT)) {
595 // Turn this into a trap.
596 CXXScopeSpec SS;
Abramo Bagnara7945c982012-01-27 09:46:47 +0000597 SourceLocation TemplateKWLoc;
Douglas Gregor347e0f22011-05-21 19:26:31 +0000598 UnqualifiedId Name;
599 Name.setIdentifier(PP.getIdentifierInfo("__builtin_trap"),
600 E->getLocStart());
Abramo Bagnara7945c982012-01-27 09:46:47 +0000601 ExprResult TrapFn = ActOnIdExpression(TUScope, SS, TemplateKWLoc, Name,
602 true, false);
Douglas Gregor347e0f22011-05-21 19:26:31 +0000603 if (TrapFn.isInvalid())
604 return ExprError();
605
606 ExprResult Call = ActOnCallExpr(TUScope, TrapFn.get(), E->getLocStart(),
607 MultiExprArg(), E->getLocEnd());
608 if (Call.isInvalid())
609 return ExprError();
610
611 ExprResult Comma = ActOnBinOp(TUScope, E->getLocStart(), tok::comma,
612 Call.get(), E);
613 if (Comma.isInvalid())
John McCall1cd60a22011-08-26 18:41:18 +0000614 return ExprError();
Douglas Gregor347e0f22011-05-21 19:26:31 +0000615 E = Comma.get();
616 }
Douglas Gregor253cadf2011-05-21 16:27:21 +0000617 }
Fariborz Jahanianbf482812012-03-02 17:05:03 +0000618 // c++ rules are enforced elsewhere.
David Blaikiebbafb8a2012-03-11 07:00:24 +0000619 if (!getLangOpts().CPlusPlus &&
Fariborz Jahanian3854a552012-03-01 23:42:00 +0000620 RequireCompleteType(E->getExprLoc(), E->getType(),
Fariborz Jahanianbf482812012-03-02 17:05:03 +0000621 diag::err_call_incomplete_argument))
Fariborz Jahanian3854a552012-03-01 23:42:00 +0000622 return ExprError();
Douglas Gregor253cadf2011-05-21 16:27:21 +0000623
John Wiegley01296292011-04-08 18:41:53 +0000624 return Owned(E);
Anders Carlssona7d069d2009-01-16 16:48:51 +0000625}
626
Richard Trieu7aa58f12011-09-02 20:58:51 +0000627/// \brief Converts an integer to complex float type. Helper function of
628/// UsualArithmeticConversions()
629///
630/// \return false if the integer expression is an integer type and is
631/// successfully converted to the complex type.
Richard Trieuba63ce62011-09-09 01:45:06 +0000632static bool handleIntegerToComplexFloatConversion(Sema &S, ExprResult &IntExpr,
633 ExprResult &ComplexExpr,
634 QualType IntTy,
635 QualType ComplexTy,
636 bool SkipCast) {
637 if (IntTy->isComplexType() || IntTy->isRealFloatingType()) return true;
638 if (SkipCast) return false;
639 if (IntTy->isIntegerType()) {
640 QualType fpTy = cast<ComplexType>(ComplexTy)->getElementType();
641 IntExpr = S.ImpCastExprToType(IntExpr.take(), fpTy, CK_IntegralToFloating);
642 IntExpr = S.ImpCastExprToType(IntExpr.take(), ComplexTy,
Richard Trieu7aa58f12011-09-02 20:58:51 +0000643 CK_FloatingRealToComplex);
644 } else {
Richard Trieuba63ce62011-09-09 01:45:06 +0000645 assert(IntTy->isComplexIntegerType());
646 IntExpr = S.ImpCastExprToType(IntExpr.take(), ComplexTy,
Richard Trieu7aa58f12011-09-02 20:58:51 +0000647 CK_IntegralComplexToFloatingComplex);
648 }
649 return false;
650}
651
652/// \brief Takes two complex float types and converts them to the same type.
653/// Helper function of UsualArithmeticConversions()
654static QualType
Richard Trieu5065cdd2011-09-06 18:25:09 +0000655handleComplexFloatToComplexFloatConverstion(Sema &S, ExprResult &LHS,
656 ExprResult &RHS, QualType LHSType,
657 QualType RHSType,
Richard Trieuba63ce62011-09-09 01:45:06 +0000658 bool IsCompAssign) {
Richard Trieu5065cdd2011-09-06 18:25:09 +0000659 int order = S.Context.getFloatingTypeOrder(LHSType, RHSType);
Richard Trieu7aa58f12011-09-02 20:58:51 +0000660
661 if (order < 0) {
662 // _Complex float -> _Complex double
Richard Trieuba63ce62011-09-09 01:45:06 +0000663 if (!IsCompAssign)
Richard Trieu5065cdd2011-09-06 18:25:09 +0000664 LHS = S.ImpCastExprToType(LHS.take(), RHSType, CK_FloatingComplexCast);
665 return RHSType;
Richard Trieu7aa58f12011-09-02 20:58:51 +0000666 }
667 if (order > 0)
668 // _Complex float -> _Complex double
Richard Trieu5065cdd2011-09-06 18:25:09 +0000669 RHS = S.ImpCastExprToType(RHS.take(), LHSType, CK_FloatingComplexCast);
670 return LHSType;
Richard Trieu7aa58f12011-09-02 20:58:51 +0000671}
672
673/// \brief Converts otherExpr to complex float and promotes complexExpr if
674/// necessary. Helper function of UsualArithmeticConversions()
675static QualType handleOtherComplexFloatConversion(Sema &S,
Richard Trieuba63ce62011-09-09 01:45:06 +0000676 ExprResult &ComplexExpr,
677 ExprResult &OtherExpr,
678 QualType ComplexTy,
679 QualType OtherTy,
680 bool ConvertComplexExpr,
681 bool ConvertOtherExpr) {
682 int order = S.Context.getFloatingTypeOrder(ComplexTy, OtherTy);
Richard Trieu7aa58f12011-09-02 20:58:51 +0000683
684 // If just the complexExpr is complex, the otherExpr needs to be converted,
685 // and the complexExpr might need to be promoted.
686 if (order > 0) { // complexExpr is wider
687 // float -> _Complex double
Richard Trieuba63ce62011-09-09 01:45:06 +0000688 if (ConvertOtherExpr) {
689 QualType fp = cast<ComplexType>(ComplexTy)->getElementType();
690 OtherExpr = S.ImpCastExprToType(OtherExpr.take(), fp, CK_FloatingCast);
691 OtherExpr = S.ImpCastExprToType(OtherExpr.take(), ComplexTy,
Richard Trieu7aa58f12011-09-02 20:58:51 +0000692 CK_FloatingRealToComplex);
693 }
Richard Trieuba63ce62011-09-09 01:45:06 +0000694 return ComplexTy;
Richard Trieu7aa58f12011-09-02 20:58:51 +0000695 }
696
697 // otherTy is at least as wide. Find its corresponding complex type.
Richard Trieuba63ce62011-09-09 01:45:06 +0000698 QualType result = (order == 0 ? ComplexTy :
699 S.Context.getComplexType(OtherTy));
Richard Trieu7aa58f12011-09-02 20:58:51 +0000700
701 // double -> _Complex double
Richard Trieuba63ce62011-09-09 01:45:06 +0000702 if (ConvertOtherExpr)
703 OtherExpr = S.ImpCastExprToType(OtherExpr.take(), result,
Richard Trieu7aa58f12011-09-02 20:58:51 +0000704 CK_FloatingRealToComplex);
705
706 // _Complex float -> _Complex double
Richard Trieuba63ce62011-09-09 01:45:06 +0000707 if (ConvertComplexExpr && order < 0)
708 ComplexExpr = S.ImpCastExprToType(ComplexExpr.take(), result,
Richard Trieu7aa58f12011-09-02 20:58:51 +0000709 CK_FloatingComplexCast);
710
711 return result;
712}
713
714/// \brief Handle arithmetic conversion with complex types. Helper function of
715/// UsualArithmeticConversions()
Richard Trieu5065cdd2011-09-06 18:25:09 +0000716static QualType handleComplexFloatConversion(Sema &S, ExprResult &LHS,
717 ExprResult &RHS, QualType LHSType,
718 QualType RHSType,
Richard Trieuba63ce62011-09-09 01:45:06 +0000719 bool IsCompAssign) {
Richard Trieu7aa58f12011-09-02 20:58:51 +0000720 // if we have an integer operand, the result is the complex type.
Richard Trieu5065cdd2011-09-06 18:25:09 +0000721 if (!handleIntegerToComplexFloatConversion(S, RHS, LHS, RHSType, LHSType,
Richard Trieu7aa58f12011-09-02 20:58:51 +0000722 /*skipCast*/false))
Richard Trieu5065cdd2011-09-06 18:25:09 +0000723 return LHSType;
724 if (!handleIntegerToComplexFloatConversion(S, LHS, RHS, LHSType, RHSType,
Richard Trieuba63ce62011-09-09 01:45:06 +0000725 /*skipCast*/IsCompAssign))
Richard Trieu5065cdd2011-09-06 18:25:09 +0000726 return RHSType;
Richard Trieu7aa58f12011-09-02 20:58:51 +0000727
728 // This handles complex/complex, complex/float, or float/complex.
729 // When both operands are complex, the shorter operand is converted to the
730 // type of the longer, and that is the type of the result. This corresponds
731 // to what is done when combining two real floating-point operands.
732 // The fun begins when size promotion occur across type domains.
733 // From H&S 6.3.4: When one operand is complex and the other is a real
734 // floating-point type, the less precise type is converted, within it's
735 // real or complex domain, to the precision of the other type. For example,
736 // when combining a "long double" with a "double _Complex", the
737 // "double _Complex" is promoted to "long double _Complex".
738
Richard Trieu5065cdd2011-09-06 18:25:09 +0000739 bool LHSComplexFloat = LHSType->isComplexType();
740 bool RHSComplexFloat = RHSType->isComplexType();
Richard Trieu7aa58f12011-09-02 20:58:51 +0000741
742 // If both are complex, just cast to the more precise type.
743 if (LHSComplexFloat && RHSComplexFloat)
Richard Trieu5065cdd2011-09-06 18:25:09 +0000744 return handleComplexFloatToComplexFloatConverstion(S, LHS, RHS,
745 LHSType, RHSType,
Richard Trieuba63ce62011-09-09 01:45:06 +0000746 IsCompAssign);
Richard Trieu7aa58f12011-09-02 20:58:51 +0000747
748 // If only one operand is complex, promote it if necessary and convert the
749 // other operand to complex.
750 if (LHSComplexFloat)
751 return handleOtherComplexFloatConversion(
Richard Trieuba63ce62011-09-09 01:45:06 +0000752 S, LHS, RHS, LHSType, RHSType, /*convertComplexExpr*/!IsCompAssign,
Richard Trieu7aa58f12011-09-02 20:58:51 +0000753 /*convertOtherExpr*/ true);
754
755 assert(RHSComplexFloat);
756 return handleOtherComplexFloatConversion(
Richard Trieu5065cdd2011-09-06 18:25:09 +0000757 S, RHS, LHS, RHSType, LHSType, /*convertComplexExpr*/true,
Richard Trieuba63ce62011-09-09 01:45:06 +0000758 /*convertOtherExpr*/ !IsCompAssign);
Richard Trieu7aa58f12011-09-02 20:58:51 +0000759}
760
761/// \brief Hande arithmetic conversion from integer to float. Helper function
762/// of UsualArithmeticConversions()
Richard Trieuba63ce62011-09-09 01:45:06 +0000763static QualType handleIntToFloatConversion(Sema &S, ExprResult &FloatExpr,
764 ExprResult &IntExpr,
765 QualType FloatTy, QualType IntTy,
766 bool ConvertFloat, bool ConvertInt) {
767 if (IntTy->isIntegerType()) {
768 if (ConvertInt)
Richard Trieu7aa58f12011-09-02 20:58:51 +0000769 // Convert intExpr to the lhs floating point type.
Richard Trieuba63ce62011-09-09 01:45:06 +0000770 IntExpr = S.ImpCastExprToType(IntExpr.take(), FloatTy,
Richard Trieu7aa58f12011-09-02 20:58:51 +0000771 CK_IntegralToFloating);
Richard Trieuba63ce62011-09-09 01:45:06 +0000772 return FloatTy;
Richard Trieu7aa58f12011-09-02 20:58:51 +0000773 }
774
775 // Convert both sides to the appropriate complex float.
Richard Trieuba63ce62011-09-09 01:45:06 +0000776 assert(IntTy->isComplexIntegerType());
777 QualType result = S.Context.getComplexType(FloatTy);
Richard Trieu7aa58f12011-09-02 20:58:51 +0000778
779 // _Complex int -> _Complex float
Richard Trieuba63ce62011-09-09 01:45:06 +0000780 if (ConvertInt)
781 IntExpr = S.ImpCastExprToType(IntExpr.take(), result,
Richard Trieu7aa58f12011-09-02 20:58:51 +0000782 CK_IntegralComplexToFloatingComplex);
783
784 // float -> _Complex float
Richard Trieuba63ce62011-09-09 01:45:06 +0000785 if (ConvertFloat)
786 FloatExpr = S.ImpCastExprToType(FloatExpr.take(), result,
Richard Trieu7aa58f12011-09-02 20:58:51 +0000787 CK_FloatingRealToComplex);
788
789 return result;
790}
791
792/// \brief Handle arithmethic conversion with floating point types. Helper
793/// function of UsualArithmeticConversions()
Richard Trieucfe3f212011-09-06 18:38:41 +0000794static QualType handleFloatConversion(Sema &S, ExprResult &LHS,
795 ExprResult &RHS, QualType LHSType,
Richard Trieuba63ce62011-09-09 01:45:06 +0000796 QualType RHSType, bool IsCompAssign) {
Richard Trieucfe3f212011-09-06 18:38:41 +0000797 bool LHSFloat = LHSType->isRealFloatingType();
798 bool RHSFloat = RHSType->isRealFloatingType();
Richard Trieu7aa58f12011-09-02 20:58:51 +0000799
800 // If we have two real floating types, convert the smaller operand
801 // to the bigger result.
802 if (LHSFloat && RHSFloat) {
Richard Trieucfe3f212011-09-06 18:38:41 +0000803 int order = S.Context.getFloatingTypeOrder(LHSType, RHSType);
Richard Trieu7aa58f12011-09-02 20:58:51 +0000804 if (order > 0) {
Richard Trieucfe3f212011-09-06 18:38:41 +0000805 RHS = S.ImpCastExprToType(RHS.take(), LHSType, CK_FloatingCast);
806 return LHSType;
Richard Trieu7aa58f12011-09-02 20:58:51 +0000807 }
808
809 assert(order < 0 && "illegal float comparison");
Richard Trieuba63ce62011-09-09 01:45:06 +0000810 if (!IsCompAssign)
Richard Trieucfe3f212011-09-06 18:38:41 +0000811 LHS = S.ImpCastExprToType(LHS.take(), RHSType, CK_FloatingCast);
812 return RHSType;
Richard Trieu7aa58f12011-09-02 20:58:51 +0000813 }
814
815 if (LHSFloat)
Richard Trieucfe3f212011-09-06 18:38:41 +0000816 return handleIntToFloatConversion(S, LHS, RHS, LHSType, RHSType,
Richard Trieuba63ce62011-09-09 01:45:06 +0000817 /*convertFloat=*/!IsCompAssign,
Richard Trieu7aa58f12011-09-02 20:58:51 +0000818 /*convertInt=*/ true);
819 assert(RHSFloat);
Richard Trieucfe3f212011-09-06 18:38:41 +0000820 return handleIntToFloatConversion(S, RHS, LHS, RHSType, LHSType,
Richard Trieu7aa58f12011-09-02 20:58:51 +0000821 /*convertInt=*/ true,
Richard Trieuba63ce62011-09-09 01:45:06 +0000822 /*convertFloat=*/!IsCompAssign);
Richard Trieu7aa58f12011-09-02 20:58:51 +0000823}
824
825/// \brief Handle conversions with GCC complex int extension. Helper function
Benjamin Kramer499c68b2011-09-06 19:57:14 +0000826/// of UsualArithmeticConversions()
Richard Trieu7aa58f12011-09-02 20:58:51 +0000827// FIXME: if the operands are (int, _Complex long), we currently
828// don't promote the complex. Also, signedness?
Benjamin Kramer499c68b2011-09-06 19:57:14 +0000829static QualType handleComplexIntConversion(Sema &S, ExprResult &LHS,
830 ExprResult &RHS, QualType LHSType,
831 QualType RHSType,
Richard Trieuba63ce62011-09-09 01:45:06 +0000832 bool IsCompAssign) {
Richard Trieucfe3f212011-09-06 18:38:41 +0000833 const ComplexType *LHSComplexInt = LHSType->getAsComplexIntegerType();
834 const ComplexType *RHSComplexInt = RHSType->getAsComplexIntegerType();
Richard Trieu7aa58f12011-09-02 20:58:51 +0000835
Richard Trieucfe3f212011-09-06 18:38:41 +0000836 if (LHSComplexInt && RHSComplexInt) {
837 int order = S.Context.getIntegerTypeOrder(LHSComplexInt->getElementType(),
838 RHSComplexInt->getElementType());
Richard Trieu7aa58f12011-09-02 20:58:51 +0000839 assert(order && "inequal types with equal element ordering");
840 if (order > 0) {
841 // _Complex int -> _Complex long
Richard Trieucfe3f212011-09-06 18:38:41 +0000842 RHS = S.ImpCastExprToType(RHS.take(), LHSType, CK_IntegralComplexCast);
843 return LHSType;
Richard Trieu7aa58f12011-09-02 20:58:51 +0000844 }
845
Richard Trieuba63ce62011-09-09 01:45:06 +0000846 if (!IsCompAssign)
Richard Trieucfe3f212011-09-06 18:38:41 +0000847 LHS = S.ImpCastExprToType(LHS.take(), RHSType, CK_IntegralComplexCast);
848 return RHSType;
Richard Trieu7aa58f12011-09-02 20:58:51 +0000849 }
850
Richard Trieucfe3f212011-09-06 18:38:41 +0000851 if (LHSComplexInt) {
Richard Trieu7aa58f12011-09-02 20:58:51 +0000852 // int -> _Complex int
Eli Friedman47133be2011-11-12 03:56:23 +0000853 // FIXME: This needs to take integer ranks into account
854 RHS = S.ImpCastExprToType(RHS.take(), LHSComplexInt->getElementType(),
855 CK_IntegralCast);
Richard Trieucfe3f212011-09-06 18:38:41 +0000856 RHS = S.ImpCastExprToType(RHS.take(), LHSType, CK_IntegralRealToComplex);
857 return LHSType;
Richard Trieu7aa58f12011-09-02 20:58:51 +0000858 }
859
Richard Trieucfe3f212011-09-06 18:38:41 +0000860 assert(RHSComplexInt);
Richard Trieu7aa58f12011-09-02 20:58:51 +0000861 // int -> _Complex int
Eli Friedman47133be2011-11-12 03:56:23 +0000862 // FIXME: This needs to take integer ranks into account
863 if (!IsCompAssign) {
864 LHS = S.ImpCastExprToType(LHS.take(), RHSComplexInt->getElementType(),
865 CK_IntegralCast);
Richard Trieucfe3f212011-09-06 18:38:41 +0000866 LHS = S.ImpCastExprToType(LHS.take(), RHSType, CK_IntegralRealToComplex);
Eli Friedman47133be2011-11-12 03:56:23 +0000867 }
Richard Trieucfe3f212011-09-06 18:38:41 +0000868 return RHSType;
Richard Trieu7aa58f12011-09-02 20:58:51 +0000869}
870
871/// \brief Handle integer arithmetic conversions. Helper function of
872/// UsualArithmeticConversions()
Richard Trieu9a52fbb2011-09-06 19:52:52 +0000873static QualType handleIntegerConversion(Sema &S, ExprResult &LHS,
874 ExprResult &RHS, QualType LHSType,
Richard Trieuba63ce62011-09-09 01:45:06 +0000875 QualType RHSType, bool IsCompAssign) {
Richard Trieu7aa58f12011-09-02 20:58:51 +0000876 // The rules for this case are in C99 6.3.1.8
Richard Trieu9a52fbb2011-09-06 19:52:52 +0000877 int order = S.Context.getIntegerTypeOrder(LHSType, RHSType);
878 bool LHSSigned = LHSType->hasSignedIntegerRepresentation();
879 bool RHSSigned = RHSType->hasSignedIntegerRepresentation();
880 if (LHSSigned == RHSSigned) {
Richard Trieu7aa58f12011-09-02 20:58:51 +0000881 // Same signedness; use the higher-ranked type
882 if (order >= 0) {
Richard Trieu9a52fbb2011-09-06 19:52:52 +0000883 RHS = S.ImpCastExprToType(RHS.take(), LHSType, CK_IntegralCast);
884 return LHSType;
Richard Trieuba63ce62011-09-09 01:45:06 +0000885 } else if (!IsCompAssign)
Richard Trieu9a52fbb2011-09-06 19:52:52 +0000886 LHS = S.ImpCastExprToType(LHS.take(), RHSType, CK_IntegralCast);
887 return RHSType;
888 } else if (order != (LHSSigned ? 1 : -1)) {
Richard Trieu7aa58f12011-09-02 20:58:51 +0000889 // The unsigned type has greater than or equal rank to the
890 // signed type, so use the unsigned type
Richard Trieu9a52fbb2011-09-06 19:52:52 +0000891 if (RHSSigned) {
892 RHS = S.ImpCastExprToType(RHS.take(), LHSType, CK_IntegralCast);
893 return LHSType;
Richard Trieuba63ce62011-09-09 01:45:06 +0000894 } else if (!IsCompAssign)
Richard Trieu9a52fbb2011-09-06 19:52:52 +0000895 LHS = S.ImpCastExprToType(LHS.take(), RHSType, CK_IntegralCast);
896 return RHSType;
897 } else if (S.Context.getIntWidth(LHSType) != S.Context.getIntWidth(RHSType)) {
Richard Trieu7aa58f12011-09-02 20:58:51 +0000898 // The two types are different widths; if we are here, that
899 // means the signed type is larger than the unsigned type, so
900 // use the signed type.
Richard Trieu9a52fbb2011-09-06 19:52:52 +0000901 if (LHSSigned) {
902 RHS = S.ImpCastExprToType(RHS.take(), LHSType, CK_IntegralCast);
903 return LHSType;
Richard Trieuba63ce62011-09-09 01:45:06 +0000904 } else if (!IsCompAssign)
Richard Trieu9a52fbb2011-09-06 19:52:52 +0000905 LHS = S.ImpCastExprToType(LHS.take(), RHSType, CK_IntegralCast);
906 return RHSType;
Richard Trieu7aa58f12011-09-02 20:58:51 +0000907 } else {
908 // The signed type is higher-ranked than the unsigned type,
909 // but isn't actually any bigger (like unsigned int and long
910 // on most 32-bit systems). Use the unsigned type corresponding
911 // to the signed type.
912 QualType result =
Richard Trieu9a52fbb2011-09-06 19:52:52 +0000913 S.Context.getCorrespondingUnsignedType(LHSSigned ? LHSType : RHSType);
914 RHS = S.ImpCastExprToType(RHS.take(), result, CK_IntegralCast);
Richard Trieuba63ce62011-09-09 01:45:06 +0000915 if (!IsCompAssign)
Richard Trieu9a52fbb2011-09-06 19:52:52 +0000916 LHS = S.ImpCastExprToType(LHS.take(), result, CK_IntegralCast);
Richard Trieu7aa58f12011-09-02 20:58:51 +0000917 return result;
918 }
919}
920
Chris Lattner513165e2008-07-25 21:10:04 +0000921/// UsualArithmeticConversions - Performs various conversions that are common to
922/// binary operators (C99 6.3.1.8). If both operands aren't arithmetic, this
Mike Stump11289f42009-09-09 15:08:12 +0000923/// routine returns the first non-arithmetic type found. The client is
Chris Lattner513165e2008-07-25 21:10:04 +0000924/// responsible for emitting appropriate error diagnostics.
925/// FIXME: verify the conversion rules for "complex int" are consistent with
926/// GCC.
Richard Trieu9a52fbb2011-09-06 19:52:52 +0000927QualType Sema::UsualArithmeticConversions(ExprResult &LHS, ExprResult &RHS,
Richard Trieuba63ce62011-09-09 01:45:06 +0000928 bool IsCompAssign) {
929 if (!IsCompAssign) {
Richard Trieu9a52fbb2011-09-06 19:52:52 +0000930 LHS = UsualUnaryConversions(LHS.take());
931 if (LHS.isInvalid())
John Wiegley01296292011-04-08 18:41:53 +0000932 return QualType();
933 }
Eli Friedman8b7b1b12009-03-28 01:22:36 +0000934
Richard Trieu9a52fbb2011-09-06 19:52:52 +0000935 RHS = UsualUnaryConversions(RHS.take());
936 if (RHS.isInvalid())
John Wiegley01296292011-04-08 18:41:53 +0000937 return QualType();
Douglas Gregora11693b2008-11-12 17:17:38 +0000938
Mike Stump11289f42009-09-09 15:08:12 +0000939 // For conversion purposes, we ignore any qualifiers.
Chris Lattner513165e2008-07-25 21:10:04 +0000940 // For example, "const float" and "float" are equivalent.
Richard Trieu9a52fbb2011-09-06 19:52:52 +0000941 QualType LHSType =
942 Context.getCanonicalType(LHS.get()->getType()).getUnqualifiedType();
943 QualType RHSType =
944 Context.getCanonicalType(RHS.get()->getType()).getUnqualifiedType();
Douglas Gregora11693b2008-11-12 17:17:38 +0000945
946 // If both types are identical, no conversion is needed.
Richard Trieu9a52fbb2011-09-06 19:52:52 +0000947 if (LHSType == RHSType)
948 return LHSType;
Douglas Gregora11693b2008-11-12 17:17:38 +0000949
950 // If either side is a non-arithmetic type (e.g. a pointer), we are done.
951 // The caller can deal with this (e.g. pointer + int).
Richard Trieu9a52fbb2011-09-06 19:52:52 +0000952 if (!LHSType->isArithmeticType() || !RHSType->isArithmeticType())
953 return LHSType;
Douglas Gregora11693b2008-11-12 17:17:38 +0000954
John McCalld005ac92010-11-13 08:17:45 +0000955 // Apply unary and bitfield promotions to the LHS's type.
Richard Trieu9a52fbb2011-09-06 19:52:52 +0000956 QualType LHSUnpromotedType = LHSType;
957 if (LHSType->isPromotableIntegerType())
958 LHSType = Context.getPromotedIntegerType(LHSType);
959 QualType LHSBitfieldPromoteTy = Context.isPromotableBitField(LHS.get());
Douglas Gregord2c2d172009-05-02 00:36:19 +0000960 if (!LHSBitfieldPromoteTy.isNull())
Richard Trieu9a52fbb2011-09-06 19:52:52 +0000961 LHSType = LHSBitfieldPromoteTy;
Richard Trieuba63ce62011-09-09 01:45:06 +0000962 if (LHSType != LHSUnpromotedType && !IsCompAssign)
Richard Trieu9a52fbb2011-09-06 19:52:52 +0000963 LHS = ImpCastExprToType(LHS.take(), LHSType, CK_IntegralCast);
Douglas Gregord2c2d172009-05-02 00:36:19 +0000964
John McCalld005ac92010-11-13 08:17:45 +0000965 // If both types are identical, no conversion is needed.
Richard Trieu9a52fbb2011-09-06 19:52:52 +0000966 if (LHSType == RHSType)
967 return LHSType;
John McCalld005ac92010-11-13 08:17:45 +0000968
969 // At this point, we have two different arithmetic types.
970
971 // Handle complex types first (C99 6.3.1.8p1).
Richard Trieu9a52fbb2011-09-06 19:52:52 +0000972 if (LHSType->isComplexType() || RHSType->isComplexType())
973 return handleComplexFloatConversion(*this, LHS, RHS, LHSType, RHSType,
Richard Trieuba63ce62011-09-09 01:45:06 +0000974 IsCompAssign);
John McCalld005ac92010-11-13 08:17:45 +0000975
976 // Now handle "real" floating types (i.e. float, double, long double).
Richard Trieu9a52fbb2011-09-06 19:52:52 +0000977 if (LHSType->isRealFloatingType() || RHSType->isRealFloatingType())
978 return handleFloatConversion(*this, LHS, RHS, LHSType, RHSType,
Richard Trieuba63ce62011-09-09 01:45:06 +0000979 IsCompAssign);
John McCalld005ac92010-11-13 08:17:45 +0000980
981 // Handle GCC complex int extension.
Richard Trieu9a52fbb2011-09-06 19:52:52 +0000982 if (LHSType->isComplexIntegerType() || RHSType->isComplexIntegerType())
Benjamin Kramer499c68b2011-09-06 19:57:14 +0000983 return handleComplexIntConversion(*this, LHS, RHS, LHSType, RHSType,
Richard Trieuba63ce62011-09-09 01:45:06 +0000984 IsCompAssign);
John McCalld005ac92010-11-13 08:17:45 +0000985
986 // Finally, we have two differing integer types.
Richard Trieu9a52fbb2011-09-06 19:52:52 +0000987 return handleIntegerConversion(*this, LHS, RHS, LHSType, RHSType,
Richard Trieuba63ce62011-09-09 01:45:06 +0000988 IsCompAssign);
Douglas Gregora11693b2008-11-12 17:17:38 +0000989}
990
Chris Lattner513165e2008-07-25 21:10:04 +0000991//===----------------------------------------------------------------------===//
992// Semantic Analysis for various Expression Types
993//===----------------------------------------------------------------------===//
994
995
Peter Collingbourne91147592011-04-15 00:35:48 +0000996ExprResult
997Sema::ActOnGenericSelectionExpr(SourceLocation KeyLoc,
998 SourceLocation DefaultLoc,
999 SourceLocation RParenLoc,
1000 Expr *ControllingExpr,
Richard Trieuba63ce62011-09-09 01:45:06 +00001001 MultiTypeArg ArgTypes,
1002 MultiExprArg ArgExprs) {
1003 unsigned NumAssocs = ArgTypes.size();
1004 assert(NumAssocs == ArgExprs.size());
Peter Collingbourne91147592011-04-15 00:35:48 +00001005
Richard Trieuba63ce62011-09-09 01:45:06 +00001006 ParsedType *ParsedTypes = ArgTypes.release();
1007 Expr **Exprs = ArgExprs.release();
Peter Collingbourne91147592011-04-15 00:35:48 +00001008
1009 TypeSourceInfo **Types = new TypeSourceInfo*[NumAssocs];
1010 for (unsigned i = 0; i < NumAssocs; ++i) {
1011 if (ParsedTypes[i])
1012 (void) GetTypeFromParser(ParsedTypes[i], &Types[i]);
1013 else
1014 Types[i] = 0;
1015 }
1016
1017 ExprResult ER = CreateGenericSelectionExpr(KeyLoc, DefaultLoc, RParenLoc,
1018 ControllingExpr, Types, Exprs,
1019 NumAssocs);
Benjamin Kramer34623762011-04-15 11:21:57 +00001020 delete [] Types;
Peter Collingbourne91147592011-04-15 00:35:48 +00001021 return ER;
1022}
1023
1024ExprResult
1025Sema::CreateGenericSelectionExpr(SourceLocation KeyLoc,
1026 SourceLocation DefaultLoc,
1027 SourceLocation RParenLoc,
1028 Expr *ControllingExpr,
1029 TypeSourceInfo **Types,
1030 Expr **Exprs,
1031 unsigned NumAssocs) {
1032 bool TypeErrorFound = false,
1033 IsResultDependent = ControllingExpr->isTypeDependent(),
1034 ContainsUnexpandedParameterPack
1035 = ControllingExpr->containsUnexpandedParameterPack();
1036
1037 for (unsigned i = 0; i < NumAssocs; ++i) {
1038 if (Exprs[i]->containsUnexpandedParameterPack())
1039 ContainsUnexpandedParameterPack = true;
1040
1041 if (Types[i]) {
1042 if (Types[i]->getType()->containsUnexpandedParameterPack())
1043 ContainsUnexpandedParameterPack = true;
1044
1045 if (Types[i]->getType()->isDependentType()) {
1046 IsResultDependent = true;
1047 } else {
Benjamin Kramere56f3932011-12-23 17:00:35 +00001048 // C11 6.5.1.1p2 "The type name in a generic association shall specify a
Peter Collingbourne91147592011-04-15 00:35:48 +00001049 // complete object type other than a variably modified type."
1050 unsigned D = 0;
1051 if (Types[i]->getType()->isIncompleteType())
1052 D = diag::err_assoc_type_incomplete;
1053 else if (!Types[i]->getType()->isObjectType())
1054 D = diag::err_assoc_type_nonobject;
1055 else if (Types[i]->getType()->isVariablyModifiedType())
1056 D = diag::err_assoc_type_variably_modified;
1057
1058 if (D != 0) {
1059 Diag(Types[i]->getTypeLoc().getBeginLoc(), D)
1060 << Types[i]->getTypeLoc().getSourceRange()
1061 << Types[i]->getType();
1062 TypeErrorFound = true;
1063 }
1064
Benjamin Kramere56f3932011-12-23 17:00:35 +00001065 // C11 6.5.1.1p2 "No two generic associations in the same generic
Peter Collingbourne91147592011-04-15 00:35:48 +00001066 // selection shall specify compatible types."
1067 for (unsigned j = i+1; j < NumAssocs; ++j)
1068 if (Types[j] && !Types[j]->getType()->isDependentType() &&
1069 Context.typesAreCompatible(Types[i]->getType(),
1070 Types[j]->getType())) {
1071 Diag(Types[j]->getTypeLoc().getBeginLoc(),
1072 diag::err_assoc_compatible_types)
1073 << Types[j]->getTypeLoc().getSourceRange()
1074 << Types[j]->getType()
1075 << Types[i]->getType();
1076 Diag(Types[i]->getTypeLoc().getBeginLoc(),
1077 diag::note_compat_assoc)
1078 << Types[i]->getTypeLoc().getSourceRange()
1079 << Types[i]->getType();
1080 TypeErrorFound = true;
1081 }
1082 }
1083 }
1084 }
1085 if (TypeErrorFound)
1086 return ExprError();
1087
1088 // If we determined that the generic selection is result-dependent, don't
1089 // try to compute the result expression.
1090 if (IsResultDependent)
1091 return Owned(new (Context) GenericSelectionExpr(
1092 Context, KeyLoc, ControllingExpr,
1093 Types, Exprs, NumAssocs, DefaultLoc,
1094 RParenLoc, ContainsUnexpandedParameterPack));
1095
Chris Lattner0e62c1c2011-07-23 10:55:15 +00001096 SmallVector<unsigned, 1> CompatIndices;
Peter Collingbourne91147592011-04-15 00:35:48 +00001097 unsigned DefaultIndex = -1U;
1098 for (unsigned i = 0; i < NumAssocs; ++i) {
1099 if (!Types[i])
1100 DefaultIndex = i;
1101 else if (Context.typesAreCompatible(ControllingExpr->getType(),
1102 Types[i]->getType()))
1103 CompatIndices.push_back(i);
1104 }
1105
Benjamin Kramere56f3932011-12-23 17:00:35 +00001106 // C11 6.5.1.1p2 "The controlling expression of a generic selection shall have
Peter Collingbourne91147592011-04-15 00:35:48 +00001107 // type compatible with at most one of the types named in its generic
1108 // association list."
1109 if (CompatIndices.size() > 1) {
1110 // We strip parens here because the controlling expression is typically
1111 // parenthesized in macro definitions.
1112 ControllingExpr = ControllingExpr->IgnoreParens();
1113 Diag(ControllingExpr->getLocStart(), diag::err_generic_sel_multi_match)
1114 << ControllingExpr->getSourceRange() << ControllingExpr->getType()
1115 << (unsigned) CompatIndices.size();
Chris Lattner0e62c1c2011-07-23 10:55:15 +00001116 for (SmallVector<unsigned, 1>::iterator I = CompatIndices.begin(),
Peter Collingbourne91147592011-04-15 00:35:48 +00001117 E = CompatIndices.end(); I != E; ++I) {
1118 Diag(Types[*I]->getTypeLoc().getBeginLoc(),
1119 diag::note_compat_assoc)
1120 << Types[*I]->getTypeLoc().getSourceRange()
1121 << Types[*I]->getType();
1122 }
1123 return ExprError();
1124 }
1125
Benjamin Kramere56f3932011-12-23 17:00:35 +00001126 // C11 6.5.1.1p2 "If a generic selection has no default generic association,
Peter Collingbourne91147592011-04-15 00:35:48 +00001127 // its controlling expression shall have type compatible with exactly one of
1128 // the types named in its generic association list."
1129 if (DefaultIndex == -1U && CompatIndices.size() == 0) {
1130 // We strip parens here because the controlling expression is typically
1131 // parenthesized in macro definitions.
1132 ControllingExpr = ControllingExpr->IgnoreParens();
1133 Diag(ControllingExpr->getLocStart(), diag::err_generic_sel_no_match)
1134 << ControllingExpr->getSourceRange() << ControllingExpr->getType();
1135 return ExprError();
1136 }
1137
Benjamin Kramere56f3932011-12-23 17:00:35 +00001138 // C11 6.5.1.1p3 "If a generic selection has a generic association with a
Peter Collingbourne91147592011-04-15 00:35:48 +00001139 // type name that is compatible with the type of the controlling expression,
1140 // then the result expression of the generic selection is the expression
1141 // in that generic association. Otherwise, the result expression of the
1142 // generic selection is the expression in the default generic association."
1143 unsigned ResultIndex =
1144 CompatIndices.size() ? CompatIndices[0] : DefaultIndex;
1145
1146 return Owned(new (Context) GenericSelectionExpr(
1147 Context, KeyLoc, ControllingExpr,
1148 Types, Exprs, NumAssocs, DefaultLoc,
1149 RParenLoc, ContainsUnexpandedParameterPack,
1150 ResultIndex));
1151}
1152
Richard Smith75b67d62012-03-08 01:34:56 +00001153/// getUDSuffixLoc - Create a SourceLocation for a ud-suffix, given the
1154/// location of the token and the offset of the ud-suffix within it.
1155static SourceLocation getUDSuffixLoc(Sema &S, SourceLocation TokLoc,
1156 unsigned Offset) {
1157 return Lexer::AdvanceToTokenCharacter(TokLoc, Offset, S.getSourceManager(),
David Blaikiebbafb8a2012-03-11 07:00:24 +00001158 S.getLangOpts());
Richard Smith75b67d62012-03-08 01:34:56 +00001159}
1160
Richard Smithbcc22fc2012-03-09 08:00:36 +00001161/// BuildCookedLiteralOperatorCall - A user-defined literal was found. Look up
1162/// the corresponding cooked (non-raw) literal operator, and build a call to it.
1163static ExprResult BuildCookedLiteralOperatorCall(Sema &S, Scope *Scope,
1164 IdentifierInfo *UDSuffix,
1165 SourceLocation UDSuffixLoc,
1166 ArrayRef<Expr*> Args,
1167 SourceLocation LitEndLoc) {
1168 assert(Args.size() <= 2 && "too many arguments for literal operator");
1169
1170 QualType ArgTy[2];
1171 for (unsigned ArgIdx = 0; ArgIdx != Args.size(); ++ArgIdx) {
1172 ArgTy[ArgIdx] = Args[ArgIdx]->getType();
1173 if (ArgTy[ArgIdx]->isArrayType())
1174 ArgTy[ArgIdx] = S.Context.getArrayDecayedType(ArgTy[ArgIdx]);
1175 }
1176
1177 DeclarationName OpName =
1178 S.Context.DeclarationNames.getCXXLiteralOperatorName(UDSuffix);
1179 DeclarationNameInfo OpNameInfo(OpName, UDSuffixLoc);
1180 OpNameInfo.setCXXLiteralOperatorNameLoc(UDSuffixLoc);
1181
1182 LookupResult R(S, OpName, UDSuffixLoc, Sema::LookupOrdinaryName);
1183 if (S.LookupLiteralOperator(Scope, R, llvm::makeArrayRef(ArgTy, Args.size()),
1184 /*AllowRawAndTemplate*/false) == Sema::LOLR_Error)
1185 return ExprError();
1186
1187 return S.BuildLiteralOperatorCall(R, OpNameInfo, Args, LitEndLoc);
1188}
1189
Steve Naroff83895f72007-09-16 03:34:24 +00001190/// ActOnStringLiteral - The specified tokens were lexed as pasted string
Chris Lattner5b183d82006-11-10 05:03:26 +00001191/// fragments (e.g. "foo" "bar" L"baz"). The result string has to handle string
1192/// concatenation ([C99 5.1.1.2, translation phase #6]), so it may come from
1193/// multiple tokens. However, the common case is that StringToks points to one
1194/// string.
Sebastian Redlffbcf962009-01-18 18:53:16 +00001195///
John McCalldadc5752010-08-24 06:29:42 +00001196ExprResult
Richard Smithbcc22fc2012-03-09 08:00:36 +00001197Sema::ActOnStringLiteral(const Token *StringToks, unsigned NumStringToks,
1198 Scope *UDLScope) {
Chris Lattner5b183d82006-11-10 05:03:26 +00001199 assert(NumStringToks && "Must have at least one string!");
1200
Chris Lattner8a24e582009-01-16 18:51:42 +00001201 StringLiteralParser Literal(StringToks, NumStringToks, PP);
Steve Naroff4f88b312007-03-13 22:37:02 +00001202 if (Literal.hadError)
Sebastian Redlffbcf962009-01-18 18:53:16 +00001203 return ExprError();
Chris Lattner5b183d82006-11-10 05:03:26 +00001204
Chris Lattner0e62c1c2011-07-23 10:55:15 +00001205 SmallVector<SourceLocation, 4> StringTokLocs;
Chris Lattner5b183d82006-11-10 05:03:26 +00001206 for (unsigned i = 0; i != NumStringToks; ++i)
1207 StringTokLocs.push_back(StringToks[i].getLocation());
Chris Lattner36fc8792008-02-11 00:02:17 +00001208
Chris Lattner36fc8792008-02-11 00:02:17 +00001209 QualType StrTy = Context.CharTy;
Douglas Gregorfb65e592011-07-27 05:40:30 +00001210 if (Literal.isWide())
Anders Carlsson6b06e182011-04-06 18:42:48 +00001211 StrTy = Context.getWCharType();
Douglas Gregorfb65e592011-07-27 05:40:30 +00001212 else if (Literal.isUTF16())
1213 StrTy = Context.Char16Ty;
1214 else if (Literal.isUTF32())
1215 StrTy = Context.Char32Ty;
Eli Friedmanfcec6302011-11-01 02:23:42 +00001216 else if (Literal.isPascal())
Anders Carlsson6b06e182011-04-06 18:42:48 +00001217 StrTy = Context.UnsignedCharTy;
Douglas Gregoraa1e21d2008-09-12 00:47:35 +00001218
Douglas Gregorfb65e592011-07-27 05:40:30 +00001219 StringLiteral::StringKind Kind = StringLiteral::Ascii;
1220 if (Literal.isWide())
1221 Kind = StringLiteral::Wide;
1222 else if (Literal.isUTF8())
1223 Kind = StringLiteral::UTF8;
1224 else if (Literal.isUTF16())
1225 Kind = StringLiteral::UTF16;
1226 else if (Literal.isUTF32())
1227 Kind = StringLiteral::UTF32;
1228
Douglas Gregoraa1e21d2008-09-12 00:47:35 +00001229 // A C++ string literal has a const-qualified element type (C++ 2.13.4p1).
David Blaikiebbafb8a2012-03-11 07:00:24 +00001230 if (getLangOpts().CPlusPlus || getLangOpts().ConstStrings)
Douglas Gregoraa1e21d2008-09-12 00:47:35 +00001231 StrTy.addConst();
Sebastian Redlffbcf962009-01-18 18:53:16 +00001232
Chris Lattner36fc8792008-02-11 00:02:17 +00001233 // Get an array type for the string, according to C99 6.4.5. This includes
1234 // the nul terminator character as well as the string length for pascal
1235 // strings.
1236 StrTy = Context.getConstantArrayType(StrTy,
Chris Lattnerd42c29f2009-02-26 23:01:51 +00001237 llvm::APInt(32, Literal.GetNumStringChars()+1),
Chris Lattner36fc8792008-02-11 00:02:17 +00001238 ArrayType::Normal, 0);
Mike Stump11289f42009-09-09 15:08:12 +00001239
Chris Lattner5b183d82006-11-10 05:03:26 +00001240 // Pass &StringTokLocs[0], StringTokLocs.size() to factory!
Richard Smithc67fdd42012-03-07 08:35:16 +00001241 StringLiteral *Lit = StringLiteral::Create(Context, Literal.GetString(),
1242 Kind, Literal.Pascal, StrTy,
1243 &StringTokLocs[0],
1244 StringTokLocs.size());
1245 if (Literal.getUDSuffix().empty())
1246 return Owned(Lit);
1247
1248 // We're building a user-defined literal.
1249 IdentifierInfo *UDSuffix = &Context.Idents.get(Literal.getUDSuffix());
Richard Smith75b67d62012-03-08 01:34:56 +00001250 SourceLocation UDSuffixLoc =
1251 getUDSuffixLoc(*this, StringTokLocs[Literal.getUDSuffixToken()],
1252 Literal.getUDSuffixOffset());
Richard Smithc67fdd42012-03-07 08:35:16 +00001253
Richard Smithbcc22fc2012-03-09 08:00:36 +00001254 // Make sure we're allowed user-defined literals here.
1255 if (!UDLScope)
1256 return ExprError(Diag(UDSuffixLoc, diag::err_invalid_string_udl));
1257
Richard Smithc67fdd42012-03-07 08:35:16 +00001258 // C++11 [lex.ext]p5: The literal L is treated as a call of the form
1259 // operator "" X (str, len)
1260 QualType SizeType = Context.getSizeType();
1261 llvm::APInt Len(Context.getIntWidth(SizeType), Literal.GetNumStringChars());
1262 IntegerLiteral *LenArg = IntegerLiteral::Create(Context, Len, SizeType,
1263 StringTokLocs[0]);
1264 Expr *Args[] = { Lit, LenArg };
Richard Smithbcc22fc2012-03-09 08:00:36 +00001265 return BuildCookedLiteralOperatorCall(*this, UDLScope, UDSuffix, UDSuffixLoc,
1266 Args, StringTokLocs.back());
Chris Lattner5b183d82006-11-10 05:03:26 +00001267}
1268
John McCalldadc5752010-08-24 06:29:42 +00001269ExprResult
John McCall7decc9e2010-11-18 06:31:45 +00001270Sema::BuildDeclRefExpr(ValueDecl *D, QualType Ty, ExprValueKind VK,
John McCallf4cd4f92011-02-09 01:13:10 +00001271 SourceLocation Loc,
1272 const CXXScopeSpec *SS) {
Abramo Bagnarad6d2f182010-08-11 22:01:17 +00001273 DeclarationNameInfo NameInfo(D->getDeclName(), Loc);
John McCall7decc9e2010-11-18 06:31:45 +00001274 return BuildDeclRefExpr(D, Ty, VK, NameInfo, SS);
Abramo Bagnarad6d2f182010-08-11 22:01:17 +00001275}
1276
John McCallf4cd4f92011-02-09 01:13:10 +00001277/// BuildDeclRefExpr - Build an expression that references a
1278/// declaration that does not require a closure capture.
John McCalldadc5752010-08-24 06:29:42 +00001279ExprResult
John McCallf4cd4f92011-02-09 01:13:10 +00001280Sema::BuildDeclRefExpr(ValueDecl *D, QualType Ty, ExprValueKind VK,
Abramo Bagnarad6d2f182010-08-11 22:01:17 +00001281 const DeclarationNameInfo &NameInfo,
1282 const CXXScopeSpec *SS) {
David Blaikiebbafb8a2012-03-11 07:00:24 +00001283 if (getLangOpts().CUDA)
Peter Collingbourne7277fe82011-10-02 23:49:40 +00001284 if (const FunctionDecl *Caller = dyn_cast<FunctionDecl>(CurContext))
1285 if (const FunctionDecl *Callee = dyn_cast<FunctionDecl>(D)) {
1286 CUDAFunctionTarget CallerTarget = IdentifyCUDATarget(Caller),
1287 CalleeTarget = IdentifyCUDATarget(Callee);
1288 if (CheckCUDATarget(CallerTarget, CalleeTarget)) {
1289 Diag(NameInfo.getLoc(), diag::err_ref_bad_target)
1290 << CalleeTarget << D->getIdentifier() << CallerTarget;
1291 Diag(D->getLocation(), diag::note_previous_decl)
1292 << D->getIdentifier();
1293 return ExprError();
1294 }
1295 }
1296
John McCall113bee02012-03-10 09:33:50 +00001297 bool refersToEnclosingScope =
1298 (CurContext != D->getDeclContext() &&
1299 D->getDeclContext()->isFunctionOrMethod());
1300
Eli Friedmanfa0df832012-02-02 03:46:19 +00001301 DeclRefExpr *E = DeclRefExpr::Create(Context,
1302 SS ? SS->getWithLocInContext(Context)
1303 : NestedNameSpecifierLoc(),
John McCall113bee02012-03-10 09:33:50 +00001304 SourceLocation(),
1305 D, refersToEnclosingScope,
1306 NameInfo, Ty, VK);
Mike Stump11289f42009-09-09 15:08:12 +00001307
Eli Friedmanfa0df832012-02-02 03:46:19 +00001308 MarkDeclRefReferenced(E);
John McCall086a4642010-11-24 05:12:34 +00001309
1310 // Just in case we're building an illegal pointer-to-member.
Richard Smithcaf33902011-10-10 18:28:20 +00001311 FieldDecl *FD = dyn_cast<FieldDecl>(D);
1312 if (FD && FD->isBitField())
John McCall086a4642010-11-24 05:12:34 +00001313 E->setObjectKind(OK_BitField);
1314
1315 return Owned(E);
Douglas Gregorc7acfdf2009-01-06 05:10:23 +00001316}
1317
Abramo Bagnarad6d2f182010-08-11 22:01:17 +00001318/// Decomposes the given name into a DeclarationNameInfo, its location, and
John McCall10eae182009-11-30 22:42:35 +00001319/// possibly a list of template arguments.
1320///
1321/// If this produces template arguments, it is permitted to call
1322/// DecomposeTemplateName.
1323///
1324/// This actually loses a lot of source location information for
1325/// non-standard name kinds; we should consider preserving that in
1326/// some way.
Richard Trieucfc491d2011-08-02 04:35:43 +00001327void
1328Sema::DecomposeUnqualifiedId(const UnqualifiedId &Id,
1329 TemplateArgumentListInfo &Buffer,
1330 DeclarationNameInfo &NameInfo,
1331 const TemplateArgumentListInfo *&TemplateArgs) {
John McCall10eae182009-11-30 22:42:35 +00001332 if (Id.getKind() == UnqualifiedId::IK_TemplateId) {
1333 Buffer.setLAngleLoc(Id.TemplateId->LAngleLoc);
1334 Buffer.setRAngleLoc(Id.TemplateId->RAngleLoc);
1335
Douglas Gregor5476205b2011-06-23 00:49:38 +00001336 ASTTemplateArgsPtr TemplateArgsPtr(*this,
John McCall10eae182009-11-30 22:42:35 +00001337 Id.TemplateId->getTemplateArgs(),
1338 Id.TemplateId->NumArgs);
Douglas Gregor5476205b2011-06-23 00:49:38 +00001339 translateTemplateArguments(TemplateArgsPtr, Buffer);
John McCall10eae182009-11-30 22:42:35 +00001340 TemplateArgsPtr.release();
1341
John McCall3e56fd42010-08-23 07:28:44 +00001342 TemplateName TName = Id.TemplateId->Template.get();
Abramo Bagnarad6d2f182010-08-11 22:01:17 +00001343 SourceLocation TNameLoc = Id.TemplateId->TemplateNameLoc;
Douglas Gregor5476205b2011-06-23 00:49:38 +00001344 NameInfo = Context.getNameForTemplate(TName, TNameLoc);
John McCall10eae182009-11-30 22:42:35 +00001345 TemplateArgs = &Buffer;
1346 } else {
Douglas Gregor5476205b2011-06-23 00:49:38 +00001347 NameInfo = GetNameFromUnqualifiedId(Id);
John McCall10eae182009-11-30 22:42:35 +00001348 TemplateArgs = 0;
1349 }
1350}
1351
John McCalld681c392009-12-16 08:11:27 +00001352/// Diagnose an empty lookup.
1353///
1354/// \return false if new lookup candidates were found
Nick Lewyckyc96c37f2010-07-06 19:51:49 +00001355bool Sema::DiagnoseEmptyLookup(Scope *S, CXXScopeSpec &SS, LookupResult &R,
Kaelyn Uhrain79d01c12012-01-18 05:58:54 +00001356 CorrectionCandidateCallback &CCC,
Kaelyn Uhrain42830922011-08-05 00:09:52 +00001357 TemplateArgumentListInfo *ExplicitTemplateArgs,
Ahmed Charlesb24b9aa2012-02-25 11:00:22 +00001358 llvm::ArrayRef<Expr *> Args) {
John McCalld681c392009-12-16 08:11:27 +00001359 DeclarationName Name = R.getLookupName();
1360
John McCalld681c392009-12-16 08:11:27 +00001361 unsigned diagnostic = diag::err_undeclared_var_use;
Douglas Gregor598b08f2009-12-31 05:20:13 +00001362 unsigned diagnostic_suggest = diag::err_undeclared_var_use_suggest;
John McCalld681c392009-12-16 08:11:27 +00001363 if (Name.getNameKind() == DeclarationName::CXXOperatorName ||
1364 Name.getNameKind() == DeclarationName::CXXLiteralOperatorName ||
Douglas Gregor598b08f2009-12-31 05:20:13 +00001365 Name.getNameKind() == DeclarationName::CXXConversionFunctionName) {
John McCalld681c392009-12-16 08:11:27 +00001366 diagnostic = diag::err_undeclared_use;
Douglas Gregor598b08f2009-12-31 05:20:13 +00001367 diagnostic_suggest = diag::err_undeclared_use_suggest;
1368 }
John McCalld681c392009-12-16 08:11:27 +00001369
Douglas Gregor598b08f2009-12-31 05:20:13 +00001370 // If the original lookup was an unqualified lookup, fake an
1371 // unqualified lookup. This is useful when (for example) the
1372 // original lookup would not have found something because it was a
1373 // dependent name.
Francois Pichetde232cb2011-11-25 01:10:54 +00001374 DeclContext *DC = SS.isEmpty() ? CurContext : 0;
1375 while (DC) {
John McCalld681c392009-12-16 08:11:27 +00001376 if (isa<CXXRecordDecl>(DC)) {
1377 LookupQualifiedName(R, DC);
1378
1379 if (!R.empty()) {
1380 // Don't give errors about ambiguities in this lookup.
1381 R.suppressDiagnostics();
1382
Francois Pichet857f9d62011-11-17 03:44:24 +00001383 // During a default argument instantiation the CurContext points
1384 // to a CXXMethodDecl; but we can't apply a this-> fixit inside a
1385 // function parameter list, hence add an explicit check.
1386 bool isDefaultArgument = !ActiveTemplateInstantiations.empty() &&
1387 ActiveTemplateInstantiations.back().Kind ==
1388 ActiveTemplateInstantiation::DefaultFunctionArgumentInstantiation;
John McCalld681c392009-12-16 08:11:27 +00001389 CXXMethodDecl *CurMethod = dyn_cast<CXXMethodDecl>(CurContext);
1390 bool isInstance = CurMethod &&
1391 CurMethod->isInstance() &&
Francois Pichet857f9d62011-11-17 03:44:24 +00001392 DC == CurMethod->getParent() && !isDefaultArgument;
1393
John McCalld681c392009-12-16 08:11:27 +00001394
1395 // Give a code modification hint to insert 'this->'.
1396 // TODO: fixit for inserting 'Base<T>::' in the other cases.
1397 // Actually quite difficult!
Nick Lewyckyc96c37f2010-07-06 19:51:49 +00001398 if (isInstance) {
Nick Lewyckyc96c37f2010-07-06 19:51:49 +00001399 UnresolvedLookupExpr *ULE = cast<UnresolvedLookupExpr>(
1400 CallsUndergoingInstantiation.back()->getCallee());
Nick Lewyckyfe712382010-08-20 20:54:15 +00001401 CXXMethodDecl *DepMethod = cast_or_null<CXXMethodDecl>(
Nick Lewyckyc96c37f2010-07-06 19:51:49 +00001402 CurMethod->getInstantiatedFromMemberFunction());
Eli Friedman04831922010-08-22 01:00:03 +00001403 if (DepMethod) {
David Blaikiebbafb8a2012-03-11 07:00:24 +00001404 if (getLangOpts().MicrosoftMode)
Francois Pichetbcf64712011-09-07 00:14:57 +00001405 diagnostic = diag::warn_found_via_dependent_bases_lookup;
Nick Lewyckyfe712382010-08-20 20:54:15 +00001406 Diag(R.getNameLoc(), diagnostic) << Name
1407 << FixItHint::CreateInsertion(R.getNameLoc(), "this->");
1408 QualType DepThisType = DepMethod->getThisType(Context);
Eli Friedman73a04092012-01-07 04:59:52 +00001409 CheckCXXThisCapture(R.getNameLoc());
Nick Lewyckyfe712382010-08-20 20:54:15 +00001410 CXXThisExpr *DepThis = new (Context) CXXThisExpr(
1411 R.getNameLoc(), DepThisType, false);
1412 TemplateArgumentListInfo TList;
1413 if (ULE->hasExplicitTemplateArgs())
1414 ULE->copyTemplateArgumentsInto(TList);
Douglas Gregore16af532011-02-28 18:50:33 +00001415
Douglas Gregore16af532011-02-28 18:50:33 +00001416 CXXScopeSpec SS;
Douglas Gregor0da1d432011-02-28 20:01:57 +00001417 SS.Adopt(ULE->getQualifierLoc());
Nick Lewyckyfe712382010-08-20 20:54:15 +00001418 CXXDependentScopeMemberExpr *DepExpr =
1419 CXXDependentScopeMemberExpr::Create(
1420 Context, DepThis, DepThisType, true, SourceLocation(),
Abramo Bagnara7945c982012-01-27 09:46:47 +00001421 SS.getWithLocInContext(Context),
1422 ULE->getTemplateKeywordLoc(), 0,
Francois Pichet4391c752011-09-04 23:00:48 +00001423 R.getLookupNameInfo(),
1424 ULE->hasExplicitTemplateArgs() ? &TList : 0);
Nick Lewyckyfe712382010-08-20 20:54:15 +00001425 CallsUndergoingInstantiation.back()->setCallee(DepExpr);
Eli Friedman04831922010-08-22 01:00:03 +00001426 } else {
Nick Lewyckyfe712382010-08-20 20:54:15 +00001427 // FIXME: we should be able to handle this case too. It is correct
1428 // to add this-> here. This is a workaround for PR7947.
1429 Diag(R.getNameLoc(), diagnostic) << Name;
Eli Friedman04831922010-08-22 01:00:03 +00001430 }
Nick Lewyckyc96c37f2010-07-06 19:51:49 +00001431 } else {
David Blaikiebbafb8a2012-03-11 07:00:24 +00001432 if (getLangOpts().MicrosoftMode)
Francois Pichet78286b22011-11-15 23:33:34 +00001433 diagnostic = diag::warn_found_via_dependent_bases_lookup;
John McCalld681c392009-12-16 08:11:27 +00001434 Diag(R.getNameLoc(), diagnostic) << Name;
Nick Lewyckyc96c37f2010-07-06 19:51:49 +00001435 }
John McCalld681c392009-12-16 08:11:27 +00001436
1437 // Do we really want to note all of these?
1438 for (LookupResult::iterator I = R.begin(), E = R.end(); I != E; ++I)
1439 Diag((*I)->getLocation(), diag::note_dependent_var_use);
1440
Francois Pichet857f9d62011-11-17 03:44:24 +00001441 // Return true if we are inside a default argument instantiation
1442 // and the found name refers to an instance member function, otherwise
1443 // the function calling DiagnoseEmptyLookup will try to create an
1444 // implicit member call and this is wrong for default argument.
1445 if (isDefaultArgument && ((*R.begin())->isCXXInstanceMember())) {
1446 Diag(R.getNameLoc(), diag::err_member_call_without_object);
1447 return true;
1448 }
1449
John McCalld681c392009-12-16 08:11:27 +00001450 // Tell the callee to try to recover.
1451 return false;
1452 }
Douglas Gregor86b8d9f2010-08-09 22:38:14 +00001453
1454 R.clear();
John McCalld681c392009-12-16 08:11:27 +00001455 }
Francois Pichetde232cb2011-11-25 01:10:54 +00001456
1457 // In Microsoft mode, if we are performing lookup from within a friend
1458 // function definition declared at class scope then we must set
1459 // DC to the lexical parent to be able to search into the parent
1460 // class.
David Blaikiebbafb8a2012-03-11 07:00:24 +00001461 if (getLangOpts().MicrosoftMode && isa<FunctionDecl>(DC) &&
Francois Pichetde232cb2011-11-25 01:10:54 +00001462 cast<FunctionDecl>(DC)->getFriendObjectKind() &&
1463 DC->getLexicalParent()->isRecord())
1464 DC = DC->getLexicalParent();
1465 else
1466 DC = DC->getParent();
John McCalld681c392009-12-16 08:11:27 +00001467 }
1468
Douglas Gregor598b08f2009-12-31 05:20:13 +00001469 // We didn't find anything, so try to correct for a typo.
Douglas Gregorc2fa1692011-06-28 16:20:02 +00001470 TypoCorrection Corrected;
1471 if (S && (Corrected = CorrectTypo(R.getLookupNameInfo(), R.getLookupKind(),
Kaelyn Uhrain4e8942c2012-01-31 23:49:25 +00001472 S, &SS, CCC))) {
David Blaikiebbafb8a2012-03-11 07:00:24 +00001473 std::string CorrectedStr(Corrected.getAsString(getLangOpts()));
1474 std::string CorrectedQuotedStr(Corrected.getQuoted(getLangOpts()));
Douglas Gregorc2fa1692011-06-28 16:20:02 +00001475 R.setLookupName(Corrected.getCorrection());
1476
Hans Wennborg38198de2011-07-12 08:45:31 +00001477 if (NamedDecl *ND = Corrected.getCorrectionDecl()) {
Kaelyn Uhrainacbdc572011-08-03 20:36:05 +00001478 if (Corrected.isOverloaded()) {
1479 OverloadCandidateSet OCS(R.getNameLoc());
1480 OverloadCandidateSet::iterator Best;
1481 for (TypoCorrection::decl_iterator CD = Corrected.begin(),
1482 CDEnd = Corrected.end();
1483 CD != CDEnd; ++CD) {
Kaelyn Uhrain62422202011-08-08 17:35:31 +00001484 if (FunctionTemplateDecl *FTD =
Kaelyn Uhrain42830922011-08-05 00:09:52 +00001485 dyn_cast<FunctionTemplateDecl>(*CD))
1486 AddTemplateOverloadCandidate(
1487 FTD, DeclAccessPair::make(FTD, AS_none), ExplicitTemplateArgs,
Ahmed Charlesb24b9aa2012-02-25 11:00:22 +00001488 Args, OCS);
Kaelyn Uhrain62422202011-08-08 17:35:31 +00001489 else if (FunctionDecl *FD = dyn_cast<FunctionDecl>(*CD))
1490 if (!ExplicitTemplateArgs || ExplicitTemplateArgs->size() == 0)
1491 AddOverloadCandidate(FD, DeclAccessPair::make(FD, AS_none),
Ahmed Charlesb24b9aa2012-02-25 11:00:22 +00001492 Args, OCS);
Kaelyn Uhrainacbdc572011-08-03 20:36:05 +00001493 }
1494 switch (OCS.BestViableFunction(*this, R.getNameLoc(), Best)) {
1495 case OR_Success:
1496 ND = Best->Function;
1497 break;
1498 default:
Kaelyn Uhrainea350182011-08-04 23:30:54 +00001499 break;
Kaelyn Uhrainacbdc572011-08-03 20:36:05 +00001500 }
1501 }
Douglas Gregorc2fa1692011-06-28 16:20:02 +00001502 R.addDecl(ND);
1503 if (isa<ValueDecl>(ND) || isa<FunctionTemplateDecl>(ND)) {
Douglas Gregor280e1ee2010-04-14 20:04:41 +00001504 if (SS.isEmpty())
Douglas Gregorc2fa1692011-06-28 16:20:02 +00001505 Diag(R.getNameLoc(), diagnostic_suggest) << Name << CorrectedQuotedStr
1506 << FixItHint::CreateReplacement(R.getNameLoc(), CorrectedStr);
Douglas Gregor280e1ee2010-04-14 20:04:41 +00001507 else
1508 Diag(R.getNameLoc(), diag::err_no_member_suggest)
Douglas Gregorc2fa1692011-06-28 16:20:02 +00001509 << Name << computeDeclContext(SS, false) << CorrectedQuotedStr
Douglas Gregor280e1ee2010-04-14 20:04:41 +00001510 << SS.getRange()
Douglas Gregorc2fa1692011-06-28 16:20:02 +00001511 << FixItHint::CreateReplacement(R.getNameLoc(), CorrectedStr);
1512 if (ND)
Douglas Gregor280e1ee2010-04-14 20:04:41 +00001513 Diag(ND->getLocation(), diag::note_previous_decl)
Douglas Gregorc2fa1692011-06-28 16:20:02 +00001514 << CorrectedQuotedStr;
Douglas Gregor280e1ee2010-04-14 20:04:41 +00001515
1516 // Tell the callee to try to recover.
1517 return false;
1518 }
Alexis Huntc46382e2010-04-28 23:02:27 +00001519
Douglas Gregorc2fa1692011-06-28 16:20:02 +00001520 if (isa<TypeDecl>(ND) || isa<ObjCInterfaceDecl>(ND)) {
Douglas Gregor280e1ee2010-04-14 20:04:41 +00001521 // FIXME: If we ended up with a typo for a type name or
1522 // Objective-C class name, we're in trouble because the parser
1523 // is in the wrong place to recover. Suggest the typo
1524 // correction, but don't make it a fix-it since we're not going
1525 // to recover well anyway.
1526 if (SS.isEmpty())
Richard Trieucfc491d2011-08-02 04:35:43 +00001527 Diag(R.getNameLoc(), diagnostic_suggest)
1528 << Name << CorrectedQuotedStr;
Douglas Gregor280e1ee2010-04-14 20:04:41 +00001529 else
1530 Diag(R.getNameLoc(), diag::err_no_member_suggest)
Douglas Gregorc2fa1692011-06-28 16:20:02 +00001531 << Name << computeDeclContext(SS, false) << CorrectedQuotedStr
Douglas Gregor280e1ee2010-04-14 20:04:41 +00001532 << SS.getRange();
1533
1534 // Don't try to recover; it won't work.
1535 return true;
1536 }
1537 } else {
Alexis Huntc46382e2010-04-28 23:02:27 +00001538 // FIXME: We found a keyword. Suggest it, but don't provide a fix-it
Douglas Gregor280e1ee2010-04-14 20:04:41 +00001539 // because we aren't able to recover.
Douglas Gregor25363982010-01-01 00:15:04 +00001540 if (SS.isEmpty())
Douglas Gregorc2fa1692011-06-28 16:20:02 +00001541 Diag(R.getNameLoc(), diagnostic_suggest) << Name << CorrectedQuotedStr;
Kovarththanan Rajaratnamba2c6522010-03-13 10:17:05 +00001542 else
Douglas Gregor25363982010-01-01 00:15:04 +00001543 Diag(R.getNameLoc(), diag::err_no_member_suggest)
Douglas Gregorc2fa1692011-06-28 16:20:02 +00001544 << Name << computeDeclContext(SS, false) << CorrectedQuotedStr
Douglas Gregor280e1ee2010-04-14 20:04:41 +00001545 << SS.getRange();
Douglas Gregor25363982010-01-01 00:15:04 +00001546 return true;
1547 }
Douglas Gregor598b08f2009-12-31 05:20:13 +00001548 }
Douglas Gregorc2fa1692011-06-28 16:20:02 +00001549 R.clear();
Douglas Gregor598b08f2009-12-31 05:20:13 +00001550
1551 // Emit a special diagnostic for failed member lookups.
1552 // FIXME: computing the declaration context might fail here (?)
1553 if (!SS.isEmpty()) {
1554 Diag(R.getNameLoc(), diag::err_no_member)
1555 << Name << computeDeclContext(SS, false)
1556 << SS.getRange();
1557 return true;
1558 }
1559
John McCalld681c392009-12-16 08:11:27 +00001560 // Give up, we can't recover.
1561 Diag(R.getNameLoc(), diagnostic) << Name;
1562 return true;
1563}
1564
John McCalldadc5752010-08-24 06:29:42 +00001565ExprResult Sema::ActOnIdExpression(Scope *S,
John McCall24d18942010-08-24 22:52:39 +00001566 CXXScopeSpec &SS,
Abramo Bagnara7945c982012-01-27 09:46:47 +00001567 SourceLocation TemplateKWLoc,
John McCall24d18942010-08-24 22:52:39 +00001568 UnqualifiedId &Id,
1569 bool HasTrailingLParen,
Kaelyn Uhrain77e21fc2012-01-25 20:49:08 +00001570 bool IsAddressOfOperand,
1571 CorrectionCandidateCallback *CCC) {
Richard Trieuba63ce62011-09-09 01:45:06 +00001572 assert(!(IsAddressOfOperand && HasTrailingLParen) &&
John McCalle66edc12009-11-24 19:00:30 +00001573 "cannot be direct & operand and have a trailing lparen");
1574
1575 if (SS.isInvalid())
Douglas Gregored8f2882009-01-30 01:04:22 +00001576 return ExprError();
Douglas Gregor90a1a652009-03-19 17:26:29 +00001577
John McCall10eae182009-11-30 22:42:35 +00001578 TemplateArgumentListInfo TemplateArgsBuffer;
John McCalle66edc12009-11-24 19:00:30 +00001579
1580 // Decompose the UnqualifiedId into the following data.
Abramo Bagnarad6d2f182010-08-11 22:01:17 +00001581 DeclarationNameInfo NameInfo;
John McCalle66edc12009-11-24 19:00:30 +00001582 const TemplateArgumentListInfo *TemplateArgs;
Douglas Gregor5476205b2011-06-23 00:49:38 +00001583 DecomposeUnqualifiedId(Id, TemplateArgsBuffer, NameInfo, TemplateArgs);
Douglas Gregor90a1a652009-03-19 17:26:29 +00001584
Abramo Bagnarad6d2f182010-08-11 22:01:17 +00001585 DeclarationName Name = NameInfo.getName();
Douglas Gregor4ea80432008-11-18 15:03:34 +00001586 IdentifierInfo *II = Name.getAsIdentifierInfo();
Abramo Bagnarad6d2f182010-08-11 22:01:17 +00001587 SourceLocation NameLoc = NameInfo.getLoc();
John McCalld14a8642009-11-21 08:51:07 +00001588
John McCalle66edc12009-11-24 19:00:30 +00001589 // C++ [temp.dep.expr]p3:
1590 // An id-expression is type-dependent if it contains:
Douglas Gregorea0a0a92010-01-11 18:40:55 +00001591 // -- an identifier that was declared with a dependent type,
1592 // (note: handled after lookup)
1593 // -- a template-id that is dependent,
1594 // (note: handled in BuildTemplateIdExpr)
1595 // -- a conversion-function-id that specifies a dependent type,
John McCalle66edc12009-11-24 19:00:30 +00001596 // -- a nested-name-specifier that contains a class-name that
1597 // names a dependent type.
1598 // Determine whether this is a member of an unknown specialization;
1599 // we need to handle these differently.
Eli Friedman964dbda2010-08-06 23:41:47 +00001600 bool DependentID = false;
1601 if (Name.getNameKind() == DeclarationName::CXXConversionFunctionName &&
1602 Name.getCXXNameType()->isDependentType()) {
1603 DependentID = true;
1604 } else if (SS.isSet()) {
Chris Lattnerebb5c6c2011-02-18 01:27:55 +00001605 if (DeclContext *DC = computeDeclContext(SS, false)) {
Eli Friedman964dbda2010-08-06 23:41:47 +00001606 if (RequireCompleteDeclContext(SS, DC))
1607 return ExprError();
Eli Friedman964dbda2010-08-06 23:41:47 +00001608 } else {
1609 DependentID = true;
1610 }
1611 }
1612
Chris Lattnerebb5c6c2011-02-18 01:27:55 +00001613 if (DependentID)
Abramo Bagnara7945c982012-01-27 09:46:47 +00001614 return ActOnDependentIdExpression(SS, TemplateKWLoc, NameInfo,
1615 IsAddressOfOperand, TemplateArgs);
Chris Lattnerebb5c6c2011-02-18 01:27:55 +00001616
John McCalle66edc12009-11-24 19:00:30 +00001617 // Perform the required lookup.
Fariborz Jahanian7f4427f2011-07-12 17:16:56 +00001618 LookupResult R(*this, NameInfo,
1619 (Id.getKind() == UnqualifiedId::IK_ImplicitSelfParam)
1620 ? LookupObjCImplicitSelfParam : LookupOrdinaryName);
John McCalle66edc12009-11-24 19:00:30 +00001621 if (TemplateArgs) {
Douglas Gregor3e51e172010-05-20 20:58:56 +00001622 // Lookup the template name again to correctly establish the context in
1623 // which it was found. This is really unfortunate as we already did the
1624 // lookup to determine that it was a template name in the first place. If
1625 // this becomes a performance hit, we can work harder to preserve those
1626 // results until we get here but it's likely not worth it.
Douglas Gregor786123d2010-05-21 23:18:07 +00001627 bool MemberOfUnknownSpecialization;
1628 LookupTemplateName(R, S, SS, QualType(), /*EnteringContext=*/false,
1629 MemberOfUnknownSpecialization);
Douglas Gregora5226932011-02-04 13:35:07 +00001630
1631 if (MemberOfUnknownSpecialization ||
1632 (R.getResultKind() == LookupResult::NotFoundInCurrentInstantiation))
Abramo Bagnara7945c982012-01-27 09:46:47 +00001633 return ActOnDependentIdExpression(SS, TemplateKWLoc, NameInfo,
1634 IsAddressOfOperand, TemplateArgs);
John McCalle66edc12009-11-24 19:00:30 +00001635 } else {
Benjamin Kramer46921442012-01-20 14:57:34 +00001636 bool IvarLookupFollowUp = II && !SS.isSet() && getCurMethodDecl();
Fariborz Jahanian6fada5b2010-01-12 23:58:59 +00001637 LookupParsedName(R, S, &SS, !IvarLookupFollowUp);
Mike Stump11289f42009-09-09 15:08:12 +00001638
Douglas Gregora5226932011-02-04 13:35:07 +00001639 // If the result might be in a dependent base class, this is a dependent
1640 // id-expression.
1641 if (R.getResultKind() == LookupResult::NotFoundInCurrentInstantiation)
Abramo Bagnara7945c982012-01-27 09:46:47 +00001642 return ActOnDependentIdExpression(SS, TemplateKWLoc, NameInfo,
1643 IsAddressOfOperand, TemplateArgs);
1644
John McCalle66edc12009-11-24 19:00:30 +00001645 // If this reference is in an Objective-C method, then we need to do
1646 // some special Objective-C lookup, too.
Fariborz Jahanian6fada5b2010-01-12 23:58:59 +00001647 if (IvarLookupFollowUp) {
John McCalldadc5752010-08-24 06:29:42 +00001648 ExprResult E(LookupInObjCMethod(R, S, II, true));
John McCalle66edc12009-11-24 19:00:30 +00001649 if (E.isInvalid())
1650 return ExprError();
Mike Stump11289f42009-09-09 15:08:12 +00001651
Chris Lattnerebb5c6c2011-02-18 01:27:55 +00001652 if (Expr *Ex = E.takeAs<Expr>())
1653 return Owned(Ex);
Steve Naroffebf4cb42008-06-02 23:03:37 +00001654 }
Chris Lattner59a25942008-03-31 00:36:02 +00001655 }
Douglas Gregorf15f5d32009-02-16 19:28:42 +00001656
John McCalle66edc12009-11-24 19:00:30 +00001657 if (R.isAmbiguous())
1658 return ExprError();
1659
Douglas Gregor171c45a2009-02-18 21:56:37 +00001660 // Determine whether this name might be a candidate for
1661 // argument-dependent lookup.
John McCalle66edc12009-11-24 19:00:30 +00001662 bool ADL = UseArgumentDependentLookup(SS, R, HasTrailingLParen);
Douglas Gregor171c45a2009-02-18 21:56:37 +00001663
John McCalle66edc12009-11-24 19:00:30 +00001664 if (R.empty() && !ADL) {
Bill Wendling4073ed52007-02-13 01:51:42 +00001665 // Otherwise, this could be an implicitly declared function reference (legal
John McCalle66edc12009-11-24 19:00:30 +00001666 // in C90, extension in C99, forbidden in C++).
David Blaikiebbafb8a2012-03-11 07:00:24 +00001667 if (HasTrailingLParen && II && !getLangOpts().CPlusPlus) {
John McCalle66edc12009-11-24 19:00:30 +00001668 NamedDecl *D = ImplicitlyDefineFunction(NameLoc, *II, S);
1669 if (D) R.addDecl(D);
1670 }
1671
1672 // If this name wasn't predeclared and if this is not a function
1673 // call, diagnose the problem.
1674 if (R.empty()) {
Francois Pichetd8e4e412011-09-24 10:38:05 +00001675
1676 // In Microsoft mode, if we are inside a template class member function
1677 // and we can't resolve an identifier then assume the identifier is type
1678 // dependent. The goal is to postpone name lookup to instantiation time
1679 // to be able to search into type dependent base classes.
David Blaikiebbafb8a2012-03-11 07:00:24 +00001680 if (getLangOpts().MicrosoftMode && CurContext->isDependentContext() &&
Francois Pichetd8e4e412011-09-24 10:38:05 +00001681 isa<CXXMethodDecl>(CurContext))
Abramo Bagnara7945c982012-01-27 09:46:47 +00001682 return ActOnDependentIdExpression(SS, TemplateKWLoc, NameInfo,
1683 IsAddressOfOperand, TemplateArgs);
Francois Pichetd8e4e412011-09-24 10:38:05 +00001684
Kaelyn Uhrain79d01c12012-01-18 05:58:54 +00001685 CorrectionCandidateCallback DefaultValidator;
Kaelyn Uhrain77e21fc2012-01-25 20:49:08 +00001686 if (DiagnoseEmptyLookup(S, SS, R, CCC ? *CCC : DefaultValidator))
John McCalld681c392009-12-16 08:11:27 +00001687 return ExprError();
1688
1689 assert(!R.empty() &&
1690 "DiagnoseEmptyLookup returned false but added no results");
Douglas Gregor35b0bac2010-01-03 18:01:57 +00001691
1692 // If we found an Objective-C instance variable, let
1693 // LookupInObjCMethod build the appropriate expression to
Kovarththanan Rajaratnamba2c6522010-03-13 10:17:05 +00001694 // reference the ivar.
Douglas Gregor35b0bac2010-01-03 18:01:57 +00001695 if (ObjCIvarDecl *Ivar = R.getAsSingle<ObjCIvarDecl>()) {
1696 R.clear();
John McCalldadc5752010-08-24 06:29:42 +00001697 ExprResult E(LookupInObjCMethod(R, S, Ivar->getIdentifier()));
Fariborz Jahanian44653702011-09-23 23:11:38 +00001698 // In a hopelessly buggy code, Objective-C instance variable
1699 // lookup fails and no expression will be built to reference it.
1700 if (!E.isInvalid() && !E.get())
1701 return ExprError();
Douglas Gregor35b0bac2010-01-03 18:01:57 +00001702 return move(E);
1703 }
Steve Naroff92e30f82007-04-02 22:35:25 +00001704 }
Chris Lattner17ed4872006-11-20 04:58:19 +00001705 }
Mike Stump11289f42009-09-09 15:08:12 +00001706
John McCalle66edc12009-11-24 19:00:30 +00001707 // This is guaranteed from this point on.
1708 assert(!R.empty() || ADL);
1709
John McCall2d74de92009-12-01 22:10:20 +00001710 // Check whether this might be a C++ implicit instance member access.
John McCall24d18942010-08-24 22:52:39 +00001711 // C++ [class.mfct.non-static]p3:
1712 // When an id-expression that is not part of a class member access
1713 // syntax and not used to form a pointer to member is used in the
1714 // body of a non-static member function of class X, if name lookup
1715 // resolves the name in the id-expression to a non-static non-type
1716 // member of some class C, the id-expression is transformed into a
1717 // class member access expression using (*this) as the
1718 // postfix-expression to the left of the . operator.
John McCall8d08b9b2010-08-27 09:08:28 +00001719 //
1720 // But we don't actually need to do this for '&' operands if R
1721 // resolved to a function or overloaded function set, because the
1722 // expression is ill-formed if it actually works out to be a
1723 // non-static member function:
1724 //
1725 // C++ [expr.ref]p4:
1726 // Otherwise, if E1.E2 refers to a non-static member function. . .
1727 // [t]he expression can be used only as the left-hand operand of a
1728 // member function call.
1729 //
1730 // There are other safeguards against such uses, but it's important
1731 // to get this right here so that we don't end up making a
1732 // spuriously dependent expression if we're inside a dependent
1733 // instance method.
John McCall57500772009-12-16 12:17:52 +00001734 if (!R.empty() && (*R.begin())->isCXXClassMember()) {
John McCall8d08b9b2010-08-27 09:08:28 +00001735 bool MightBeImplicitMember;
Richard Trieuba63ce62011-09-09 01:45:06 +00001736 if (!IsAddressOfOperand)
John McCall8d08b9b2010-08-27 09:08:28 +00001737 MightBeImplicitMember = true;
1738 else if (!SS.isEmpty())
1739 MightBeImplicitMember = false;
1740 else if (R.isOverloadedResult())
1741 MightBeImplicitMember = false;
Douglas Gregor1262b062010-08-30 16:00:47 +00001742 else if (R.isUnresolvableResult())
1743 MightBeImplicitMember = true;
John McCall8d08b9b2010-08-27 09:08:28 +00001744 else
Francois Pichet783dd6e2010-11-21 06:08:52 +00001745 MightBeImplicitMember = isa<FieldDecl>(R.getFoundDecl()) ||
1746 isa<IndirectFieldDecl>(R.getFoundDecl());
John McCall8d08b9b2010-08-27 09:08:28 +00001747
1748 if (MightBeImplicitMember)
Abramo Bagnara7945c982012-01-27 09:46:47 +00001749 return BuildPossibleImplicitMemberExpr(SS, TemplateKWLoc,
1750 R, TemplateArgs);
John McCallb53bbd42009-11-22 01:44:31 +00001751 }
1752
Abramo Bagnara65f7c3d2012-02-06 14:31:00 +00001753 if (TemplateArgs || TemplateKWLoc.isValid())
1754 return BuildTemplateIdExpr(SS, TemplateKWLoc, R, ADL, TemplateArgs);
John McCallb53bbd42009-11-22 01:44:31 +00001755
John McCalle66edc12009-11-24 19:00:30 +00001756 return BuildDeclarationNameExpr(SS, R, ADL);
1757}
1758
John McCall10eae182009-11-30 22:42:35 +00001759/// BuildQualifiedDeclarationNameExpr - Build a C++ qualified
1760/// declaration name, generally during template instantiation.
1761/// There's a large number of things which don't need to be done along
1762/// this path.
John McCalldadc5752010-08-24 06:29:42 +00001763ExprResult
Jeffrey Yasskinc76498d2010-04-08 16:38:48 +00001764Sema::BuildQualifiedDeclarationNameExpr(CXXScopeSpec &SS,
Abramo Bagnarad6d2f182010-08-11 22:01:17 +00001765 const DeclarationNameInfo &NameInfo) {
John McCalle66edc12009-11-24 19:00:30 +00001766 DeclContext *DC;
Douglas Gregora02bb342010-04-28 07:04:26 +00001767 if (!(DC = computeDeclContext(SS, false)) || DC->isDependentContext())
Abramo Bagnara65f7c3d2012-02-06 14:31:00 +00001768 return BuildDependentDeclRefExpr(SS, /*TemplateKWLoc=*/SourceLocation(),
1769 NameInfo, /*TemplateArgs=*/0);
John McCalle66edc12009-11-24 19:00:30 +00001770
John McCall0b66eb32010-05-01 00:40:08 +00001771 if (RequireCompleteDeclContext(SS, DC))
Douglas Gregora02bb342010-04-28 07:04:26 +00001772 return ExprError();
1773
Abramo Bagnarad6d2f182010-08-11 22:01:17 +00001774 LookupResult R(*this, NameInfo, LookupOrdinaryName);
John McCalle66edc12009-11-24 19:00:30 +00001775 LookupQualifiedName(R, DC);
1776
1777 if (R.isAmbiguous())
1778 return ExprError();
1779
1780 if (R.empty()) {
Abramo Bagnarad6d2f182010-08-11 22:01:17 +00001781 Diag(NameInfo.getLoc(), diag::err_no_member)
1782 << NameInfo.getName() << DC << SS.getRange();
John McCalle66edc12009-11-24 19:00:30 +00001783 return ExprError();
1784 }
1785
1786 return BuildDeclarationNameExpr(SS, R, /*ADL*/ false);
1787}
1788
1789/// LookupInObjCMethod - The parser has read a name in, and Sema has
1790/// detected that we're currently inside an ObjC method. Perform some
1791/// additional lookup.
1792///
1793/// Ideally, most of this would be done by lookup, but there's
1794/// actually quite a lot of extra work involved.
1795///
1796/// Returns a null sentinel to indicate trivial success.
John McCalldadc5752010-08-24 06:29:42 +00001797ExprResult
John McCalle66edc12009-11-24 19:00:30 +00001798Sema::LookupInObjCMethod(LookupResult &Lookup, Scope *S,
Chris Lattnera36ec422010-04-11 08:28:14 +00001799 IdentifierInfo *II, bool AllowBuiltinCreation) {
John McCalle66edc12009-11-24 19:00:30 +00001800 SourceLocation Loc = Lookup.getNameLoc();
Chris Lattner87313662010-04-12 05:10:17 +00001801 ObjCMethodDecl *CurMethod = getCurMethodDecl();
Alexis Huntc46382e2010-04-28 23:02:27 +00001802
John McCalle66edc12009-11-24 19:00:30 +00001803 // There are two cases to handle here. 1) scoped lookup could have failed,
1804 // in which case we should look for an ivar. 2) scoped lookup could have
1805 // found a decl, but that decl is outside the current instance method (i.e.
1806 // a global variable). In these two cases, we do a lookup for an ivar with
1807 // this name, if the lookup sucedes, we replace it our current decl.
1808
1809 // If we're in a class method, we don't normally want to look for
1810 // ivars. But if we don't find anything else, and there's an
1811 // ivar, that's an error.
Chris Lattner87313662010-04-12 05:10:17 +00001812 bool IsClassMethod = CurMethod->isClassMethod();
John McCalle66edc12009-11-24 19:00:30 +00001813
1814 bool LookForIvars;
1815 if (Lookup.empty())
1816 LookForIvars = true;
1817 else if (IsClassMethod)
1818 LookForIvars = false;
1819 else
1820 LookForIvars = (Lookup.isSingleResult() &&
1821 Lookup.getFoundDecl()->isDefinedOutsideFunctionOrMethod());
Fariborz Jahanian45878032010-02-09 19:31:38 +00001822 ObjCInterfaceDecl *IFace = 0;
John McCalle66edc12009-11-24 19:00:30 +00001823 if (LookForIvars) {
Chris Lattner87313662010-04-12 05:10:17 +00001824 IFace = CurMethod->getClassInterface();
John McCalle66edc12009-11-24 19:00:30 +00001825 ObjCInterfaceDecl *ClassDeclared;
Argyrios Kyrtzidis4e8b1362011-10-19 02:25:16 +00001826 ObjCIvarDecl *IV = 0;
1827 if (IFace && (IV = IFace->lookupInstanceVariable(II, ClassDeclared))) {
John McCalle66edc12009-11-24 19:00:30 +00001828 // Diagnose using an ivar in a class method.
1829 if (IsClassMethod)
1830 return ExprError(Diag(Loc, diag::error_ivar_use_in_class_method)
1831 << IV->getDeclName());
1832
1833 // If we're referencing an invalid decl, just return this as a silent
1834 // error node. The error diagnostic was already emitted on the decl.
1835 if (IV->isInvalidDecl())
1836 return ExprError();
1837
1838 // Check if referencing a field with __attribute__((deprecated)).
1839 if (DiagnoseUseOfDecl(IV, Loc))
1840 return ExprError();
1841
1842 // Diagnose the use of an ivar outside of the declaring class.
1843 if (IV->getAccessControl() == ObjCIvarDecl::Private &&
Fariborz Jahaniand6cb4a82012-03-07 00:58:41 +00001844 !declaresSameEntity(ClassDeclared, IFace) &&
David Blaikiebbafb8a2012-03-11 07:00:24 +00001845 !getLangOpts().DebuggerSupport)
John McCalle66edc12009-11-24 19:00:30 +00001846 Diag(Loc, diag::error_private_ivar_access) << IV->getDeclName();
1847
1848 // FIXME: This should use a new expr for a direct reference, don't
1849 // turn this into Self->ivar, just return a BareIVarExpr or something.
1850 IdentifierInfo &II = Context.Idents.get("self");
1851 UnqualifiedId SelfName;
Kovarththanan Rajaratnamba2c6522010-03-13 10:17:05 +00001852 SelfName.setIdentifier(&II, SourceLocation());
Fariborz Jahanian7f4427f2011-07-12 17:16:56 +00001853 SelfName.setKind(UnqualifiedId::IK_ImplicitSelfParam);
John McCalle66edc12009-11-24 19:00:30 +00001854 CXXScopeSpec SelfScopeSpec;
Abramo Bagnara7945c982012-01-27 09:46:47 +00001855 SourceLocation TemplateKWLoc;
1856 ExprResult SelfExpr = ActOnIdExpression(S, SelfScopeSpec, TemplateKWLoc,
Douglas Gregora1ed39b2010-09-22 16:33:13 +00001857 SelfName, false, false);
1858 if (SelfExpr.isInvalid())
1859 return ExprError();
1860
John Wiegley01296292011-04-08 18:41:53 +00001861 SelfExpr = DefaultLvalueConversion(SelfExpr.take());
1862 if (SelfExpr.isInvalid())
1863 return ExprError();
John McCall27584242010-12-06 20:48:59 +00001864
Eli Friedmanfa0df832012-02-02 03:46:19 +00001865 MarkAnyDeclReferenced(Loc, IV);
John McCalle66edc12009-11-24 19:00:30 +00001866 return Owned(new (Context)
1867 ObjCIvarRefExpr(IV, IV->getType(), Loc,
John Wiegley01296292011-04-08 18:41:53 +00001868 SelfExpr.take(), true, true));
John McCalle66edc12009-11-24 19:00:30 +00001869 }
Chris Lattner87313662010-04-12 05:10:17 +00001870 } else if (CurMethod->isInstanceMethod()) {
John McCalle66edc12009-11-24 19:00:30 +00001871 // We should warn if a local variable hides an ivar.
Fariborz Jahanian557fc9a2011-11-08 22:51:27 +00001872 if (ObjCInterfaceDecl *IFace = CurMethod->getClassInterface()) {
1873 ObjCInterfaceDecl *ClassDeclared;
1874 if (ObjCIvarDecl *IV = IFace->lookupInstanceVariable(II, ClassDeclared)) {
1875 if (IV->getAccessControl() != ObjCIvarDecl::Private ||
Douglas Gregor0b144e12011-12-15 00:29:59 +00001876 declaresSameEntity(IFace, ClassDeclared))
Fariborz Jahanian557fc9a2011-11-08 22:51:27 +00001877 Diag(Loc, diag::warn_ivar_use_hidden) << IV->getDeclName();
1878 }
John McCalle66edc12009-11-24 19:00:30 +00001879 }
Fariborz Jahanian028b9e12011-12-20 22:21:08 +00001880 } else if (Lookup.isSingleResult() &&
1881 Lookup.getFoundDecl()->isDefinedOutsideFunctionOrMethod()) {
1882 // If accessing a stand-alone ivar in a class method, this is an error.
1883 if (const ObjCIvarDecl *IV = dyn_cast<ObjCIvarDecl>(Lookup.getFoundDecl()))
1884 return ExprError(Diag(Loc, diag::error_ivar_use_in_class_method)
1885 << IV->getDeclName());
John McCalle66edc12009-11-24 19:00:30 +00001886 }
1887
Fariborz Jahanian6fada5b2010-01-12 23:58:59 +00001888 if (Lookup.empty() && II && AllowBuiltinCreation) {
1889 // FIXME. Consolidate this with similar code in LookupName.
1890 if (unsigned BuiltinID = II->getBuiltinID()) {
David Blaikiebbafb8a2012-03-11 07:00:24 +00001891 if (!(getLangOpts().CPlusPlus &&
Fariborz Jahanian6fada5b2010-01-12 23:58:59 +00001892 Context.BuiltinInfo.isPredefinedLibFunction(BuiltinID))) {
1893 NamedDecl *D = LazilyCreateBuiltin((IdentifierInfo *)II, BuiltinID,
1894 S, Lookup.isForRedeclaration(),
1895 Lookup.getNameLoc());
1896 if (D) Lookup.addDecl(D);
1897 }
1898 }
1899 }
John McCalle66edc12009-11-24 19:00:30 +00001900 // Sentinel value saying that we didn't do anything special.
1901 return Owned((Expr*) 0);
Douglas Gregor3256d042009-06-30 15:47:41 +00001902}
John McCalld14a8642009-11-21 08:51:07 +00001903
John McCall16df1e52010-03-30 21:47:33 +00001904/// \brief Cast a base object to a member's actual type.
1905///
1906/// Logically this happens in three phases:
1907///
1908/// * First we cast from the base type to the naming class.
1909/// The naming class is the class into which we were looking
1910/// when we found the member; it's the qualifier type if a
1911/// qualifier was provided, and otherwise it's the base type.
1912///
1913/// * Next we cast from the naming class to the declaring class.
1914/// If the member we found was brought into a class's scope by
1915/// a using declaration, this is that class; otherwise it's
1916/// the class declaring the member.
1917///
1918/// * Finally we cast from the declaring class to the "true"
1919/// declaring class of the member. This conversion does not
1920/// obey access control.
John Wiegley01296292011-04-08 18:41:53 +00001921ExprResult
1922Sema::PerformObjectMemberConversion(Expr *From,
Douglas Gregorcc3f3252010-03-03 23:55:11 +00001923 NestedNameSpecifier *Qualifier,
John McCall16df1e52010-03-30 21:47:33 +00001924 NamedDecl *FoundDecl,
Douglas Gregorcc3f3252010-03-03 23:55:11 +00001925 NamedDecl *Member) {
1926 CXXRecordDecl *RD = dyn_cast<CXXRecordDecl>(Member->getDeclContext());
1927 if (!RD)
John Wiegley01296292011-04-08 18:41:53 +00001928 return Owned(From);
Kovarththanan Rajaratnamba2c6522010-03-13 10:17:05 +00001929
Douglas Gregorcc3f3252010-03-03 23:55:11 +00001930 QualType DestRecordType;
1931 QualType DestType;
1932 QualType FromRecordType;
1933 QualType FromType = From->getType();
1934 bool PointerConversions = false;
1935 if (isa<FieldDecl>(Member)) {
1936 DestRecordType = Context.getCanonicalType(Context.getTypeDeclType(RD));
Kovarththanan Rajaratnamba2c6522010-03-13 10:17:05 +00001937
Douglas Gregorcc3f3252010-03-03 23:55:11 +00001938 if (FromType->getAs<PointerType>()) {
1939 DestType = Context.getPointerType(DestRecordType);
1940 FromRecordType = FromType->getPointeeType();
1941 PointerConversions = true;
1942 } else {
1943 DestType = DestRecordType;
1944 FromRecordType = FromType;
Fariborz Jahanianbb67b822009-07-29 18:40:24 +00001945 }
Douglas Gregorcc3f3252010-03-03 23:55:11 +00001946 } else if (CXXMethodDecl *Method = dyn_cast<CXXMethodDecl>(Member)) {
1947 if (Method->isStatic())
John Wiegley01296292011-04-08 18:41:53 +00001948 return Owned(From);
Kovarththanan Rajaratnamba2c6522010-03-13 10:17:05 +00001949
Douglas Gregorcc3f3252010-03-03 23:55:11 +00001950 DestType = Method->getThisType(Context);
1951 DestRecordType = DestType->getPointeeType();
Kovarththanan Rajaratnamba2c6522010-03-13 10:17:05 +00001952
Douglas Gregorcc3f3252010-03-03 23:55:11 +00001953 if (FromType->getAs<PointerType>()) {
1954 FromRecordType = FromType->getPointeeType();
1955 PointerConversions = true;
1956 } else {
1957 FromRecordType = FromType;
1958 DestType = DestRecordType;
1959 }
1960 } else {
1961 // No conversion necessary.
John Wiegley01296292011-04-08 18:41:53 +00001962 return Owned(From);
Douglas Gregorcc3f3252010-03-03 23:55:11 +00001963 }
Kovarththanan Rajaratnamba2c6522010-03-13 10:17:05 +00001964
Douglas Gregorcc3f3252010-03-03 23:55:11 +00001965 if (DestType->isDependentType() || FromType->isDependentType())
John Wiegley01296292011-04-08 18:41:53 +00001966 return Owned(From);
Kovarththanan Rajaratnamba2c6522010-03-13 10:17:05 +00001967
Douglas Gregorcc3f3252010-03-03 23:55:11 +00001968 // If the unqualified types are the same, no conversion is necessary.
1969 if (Context.hasSameUnqualifiedType(FromRecordType, DestRecordType))
John Wiegley01296292011-04-08 18:41:53 +00001970 return Owned(From);
Kovarththanan Rajaratnamba2c6522010-03-13 10:17:05 +00001971
John McCall16df1e52010-03-30 21:47:33 +00001972 SourceRange FromRange = From->getSourceRange();
1973 SourceLocation FromLoc = FromRange.getBegin();
1974
Eli Friedmanbe4b3632011-09-27 21:58:52 +00001975 ExprValueKind VK = From->getValueKind();
Sebastian Redlc57d34b2010-07-20 04:20:21 +00001976
Douglas Gregorcc3f3252010-03-03 23:55:11 +00001977 // C++ [class.member.lookup]p8:
Kovarththanan Rajaratnamba2c6522010-03-13 10:17:05 +00001978 // [...] Ambiguities can often be resolved by qualifying a name with its
Douglas Gregorcc3f3252010-03-03 23:55:11 +00001979 // class name.
1980 //
1981 // If the member was a qualified name and the qualified referred to a
1982 // specific base subobject type, we'll cast to that intermediate type
1983 // first and then to the object in which the member is declared. That allows
1984 // one to resolve ambiguities in, e.g., a diamond-shaped hierarchy such as:
1985 //
1986 // class Base { public: int x; };
1987 // class Derived1 : public Base { };
1988 // class Derived2 : public Base { };
1989 // class VeryDerived : public Derived1, public Derived2 { void f(); };
1990 //
1991 // void VeryDerived::f() {
1992 // x = 17; // error: ambiguous base subobjects
1993 // Derived1::x = 17; // okay, pick the Base subobject of Derived1
1994 // }
Douglas Gregorcc3f3252010-03-03 23:55:11 +00001995 if (Qualifier) {
John McCall16df1e52010-03-30 21:47:33 +00001996 QualType QType = QualType(Qualifier->getAsType(), 0);
1997 assert(!QType.isNull() && "lookup done with dependent qualifier?");
1998 assert(QType->isRecordType() && "lookup done with non-record type");
1999
2000 QualType QRecordType = QualType(QType->getAs<RecordType>(), 0);
2001
2002 // In C++98, the qualifier type doesn't actually have to be a base
2003 // type of the object type, in which case we just ignore it.
2004 // Otherwise build the appropriate casts.
2005 if (IsDerivedFrom(FromRecordType, QRecordType)) {
John McCallcf142162010-08-07 06:22:56 +00002006 CXXCastPath BasePath;
John McCall16df1e52010-03-30 21:47:33 +00002007 if (CheckDerivedToBaseConversion(FromRecordType, QRecordType,
Anders Carlssonb78feca2010-04-24 19:22:20 +00002008 FromLoc, FromRange, &BasePath))
John Wiegley01296292011-04-08 18:41:53 +00002009 return ExprError();
John McCall16df1e52010-03-30 21:47:33 +00002010
Douglas Gregorcc3f3252010-03-03 23:55:11 +00002011 if (PointerConversions)
John McCall16df1e52010-03-30 21:47:33 +00002012 QType = Context.getPointerType(QType);
John Wiegley01296292011-04-08 18:41:53 +00002013 From = ImpCastExprToType(From, QType, CK_UncheckedDerivedToBase,
2014 VK, &BasePath).take();
John McCall16df1e52010-03-30 21:47:33 +00002015
2016 FromType = QType;
2017 FromRecordType = QRecordType;
2018
2019 // If the qualifier type was the same as the destination type,
2020 // we're done.
2021 if (Context.hasSameUnqualifiedType(FromRecordType, DestRecordType))
John Wiegley01296292011-04-08 18:41:53 +00002022 return Owned(From);
Douglas Gregorcc3f3252010-03-03 23:55:11 +00002023 }
2024 }
Kovarththanan Rajaratnamba2c6522010-03-13 10:17:05 +00002025
John McCall16df1e52010-03-30 21:47:33 +00002026 bool IgnoreAccess = false;
Douglas Gregorcc3f3252010-03-03 23:55:11 +00002027
John McCall16df1e52010-03-30 21:47:33 +00002028 // If we actually found the member through a using declaration, cast
2029 // down to the using declaration's type.
2030 //
2031 // Pointer equality is fine here because only one declaration of a
2032 // class ever has member declarations.
2033 if (FoundDecl->getDeclContext() != Member->getDeclContext()) {
2034 assert(isa<UsingShadowDecl>(FoundDecl));
2035 QualType URecordType = Context.getTypeDeclType(
2036 cast<CXXRecordDecl>(FoundDecl->getDeclContext()));
2037
2038 // We only need to do this if the naming-class to declaring-class
2039 // conversion is non-trivial.
2040 if (!Context.hasSameUnqualifiedType(FromRecordType, URecordType)) {
2041 assert(IsDerivedFrom(FromRecordType, URecordType));
John McCallcf142162010-08-07 06:22:56 +00002042 CXXCastPath BasePath;
John McCall16df1e52010-03-30 21:47:33 +00002043 if (CheckDerivedToBaseConversion(FromRecordType, URecordType,
Anders Carlssonb78feca2010-04-24 19:22:20 +00002044 FromLoc, FromRange, &BasePath))
John Wiegley01296292011-04-08 18:41:53 +00002045 return ExprError();
Alexis Huntc46382e2010-04-28 23:02:27 +00002046
John McCall16df1e52010-03-30 21:47:33 +00002047 QualType UType = URecordType;
2048 if (PointerConversions)
2049 UType = Context.getPointerType(UType);
John Wiegley01296292011-04-08 18:41:53 +00002050 From = ImpCastExprToType(From, UType, CK_UncheckedDerivedToBase,
2051 VK, &BasePath).take();
John McCall16df1e52010-03-30 21:47:33 +00002052 FromType = UType;
2053 FromRecordType = URecordType;
2054 }
2055
2056 // We don't do access control for the conversion from the
2057 // declaring class to the true declaring class.
2058 IgnoreAccess = true;
Douglas Gregorcc3f3252010-03-03 23:55:11 +00002059 }
Kovarththanan Rajaratnamba2c6522010-03-13 10:17:05 +00002060
John McCallcf142162010-08-07 06:22:56 +00002061 CXXCastPath BasePath;
Anders Carlssonb78feca2010-04-24 19:22:20 +00002062 if (CheckDerivedToBaseConversion(FromRecordType, DestRecordType,
2063 FromLoc, FromRange, &BasePath,
John McCall16df1e52010-03-30 21:47:33 +00002064 IgnoreAccess))
John Wiegley01296292011-04-08 18:41:53 +00002065 return ExprError();
Kovarththanan Rajaratnamba2c6522010-03-13 10:17:05 +00002066
John Wiegley01296292011-04-08 18:41:53 +00002067 return ImpCastExprToType(From, DestType, CK_UncheckedDerivedToBase,
2068 VK, &BasePath);
Fariborz Jahanianbb67b822009-07-29 18:40:24 +00002069}
Douglas Gregor3256d042009-06-30 15:47:41 +00002070
John McCalle66edc12009-11-24 19:00:30 +00002071bool Sema::UseArgumentDependentLookup(const CXXScopeSpec &SS,
John McCallb53bbd42009-11-22 01:44:31 +00002072 const LookupResult &R,
2073 bool HasTrailingLParen) {
John McCalld14a8642009-11-21 08:51:07 +00002074 // Only when used directly as the postfix-expression of a call.
2075 if (!HasTrailingLParen)
2076 return false;
2077
2078 // Never if a scope specifier was provided.
John McCalle66edc12009-11-24 19:00:30 +00002079 if (SS.isSet())
John McCalld14a8642009-11-21 08:51:07 +00002080 return false;
2081
2082 // Only in C++ or ObjC++.
David Blaikiebbafb8a2012-03-11 07:00:24 +00002083 if (!getLangOpts().CPlusPlus)
John McCalld14a8642009-11-21 08:51:07 +00002084 return false;
2085
2086 // Turn off ADL when we find certain kinds of declarations during
2087 // normal lookup:
2088 for (LookupResult::iterator I = R.begin(), E = R.end(); I != E; ++I) {
2089 NamedDecl *D = *I;
2090
2091 // C++0x [basic.lookup.argdep]p3:
2092 // -- a declaration of a class member
2093 // Since using decls preserve this property, we check this on the
2094 // original decl.
John McCall57500772009-12-16 12:17:52 +00002095 if (D->isCXXClassMember())
John McCalld14a8642009-11-21 08:51:07 +00002096 return false;
2097
2098 // C++0x [basic.lookup.argdep]p3:
2099 // -- a block-scope function declaration that is not a
2100 // using-declaration
2101 // NOTE: we also trigger this for function templates (in fact, we
2102 // don't check the decl type at all, since all other decl types
2103 // turn off ADL anyway).
2104 if (isa<UsingShadowDecl>(D))
2105 D = cast<UsingShadowDecl>(D)->getTargetDecl();
2106 else if (D->getDeclContext()->isFunctionOrMethod())
2107 return false;
2108
2109 // C++0x [basic.lookup.argdep]p3:
2110 // -- a declaration that is neither a function or a function
2111 // template
2112 // And also for builtin functions.
2113 if (isa<FunctionDecl>(D)) {
2114 FunctionDecl *FDecl = cast<FunctionDecl>(D);
2115
2116 // But also builtin functions.
2117 if (FDecl->getBuiltinID() && FDecl->isImplicit())
2118 return false;
2119 } else if (!isa<FunctionTemplateDecl>(D))
2120 return false;
2121 }
2122
2123 return true;
2124}
2125
2126
John McCalld14a8642009-11-21 08:51:07 +00002127/// Diagnoses obvious problems with the use of the given declaration
2128/// as an expression. This is only actually called for lookups that
2129/// were not overloaded, and it doesn't promise that the declaration
2130/// will in fact be used.
2131static bool CheckDeclInExpr(Sema &S, SourceLocation Loc, NamedDecl *D) {
Richard Smithdda56e42011-04-15 14:24:37 +00002132 if (isa<TypedefNameDecl>(D)) {
John McCalld14a8642009-11-21 08:51:07 +00002133 S.Diag(Loc, diag::err_unexpected_typedef) << D->getDeclName();
2134 return true;
2135 }
2136
2137 if (isa<ObjCInterfaceDecl>(D)) {
2138 S.Diag(Loc, diag::err_unexpected_interface) << D->getDeclName();
2139 return true;
2140 }
2141
2142 if (isa<NamespaceDecl>(D)) {
2143 S.Diag(Loc, diag::err_unexpected_namespace) << D->getDeclName();
2144 return true;
2145 }
2146
2147 return false;
2148}
2149
John McCalldadc5752010-08-24 06:29:42 +00002150ExprResult
John McCalle66edc12009-11-24 19:00:30 +00002151Sema::BuildDeclarationNameExpr(const CXXScopeSpec &SS,
John McCallb53bbd42009-11-22 01:44:31 +00002152 LookupResult &R,
2153 bool NeedsADL) {
John McCall3a60c872009-12-08 22:45:53 +00002154 // If this is a single, fully-resolved result and we don't need ADL,
2155 // just build an ordinary singleton decl ref.
Douglas Gregor4b4844f2010-01-29 17:15:43 +00002156 if (!NeedsADL && R.isSingleResult() && !R.getAsSingle<FunctionTemplateDecl>())
Abramo Bagnarad6d2f182010-08-11 22:01:17 +00002157 return BuildDeclarationNameExpr(SS, R.getLookupNameInfo(),
2158 R.getFoundDecl());
John McCalld14a8642009-11-21 08:51:07 +00002159
2160 // We only need to check the declaration if there's exactly one
2161 // result, because in the overloaded case the results can only be
2162 // functions and function templates.
John McCallb53bbd42009-11-22 01:44:31 +00002163 if (R.isSingleResult() &&
2164 CheckDeclInExpr(*this, R.getNameLoc(), R.getFoundDecl()))
John McCalld14a8642009-11-21 08:51:07 +00002165 return ExprError();
2166
John McCall58cc69d2010-01-27 01:50:18 +00002167 // Otherwise, just build an unresolved lookup expression. Suppress
2168 // any lookup-related diagnostics; we'll hash these out later, when
2169 // we've picked a target.
2170 R.suppressDiagnostics();
2171
John McCalld14a8642009-11-21 08:51:07 +00002172 UnresolvedLookupExpr *ULE
Douglas Gregora6e053e2010-12-15 01:34:56 +00002173 = UnresolvedLookupExpr::Create(Context, R.getNamingClass(),
Douglas Gregor0da1d432011-02-28 20:01:57 +00002174 SS.getWithLocInContext(Context),
2175 R.getLookupNameInfo(),
Douglas Gregor30a4f4c2010-05-23 18:57:34 +00002176 NeedsADL, R.isOverloadedResult(),
2177 R.begin(), R.end());
John McCalld14a8642009-11-21 08:51:07 +00002178
2179 return Owned(ULE);
2180}
Kovarththanan Rajaratnamba2c6522010-03-13 10:17:05 +00002181
John McCalld14a8642009-11-21 08:51:07 +00002182/// \brief Complete semantic analysis for a reference to the given declaration.
John McCalldadc5752010-08-24 06:29:42 +00002183ExprResult
John McCalle66edc12009-11-24 19:00:30 +00002184Sema::BuildDeclarationNameExpr(const CXXScopeSpec &SS,
Abramo Bagnarad6d2f182010-08-11 22:01:17 +00002185 const DeclarationNameInfo &NameInfo,
2186 NamedDecl *D) {
John McCalld14a8642009-11-21 08:51:07 +00002187 assert(D && "Cannot refer to a NULL declaration");
John McCall283b9012009-11-22 00:44:51 +00002188 assert(!isa<FunctionTemplateDecl>(D) &&
2189 "Cannot refer unambiguously to a function template");
John McCalld14a8642009-11-21 08:51:07 +00002190
Abramo Bagnarad6d2f182010-08-11 22:01:17 +00002191 SourceLocation Loc = NameInfo.getLoc();
John McCalld14a8642009-11-21 08:51:07 +00002192 if (CheckDeclInExpr(*this, Loc, D))
2193 return ExprError();
Steve Narofff1e53692007-03-23 22:27:02 +00002194
Douglas Gregore7488b92009-12-01 16:58:18 +00002195 if (TemplateDecl *Template = dyn_cast<TemplateDecl>(D)) {
2196 // Specifically diagnose references to class templates that are missing
2197 // a template argument list.
2198 Diag(Loc, diag::err_template_decl_ref)
2199 << Template << SS.getRange();
2200 Diag(Template->getLocation(), diag::note_template_decl_here);
2201 return ExprError();
2202 }
2203
2204 // Make sure that we're referring to a value.
2205 ValueDecl *VD = dyn_cast<ValueDecl>(D);
2206 if (!VD) {
Kovarththanan Rajaratnamba2c6522010-03-13 10:17:05 +00002207 Diag(Loc, diag::err_ref_non_value)
Douglas Gregore7488b92009-12-01 16:58:18 +00002208 << D << SS.getRange();
John McCallb48971d2009-12-18 18:35:10 +00002209 Diag(D->getLocation(), diag::note_declared_at);
Douglas Gregore7488b92009-12-01 16:58:18 +00002210 return ExprError();
2211 }
Sebastian Redlffbcf962009-01-18 18:53:16 +00002212
Douglas Gregor171c45a2009-02-18 21:56:37 +00002213 // Check whether this declaration can be used. Note that we suppress
2214 // this check when we're going to perform argument-dependent lookup
2215 // on this function name, because this might not be the function
2216 // that overload resolution actually selects.
John McCalld14a8642009-11-21 08:51:07 +00002217 if (DiagnoseUseOfDecl(VD, Loc))
Douglas Gregor171c45a2009-02-18 21:56:37 +00002218 return ExprError();
2219
Steve Naroff8de9c3a2008-09-05 22:11:13 +00002220 // Only create DeclRefExpr's for valid Decl's.
2221 if (VD->isInvalidDecl())
Sebastian Redlffbcf962009-01-18 18:53:16 +00002222 return ExprError();
2223
John McCallf3a88602011-02-03 08:15:49 +00002224 // Handle members of anonymous structs and unions. If we got here,
2225 // and the reference is to a class member indirect field, then this
2226 // must be the subject of a pointer-to-member expression.
2227 if (IndirectFieldDecl *indirectField = dyn_cast<IndirectFieldDecl>(VD))
2228 if (!indirectField->isCXXClassMember())
2229 return BuildAnonymousStructUnionMemberReference(SS, NameInfo.getLoc(),
2230 indirectField);
Francois Pichet783dd6e2010-11-21 06:08:52 +00002231
Eli Friedman9bb33f52012-02-03 02:04:35 +00002232 {
John McCallf4cd4f92011-02-09 01:13:10 +00002233 QualType type = VD->getType();
Daniel Dunbar7c2dc362011-02-10 18:29:28 +00002234 ExprValueKind valueKind = VK_RValue;
John McCallf4cd4f92011-02-09 01:13:10 +00002235
2236 switch (D->getKind()) {
2237 // Ignore all the non-ValueDecl kinds.
2238#define ABSTRACT_DECL(kind)
2239#define VALUE(type, base)
2240#define DECL(type, base) \
2241 case Decl::type:
2242#include "clang/AST/DeclNodes.inc"
2243 llvm_unreachable("invalid value decl kind");
John McCallf4cd4f92011-02-09 01:13:10 +00002244
2245 // These shouldn't make it here.
2246 case Decl::ObjCAtDefsField:
2247 case Decl::ObjCIvar:
2248 llvm_unreachable("forming non-member reference to ivar?");
John McCallf4cd4f92011-02-09 01:13:10 +00002249
2250 // Enum constants are always r-values and never references.
2251 // Unresolved using declarations are dependent.
2252 case Decl::EnumConstant:
2253 case Decl::UnresolvedUsingValue:
2254 valueKind = VK_RValue;
2255 break;
2256
2257 // Fields and indirect fields that got here must be for
2258 // pointer-to-member expressions; we just call them l-values for
2259 // internal consistency, because this subexpression doesn't really
2260 // exist in the high-level semantics.
2261 case Decl::Field:
2262 case Decl::IndirectField:
David Blaikiebbafb8a2012-03-11 07:00:24 +00002263 assert(getLangOpts().CPlusPlus &&
John McCallf4cd4f92011-02-09 01:13:10 +00002264 "building reference to field in C?");
2265
2266 // These can't have reference type in well-formed programs, but
2267 // for internal consistency we do this anyway.
2268 type = type.getNonReferenceType();
2269 valueKind = VK_LValue;
2270 break;
2271
2272 // Non-type template parameters are either l-values or r-values
2273 // depending on the type.
2274 case Decl::NonTypeTemplateParm: {
2275 if (const ReferenceType *reftype = type->getAs<ReferenceType>()) {
2276 type = reftype->getPointeeType();
2277 valueKind = VK_LValue; // even if the parameter is an r-value reference
2278 break;
2279 }
2280
2281 // For non-references, we need to strip qualifiers just in case
2282 // the template parameter was declared as 'const int' or whatever.
2283 valueKind = VK_RValue;
2284 type = type.getUnqualifiedType();
2285 break;
2286 }
2287
2288 case Decl::Var:
2289 // In C, "extern void blah;" is valid and is an r-value.
David Blaikiebbafb8a2012-03-11 07:00:24 +00002290 if (!getLangOpts().CPlusPlus &&
John McCallf4cd4f92011-02-09 01:13:10 +00002291 !type.hasQualifiers() &&
2292 type->isVoidType()) {
2293 valueKind = VK_RValue;
2294 break;
2295 }
2296 // fallthrough
2297
2298 case Decl::ImplicitParam:
Douglas Gregor812d8f62012-02-18 05:51:20 +00002299 case Decl::ParmVar: {
John McCallf4cd4f92011-02-09 01:13:10 +00002300 // These are always l-values.
2301 valueKind = VK_LValue;
2302 type = type.getNonReferenceType();
Eli Friedman9bb33f52012-02-03 02:04:35 +00002303
Douglas Gregor812d8f62012-02-18 05:51:20 +00002304 // FIXME: Does the addition of const really only apply in
2305 // potentially-evaluated contexts? Since the variable isn't actually
2306 // captured in an unevaluated context, it seems that the answer is no.
2307 if (ExprEvalContexts.back().Context != Sema::Unevaluated) {
2308 QualType CapturedType = getCapturedDeclRefType(cast<VarDecl>(VD), Loc);
2309 if (!CapturedType.isNull())
2310 type = CapturedType;
2311 }
2312
John McCallf4cd4f92011-02-09 01:13:10 +00002313 break;
Douglas Gregor812d8f62012-02-18 05:51:20 +00002314 }
2315
John McCallf4cd4f92011-02-09 01:13:10 +00002316 case Decl::Function: {
John McCall2979fe02011-04-12 00:42:48 +00002317 const FunctionType *fty = type->castAs<FunctionType>();
2318
2319 // If we're referring to a function with an __unknown_anytype
2320 // result type, make the entire expression __unknown_anytype.
2321 if (fty->getResultType() == Context.UnknownAnyTy) {
2322 type = Context.UnknownAnyTy;
2323 valueKind = VK_RValue;
2324 break;
2325 }
2326
John McCallf4cd4f92011-02-09 01:13:10 +00002327 // Functions are l-values in C++.
David Blaikiebbafb8a2012-03-11 07:00:24 +00002328 if (getLangOpts().CPlusPlus) {
John McCallf4cd4f92011-02-09 01:13:10 +00002329 valueKind = VK_LValue;
2330 break;
2331 }
2332
2333 // C99 DR 316 says that, if a function type comes from a
2334 // function definition (without a prototype), that type is only
2335 // used for checking compatibility. Therefore, when referencing
2336 // the function, we pretend that we don't have the full function
2337 // type.
John McCall2979fe02011-04-12 00:42:48 +00002338 if (!cast<FunctionDecl>(VD)->hasPrototype() &&
2339 isa<FunctionProtoType>(fty))
2340 type = Context.getFunctionNoProtoType(fty->getResultType(),
2341 fty->getExtInfo());
John McCallf4cd4f92011-02-09 01:13:10 +00002342
2343 // Functions are r-values in C.
2344 valueKind = VK_RValue;
2345 break;
2346 }
2347
2348 case Decl::CXXMethod:
John McCall2979fe02011-04-12 00:42:48 +00002349 // If we're referring to a method with an __unknown_anytype
2350 // result type, make the entire expression __unknown_anytype.
2351 // This should only be possible with a type written directly.
Richard Trieucfc491d2011-08-02 04:35:43 +00002352 if (const FunctionProtoType *proto
2353 = dyn_cast<FunctionProtoType>(VD->getType()))
John McCall2979fe02011-04-12 00:42:48 +00002354 if (proto->getResultType() == Context.UnknownAnyTy) {
2355 type = Context.UnknownAnyTy;
2356 valueKind = VK_RValue;
2357 break;
2358 }
2359
John McCallf4cd4f92011-02-09 01:13:10 +00002360 // C++ methods are l-values if static, r-values if non-static.
2361 if (cast<CXXMethodDecl>(VD)->isStatic()) {
2362 valueKind = VK_LValue;
2363 break;
2364 }
2365 // fallthrough
2366
2367 case Decl::CXXConversion:
2368 case Decl::CXXDestructor:
2369 case Decl::CXXConstructor:
2370 valueKind = VK_RValue;
2371 break;
2372 }
2373
2374 return BuildDeclRefExpr(VD, type, valueKind, NameInfo, &SS);
2375 }
Chris Lattner17ed4872006-11-20 04:58:19 +00002376}
Chris Lattnere168f762006-11-10 05:29:30 +00002377
John McCall2979fe02011-04-12 00:42:48 +00002378ExprResult Sema::ActOnPredefinedExpr(SourceLocation Loc, tok::TokenKind Kind) {
Chris Lattner6307f192008-08-10 01:53:14 +00002379 PredefinedExpr::IdentType IT;
Sebastian Redlffbcf962009-01-18 18:53:16 +00002380
Chris Lattnere168f762006-11-10 05:29:30 +00002381 switch (Kind) {
David Blaikie83d382b2011-09-23 05:06:16 +00002382 default: llvm_unreachable("Unknown simple primary expr!");
Chris Lattner6307f192008-08-10 01:53:14 +00002383 case tok::kw___func__: IT = PredefinedExpr::Func; break; // [C99 6.4.2.2]
2384 case tok::kw___FUNCTION__: IT = PredefinedExpr::Function; break;
2385 case tok::kw___PRETTY_FUNCTION__: IT = PredefinedExpr::PrettyFunction; break;
Chris Lattnere168f762006-11-10 05:29:30 +00002386 }
Chris Lattner317e6ba2008-01-12 18:39:25 +00002387
Chris Lattnera81a0272008-01-12 08:14:25 +00002388 // Pre-defined identifiers are of type char[x], where x is the length of the
2389 // string.
Mike Stump11289f42009-09-09 15:08:12 +00002390
Anders Carlsson2fb08242009-09-08 18:24:21 +00002391 Decl *currentDecl = getCurFunctionOrMethodDecl();
Fariborz Jahanian94627442010-07-23 21:53:24 +00002392 if (!currentDecl && getCurBlock())
2393 currentDecl = getCurBlock()->TheDecl;
Anders Carlsson2fb08242009-09-08 18:24:21 +00002394 if (!currentDecl) {
Chris Lattnerf45c5ec2008-12-12 05:05:20 +00002395 Diag(Loc, diag::ext_predef_outside_function);
Anders Carlsson2fb08242009-09-08 18:24:21 +00002396 currentDecl = Context.getTranslationUnitDecl();
Chris Lattnerf45c5ec2008-12-12 05:05:20 +00002397 }
Sebastian Redlffbcf962009-01-18 18:53:16 +00002398
Anders Carlsson0b209a82009-09-11 01:22:35 +00002399 QualType ResTy;
2400 if (cast<DeclContext>(currentDecl)->isDependentContext()) {
2401 ResTy = Context.DependentTy;
2402 } else {
Anders Carlsson5bd8d192010-02-11 18:20:28 +00002403 unsigned Length = PredefinedExpr::ComputeName(IT, currentDecl).length();
Sebastian Redlffbcf962009-01-18 18:53:16 +00002404
Anders Carlsson0b209a82009-09-11 01:22:35 +00002405 llvm::APInt LengthI(32, Length + 1);
John McCall8ccfcb52009-09-24 19:53:00 +00002406 ResTy = Context.CharTy.withConst();
Anders Carlsson0b209a82009-09-11 01:22:35 +00002407 ResTy = Context.getConstantArrayType(ResTy, LengthI, ArrayType::Normal, 0);
2408 }
Steve Narofff6009ed2009-01-21 00:14:39 +00002409 return Owned(new (Context) PredefinedExpr(Loc, ResTy, IT));
Chris Lattnere168f762006-11-10 05:29:30 +00002410}
2411
Richard Smithbcc22fc2012-03-09 08:00:36 +00002412ExprResult Sema::ActOnCharacterConstant(const Token &Tok, Scope *UDLScope) {
Dylan Noblesmith2c1dd272012-02-05 02:13:05 +00002413 SmallString<16> CharBuffer;
Douglas Gregordc970f02010-03-16 22:30:13 +00002414 bool Invalid = false;
Chris Lattner0e62c1c2011-07-23 10:55:15 +00002415 StringRef ThisTok = PP.getSpelling(Tok, CharBuffer, &Invalid);
Douglas Gregordc970f02010-03-16 22:30:13 +00002416 if (Invalid)
2417 return ExprError();
Sebastian Redlffbcf962009-01-18 18:53:16 +00002418
Benjamin Kramer0a1abd42010-02-27 13:44:12 +00002419 CharLiteralParser Literal(ThisTok.begin(), ThisTok.end(), Tok.getLocation(),
Douglas Gregorfb65e592011-07-27 05:40:30 +00002420 PP, Tok.getKind());
Steve Naroffae4143e2007-04-26 20:39:23 +00002421 if (Literal.hadError())
Sebastian Redlffbcf962009-01-18 18:53:16 +00002422 return ExprError();
Chris Lattneref24b382008-03-01 08:32:21 +00002423
Chris Lattnerc3847ba2009-12-30 21:19:39 +00002424 QualType Ty;
Seth Cantrell02f86052012-01-18 12:27:06 +00002425 if (Literal.isWide())
2426 Ty = Context.WCharTy; // L'x' -> wchar_t in C and C++.
Douglas Gregorfb65e592011-07-27 05:40:30 +00002427 else if (Literal.isUTF16())
Seth Cantrell02f86052012-01-18 12:27:06 +00002428 Ty = Context.Char16Ty; // u'x' -> char16_t in C11 and C++11.
Douglas Gregorfb65e592011-07-27 05:40:30 +00002429 else if (Literal.isUTF32())
Seth Cantrell02f86052012-01-18 12:27:06 +00002430 Ty = Context.Char32Ty; // U'x' -> char32_t in C11 and C++11.
David Blaikiebbafb8a2012-03-11 07:00:24 +00002431 else if (!getLangOpts().CPlusPlus || Literal.isMultiChar())
Seth Cantrell02f86052012-01-18 12:27:06 +00002432 Ty = Context.IntTy; // 'x' -> int in C, 'wxyz' -> int in C++.
Chris Lattnerc3847ba2009-12-30 21:19:39 +00002433 else
2434 Ty = Context.CharTy; // 'x' -> char in C++
Chris Lattneref24b382008-03-01 08:32:21 +00002435
Douglas Gregorfb65e592011-07-27 05:40:30 +00002436 CharacterLiteral::CharacterKind Kind = CharacterLiteral::Ascii;
2437 if (Literal.isWide())
2438 Kind = CharacterLiteral::Wide;
2439 else if (Literal.isUTF16())
2440 Kind = CharacterLiteral::UTF16;
2441 else if (Literal.isUTF32())
2442 Kind = CharacterLiteral::UTF32;
2443
Richard Smith75b67d62012-03-08 01:34:56 +00002444 Expr *Lit = new (Context) CharacterLiteral(Literal.getValue(), Kind, Ty,
2445 Tok.getLocation());
2446
2447 if (Literal.getUDSuffix().empty())
2448 return Owned(Lit);
2449
2450 // We're building a user-defined literal.
2451 IdentifierInfo *UDSuffix = &Context.Idents.get(Literal.getUDSuffix());
2452 SourceLocation UDSuffixLoc =
2453 getUDSuffixLoc(*this, Tok.getLocation(), Literal.getUDSuffixOffset());
2454
Richard Smithbcc22fc2012-03-09 08:00:36 +00002455 // Make sure we're allowed user-defined literals here.
2456 if (!UDLScope)
2457 return ExprError(Diag(UDSuffixLoc, diag::err_invalid_character_udl));
2458
Richard Smith75b67d62012-03-08 01:34:56 +00002459 // C++11 [lex.ext]p6: The literal L is treated as a call of the form
2460 // operator "" X (ch)
Richard Smithbcc22fc2012-03-09 08:00:36 +00002461 return BuildCookedLiteralOperatorCall(*this, UDLScope, UDSuffix, UDSuffixLoc,
2462 llvm::makeArrayRef(&Lit, 1),
2463 Tok.getLocation());
Steve Naroffae4143e2007-04-26 20:39:23 +00002464}
2465
Ted Kremeneke65b0862012-03-06 20:05:56 +00002466ExprResult Sema::ActOnIntegerConstant(SourceLocation Loc, uint64_t Val) {
2467 unsigned IntSize = Context.getTargetInfo().getIntWidth();
2468 return Owned(IntegerLiteral::Create(Context, llvm::APInt(IntSize, Val),
2469 Context.IntTy, Loc));
2470}
2471
Richard Smith39570d002012-03-08 08:45:32 +00002472static Expr *BuildFloatingLiteral(Sema &S, NumericLiteralParser &Literal,
2473 QualType Ty, SourceLocation Loc) {
2474 const llvm::fltSemantics &Format = S.Context.getFloatTypeSemantics(Ty);
2475
2476 using llvm::APFloat;
2477 APFloat Val(Format);
2478
2479 APFloat::opStatus result = Literal.GetFloatValue(Val);
2480
2481 // Overflow is always an error, but underflow is only an error if
2482 // we underflowed to zero (APFloat reports denormals as underflow).
2483 if ((result & APFloat::opOverflow) ||
2484 ((result & APFloat::opUnderflow) && Val.isZero())) {
2485 unsigned diagnostic;
2486 SmallString<20> buffer;
2487 if (result & APFloat::opOverflow) {
2488 diagnostic = diag::warn_float_overflow;
2489 APFloat::getLargest(Format).toString(buffer);
2490 } else {
2491 diagnostic = diag::warn_float_underflow;
2492 APFloat::getSmallest(Format).toString(buffer);
2493 }
2494
2495 S.Diag(Loc, diagnostic)
2496 << Ty
2497 << StringRef(buffer.data(), buffer.size());
2498 }
2499
2500 bool isExact = (result == APFloat::opOK);
2501 return FloatingLiteral::Create(S.Context, Val, isExact, Ty, Loc);
2502}
2503
Richard Smithbcc22fc2012-03-09 08:00:36 +00002504ExprResult Sema::ActOnNumericConstant(const Token &Tok, Scope *UDLScope) {
Sebastian Redlffbcf962009-01-18 18:53:16 +00002505 // Fast path for a single digit (which is quite common). A single digit
Richard Smithbcc22fc2012-03-09 08:00:36 +00002506 // cannot have a trigraph, escaped newline, radix prefix, or suffix.
Steve Narofff2fb89e2007-03-13 20:29:44 +00002507 if (Tok.getLength() == 1) {
Chris Lattner9240b3e2009-01-26 22:36:52 +00002508 const char Val = PP.getSpellingOfSingleCharacterNumericConstant(Tok);
Ted Kremeneke65b0862012-03-06 20:05:56 +00002509 return ActOnIntegerConstant(Tok.getLocation(), Val-'0');
Steve Narofff2fb89e2007-03-13 20:29:44 +00002510 }
Ted Kremeneke9814182009-01-13 23:19:12 +00002511
Dylan Noblesmith2c1dd272012-02-05 02:13:05 +00002512 SmallString<512> IntegerBuffer;
Chris Lattnera1cf5f92008-09-30 20:53:45 +00002513 // Add padding so that NumericLiteralParser can overread by one character.
2514 IntegerBuffer.resize(Tok.getLength()+1);
Steve Naroff8160ea22007-03-06 01:09:46 +00002515 const char *ThisTokBegin = &IntegerBuffer[0];
Sebastian Redlffbcf962009-01-18 18:53:16 +00002516
Chris Lattner67ca9252007-05-21 01:08:44 +00002517 // Get the spelling of the token, which eliminates trigraphs, etc.
Douglas Gregordc970f02010-03-16 22:30:13 +00002518 bool Invalid = false;
2519 unsigned ActualLength = PP.getSpelling(Tok, ThisTokBegin, &Invalid);
2520 if (Invalid)
2521 return ExprError();
Sebastian Redlffbcf962009-01-18 18:53:16 +00002522
Mike Stump11289f42009-09-09 15:08:12 +00002523 NumericLiteralParser Literal(ThisTokBegin, ThisTokBegin+ActualLength,
Steve Naroff451d8f162007-03-12 23:22:38 +00002524 Tok.getLocation(), PP);
Steve Narofff2fb89e2007-03-13 20:29:44 +00002525 if (Literal.hadError)
Sebastian Redlffbcf962009-01-18 18:53:16 +00002526 return ExprError();
2527
Richard Smith39570d002012-03-08 08:45:32 +00002528 if (Literal.hasUDSuffix()) {
2529 // We're building a user-defined literal.
2530 IdentifierInfo *UDSuffix = &Context.Idents.get(Literal.getUDSuffix());
2531 SourceLocation UDSuffixLoc =
2532 getUDSuffixLoc(*this, Tok.getLocation(), Literal.getUDSuffixOffset());
2533
Richard Smithbcc22fc2012-03-09 08:00:36 +00002534 // Make sure we're allowed user-defined literals here.
2535 if (!UDLScope)
2536 return ExprError(Diag(UDSuffixLoc, diag::err_invalid_numeric_udl));
Richard Smith39570d002012-03-08 08:45:32 +00002537
Richard Smithbcc22fc2012-03-09 08:00:36 +00002538 QualType CookedTy;
Richard Smith39570d002012-03-08 08:45:32 +00002539 if (Literal.isFloatingLiteral()) {
2540 // C++11 [lex.ext]p4: If S contains a literal operator with parameter type
2541 // long double, the literal is treated as a call of the form
2542 // operator "" X (f L)
Richard Smithbcc22fc2012-03-09 08:00:36 +00002543 CookedTy = Context.LongDoubleTy;
Richard Smith39570d002012-03-08 08:45:32 +00002544 } else {
2545 // C++11 [lex.ext]p3: If S contains a literal operator with parameter type
2546 // unsigned long long, the literal is treated as a call of the form
2547 // operator "" X (n ULL)
Richard Smithbcc22fc2012-03-09 08:00:36 +00002548 CookedTy = Context.UnsignedLongLongTy;
Richard Smith39570d002012-03-08 08:45:32 +00002549 }
2550
Richard Smithbcc22fc2012-03-09 08:00:36 +00002551 DeclarationName OpName =
2552 Context.DeclarationNames.getCXXLiteralOperatorName(UDSuffix);
2553 DeclarationNameInfo OpNameInfo(OpName, UDSuffixLoc);
2554 OpNameInfo.setCXXLiteralOperatorNameLoc(UDSuffixLoc);
2555
2556 // Perform literal operator lookup to determine if we're building a raw
2557 // literal or a cooked one.
2558 LookupResult R(*this, OpName, UDSuffixLoc, LookupOrdinaryName);
2559 switch (LookupLiteralOperator(UDLScope, R, llvm::makeArrayRef(&CookedTy, 1),
2560 /*AllowRawAndTemplate*/true)) {
2561 case LOLR_Error:
2562 return ExprError();
2563
2564 case LOLR_Cooked: {
2565 Expr *Lit;
2566 if (Literal.isFloatingLiteral()) {
2567 Lit = BuildFloatingLiteral(*this, Literal, CookedTy, Tok.getLocation());
2568 } else {
2569 llvm::APInt ResultVal(Context.getTargetInfo().getLongLongWidth(), 0);
2570 if (Literal.GetIntegerValue(ResultVal))
2571 Diag(Tok.getLocation(), diag::warn_integer_too_large);
2572 Lit = IntegerLiteral::Create(Context, ResultVal, CookedTy,
2573 Tok.getLocation());
2574 }
2575 return BuildLiteralOperatorCall(R, OpNameInfo,
2576 llvm::makeArrayRef(&Lit, 1),
2577 Tok.getLocation());
2578 }
2579
2580 case LOLR_Raw: {
2581 // C++11 [lit.ext]p3, p4: If S contains a raw literal operator, the
2582 // literal is treated as a call of the form
2583 // operator "" X ("n")
2584 SourceLocation TokLoc = Tok.getLocation();
2585 unsigned Length = Literal.getUDSuffixOffset();
2586 QualType StrTy = Context.getConstantArrayType(
2587 Context.CharTy, llvm::APInt(32, Length + 1),
2588 ArrayType::Normal, 0);
2589 Expr *Lit = StringLiteral::Create(
2590 Context, StringRef(ThisTokBegin, Length), StringLiteral::Ascii,
2591 /*Pascal*/false, StrTy, &TokLoc, 1);
2592 return BuildLiteralOperatorCall(R, OpNameInfo,
2593 llvm::makeArrayRef(&Lit, 1), TokLoc);
2594 }
2595
2596 case LOLR_Template:
2597 // C++11 [lit.ext]p3, p4: Otherwise (S contains a literal operator
2598 // template), L is treated as a call fo the form
2599 // operator "" X <'c1', 'c2', ... 'ck'>()
2600 // where n is the source character sequence c1 c2 ... ck.
2601 TemplateArgumentListInfo ExplicitArgs;
2602 unsigned CharBits = Context.getIntWidth(Context.CharTy);
2603 bool CharIsUnsigned = Context.CharTy->isUnsignedIntegerType();
2604 llvm::APSInt Value(CharBits, CharIsUnsigned);
2605 for (unsigned I = 0, N = Literal.getUDSuffixOffset(); I != N; ++I) {
2606 Value = ThisTokBegin[I];
2607 TemplateArgument Arg(Value, Context.CharTy);
2608 TemplateArgumentLocInfo ArgInfo;
2609 ExplicitArgs.addArgument(TemplateArgumentLoc(Arg, ArgInfo));
2610 }
2611 return BuildLiteralOperatorCall(R, OpNameInfo, ArrayRef<Expr*>(),
2612 Tok.getLocation(), &ExplicitArgs);
2613 }
2614
2615 llvm_unreachable("unexpected literal operator lookup result");
Richard Smith39570d002012-03-08 08:45:32 +00002616 }
2617
Chris Lattner1c20a172007-08-26 03:42:43 +00002618 Expr *Res;
Sebastian Redlffbcf962009-01-18 18:53:16 +00002619
Chris Lattner1c20a172007-08-26 03:42:43 +00002620 if (Literal.isFloatingLiteral()) {
Chris Lattnerec0a6d92007-09-22 18:29:59 +00002621 QualType Ty;
Chris Lattner9a8d1d92008-06-30 18:32:54 +00002622 if (Literal.isFloat)
Chris Lattnerec0a6d92007-09-22 18:29:59 +00002623 Ty = Context.FloatTy;
Chris Lattner9a8d1d92008-06-30 18:32:54 +00002624 else if (!Literal.isLong)
Chris Lattnerec0a6d92007-09-22 18:29:59 +00002625 Ty = Context.DoubleTy;
Chris Lattner9a8d1d92008-06-30 18:32:54 +00002626 else
Chris Lattner7570e9c2008-03-08 08:52:55 +00002627 Ty = Context.LongDoubleTy;
Chris Lattner9a8d1d92008-06-30 18:32:54 +00002628
Richard Smith39570d002012-03-08 08:45:32 +00002629 Res = BuildFloatingLiteral(*this, Literal, Ty, Tok.getLocation());
Sebastian Redlffbcf962009-01-18 18:53:16 +00002630
Peter Collingbournec77f85b2011-03-11 19:24:59 +00002631 if (Ty == Context.DoubleTy) {
David Blaikiebbafb8a2012-03-11 07:00:24 +00002632 if (getLangOpts().SinglePrecisionConstants) {
John Wiegley01296292011-04-08 18:41:53 +00002633 Res = ImpCastExprToType(Res, Context.FloatTy, CK_FloatingCast).take();
David Blaikiebbafb8a2012-03-11 07:00:24 +00002634 } else if (getLangOpts().OpenCL && !getOpenCLOptions().cl_khr_fp64) {
Peter Collingbournec77f85b2011-03-11 19:24:59 +00002635 Diag(Tok.getLocation(), diag::warn_double_const_requires_fp64);
John Wiegley01296292011-04-08 18:41:53 +00002636 Res = ImpCastExprToType(Res, Context.FloatTy, CK_FloatingCast).take();
Peter Collingbournec77f85b2011-03-11 19:24:59 +00002637 }
2638 }
Chris Lattner1c20a172007-08-26 03:42:43 +00002639 } else if (!Literal.isIntegerLiteral()) {
Sebastian Redlffbcf962009-01-18 18:53:16 +00002640 return ExprError();
Chris Lattner1c20a172007-08-26 03:42:43 +00002641 } else {
Chris Lattner24d5bfe2008-04-02 04:24:33 +00002642 QualType Ty;
Chris Lattner67ca9252007-05-21 01:08:44 +00002643
Neil Boothac582c52007-08-29 22:00:19 +00002644 // long long is a C99 feature.
David Blaikiebbafb8a2012-03-11 07:00:24 +00002645 if (!getLangOpts().C99 && Literal.isLongLong)
Richard Smith0bf8a4922011-10-18 20:49:44 +00002646 Diag(Tok.getLocation(),
David Blaikiebbafb8a2012-03-11 07:00:24 +00002647 getLangOpts().CPlusPlus0x ?
Richard Smith0bf8a4922011-10-18 20:49:44 +00002648 diag::warn_cxx98_compat_longlong : diag::ext_longlong);
Neil Boothac582c52007-08-29 22:00:19 +00002649
Chris Lattner67ca9252007-05-21 01:08:44 +00002650 // Get the value in the widest-possible width.
Stephen Canonfdc6c1a2012-05-03 22:49:43 +00002651 unsigned MaxWidth = Context.getTargetInfo().getIntMaxTWidth();
2652 // The microsoft literal suffix extensions support 128-bit literals, which
2653 // may be wider than [u]intmax_t.
2654 if (Literal.isMicrosoftInteger && MaxWidth < 128)
2655 MaxWidth = 128;
2656 llvm::APInt ResultVal(MaxWidth, 0);
Sebastian Redlffbcf962009-01-18 18:53:16 +00002657
Chris Lattner67ca9252007-05-21 01:08:44 +00002658 if (Literal.GetIntegerValue(ResultVal)) {
2659 // If this value didn't fit into uintmax_t, warn and force to ull.
2660 Diag(Tok.getLocation(), diag::warn_integer_too_large);
Chris Lattner24d5bfe2008-04-02 04:24:33 +00002661 Ty = Context.UnsignedLongLongTy;
2662 assert(Context.getTypeSize(Ty) == ResultVal.getBitWidth() &&
Chris Lattner37e05872008-03-05 18:54:05 +00002663 "long long is not intmax_t?");
Steve Naroff09ef4742007-03-09 23:16:33 +00002664 } else {
Chris Lattner67ca9252007-05-21 01:08:44 +00002665 // If this value fits into a ULL, try to figure out what else it fits into
2666 // according to the rules of C99 6.4.4.1p5.
Sebastian Redlffbcf962009-01-18 18:53:16 +00002667
Chris Lattner67ca9252007-05-21 01:08:44 +00002668 // Octal, Hexadecimal, and integers with a U suffix are allowed to
2669 // be an unsigned int.
2670 bool AllowUnsigned = Literal.isUnsigned || Literal.getRadix() != 10;
2671
2672 // Check from smallest to largest, picking the smallest type we can.
Chris Lattner55258cf2008-05-09 05:59:00 +00002673 unsigned Width = 0;
Chris Lattner7b939cf2007-08-23 21:58:08 +00002674 if (!Literal.isLong && !Literal.isLongLong) {
2675 // Are int/unsigned possibilities?
Douglas Gregore8bbc122011-09-02 00:18:52 +00002676 unsigned IntSize = Context.getTargetInfo().getIntWidth();
Sebastian Redlffbcf962009-01-18 18:53:16 +00002677
Chris Lattner67ca9252007-05-21 01:08:44 +00002678 // Does it fit in a unsigned int?
2679 if (ResultVal.isIntN(IntSize)) {
2680 // Does it fit in a signed int?
2681 if (!Literal.isUnsigned && ResultVal[IntSize-1] == 0)
Chris Lattner24d5bfe2008-04-02 04:24:33 +00002682 Ty = Context.IntTy;
Chris Lattner67ca9252007-05-21 01:08:44 +00002683 else if (AllowUnsigned)
Chris Lattner24d5bfe2008-04-02 04:24:33 +00002684 Ty = Context.UnsignedIntTy;
Chris Lattner55258cf2008-05-09 05:59:00 +00002685 Width = IntSize;
Chris Lattner67ca9252007-05-21 01:08:44 +00002686 }
Chris Lattner67ca9252007-05-21 01:08:44 +00002687 }
Sebastian Redlffbcf962009-01-18 18:53:16 +00002688
Chris Lattner67ca9252007-05-21 01:08:44 +00002689 // Are long/unsigned long possibilities?
Chris Lattner24d5bfe2008-04-02 04:24:33 +00002690 if (Ty.isNull() && !Literal.isLongLong) {
Douglas Gregore8bbc122011-09-02 00:18:52 +00002691 unsigned LongSize = Context.getTargetInfo().getLongWidth();
Sebastian Redlffbcf962009-01-18 18:53:16 +00002692
Chris Lattner67ca9252007-05-21 01:08:44 +00002693 // Does it fit in a unsigned long?
2694 if (ResultVal.isIntN(LongSize)) {
2695 // Does it fit in a signed long?
2696 if (!Literal.isUnsigned && ResultVal[LongSize-1] == 0)
Chris Lattner24d5bfe2008-04-02 04:24:33 +00002697 Ty = Context.LongTy;
Chris Lattner67ca9252007-05-21 01:08:44 +00002698 else if (AllowUnsigned)
Chris Lattner24d5bfe2008-04-02 04:24:33 +00002699 Ty = Context.UnsignedLongTy;
Chris Lattner55258cf2008-05-09 05:59:00 +00002700 Width = LongSize;
Chris Lattner67ca9252007-05-21 01:08:44 +00002701 }
Sebastian Redlffbcf962009-01-18 18:53:16 +00002702 }
2703
Stephen Canonfdc6c1a2012-05-03 22:49:43 +00002704 // Check long long if needed.
Chris Lattner24d5bfe2008-04-02 04:24:33 +00002705 if (Ty.isNull()) {
Douglas Gregore8bbc122011-09-02 00:18:52 +00002706 unsigned LongLongSize = Context.getTargetInfo().getLongLongWidth();
Sebastian Redlffbcf962009-01-18 18:53:16 +00002707
Chris Lattner67ca9252007-05-21 01:08:44 +00002708 // Does it fit in a unsigned long long?
2709 if (ResultVal.isIntN(LongLongSize)) {
2710 // Does it fit in a signed long long?
Francois Pichetc3e73b32011-01-11 23:38:13 +00002711 // To be compatible with MSVC, hex integer literals ending with the
2712 // LL or i64 suffix are always signed in Microsoft mode.
Francois Pichetbf711d92011-01-11 12:23:00 +00002713 if (!Literal.isUnsigned && (ResultVal[LongLongSize-1] == 0 ||
David Blaikiebbafb8a2012-03-11 07:00:24 +00002714 (getLangOpts().MicrosoftExt && Literal.isLongLong)))
Chris Lattner24d5bfe2008-04-02 04:24:33 +00002715 Ty = Context.LongLongTy;
Chris Lattner67ca9252007-05-21 01:08:44 +00002716 else if (AllowUnsigned)
Chris Lattner24d5bfe2008-04-02 04:24:33 +00002717 Ty = Context.UnsignedLongLongTy;
Chris Lattner55258cf2008-05-09 05:59:00 +00002718 Width = LongLongSize;
Chris Lattner67ca9252007-05-21 01:08:44 +00002719 }
2720 }
Stephen Canonfdc6c1a2012-05-03 22:49:43 +00002721
2722 // If it doesn't fit in unsigned long long, and we're using Microsoft
2723 // extensions, then its a 128-bit integer literal.
2724 if (Ty.isNull() && Literal.isMicrosoftInteger) {
2725 if (Literal.isUnsigned)
2726 Ty = Context.UnsignedInt128Ty;
2727 else
2728 Ty = Context.Int128Ty;
2729 Width = 128;
2730 }
Sebastian Redlffbcf962009-01-18 18:53:16 +00002731
Chris Lattner67ca9252007-05-21 01:08:44 +00002732 // If we still couldn't decide a type, we probably have something that
2733 // does not fit in a signed long long, but has no U suffix.
Chris Lattner24d5bfe2008-04-02 04:24:33 +00002734 if (Ty.isNull()) {
Chris Lattner67ca9252007-05-21 01:08:44 +00002735 Diag(Tok.getLocation(), diag::warn_integer_too_large_for_signed);
Chris Lattner24d5bfe2008-04-02 04:24:33 +00002736 Ty = Context.UnsignedLongLongTy;
Douglas Gregore8bbc122011-09-02 00:18:52 +00002737 Width = Context.getTargetInfo().getLongLongWidth();
Chris Lattner67ca9252007-05-21 01:08:44 +00002738 }
Sebastian Redlffbcf962009-01-18 18:53:16 +00002739
Chris Lattner55258cf2008-05-09 05:59:00 +00002740 if (ResultVal.getBitWidth() != Width)
Jay Foad6d4db0c2010-12-07 08:25:34 +00002741 ResultVal = ResultVal.trunc(Width);
Steve Naroff09ef4742007-03-09 23:16:33 +00002742 }
Argyrios Kyrtzidis43b20572010-08-28 09:06:06 +00002743 Res = IntegerLiteral::Create(Context, ResultVal, Ty, Tok.getLocation());
Steve Naroff09ef4742007-03-09 23:16:33 +00002744 }
Sebastian Redlffbcf962009-01-18 18:53:16 +00002745
Chris Lattner1c20a172007-08-26 03:42:43 +00002746 // If this is an imaginary literal, create the ImaginaryLiteral wrapper.
2747 if (Literal.isImaginary)
Mike Stump11289f42009-09-09 15:08:12 +00002748 Res = new (Context) ImaginaryLiteral(Res,
Steve Narofff6009ed2009-01-21 00:14:39 +00002749 Context.getComplexType(Res->getType()));
Sebastian Redlffbcf962009-01-18 18:53:16 +00002750
2751 return Owned(Res);
Chris Lattnere168f762006-11-10 05:29:30 +00002752}
2753
Richard Trieuba63ce62011-09-09 01:45:06 +00002754ExprResult Sema::ActOnParenExpr(SourceLocation L, SourceLocation R, Expr *E) {
Chris Lattner24d5bfe2008-04-02 04:24:33 +00002755 assert((E != 0) && "ActOnParenExpr() missing expr");
Steve Narofff6009ed2009-01-21 00:14:39 +00002756 return Owned(new (Context) ParenExpr(L, R, E));
Chris Lattnere168f762006-11-10 05:29:30 +00002757}
2758
Chandler Carruth62da79c2011-05-26 08:53:12 +00002759static bool CheckVecStepTraitOperandType(Sema &S, QualType T,
2760 SourceLocation Loc,
2761 SourceRange ArgRange) {
2762 // [OpenCL 1.1 6.11.12] "The vec_step built-in function takes a built-in
2763 // scalar or vector data type argument..."
2764 // Every built-in scalar type (OpenCL 1.1 6.1.1) is either an arithmetic
2765 // type (C99 6.2.5p18) or void.
2766 if (!(T->isArithmeticType() || T->isVoidType() || T->isVectorType())) {
2767 S.Diag(Loc, diag::err_vecstep_non_scalar_vector_type)
2768 << T << ArgRange;
2769 return true;
2770 }
2771
2772 assert((T->isVoidType() || !T->isIncompleteType()) &&
2773 "Scalar types should always be complete");
2774 return false;
2775}
2776
Chandler Carruthcea1aac2011-05-26 08:53:16 +00002777static bool CheckExtensionTraitOperandType(Sema &S, QualType T,
2778 SourceLocation Loc,
2779 SourceRange ArgRange,
2780 UnaryExprOrTypeTrait TraitKind) {
2781 // C99 6.5.3.4p1:
2782 if (T->isFunctionType()) {
2783 // alignof(function) is allowed as an extension.
2784 if (TraitKind == UETT_SizeOf)
2785 S.Diag(Loc, diag::ext_sizeof_function_type) << ArgRange;
2786 return false;
2787 }
2788
2789 // Allow sizeof(void)/alignof(void) as an extension.
2790 if (T->isVoidType()) {
2791 S.Diag(Loc, diag::ext_sizeof_void_type) << TraitKind << ArgRange;
2792 return false;
2793 }
2794
2795 return true;
2796}
2797
2798static bool CheckObjCTraitOperandConstraints(Sema &S, QualType T,
2799 SourceLocation Loc,
2800 SourceRange ArgRange,
2801 UnaryExprOrTypeTrait TraitKind) {
2802 // Reject sizeof(interface) and sizeof(interface<proto>) in 64-bit mode.
2803 if (S.LangOpts.ObjCNonFragileABI && T->isObjCObjectType()) {
2804 S.Diag(Loc, diag::err_sizeof_nonfragile_interface)
2805 << T << (TraitKind == UETT_SizeOf)
2806 << ArgRange;
2807 return true;
2808 }
2809
2810 return false;
2811}
2812
Chandler Carruth14502c22011-05-26 08:53:10 +00002813/// \brief Check the constrains on expression operands to unary type expression
2814/// and type traits.
2815///
Chandler Carruth7c430c02011-05-27 01:33:31 +00002816/// Completes any types necessary and validates the constraints on the operand
2817/// expression. The logic mostly mirrors the type-based overload, but may modify
2818/// the expression as it completes the type for that expression through template
2819/// instantiation, etc.
Richard Trieuba63ce62011-09-09 01:45:06 +00002820bool Sema::CheckUnaryExprOrTypeTraitOperand(Expr *E,
Chandler Carruth14502c22011-05-26 08:53:10 +00002821 UnaryExprOrTypeTrait ExprKind) {
Richard Trieuba63ce62011-09-09 01:45:06 +00002822 QualType ExprTy = E->getType();
Chandler Carruth7c430c02011-05-27 01:33:31 +00002823
2824 // C++ [expr.sizeof]p2: "When applied to a reference or a reference type,
2825 // the result is the size of the referenced type."
2826 // C++ [expr.alignof]p3: "When alignof is applied to a reference type, the
2827 // result shall be the alignment of the referenced type."
2828 if (const ReferenceType *Ref = ExprTy->getAs<ReferenceType>())
2829 ExprTy = Ref->getPointeeType();
2830
2831 if (ExprKind == UETT_VecStep)
Richard Trieuba63ce62011-09-09 01:45:06 +00002832 return CheckVecStepTraitOperandType(*this, ExprTy, E->getExprLoc(),
2833 E->getSourceRange());
Chandler Carruth7c430c02011-05-27 01:33:31 +00002834
2835 // Whitelist some types as extensions
Richard Trieuba63ce62011-09-09 01:45:06 +00002836 if (!CheckExtensionTraitOperandType(*this, ExprTy, E->getExprLoc(),
2837 E->getSourceRange(), ExprKind))
Chandler Carruth7c430c02011-05-27 01:33:31 +00002838 return false;
2839
Richard Trieuba63ce62011-09-09 01:45:06 +00002840 if (RequireCompleteExprType(E,
Douglas Gregor7bfb2d02012-05-04 16:32:21 +00002841 diag::err_sizeof_alignof_incomplete_type,
2842 ExprKind, E->getSourceRange()))
Chandler Carruth7c430c02011-05-27 01:33:31 +00002843 return true;
2844
2845 // Completeing the expression's type may have changed it.
Richard Trieuba63ce62011-09-09 01:45:06 +00002846 ExprTy = E->getType();
Chandler Carruth7c430c02011-05-27 01:33:31 +00002847 if (const ReferenceType *Ref = ExprTy->getAs<ReferenceType>())
2848 ExprTy = Ref->getPointeeType();
2849
Richard Trieuba63ce62011-09-09 01:45:06 +00002850 if (CheckObjCTraitOperandConstraints(*this, ExprTy, E->getExprLoc(),
2851 E->getSourceRange(), ExprKind))
Chandler Carruth7c430c02011-05-27 01:33:31 +00002852 return true;
2853
Nico Weber0870deb2011-06-15 02:47:03 +00002854 if (ExprKind == UETT_SizeOf) {
Richard Trieuba63ce62011-09-09 01:45:06 +00002855 if (DeclRefExpr *DeclRef = dyn_cast<DeclRefExpr>(E->IgnoreParens())) {
Nico Weber0870deb2011-06-15 02:47:03 +00002856 if (ParmVarDecl *PVD = dyn_cast<ParmVarDecl>(DeclRef->getFoundDecl())) {
2857 QualType OType = PVD->getOriginalType();
2858 QualType Type = PVD->getType();
2859 if (Type->isPointerType() && OType->isArrayType()) {
Richard Trieuba63ce62011-09-09 01:45:06 +00002860 Diag(E->getExprLoc(), diag::warn_sizeof_array_param)
Nico Weber0870deb2011-06-15 02:47:03 +00002861 << Type << OType;
2862 Diag(PVD->getLocation(), diag::note_declared_at);
2863 }
2864 }
2865 }
2866 }
2867
Chandler Carruth7c430c02011-05-27 01:33:31 +00002868 return false;
Chandler Carruth14502c22011-05-26 08:53:10 +00002869}
2870
2871/// \brief Check the constraints on operands to unary expression and type
2872/// traits.
2873///
2874/// This will complete any types necessary, and validate the various constraints
2875/// on those operands.
2876///
Steve Naroff71b59a92007-06-04 22:22:31 +00002877/// The UsualUnaryConversions() function is *not* called by this routine.
Chandler Carruth14502c22011-05-26 08:53:10 +00002878/// C99 6.3.2.1p[2-4] all state:
2879/// Except when it is the operand of the sizeof operator ...
2880///
2881/// C++ [expr.sizeof]p4
2882/// The lvalue-to-rvalue, array-to-pointer, and function-to-pointer
2883/// standard conversions are not applied to the operand of sizeof.
2884///
2885/// This policy is followed for all of the unary trait expressions.
Richard Trieuba63ce62011-09-09 01:45:06 +00002886bool Sema::CheckUnaryExprOrTypeTraitOperand(QualType ExprType,
Peter Collingbournee190dee2011-03-11 19:24:49 +00002887 SourceLocation OpLoc,
2888 SourceRange ExprRange,
2889 UnaryExprOrTypeTrait ExprKind) {
Richard Trieuba63ce62011-09-09 01:45:06 +00002890 if (ExprType->isDependentType())
Sebastian Redl8d2ccae2009-02-26 14:39:58 +00002891 return false;
2892
Sebastian Redl22e2e5c2009-11-23 17:18:46 +00002893 // C++ [expr.sizeof]p2: "When applied to a reference or a reference type,
2894 // the result is the size of the referenced type."
2895 // C++ [expr.alignof]p3: "When alignof is applied to a reference type, the
2896 // result shall be the alignment of the referenced type."
Richard Trieuba63ce62011-09-09 01:45:06 +00002897 if (const ReferenceType *Ref = ExprType->getAs<ReferenceType>())
2898 ExprType = Ref->getPointeeType();
Sebastian Redl22e2e5c2009-11-23 17:18:46 +00002899
Chandler Carruth62da79c2011-05-26 08:53:12 +00002900 if (ExprKind == UETT_VecStep)
Richard Trieuba63ce62011-09-09 01:45:06 +00002901 return CheckVecStepTraitOperandType(*this, ExprType, OpLoc, ExprRange);
Peter Collingbournee190dee2011-03-11 19:24:49 +00002902
Chandler Carruthcea1aac2011-05-26 08:53:16 +00002903 // Whitelist some types as extensions
Richard Trieuba63ce62011-09-09 01:45:06 +00002904 if (!CheckExtensionTraitOperandType(*this, ExprType, OpLoc, ExprRange,
Chandler Carruthcea1aac2011-05-26 08:53:16 +00002905 ExprKind))
Chris Lattnerb1355b12009-01-24 19:46:37 +00002906 return false;
Mike Stump11289f42009-09-09 15:08:12 +00002907
Richard Trieuba63ce62011-09-09 01:45:06 +00002908 if (RequireCompleteType(OpLoc, ExprType,
Douglas Gregor7bfb2d02012-05-04 16:32:21 +00002909 diag::err_sizeof_alignof_incomplete_type,
2910 ExprKind, ExprRange))
Chris Lattner62975a72009-04-24 00:30:45 +00002911 return true;
Mike Stump11289f42009-09-09 15:08:12 +00002912
Richard Trieuba63ce62011-09-09 01:45:06 +00002913 if (CheckObjCTraitOperandConstraints(*this, ExprType, OpLoc, ExprRange,
Chandler Carruthcea1aac2011-05-26 08:53:16 +00002914 ExprKind))
Chris Lattnercd2a8c52009-04-24 22:30:50 +00002915 return true;
Mike Stump11289f42009-09-09 15:08:12 +00002916
Chris Lattner62975a72009-04-24 00:30:45 +00002917 return false;
Steve Naroff043d45d2007-05-15 02:32:35 +00002918}
2919
Chandler Carruth14502c22011-05-26 08:53:10 +00002920static bool CheckAlignOfExpr(Sema &S, Expr *E) {
Chris Lattner8dff0172009-01-24 20:17:12 +00002921 E = E->IgnoreParens();
Sebastian Redl8d2ccae2009-02-26 14:39:58 +00002922
Mike Stump11289f42009-09-09 15:08:12 +00002923 // alignof decl is always ok.
Chris Lattner8dff0172009-01-24 20:17:12 +00002924 if (isa<DeclRefExpr>(E))
2925 return false;
Sebastian Redl8d2ccae2009-02-26 14:39:58 +00002926
2927 // Cannot know anything else if the expression is dependent.
2928 if (E->isTypeDependent())
2929 return false;
2930
Douglas Gregor71235ec2009-05-02 02:18:30 +00002931 if (E->getBitField()) {
Chandler Carruth14502c22011-05-26 08:53:10 +00002932 S.Diag(E->getExprLoc(), diag::err_sizeof_alignof_bitfield)
2933 << 1 << E->getSourceRange();
Douglas Gregor71235ec2009-05-02 02:18:30 +00002934 return true;
Chris Lattner8dff0172009-01-24 20:17:12 +00002935 }
Douglas Gregor71235ec2009-05-02 02:18:30 +00002936
2937 // Alignment of a field access is always okay, so long as it isn't a
2938 // bit-field.
2939 if (MemberExpr *ME = dyn_cast<MemberExpr>(E))
Mike Stump212005c2009-07-22 18:58:19 +00002940 if (isa<FieldDecl>(ME->getMemberDecl()))
Douglas Gregor71235ec2009-05-02 02:18:30 +00002941 return false;
2942
Chandler Carruth14502c22011-05-26 08:53:10 +00002943 return S.CheckUnaryExprOrTypeTraitOperand(E, UETT_AlignOf);
Peter Collingbournee190dee2011-03-11 19:24:49 +00002944}
2945
Chandler Carruth14502c22011-05-26 08:53:10 +00002946bool Sema::CheckVecStepExpr(Expr *E) {
Peter Collingbournee190dee2011-03-11 19:24:49 +00002947 E = E->IgnoreParens();
2948
2949 // Cannot know anything else if the expression is dependent.
2950 if (E->isTypeDependent())
2951 return false;
2952
Chandler Carruth14502c22011-05-26 08:53:10 +00002953 return CheckUnaryExprOrTypeTraitOperand(E, UETT_VecStep);
Chris Lattner8dff0172009-01-24 20:17:12 +00002954}
2955
Douglas Gregor0950e412009-03-13 21:01:28 +00002956/// \brief Build a sizeof or alignof expression given a type operand.
John McCalldadc5752010-08-24 06:29:42 +00002957ExprResult
Peter Collingbournee190dee2011-03-11 19:24:49 +00002958Sema::CreateUnaryExprOrTypeTraitExpr(TypeSourceInfo *TInfo,
2959 SourceLocation OpLoc,
2960 UnaryExprOrTypeTrait ExprKind,
2961 SourceRange R) {
John McCallbcd03502009-12-07 02:54:59 +00002962 if (!TInfo)
Douglas Gregor0950e412009-03-13 21:01:28 +00002963 return ExprError();
2964
John McCallbcd03502009-12-07 02:54:59 +00002965 QualType T = TInfo->getType();
John McCall4c98fd82009-11-04 07:28:41 +00002966
Douglas Gregor0950e412009-03-13 21:01:28 +00002967 if (!T->isDependentType() &&
Peter Collingbournee190dee2011-03-11 19:24:49 +00002968 CheckUnaryExprOrTypeTraitOperand(T, OpLoc, R, ExprKind))
Douglas Gregor0950e412009-03-13 21:01:28 +00002969 return ExprError();
2970
2971 // C99 6.5.3.4p4: the type (an unsigned integer type) is size_t.
Peter Collingbournee190dee2011-03-11 19:24:49 +00002972 return Owned(new (Context) UnaryExprOrTypeTraitExpr(ExprKind, TInfo,
2973 Context.getSizeType(),
2974 OpLoc, R.getEnd()));
Douglas Gregor0950e412009-03-13 21:01:28 +00002975}
2976
2977/// \brief Build a sizeof or alignof expression given an expression
2978/// operand.
John McCalldadc5752010-08-24 06:29:42 +00002979ExprResult
Chandler Carrutha923fb22011-05-29 07:32:14 +00002980Sema::CreateUnaryExprOrTypeTraitExpr(Expr *E, SourceLocation OpLoc,
2981 UnaryExprOrTypeTrait ExprKind) {
Douglas Gregor835af982011-06-22 23:21:00 +00002982 ExprResult PE = CheckPlaceholderExpr(E);
2983 if (PE.isInvalid())
2984 return ExprError();
2985
2986 E = PE.get();
2987
Douglas Gregor0950e412009-03-13 21:01:28 +00002988 // Verify that the operand is valid.
2989 bool isInvalid = false;
2990 if (E->isTypeDependent()) {
2991 // Delay type-checking for type-dependent expressions.
Peter Collingbournee190dee2011-03-11 19:24:49 +00002992 } else if (ExprKind == UETT_AlignOf) {
Chandler Carruth14502c22011-05-26 08:53:10 +00002993 isInvalid = CheckAlignOfExpr(*this, E);
Peter Collingbournee190dee2011-03-11 19:24:49 +00002994 } else if (ExprKind == UETT_VecStep) {
Chandler Carruth14502c22011-05-26 08:53:10 +00002995 isInvalid = CheckVecStepExpr(E);
Douglas Gregor71235ec2009-05-02 02:18:30 +00002996 } else if (E->getBitField()) { // C99 6.5.3.4p1.
Chandler Carruth14502c22011-05-26 08:53:10 +00002997 Diag(E->getExprLoc(), diag::err_sizeof_alignof_bitfield) << 0;
Douglas Gregor0950e412009-03-13 21:01:28 +00002998 isInvalid = true;
2999 } else {
Chandler Carruth14502c22011-05-26 08:53:10 +00003000 isInvalid = CheckUnaryExprOrTypeTraitOperand(E, UETT_SizeOf);
Douglas Gregor0950e412009-03-13 21:01:28 +00003001 }
3002
3003 if (isInvalid)
3004 return ExprError();
3005
Eli Friedmane0afc982012-01-21 01:01:51 +00003006 if (ExprKind == UETT_SizeOf && E->getType()->isVariableArrayType()) {
3007 PE = TranformToPotentiallyEvaluated(E);
3008 if (PE.isInvalid()) return ExprError();
3009 E = PE.take();
3010 }
3011
Douglas Gregor0950e412009-03-13 21:01:28 +00003012 // C99 6.5.3.4p4: the type (an unsigned integer type) is size_t.
Chandler Carruth14502c22011-05-26 08:53:10 +00003013 return Owned(new (Context) UnaryExprOrTypeTraitExpr(
Chandler Carrutha923fb22011-05-29 07:32:14 +00003014 ExprKind, E, Context.getSizeType(), OpLoc,
Chandler Carruth14502c22011-05-26 08:53:10 +00003015 E->getSourceRange().getEnd()));
Douglas Gregor0950e412009-03-13 21:01:28 +00003016}
3017
Peter Collingbournee190dee2011-03-11 19:24:49 +00003018/// ActOnUnaryExprOrTypeTraitExpr - Handle @c sizeof(type) and @c sizeof @c
3019/// expr and the same for @c alignof and @c __alignof
Sebastian Redl6f282892008-11-11 17:56:53 +00003020/// Note that the ArgRange is invalid if isType is false.
John McCalldadc5752010-08-24 06:29:42 +00003021ExprResult
Peter Collingbournee190dee2011-03-11 19:24:49 +00003022Sema::ActOnUnaryExprOrTypeTraitExpr(SourceLocation OpLoc,
Richard Trieuba63ce62011-09-09 01:45:06 +00003023 UnaryExprOrTypeTrait ExprKind, bool IsType,
Peter Collingbournee190dee2011-03-11 19:24:49 +00003024 void *TyOrEx, const SourceRange &ArgRange) {
Chris Lattner0d8b1a12006-11-20 04:34:45 +00003025 // If error parsing type, ignore.
Sebastian Redlc215cfc2009-01-19 00:08:26 +00003026 if (TyOrEx == 0) return ExprError();
Steve Naroff043d45d2007-05-15 02:32:35 +00003027
Richard Trieuba63ce62011-09-09 01:45:06 +00003028 if (IsType) {
John McCallbcd03502009-12-07 02:54:59 +00003029 TypeSourceInfo *TInfo;
John McCallba7bf592010-08-24 05:47:05 +00003030 (void) GetTypeFromParser(ParsedType::getFromOpaquePtr(TyOrEx), &TInfo);
Peter Collingbournee190dee2011-03-11 19:24:49 +00003031 return CreateUnaryExprOrTypeTraitExpr(TInfo, OpLoc, ExprKind, ArgRange);
Mike Stump11289f42009-09-09 15:08:12 +00003032 }
Sebastian Redl6f282892008-11-11 17:56:53 +00003033
Douglas Gregor0950e412009-03-13 21:01:28 +00003034 Expr *ArgEx = (Expr *)TyOrEx;
Chandler Carrutha923fb22011-05-29 07:32:14 +00003035 ExprResult Result = CreateUnaryExprOrTypeTraitExpr(ArgEx, OpLoc, ExprKind);
Douglas Gregor0950e412009-03-13 21:01:28 +00003036 return move(Result);
Chris Lattnere168f762006-11-10 05:29:30 +00003037}
3038
John Wiegley01296292011-04-08 18:41:53 +00003039static QualType CheckRealImagOperand(Sema &S, ExprResult &V, SourceLocation Loc,
Richard Trieuba63ce62011-09-09 01:45:06 +00003040 bool IsReal) {
John Wiegley01296292011-04-08 18:41:53 +00003041 if (V.get()->isTypeDependent())
John McCall4bc41ae2010-11-18 19:01:18 +00003042 return S.Context.DependentTy;
Mike Stump11289f42009-09-09 15:08:12 +00003043
John McCall34376a62010-12-04 03:47:34 +00003044 // _Real and _Imag are only l-values for normal l-values.
John Wiegley01296292011-04-08 18:41:53 +00003045 if (V.get()->getObjectKind() != OK_Ordinary) {
3046 V = S.DefaultLvalueConversion(V.take());
3047 if (V.isInvalid())
3048 return QualType();
3049 }
John McCall34376a62010-12-04 03:47:34 +00003050
Chris Lattnere267f5d2007-08-26 05:39:26 +00003051 // These operators return the element type of a complex type.
John Wiegley01296292011-04-08 18:41:53 +00003052 if (const ComplexType *CT = V.get()->getType()->getAs<ComplexType>())
Chris Lattner30b5dd02007-08-24 21:16:53 +00003053 return CT->getElementType();
Mike Stump11289f42009-09-09 15:08:12 +00003054
Chris Lattnere267f5d2007-08-26 05:39:26 +00003055 // Otherwise they pass through real integer and floating point types here.
John Wiegley01296292011-04-08 18:41:53 +00003056 if (V.get()->getType()->isArithmeticType())
3057 return V.get()->getType();
Mike Stump11289f42009-09-09 15:08:12 +00003058
John McCall36226622010-10-12 02:09:17 +00003059 // Test for placeholders.
John McCall3aef3d82011-04-10 19:13:55 +00003060 ExprResult PR = S.CheckPlaceholderExpr(V.get());
John McCall36226622010-10-12 02:09:17 +00003061 if (PR.isInvalid()) return QualType();
John Wiegley01296292011-04-08 18:41:53 +00003062 if (PR.get() != V.get()) {
3063 V = move(PR);
Richard Trieuba63ce62011-09-09 01:45:06 +00003064 return CheckRealImagOperand(S, V, Loc, IsReal);
John McCall36226622010-10-12 02:09:17 +00003065 }
3066
Chris Lattnere267f5d2007-08-26 05:39:26 +00003067 // Reject anything else.
John Wiegley01296292011-04-08 18:41:53 +00003068 S.Diag(Loc, diag::err_realimag_invalid_type) << V.get()->getType()
Richard Trieuba63ce62011-09-09 01:45:06 +00003069 << (IsReal ? "__real" : "__imag");
Chris Lattnere267f5d2007-08-26 05:39:26 +00003070 return QualType();
Chris Lattner30b5dd02007-08-24 21:16:53 +00003071}
3072
3073
Chris Lattnere168f762006-11-10 05:29:30 +00003074
John McCalldadc5752010-08-24 06:29:42 +00003075ExprResult
Sebastian Redlc215cfc2009-01-19 00:08:26 +00003076Sema::ActOnPostfixUnaryOp(Scope *S, SourceLocation OpLoc,
John McCallb268a282010-08-23 23:25:46 +00003077 tok::TokenKind Kind, Expr *Input) {
John McCalle3027922010-08-25 11:45:40 +00003078 UnaryOperatorKind Opc;
Chris Lattnere168f762006-11-10 05:29:30 +00003079 switch (Kind) {
David Blaikie83d382b2011-09-23 05:06:16 +00003080 default: llvm_unreachable("Unknown unary op!");
John McCalle3027922010-08-25 11:45:40 +00003081 case tok::plusplus: Opc = UO_PostInc; break;
3082 case tok::minusminus: Opc = UO_PostDec; break;
Chris Lattnere168f762006-11-10 05:29:30 +00003083 }
Sebastian Redlc215cfc2009-01-19 00:08:26 +00003084
Sebastian Redla9351792012-02-11 23:51:47 +00003085 // Since this might is a postfix expression, get rid of ParenListExprs.
3086 ExprResult Result = MaybeConvertParenListExprToParenExpr(S, Input);
3087 if (Result.isInvalid()) return ExprError();
3088 Input = Result.take();
3089
John McCallb268a282010-08-23 23:25:46 +00003090 return BuildUnaryOp(S, OpLoc, Opc, Input);
Chris Lattnere168f762006-11-10 05:29:30 +00003091}
3092
John McCalldadc5752010-08-24 06:29:42 +00003093ExprResult
John McCallb268a282010-08-23 23:25:46 +00003094Sema::ActOnArraySubscriptExpr(Scope *S, Expr *Base, SourceLocation LLoc,
3095 Expr *Idx, SourceLocation RLoc) {
Nate Begeman5ec4b312009-08-10 23:49:36 +00003096 // Since this might be a postfix expression, get rid of ParenListExprs.
John McCalldadc5752010-08-24 06:29:42 +00003097 ExprResult Result = MaybeConvertParenListExprToParenExpr(S, Base);
John McCallb268a282010-08-23 23:25:46 +00003098 if (Result.isInvalid()) return ExprError();
3099 Base = Result.take();
Nate Begeman5ec4b312009-08-10 23:49:36 +00003100
John McCallb268a282010-08-23 23:25:46 +00003101 Expr *LHSExp = Base, *RHSExp = Idx;
Mike Stump11289f42009-09-09 15:08:12 +00003102
David Blaikiebbafb8a2012-03-11 07:00:24 +00003103 if (getLangOpts().CPlusPlus &&
Douglas Gregor7a77a6b2009-05-19 00:01:19 +00003104 (LHSExp->isTypeDependent() || RHSExp->isTypeDependent())) {
Douglas Gregor7a77a6b2009-05-19 00:01:19 +00003105 return Owned(new (Context) ArraySubscriptExpr(LHSExp, RHSExp,
John McCall7decc9e2010-11-18 06:31:45 +00003106 Context.DependentTy,
3107 VK_LValue, OK_Ordinary,
3108 RLoc));
Douglas Gregor7a77a6b2009-05-19 00:01:19 +00003109 }
3110
David Blaikiebbafb8a2012-03-11 07:00:24 +00003111 if (getLangOpts().CPlusPlus &&
Sebastian Redlc215cfc2009-01-19 00:08:26 +00003112 (LHSExp->getType()->isRecordType() ||
Eli Friedman254a1a22008-12-15 22:34:21 +00003113 LHSExp->getType()->isEnumeralType() ||
3114 RHSExp->getType()->isRecordType() ||
Ted Kremeneke65b0862012-03-06 20:05:56 +00003115 RHSExp->getType()->isEnumeralType()) &&
3116 !LHSExp->getType()->isObjCObjectPointerType()) {
John McCallb268a282010-08-23 23:25:46 +00003117 return CreateOverloadedArraySubscriptExpr(LLoc, RLoc, Base, Idx);
Douglas Gregor40412ac2008-11-19 17:17:41 +00003118 }
3119
John McCallb268a282010-08-23 23:25:46 +00003120 return CreateBuiltinArraySubscriptExpr(Base, LLoc, Idx, RLoc);
Sebastian Redladba46e2009-10-29 20:17:01 +00003121}
3122
3123
John McCalldadc5752010-08-24 06:29:42 +00003124ExprResult
John McCallb268a282010-08-23 23:25:46 +00003125Sema::CreateBuiltinArraySubscriptExpr(Expr *Base, SourceLocation LLoc,
Richard Trieuba63ce62011-09-09 01:45:06 +00003126 Expr *Idx, SourceLocation RLoc) {
John McCallb268a282010-08-23 23:25:46 +00003127 Expr *LHSExp = Base;
3128 Expr *RHSExp = Idx;
Sebastian Redladba46e2009-10-29 20:17:01 +00003129
Chris Lattner36d572b2007-07-16 00:14:47 +00003130 // Perform default conversions.
John Wiegley01296292011-04-08 18:41:53 +00003131 if (!LHSExp->getType()->getAs<VectorType>()) {
3132 ExprResult Result = DefaultFunctionArrayLvalueConversion(LHSExp);
3133 if (Result.isInvalid())
3134 return ExprError();
3135 LHSExp = Result.take();
3136 }
3137 ExprResult Result = DefaultFunctionArrayLvalueConversion(RHSExp);
3138 if (Result.isInvalid())
3139 return ExprError();
3140 RHSExp = Result.take();
Sebastian Redlc215cfc2009-01-19 00:08:26 +00003141
Chris Lattner36d572b2007-07-16 00:14:47 +00003142 QualType LHSTy = LHSExp->getType(), RHSTy = RHSExp->getType();
John McCall7decc9e2010-11-18 06:31:45 +00003143 ExprValueKind VK = VK_LValue;
3144 ExprObjectKind OK = OK_Ordinary;
Steve Narofff1e53692007-03-23 22:27:02 +00003145
Steve Naroffc1aadb12007-03-28 21:49:40 +00003146 // C99 6.5.2.1p2: the expression e1[e2] is by definition precisely equivalent
Chris Lattnerf17bd422007-08-30 17:45:32 +00003147 // to the expression *((e1)+(e2)). This means the array "Base" may actually be
Mike Stump4e1f26a2009-02-19 03:04:26 +00003148 // in the subscript position. As a result, we need to derive the array base
Steve Narofff1e53692007-03-23 22:27:02 +00003149 // and index from the expression types.
Chris Lattner36d572b2007-07-16 00:14:47 +00003150 Expr *BaseExpr, *IndexExpr;
3151 QualType ResultType;
Sebastian Redl8d2ccae2009-02-26 14:39:58 +00003152 if (LHSTy->isDependentType() || RHSTy->isDependentType()) {
3153 BaseExpr = LHSExp;
3154 IndexExpr = RHSExp;
3155 ResultType = Context.DependentTy;
Ted Kremenekc23c7e62009-07-29 21:53:49 +00003156 } else if (const PointerType *PTy = LHSTy->getAs<PointerType>()) {
Chris Lattner36d572b2007-07-16 00:14:47 +00003157 BaseExpr = LHSExp;
3158 IndexExpr = RHSExp;
Chris Lattner36d572b2007-07-16 00:14:47 +00003159 ResultType = PTy->getPointeeType();
Mike Stump11289f42009-09-09 15:08:12 +00003160 } else if (const ObjCObjectPointerType *PTy =
Fariborz Jahanianba0afde2012-03-28 17:56:49 +00003161 LHSTy->getAs<ObjCObjectPointerType>()) {
Steve Naroff7cae42b2009-07-10 23:34:53 +00003162 BaseExpr = LHSExp;
3163 IndexExpr = RHSExp;
Ted Kremeneke65b0862012-03-06 20:05:56 +00003164 Result = BuildObjCSubscriptExpression(RLoc, BaseExpr, IndexExpr, 0, 0);
3165 if (!Result.isInvalid())
3166 return Owned(Result.take());
Steve Naroff7cae42b2009-07-10 23:34:53 +00003167 ResultType = PTy->getPointeeType();
Fariborz Jahanianba0afde2012-03-28 17:56:49 +00003168 } else if (const PointerType *PTy = RHSTy->getAs<PointerType>()) {
3169 // Handle the uncommon case of "123[Ptr]".
3170 BaseExpr = RHSExp;
3171 IndexExpr = LHSExp;
3172 ResultType = PTy->getPointeeType();
Mike Stump11289f42009-09-09 15:08:12 +00003173 } else if (const ObjCObjectPointerType *PTy =
John McCall9dd450b2009-09-21 23:43:11 +00003174 RHSTy->getAs<ObjCObjectPointerType>()) {
Steve Naroff7cae42b2009-07-10 23:34:53 +00003175 // Handle the uncommon case of "123[Ptr]".
3176 BaseExpr = RHSExp;
3177 IndexExpr = LHSExp;
3178 ResultType = PTy->getPointeeType();
John McCall9dd450b2009-09-21 23:43:11 +00003179 } else if (const VectorType *VTy = LHSTy->getAs<VectorType>()) {
Chris Lattner41977962007-07-31 19:29:30 +00003180 BaseExpr = LHSExp; // vectors: V[123]
Chris Lattner36d572b2007-07-16 00:14:47 +00003181 IndexExpr = RHSExp;
John McCall7decc9e2010-11-18 06:31:45 +00003182 VK = LHSExp->getValueKind();
3183 if (VK != VK_RValue)
3184 OK = OK_VectorComponent;
Nate Begemanc1bf0612009-01-18 00:45:31 +00003185
Chris Lattner36d572b2007-07-16 00:14:47 +00003186 // FIXME: need to deal with const...
3187 ResultType = VTy->getElementType();
Eli Friedmanab2784f2009-04-25 23:46:54 +00003188 } else if (LHSTy->isArrayType()) {
3189 // If we see an array that wasn't promoted by
Douglas Gregorb92a1562010-02-03 00:27:59 +00003190 // DefaultFunctionArrayLvalueConversion, it must be an array that
Eli Friedmanab2784f2009-04-25 23:46:54 +00003191 // wasn't promoted because of the C90 rule that doesn't
3192 // allow promoting non-lvalue arrays. Warn, then
3193 // force the promotion here.
3194 Diag(LHSExp->getLocStart(), diag::ext_subscript_non_lvalue) <<
3195 LHSExp->getSourceRange();
John Wiegley01296292011-04-08 18:41:53 +00003196 LHSExp = ImpCastExprToType(LHSExp, Context.getArrayDecayedType(LHSTy),
3197 CK_ArrayToPointerDecay).take();
Eli Friedmanab2784f2009-04-25 23:46:54 +00003198 LHSTy = LHSExp->getType();
3199
3200 BaseExpr = LHSExp;
3201 IndexExpr = RHSExp;
Ted Kremenekc23c7e62009-07-29 21:53:49 +00003202 ResultType = LHSTy->getAs<PointerType>()->getPointeeType();
Eli Friedmanab2784f2009-04-25 23:46:54 +00003203 } else if (RHSTy->isArrayType()) {
3204 // Same as previous, except for 123[f().a] case
3205 Diag(RHSExp->getLocStart(), diag::ext_subscript_non_lvalue) <<
3206 RHSExp->getSourceRange();
John Wiegley01296292011-04-08 18:41:53 +00003207 RHSExp = ImpCastExprToType(RHSExp, Context.getArrayDecayedType(RHSTy),
3208 CK_ArrayToPointerDecay).take();
Eli Friedmanab2784f2009-04-25 23:46:54 +00003209 RHSTy = RHSExp->getType();
3210
3211 BaseExpr = RHSExp;
3212 IndexExpr = LHSExp;
Ted Kremenekc23c7e62009-07-29 21:53:49 +00003213 ResultType = RHSTy->getAs<PointerType>()->getPointeeType();
Steve Naroffb3096442007-06-09 03:47:53 +00003214 } else {
Chris Lattner003af242009-04-25 22:50:55 +00003215 return ExprError(Diag(LLoc, diag::err_typecheck_subscript_value)
3216 << LHSExp->getSourceRange() << RHSExp->getSourceRange());
Sebastian Redlc215cfc2009-01-19 00:08:26 +00003217 }
Steve Naroffc1aadb12007-03-28 21:49:40 +00003218 // C99 6.5.2.1p1
Douglas Gregor5cc2c8b2010-07-23 15:58:24 +00003219 if (!IndexExpr->getType()->isIntegerType() && !IndexExpr->isTypeDependent())
Chris Lattner003af242009-04-25 22:50:55 +00003220 return ExprError(Diag(LLoc, diag::err_typecheck_subscript_not_integer)
3221 << IndexExpr->getSourceRange());
Steve Naroffb29cdd52007-07-10 18:23:31 +00003222
Daniel Dunbar4782a6e2009-09-17 06:31:17 +00003223 if ((IndexExpr->getType()->isSpecificBuiltinType(BuiltinType::Char_S) ||
Sam Weinigb7608d72009-09-14 20:14:57 +00003224 IndexExpr->getType()->isSpecificBuiltinType(BuiltinType::Char_U))
3225 && !IndexExpr->isTypeDependent())
Sam Weinig914244e2009-09-14 01:58:58 +00003226 Diag(LLoc, diag::warn_subscript_is_char) << IndexExpr->getSourceRange();
3227
Douglas Gregorac1fb652009-03-24 19:52:54 +00003228 // C99 6.5.2.1p1: "shall have type "pointer to *object* type". Similarly,
Mike Stump11289f42009-09-09 15:08:12 +00003229 // C++ [expr.sub]p1: The type "T" shall be a completely-defined object
3230 // type. Note that Functions are not objects, and that (in C99 parlance)
Douglas Gregorac1fb652009-03-24 19:52:54 +00003231 // incomplete types are not object types.
3232 if (ResultType->isFunctionType()) {
3233 Diag(BaseExpr->getLocStart(), diag::err_subscript_function_type)
3234 << ResultType << BaseExpr->getSourceRange();
3235 return ExprError();
3236 }
Mike Stump11289f42009-09-09 15:08:12 +00003237
David Blaikiebbafb8a2012-03-11 07:00:24 +00003238 if (ResultType->isVoidType() && !getLangOpts().CPlusPlus) {
Abramo Bagnara3aabb4b2010-09-13 06:50:07 +00003239 // GNU extension: subscripting on pointer to void
Chandler Carruth4cc3f292011-06-27 16:32:27 +00003240 Diag(LLoc, diag::ext_gnu_subscript_void_type)
3241 << BaseExpr->getSourceRange();
John McCall4bc41ae2010-11-18 19:01:18 +00003242
3243 // C forbids expressions of unqualified void type from being l-values.
3244 // See IsCForbiddenLValueType.
3245 if (!ResultType.hasQualifiers()) VK = VK_RValue;
Abramo Bagnara3aabb4b2010-09-13 06:50:07 +00003246 } else if (!ResultType->isDependentType() &&
Mike Stump11289f42009-09-09 15:08:12 +00003247 RequireCompleteType(LLoc, ResultType,
Douglas Gregor7bfb2d02012-05-04 16:32:21 +00003248 diag::err_subscript_incomplete_type, BaseExpr))
Douglas Gregorac1fb652009-03-24 19:52:54 +00003249 return ExprError();
Mike Stump11289f42009-09-09 15:08:12 +00003250
Chris Lattner62975a72009-04-24 00:30:45 +00003251 // Diagnose bad cases where we step over interface counts.
John McCall8b07ec22010-05-15 11:32:37 +00003252 if (ResultType->isObjCObjectType() && LangOpts.ObjCNonFragileABI) {
Chris Lattner62975a72009-04-24 00:30:45 +00003253 Diag(LLoc, diag::err_subscript_nonfragile_interface)
3254 << ResultType << BaseExpr->getSourceRange();
3255 return ExprError();
3256 }
Mike Stump11289f42009-09-09 15:08:12 +00003257
John McCall4bc41ae2010-11-18 19:01:18 +00003258 assert(VK == VK_RValue || LangOpts.CPlusPlus ||
Douglas Gregor5476205b2011-06-23 00:49:38 +00003259 !ResultType.isCForbiddenLValueType());
John McCall4bc41ae2010-11-18 19:01:18 +00003260
Mike Stump4e1f26a2009-02-19 03:04:26 +00003261 return Owned(new (Context) ArraySubscriptExpr(LHSExp, RHSExp,
John McCall7decc9e2010-11-18 06:31:45 +00003262 ResultType, VK, OK, RLoc));
Chris Lattnere168f762006-11-10 05:29:30 +00003263}
3264
John McCalldadc5752010-08-24 06:29:42 +00003265ExprResult Sema::BuildCXXDefaultArgExpr(SourceLocation CallLoc,
Nico Weber44887f62010-11-29 18:19:25 +00003266 FunctionDecl *FD,
3267 ParmVarDecl *Param) {
Anders Carlsson355933d2009-08-25 03:49:14 +00003268 if (Param->hasUnparsedDefaultArg()) {
Douglas Gregor8a01b2a2010-09-11 20:24:53 +00003269 Diag(CallLoc,
Nico Weberebd45a02010-11-30 04:44:33 +00003270 diag::err_use_of_default_argument_to_function_declared_later) <<
Anders Carlsson355933d2009-08-25 03:49:14 +00003271 FD << cast<CXXRecordDecl>(FD->getDeclContext())->getDeclName();
Mike Stump11289f42009-09-09 15:08:12 +00003272 Diag(UnparsedDefaultArgLocs[Param],
Nico Weberebd45a02010-11-30 04:44:33 +00003273 diag::note_default_argument_declared_here);
Douglas Gregor8a01b2a2010-09-11 20:24:53 +00003274 return ExprError();
3275 }
3276
3277 if (Param->hasUninstantiatedDefaultArg()) {
3278 Expr *UninstExpr = Param->getUninstantiatedDefaultArg();
Anders Carlsson355933d2009-08-25 03:49:14 +00003279
Douglas Gregor8a01b2a2010-09-11 20:24:53 +00003280 // Instantiate the expression.
3281 MultiLevelTemplateArgumentList ArgList
3282 = getTemplateInstantiationArgs(FD, 0, /*RelativeToPrimary=*/true);
Anders Carlsson657bad42009-09-05 05:14:19 +00003283
Nico Weber44887f62010-11-29 18:19:25 +00003284 std::pair<const TemplateArgument *, unsigned> Innermost
Douglas Gregor8a01b2a2010-09-11 20:24:53 +00003285 = ArgList.getInnermost();
3286 InstantiatingTemplate Inst(*this, CallLoc, Param, Innermost.first,
3287 Innermost.second);
Anders Carlsson355933d2009-08-25 03:49:14 +00003288
Nico Weber44887f62010-11-29 18:19:25 +00003289 ExprResult Result;
3290 {
3291 // C++ [dcl.fct.default]p5:
3292 // The names in the [default argument] expression are bound, and
3293 // the semantic constraints are checked, at the point where the
3294 // default argument expression appears.
Nico Weberebd45a02010-11-30 04:44:33 +00003295 ContextRAII SavedContext(*this, FD);
Douglas Gregora86bc002012-02-16 21:36:18 +00003296 LocalInstantiationScope Local(*this);
Nico Weber44887f62010-11-29 18:19:25 +00003297 Result = SubstExpr(UninstExpr, ArgList);
3298 }
Douglas Gregor8a01b2a2010-09-11 20:24:53 +00003299 if (Result.isInvalid())
3300 return ExprError();
Mike Stump11289f42009-09-09 15:08:12 +00003301
Douglas Gregor8a01b2a2010-09-11 20:24:53 +00003302 // Check the expression as an initializer for the parameter.
3303 InitializedEntity Entity
Fariborz Jahanian8fb87ae2010-09-24 17:30:16 +00003304 = InitializedEntity::InitializeParameter(Context, Param);
Douglas Gregor8a01b2a2010-09-11 20:24:53 +00003305 InitializationKind Kind
3306 = InitializationKind::CreateCopy(Param->getLocation(),
Daniel Dunbar62ee6412012-03-09 18:35:03 +00003307 /*FIXME:EqualLoc*/UninstExpr->getLocStart());
Douglas Gregor8a01b2a2010-09-11 20:24:53 +00003308 Expr *ResultE = Result.takeAs<Expr>();
Douglas Gregor25ab25f2009-12-23 18:19:08 +00003309
Douglas Gregor8a01b2a2010-09-11 20:24:53 +00003310 InitializationSequence InitSeq(*this, Entity, Kind, &ResultE, 1);
3311 Result = InitSeq.Perform(*this, Entity, Kind,
3312 MultiExprArg(*this, &ResultE, 1));
3313 if (Result.isInvalid())
3314 return ExprError();
Kovarththanan Rajaratnamba2c6522010-03-13 10:17:05 +00003315
David Blaikief68e8092012-04-30 18:21:31 +00003316 Expr *Arg = Result.takeAs<Expr>();
3317 CheckImplicitConversions(Arg, Arg->getExprLoc());
Douglas Gregor8a01b2a2010-09-11 20:24:53 +00003318 // Build the default argument expression.
David Blaikief68e8092012-04-30 18:21:31 +00003319 return Owned(CXXDefaultArgExpr::Create(Context, CallLoc, Param, Arg));
Anders Carlsson355933d2009-08-25 03:49:14 +00003320 }
3321
Douglas Gregor8a01b2a2010-09-11 20:24:53 +00003322 // If the default expression creates temporaries, we need to
3323 // push them to the current stack of expression temporaries so they'll
3324 // be properly destroyed.
3325 // FIXME: We should really be rebuilding the default argument with new
3326 // bound temporaries; see the comment in PR5810.
John McCall28fc7092011-11-10 05:35:25 +00003327 // We don't need to do that with block decls, though, because
3328 // blocks in default argument expression can never capture anything.
3329 if (isa<ExprWithCleanups>(Param->getInit())) {
3330 // Set the "needs cleanups" bit regardless of whether there are
3331 // any explicit objects.
John McCall31168b02011-06-15 23:02:42 +00003332 ExprNeedsCleanups = true;
John McCall28fc7092011-11-10 05:35:25 +00003333
3334 // Append all the objects to the cleanup list. Right now, this
3335 // should always be a no-op, because blocks in default argument
3336 // expressions should never be able to capture anything.
3337 assert(!cast<ExprWithCleanups>(Param->getInit())->getNumObjects() &&
3338 "default argument expression has capturing blocks?");
Douglas Gregor6ed2fee2010-09-14 22:55:20 +00003339 }
Douglas Gregor8a01b2a2010-09-11 20:24:53 +00003340
3341 // We already type-checked the argument, so we know it works.
Douglas Gregor32b3de52010-09-11 23:32:50 +00003342 // Just mark all of the declarations in this potentially-evaluated expression
3343 // as being "referenced".
Douglas Gregor680e9e02012-02-21 19:11:17 +00003344 MarkDeclarationsReferencedInExpr(Param->getDefaultArg(),
3345 /*SkipLocalVariables=*/true);
Douglas Gregor033f6752009-12-23 23:03:06 +00003346 return Owned(CXXDefaultArgExpr::Create(Context, CallLoc, Param));
Anders Carlsson355933d2009-08-25 03:49:14 +00003347}
3348
Douglas Gregor97fd6e22008-12-22 05:46:06 +00003349/// ConvertArgumentsForCall - Converts the arguments specified in
3350/// Args/NumArgs to the parameter types of the function FDecl with
3351/// function prototype Proto. Call is the call expression itself, and
3352/// Fn is the function expression. For a C++ member function, this
3353/// routine does not attempt to convert the object argument. Returns
3354/// true if the call is ill-formed.
Mike Stump4e1f26a2009-02-19 03:04:26 +00003355bool
3356Sema::ConvertArgumentsForCall(CallExpr *Call, Expr *Fn,
Douglas Gregor97fd6e22008-12-22 05:46:06 +00003357 FunctionDecl *FDecl,
Douglas Gregordeaad8c2009-02-26 23:50:07 +00003358 const FunctionProtoType *Proto,
Douglas Gregor97fd6e22008-12-22 05:46:06 +00003359 Expr **Args, unsigned NumArgs,
Peter Collingbourne619a8c72011-10-02 23:49:29 +00003360 SourceLocation RParenLoc,
3361 bool IsExecConfig) {
John McCallbebede42011-02-26 05:39:39 +00003362 // Bail out early if calling a builtin with custom typechecking.
3363 // We don't need to do this in the
3364 if (FDecl)
3365 if (unsigned ID = FDecl->getBuiltinID())
3366 if (Context.BuiltinInfo.hasCustomTypechecking(ID))
3367 return false;
3368
Mike Stump4e1f26a2009-02-19 03:04:26 +00003369 // C99 6.5.2.2p7 - the arguments are implicitly converted, as if by
Douglas Gregor97fd6e22008-12-22 05:46:06 +00003370 // assignment, to the types of the corresponding parameter, ...
3371 unsigned NumArgsInProto = Proto->getNumArgs();
Douglas Gregorb6b99612009-01-23 21:30:56 +00003372 bool Invalid = false;
Peter Collingbourne740afe22011-10-02 23:49:20 +00003373 unsigned MinArgs = FDecl ? FDecl->getMinRequiredArguments() : NumArgsInProto;
Peter Collingbourne619a8c72011-10-02 23:49:29 +00003374 unsigned FnKind = Fn->getType()->isBlockPointerType()
3375 ? 1 /* block */
3376 : (IsExecConfig ? 3 /* kernel function (exec config) */
3377 : 0 /* function */);
Kovarththanan Rajaratnamba2c6522010-03-13 10:17:05 +00003378
Douglas Gregor97fd6e22008-12-22 05:46:06 +00003379 // If too few arguments are available (and we don't have default
3380 // arguments for the remaining parameters), don't make the call.
3381 if (NumArgs < NumArgsInProto) {
Peter Collingbourne740afe22011-10-02 23:49:20 +00003382 if (NumArgs < MinArgs) {
Richard Smith10ff50d2012-05-11 05:16:41 +00003383 if (MinArgs == 1 && FDecl && FDecl->getParamDecl(0)->getDeclName())
3384 Diag(RParenLoc, MinArgs == NumArgsInProto && !Proto->isVariadic()
3385 ? diag::err_typecheck_call_too_few_args_one
3386 : diag::err_typecheck_call_too_few_args_at_least_one)
3387 << FnKind
3388 << FDecl->getParamDecl(0) << Fn->getSourceRange();
3389 else
3390 Diag(RParenLoc, MinArgs == NumArgsInProto && !Proto->isVariadic()
3391 ? diag::err_typecheck_call_too_few_args
3392 : diag::err_typecheck_call_too_few_args_at_least)
3393 << FnKind
3394 << MinArgs << NumArgs << Fn->getSourceRange();
Peter Collingbourne3bc84ca2011-07-29 00:24:42 +00003395
3396 // Emit the location of the prototype.
Peter Collingbourne619a8c72011-10-02 23:49:29 +00003397 if (FDecl && !FDecl->getBuiltinID() && !IsExecConfig)
Peter Collingbourne3bc84ca2011-07-29 00:24:42 +00003398 Diag(FDecl->getLocStart(), diag::note_callee_decl)
3399 << FDecl;
3400
3401 return true;
3402 }
Ted Kremenek5a201952009-02-07 01:47:29 +00003403 Call->setNumArgs(Context, NumArgsInProto);
Douglas Gregor97fd6e22008-12-22 05:46:06 +00003404 }
3405
3406 // If too many are passed and not variadic, error on the extras and drop
3407 // them.
3408 if (NumArgs > NumArgsInProto) {
3409 if (!Proto->isVariadic()) {
3410 Diag(Args[NumArgsInProto]->getLocStart(),
Peter Collingbourne740afe22011-10-02 23:49:20 +00003411 MinArgs == NumArgsInProto
3412 ? diag::err_typecheck_call_too_many_args
3413 : diag::err_typecheck_call_too_many_args_at_most)
Peter Collingbourne619a8c72011-10-02 23:49:29 +00003414 << FnKind
Eric Christopher2a5aaff2010-04-16 04:56:46 +00003415 << NumArgsInProto << NumArgs << Fn->getSourceRange()
Douglas Gregor97fd6e22008-12-22 05:46:06 +00003416 << SourceRange(Args[NumArgsInProto]->getLocStart(),
3417 Args[NumArgs-1]->getLocEnd());
Ted Kremenek99a337e2011-04-04 17:22:27 +00003418
3419 // Emit the location of the prototype.
Peter Collingbourne619a8c72011-10-02 23:49:29 +00003420 if (FDecl && !FDecl->getBuiltinID() && !IsExecConfig)
Peter Collingbourne3bc84ca2011-07-29 00:24:42 +00003421 Diag(FDecl->getLocStart(), diag::note_callee_decl)
3422 << FDecl;
Ted Kremenek99a337e2011-04-04 17:22:27 +00003423
Douglas Gregor97fd6e22008-12-22 05:46:06 +00003424 // This deletes the extra arguments.
Ted Kremenek5a201952009-02-07 01:47:29 +00003425 Call->setNumArgs(Context, NumArgsInProto);
Fariborz Jahanian835026e2009-11-24 18:29:37 +00003426 return true;
Douglas Gregor97fd6e22008-12-22 05:46:06 +00003427 }
Douglas Gregor97fd6e22008-12-22 05:46:06 +00003428 }
Chris Lattner0e62c1c2011-07-23 10:55:15 +00003429 SmallVector<Expr *, 8> AllArgs;
Kovarththanan Rajaratnamba2c6522010-03-13 10:17:05 +00003430 VariadicCallType CallType =
Fariborz Jahanian6f2d25e2009-11-24 19:27:49 +00003431 Proto->isVariadic() ? VariadicFunction : VariadicDoesNotApply;
3432 if (Fn->getType()->isBlockPointerType())
3433 CallType = VariadicBlock; // Block
3434 else if (isa<MemberExpr>(Fn))
3435 CallType = VariadicMethod;
Daniel Dunbar62ee6412012-03-09 18:35:03 +00003436 Invalid = GatherArgumentsForCall(Call->getLocStart(), FDecl,
Fariborz Jahanian4fa66ce2009-11-24 21:37:28 +00003437 Proto, 0, Args, NumArgs, AllArgs, CallType);
Fariborz Jahanian835026e2009-11-24 18:29:37 +00003438 if (Invalid)
3439 return true;
3440 unsigned TotalNumArgs = AllArgs.size();
3441 for (unsigned i = 0; i < TotalNumArgs; ++i)
3442 Call->setArg(i, AllArgs[i]);
Kovarththanan Rajaratnamba2c6522010-03-13 10:17:05 +00003443
Fariborz Jahanian835026e2009-11-24 18:29:37 +00003444 return false;
3445}
Mike Stump4e1f26a2009-02-19 03:04:26 +00003446
Fariborz Jahanian835026e2009-11-24 18:29:37 +00003447bool Sema::GatherArgumentsForCall(SourceLocation CallLoc,
3448 FunctionDecl *FDecl,
3449 const FunctionProtoType *Proto,
3450 unsigned FirstProtoArg,
3451 Expr **Args, unsigned NumArgs,
Chris Lattner0e62c1c2011-07-23 10:55:15 +00003452 SmallVector<Expr *, 8> &AllArgs,
Douglas Gregor6073dca2012-02-24 23:56:31 +00003453 VariadicCallType CallType,
3454 bool AllowExplicit) {
Fariborz Jahanian835026e2009-11-24 18:29:37 +00003455 unsigned NumArgsInProto = Proto->getNumArgs();
3456 unsigned NumArgsToCheck = NumArgs;
3457 bool Invalid = false;
3458 if (NumArgs != NumArgsInProto)
3459 // Use default arguments for missing arguments
3460 NumArgsToCheck = NumArgsInProto;
3461 unsigned ArgIx = 0;
Douglas Gregor97fd6e22008-12-22 05:46:06 +00003462 // Continue to check argument types (even if we have too few/many args).
Fariborz Jahanian835026e2009-11-24 18:29:37 +00003463 for (unsigned i = FirstProtoArg; i != NumArgsToCheck; i++) {
Douglas Gregor97fd6e22008-12-22 05:46:06 +00003464 QualType ProtoArgType = Proto->getArgType(i);
Kovarththanan Rajaratnamba2c6522010-03-13 10:17:05 +00003465
Douglas Gregor97fd6e22008-12-22 05:46:06 +00003466 Expr *Arg;
Peter Collingbournea48f33f2011-10-19 00:16:45 +00003467 ParmVarDecl *Param;
Fariborz Jahanian835026e2009-11-24 18:29:37 +00003468 if (ArgIx < NumArgs) {
3469 Arg = Args[ArgIx++];
Kovarththanan Rajaratnamba2c6522010-03-13 10:17:05 +00003470
Daniel Dunbar62ee6412012-03-09 18:35:03 +00003471 if (RequireCompleteType(Arg->getLocStart(),
Eli Friedman3164fb12009-03-22 22:00:50 +00003472 ProtoArgType,
Douglas Gregor7bfb2d02012-05-04 16:32:21 +00003473 diag::err_call_incomplete_argument, Arg))
Eli Friedman3164fb12009-03-22 22:00:50 +00003474 return true;
Kovarththanan Rajaratnamba2c6522010-03-13 10:17:05 +00003475
Douglas Gregorbbeb5c32009-12-22 16:09:06 +00003476 // Pass the argument
Peter Collingbournea48f33f2011-10-19 00:16:45 +00003477 Param = 0;
Douglas Gregorbbeb5c32009-12-22 16:09:06 +00003478 if (FDecl && i < FDecl->getNumParams())
3479 Param = FDecl->getParamDecl(i);
Douglas Gregor96596c92009-12-22 07:24:36 +00003480
John McCall4124c492011-10-17 18:40:02 +00003481 // Strip the unbridged-cast placeholder expression off, if applicable.
3482 if (Arg->getType() == Context.ARCUnbridgedCastTy &&
3483 FDecl && FDecl->hasAttr<CFAuditedTransferAttr>() &&
3484 (!Param || !Param->hasAttr<CFConsumedAttr>()))
3485 Arg = stripARCUnbridgedCast(Arg);
3486
Douglas Gregorbbeb5c32009-12-22 16:09:06 +00003487 InitializedEntity Entity =
Fariborz Jahanian8fb87ae2010-09-24 17:30:16 +00003488 Param? InitializedEntity::InitializeParameter(Context, Param)
John McCall31168b02011-06-15 23:02:42 +00003489 : InitializedEntity::InitializeParameter(Context, ProtoArgType,
3490 Proto->isArgConsumed(i));
John McCalldadc5752010-08-24 06:29:42 +00003491 ExprResult ArgE = PerformCopyInitialization(Entity,
John McCall34376a62010-12-04 03:47:34 +00003492 SourceLocation(),
Douglas Gregor6073dca2012-02-24 23:56:31 +00003493 Owned(Arg),
3494 /*TopLevelOfInitList=*/false,
3495 AllowExplicit);
Douglas Gregorbbeb5c32009-12-22 16:09:06 +00003496 if (ArgE.isInvalid())
3497 return true;
3498
3499 Arg = ArgE.takeAs<Expr>();
Anders Carlsson84613c42009-06-12 16:51:40 +00003500 } else {
Peter Collingbournea48f33f2011-10-19 00:16:45 +00003501 Param = FDecl->getParamDecl(i);
Kovarththanan Rajaratnamba2c6522010-03-13 10:17:05 +00003502
John McCalldadc5752010-08-24 06:29:42 +00003503 ExprResult ArgExpr =
Fariborz Jahanian835026e2009-11-24 18:29:37 +00003504 BuildCXXDefaultArgExpr(CallLoc, FDecl, Param);
Anders Carlsson355933d2009-08-25 03:49:14 +00003505 if (ArgExpr.isInvalid())
3506 return true;
Kovarththanan Rajaratnamba2c6522010-03-13 10:17:05 +00003507
Anders Carlsson355933d2009-08-25 03:49:14 +00003508 Arg = ArgExpr.takeAs<Expr>();
Anders Carlsson84613c42009-06-12 16:51:40 +00003509 }
Kaelyn Uhrain2e7aa5a2011-08-05 23:18:04 +00003510
3511 // Check for array bounds violations for each argument to the call. This
3512 // check only triggers warnings when the argument isn't a more complex Expr
3513 // with its own checking, such as a BinaryOperator.
3514 CheckArrayAccess(Arg);
3515
Peter Collingbournea48f33f2011-10-19 00:16:45 +00003516 // Check for violations of C99 static array rules (C99 6.7.5.3p7).
3517 CheckStaticArrayArgument(CallLoc, Param, Arg);
3518
Fariborz Jahanian835026e2009-11-24 18:29:37 +00003519 AllArgs.push_back(Arg);
Douglas Gregor97fd6e22008-12-22 05:46:06 +00003520 }
Kovarththanan Rajaratnamba2c6522010-03-13 10:17:05 +00003521
Douglas Gregor97fd6e22008-12-22 05:46:06 +00003522 // If this is a variadic call, handle args passed through "...".
Fariborz Jahanian6f2d25e2009-11-24 19:27:49 +00003523 if (CallType != VariadicDoesNotApply) {
John McCall2979fe02011-04-12 00:42:48 +00003524
3525 // Assume that extern "C" functions with variadic arguments that
3526 // return __unknown_anytype aren't *really* variadic.
3527 if (Proto->getResultType() == Context.UnknownAnyTy &&
3528 FDecl && FDecl->isExternC()) {
3529 for (unsigned i = ArgIx; i != NumArgs; ++i) {
3530 ExprResult arg;
3531 if (isa<ExplicitCastExpr>(Args[i]->IgnoreParens()))
3532 arg = DefaultFunctionArrayLvalueConversion(Args[i]);
3533 else
3534 arg = DefaultVariadicArgumentPromotion(Args[i], CallType, FDecl);
3535 Invalid |= arg.isInvalid();
3536 AllArgs.push_back(arg.take());
3537 }
3538
3539 // Otherwise do argument promotion, (C99 6.5.2.2p7).
3540 } else {
3541 for (unsigned i = ArgIx; i != NumArgs; ++i) {
Richard Trieucfc491d2011-08-02 04:35:43 +00003542 ExprResult Arg = DefaultVariadicArgumentPromotion(Args[i], CallType,
3543 FDecl);
John McCall2979fe02011-04-12 00:42:48 +00003544 Invalid |= Arg.isInvalid();
3545 AllArgs.push_back(Arg.take());
3546 }
Douglas Gregor97fd6e22008-12-22 05:46:06 +00003547 }
Ted Kremenekd41f3462011-09-26 23:36:13 +00003548
3549 // Check for array bounds violations.
3550 for (unsigned i = ArgIx; i != NumArgs; ++i)
3551 CheckArrayAccess(Args[i]);
Douglas Gregor97fd6e22008-12-22 05:46:06 +00003552 }
Douglas Gregorb6b99612009-01-23 21:30:56 +00003553 return Invalid;
Douglas Gregor97fd6e22008-12-22 05:46:06 +00003554}
3555
Peter Collingbournea48f33f2011-10-19 00:16:45 +00003556static void DiagnoseCalleeStaticArrayParam(Sema &S, ParmVarDecl *PVD) {
3557 TypeLoc TL = PVD->getTypeSourceInfo()->getTypeLoc();
3558 if (ArrayTypeLoc *ATL = dyn_cast<ArrayTypeLoc>(&TL))
3559 S.Diag(PVD->getLocation(), diag::note_callee_static_array)
3560 << ATL->getLocalSourceRange();
3561}
3562
3563/// CheckStaticArrayArgument - If the given argument corresponds to a static
3564/// array parameter, check that it is non-null, and that if it is formed by
3565/// array-to-pointer decay, the underlying array is sufficiently large.
3566///
3567/// C99 6.7.5.3p7: If the keyword static also appears within the [ and ] of the
3568/// array type derivation, then for each call to the function, the value of the
3569/// corresponding actual argument shall provide access to the first element of
3570/// an array with at least as many elements as specified by the size expression.
3571void
3572Sema::CheckStaticArrayArgument(SourceLocation CallLoc,
3573 ParmVarDecl *Param,
3574 const Expr *ArgExpr) {
3575 // Static array parameters are not supported in C++.
David Blaikiebbafb8a2012-03-11 07:00:24 +00003576 if (!Param || getLangOpts().CPlusPlus)
Peter Collingbournea48f33f2011-10-19 00:16:45 +00003577 return;
3578
3579 QualType OrigTy = Param->getOriginalType();
3580
3581 const ArrayType *AT = Context.getAsArrayType(OrigTy);
3582 if (!AT || AT->getSizeModifier() != ArrayType::Static)
3583 return;
3584
3585 if (ArgExpr->isNullPointerConstant(Context,
3586 Expr::NPC_NeverValueDependent)) {
3587 Diag(CallLoc, diag::warn_null_arg) << ArgExpr->getSourceRange();
3588 DiagnoseCalleeStaticArrayParam(*this, Param);
3589 return;
3590 }
3591
3592 const ConstantArrayType *CAT = dyn_cast<ConstantArrayType>(AT);
3593 if (!CAT)
3594 return;
3595
3596 const ConstantArrayType *ArgCAT =
3597 Context.getAsConstantArrayType(ArgExpr->IgnoreParenImpCasts()->getType());
3598 if (!ArgCAT)
3599 return;
3600
3601 if (ArgCAT->getSize().ult(CAT->getSize())) {
3602 Diag(CallLoc, diag::warn_static_array_too_small)
3603 << ArgExpr->getSourceRange()
3604 << (unsigned) ArgCAT->getSize().getZExtValue()
3605 << (unsigned) CAT->getSize().getZExtValue();
3606 DiagnoseCalleeStaticArrayParam(*this, Param);
3607 }
3608}
3609
John McCall2979fe02011-04-12 00:42:48 +00003610/// Given a function expression of unknown-any type, try to rebuild it
3611/// to have a function type.
3612static ExprResult rebuildUnknownAnyFunction(Sema &S, Expr *fn);
3613
Steve Naroff83895f72007-09-16 03:34:24 +00003614/// ActOnCallExpr - Handle a call to Fn with the specified array of arguments.
Chris Lattnere168f762006-11-10 05:29:30 +00003615/// This provides the location of the left/right parens and a list of comma
3616/// locations.
John McCalldadc5752010-08-24 06:29:42 +00003617ExprResult
John McCallb268a282010-08-23 23:25:46 +00003618Sema::ActOnCallExpr(Scope *S, Expr *Fn, SourceLocation LParenLoc,
Richard Trieuba63ce62011-09-09 01:45:06 +00003619 MultiExprArg ArgExprs, SourceLocation RParenLoc,
Peter Collingbourne619a8c72011-10-02 23:49:29 +00003620 Expr *ExecConfig, bool IsExecConfig) {
Richard Trieuba63ce62011-09-09 01:45:06 +00003621 unsigned NumArgs = ArgExprs.size();
Nate Begeman5ec4b312009-08-10 23:49:36 +00003622
3623 // Since this might be a postfix expression, get rid of ParenListExprs.
John McCalldadc5752010-08-24 06:29:42 +00003624 ExprResult Result = MaybeConvertParenListExprToParenExpr(S, Fn);
John McCallb268a282010-08-23 23:25:46 +00003625 if (Result.isInvalid()) return ExprError();
3626 Fn = Result.take();
Mike Stump11289f42009-09-09 15:08:12 +00003627
Richard Trieuba63ce62011-09-09 01:45:06 +00003628 Expr **Args = ArgExprs.release();
Mike Stump11289f42009-09-09 15:08:12 +00003629
David Blaikiebbafb8a2012-03-11 07:00:24 +00003630 if (getLangOpts().CPlusPlus) {
Douglas Gregorad8a3362009-09-04 17:36:40 +00003631 // If this is a pseudo-destructor expression, build the call immediately.
3632 if (isa<CXXPseudoDestructorExpr>(Fn)) {
3633 if (NumArgs > 0) {
3634 // Pseudo-destructor calls should not have any arguments.
3635 Diag(Fn->getLocStart(), diag::err_pseudo_dtor_call_with_args)
Douglas Gregora771f462010-03-31 17:46:05 +00003636 << FixItHint::CreateRemoval(
Douglas Gregorad8a3362009-09-04 17:36:40 +00003637 SourceRange(Args[0]->getLocStart(),
3638 Args[NumArgs-1]->getLocEnd()));
Douglas Gregorad8a3362009-09-04 17:36:40 +00003639 }
Mike Stump11289f42009-09-09 15:08:12 +00003640
Douglas Gregorad8a3362009-09-04 17:36:40 +00003641 return Owned(new (Context) CallExpr(Context, Fn, 0, 0, Context.VoidTy,
John McCall7decc9e2010-11-18 06:31:45 +00003642 VK_RValue, RParenLoc));
Douglas Gregorad8a3362009-09-04 17:36:40 +00003643 }
Mike Stump11289f42009-09-09 15:08:12 +00003644
Douglas Gregorb8a9a412009-02-04 15:01:18 +00003645 // Determine whether this is a dependent call inside a C++ template,
Mike Stump4e1f26a2009-02-19 03:04:26 +00003646 // in which case we won't do any semantic analysis now.
Mike Stump87c57ac2009-05-16 07:39:55 +00003647 // FIXME: Will need to cache the results of name lookup (including ADL) in
3648 // Fn.
Douglas Gregorb8a9a412009-02-04 15:01:18 +00003649 bool Dependent = false;
3650 if (Fn->isTypeDependent())
3651 Dependent = true;
Ahmed Charlesb24b9aa2012-02-25 11:00:22 +00003652 else if (Expr::hasAnyTypeDependentArguments(
3653 llvm::makeArrayRef(Args, NumArgs)))
Douglas Gregorb8a9a412009-02-04 15:01:18 +00003654 Dependent = true;
3655
Peter Collingbourne41f85462011-02-09 21:07:24 +00003656 if (Dependent) {
3657 if (ExecConfig) {
3658 return Owned(new (Context) CUDAKernelCallExpr(
3659 Context, Fn, cast<CallExpr>(ExecConfig), Args, NumArgs,
3660 Context.DependentTy, VK_RValue, RParenLoc));
3661 } else {
3662 return Owned(new (Context) CallExpr(Context, Fn, Args, NumArgs,
3663 Context.DependentTy, VK_RValue,
3664 RParenLoc));
3665 }
3666 }
Douglas Gregorb8a9a412009-02-04 15:01:18 +00003667
3668 // Determine whether this is a call to an object (C++ [over.call.object]).
3669 if (Fn->getType()->isRecordType())
3670 return Owned(BuildCallToObjectOfClassType(S, Fn, LParenLoc, Args, NumArgs,
Douglas Gregorce5aa332010-09-09 16:33:13 +00003671 RParenLoc));
Douglas Gregorb8a9a412009-02-04 15:01:18 +00003672
John McCall2979fe02011-04-12 00:42:48 +00003673 if (Fn->getType() == Context.UnknownAnyTy) {
3674 ExprResult result = rebuildUnknownAnyFunction(*this, Fn);
3675 if (result.isInvalid()) return ExprError();
3676 Fn = result.take();
3677 }
3678
John McCall0009fcc2011-04-26 20:42:42 +00003679 if (Fn->getType() == Context.BoundMemberTy) {
John McCall2d74de92009-12-01 22:10:20 +00003680 return BuildCallToMemberFunction(S, Fn, LParenLoc, Args, NumArgs,
Douglas Gregorce5aa332010-09-09 16:33:13 +00003681 RParenLoc);
John McCall10eae182009-11-30 22:42:35 +00003682 }
John McCall0009fcc2011-04-26 20:42:42 +00003683 }
John McCall10eae182009-11-30 22:42:35 +00003684
John McCall0009fcc2011-04-26 20:42:42 +00003685 // Check for overloaded calls. This can happen even in C due to extensions.
3686 if (Fn->getType() == Context.OverloadTy) {
3687 OverloadExpr::FindResult find = OverloadExpr::find(Fn);
3688
Douglas Gregorcda22702011-10-13 18:10:35 +00003689 // We aren't supposed to apply this logic for if there's an '&' involved.
Douglas Gregorf4a06c22011-10-13 18:26:27 +00003690 if (!find.HasFormOfMemberPointer) {
John McCall0009fcc2011-04-26 20:42:42 +00003691 OverloadExpr *ovl = find.Expression;
3692 if (isa<UnresolvedLookupExpr>(ovl)) {
3693 UnresolvedLookupExpr *ULE = cast<UnresolvedLookupExpr>(ovl);
3694 return BuildOverloadedCallExpr(S, Fn, ULE, LParenLoc, Args, NumArgs,
3695 RParenLoc, ExecConfig);
3696 } else {
John McCall2d74de92009-12-01 22:10:20 +00003697 return BuildCallToMemberFunction(S, Fn, LParenLoc, Args, NumArgs,
Douglas Gregorce5aa332010-09-09 16:33:13 +00003698 RParenLoc);
Anders Carlsson61914b52009-10-03 17:40:22 +00003699 }
3700 }
Douglas Gregor97fd6e22008-12-22 05:46:06 +00003701 }
3702
Douglas Gregore254f902009-02-04 00:32:51 +00003703 // If we're directly calling a function, get the appropriate declaration.
Douglas Gregord8fb1e32011-12-01 01:37:36 +00003704 if (Fn->getType() == Context.UnknownAnyTy) {
3705 ExprResult result = rebuildUnknownAnyFunction(*this, Fn);
3706 if (result.isInvalid()) return ExprError();
3707 Fn = result.take();
3708 }
Mike Stump4e1f26a2009-02-19 03:04:26 +00003709
Eli Friedmane14b1992009-12-26 03:35:45 +00003710 Expr *NakedFn = Fn->IgnoreParens();
Douglas Gregor928479e2010-11-09 20:03:54 +00003711
John McCall57500772009-12-16 12:17:52 +00003712 NamedDecl *NDecl = 0;
Douglas Gregor59f16ed2010-10-25 20:48:33 +00003713 if (UnaryOperator *UnOp = dyn_cast<UnaryOperator>(NakedFn))
3714 if (UnOp->getOpcode() == UO_AddrOf)
3715 NakedFn = UnOp->getSubExpr()->IgnoreParens();
3716
John McCall57500772009-12-16 12:17:52 +00003717 if (isa<DeclRefExpr>(NakedFn))
3718 NDecl = cast<DeclRefExpr>(NakedFn)->getDecl();
John McCall0009fcc2011-04-26 20:42:42 +00003719 else if (isa<MemberExpr>(NakedFn))
3720 NDecl = cast<MemberExpr>(NakedFn)->getMemberDecl();
John McCall57500772009-12-16 12:17:52 +00003721
Peter Collingbourne41f85462011-02-09 21:07:24 +00003722 return BuildResolvedCallExpr(Fn, NDecl, LParenLoc, Args, NumArgs, RParenLoc,
Peter Collingbourne619a8c72011-10-02 23:49:29 +00003723 ExecConfig, IsExecConfig);
Peter Collingbourne41f85462011-02-09 21:07:24 +00003724}
3725
3726ExprResult
3727Sema::ActOnCUDAExecConfigExpr(Scope *S, SourceLocation LLLLoc,
Richard Trieuba63ce62011-09-09 01:45:06 +00003728 MultiExprArg ExecConfig, SourceLocation GGGLoc) {
Peter Collingbourne41f85462011-02-09 21:07:24 +00003729 FunctionDecl *ConfigDecl = Context.getcudaConfigureCallDecl();
3730 if (!ConfigDecl)
3731 return ExprError(Diag(LLLLoc, diag::err_undeclared_var_use)
3732 << "cudaConfigureCall");
3733 QualType ConfigQTy = ConfigDecl->getType();
3734
3735 DeclRefExpr *ConfigDR = new (Context) DeclRefExpr(
John McCall113bee02012-03-10 09:33:50 +00003736 ConfigDecl, false, ConfigQTy, VK_LValue, LLLLoc);
Eli Friedmanfa0df832012-02-02 03:46:19 +00003737 MarkFunctionReferenced(LLLLoc, ConfigDecl);
Peter Collingbourne41f85462011-02-09 21:07:24 +00003738
Peter Collingbourne619a8c72011-10-02 23:49:29 +00003739 return ActOnCallExpr(S, ConfigDR, LLLLoc, ExecConfig, GGGLoc, 0,
3740 /*IsExecConfig=*/true);
John McCall2d74de92009-12-01 22:10:20 +00003741}
3742
Tanya Lattner55808c12011-06-04 00:47:47 +00003743/// ActOnAsTypeExpr - create a new asType (bitcast) from the arguments.
3744///
3745/// __builtin_astype( value, dst type )
3746///
Richard Trieuba63ce62011-09-09 01:45:06 +00003747ExprResult Sema::ActOnAsTypeExpr(Expr *E, ParsedType ParsedDestTy,
Tanya Lattner55808c12011-06-04 00:47:47 +00003748 SourceLocation BuiltinLoc,
3749 SourceLocation RParenLoc) {
3750 ExprValueKind VK = VK_RValue;
3751 ExprObjectKind OK = OK_Ordinary;
Richard Trieuba63ce62011-09-09 01:45:06 +00003752 QualType DstTy = GetTypeFromParser(ParsedDestTy);
3753 QualType SrcTy = E->getType();
Tanya Lattner55808c12011-06-04 00:47:47 +00003754 if (Context.getTypeSize(DstTy) != Context.getTypeSize(SrcTy))
3755 return ExprError(Diag(BuiltinLoc,
3756 diag::err_invalid_astype_of_different_size)
Peter Collingbourne23f1bee2011-06-08 15:15:17 +00003757 << DstTy
3758 << SrcTy
Richard Trieuba63ce62011-09-09 01:45:06 +00003759 << E->getSourceRange());
3760 return Owned(new (Context) AsTypeExpr(E, DstTy, VK, OK, BuiltinLoc,
Richard Trieucfc491d2011-08-02 04:35:43 +00003761 RParenLoc));
Tanya Lattner55808c12011-06-04 00:47:47 +00003762}
3763
John McCall57500772009-12-16 12:17:52 +00003764/// BuildResolvedCallExpr - Build a call to a resolved expression,
3765/// i.e. an expression not of \p OverloadTy. The expression should
John McCall2d74de92009-12-01 22:10:20 +00003766/// unary-convert to an expression of function-pointer or
3767/// block-pointer type.
3768///
3769/// \param NDecl the declaration being called, if available
John McCalldadc5752010-08-24 06:29:42 +00003770ExprResult
John McCall2d74de92009-12-01 22:10:20 +00003771Sema::BuildResolvedCallExpr(Expr *Fn, NamedDecl *NDecl,
3772 SourceLocation LParenLoc,
3773 Expr **Args, unsigned NumArgs,
Peter Collingbourne41f85462011-02-09 21:07:24 +00003774 SourceLocation RParenLoc,
Peter Collingbourne619a8c72011-10-02 23:49:29 +00003775 Expr *Config, bool IsExecConfig) {
John McCall2d74de92009-12-01 22:10:20 +00003776 FunctionDecl *FDecl = dyn_cast_or_null<FunctionDecl>(NDecl);
3777
Chris Lattneraa9c7ae2008-04-08 04:40:51 +00003778 // Promote the function operand.
John Wiegley01296292011-04-08 18:41:53 +00003779 ExprResult Result = UsualUnaryConversions(Fn);
3780 if (Result.isInvalid())
3781 return ExprError();
3782 Fn = Result.take();
Chris Lattneraa9c7ae2008-04-08 04:40:51 +00003783
Chris Lattner08464942007-12-28 05:29:59 +00003784 // Make the call expr early, before semantic checks. This guarantees cleanup
3785 // of arguments and function on error.
Peter Collingbourne41f85462011-02-09 21:07:24 +00003786 CallExpr *TheCall;
3787 if (Config) {
3788 TheCall = new (Context) CUDAKernelCallExpr(Context, Fn,
3789 cast<CallExpr>(Config),
3790 Args, NumArgs,
3791 Context.BoolTy,
3792 VK_RValue,
3793 RParenLoc);
3794 } else {
3795 TheCall = new (Context) CallExpr(Context, Fn,
3796 Args, NumArgs,
3797 Context.BoolTy,
3798 VK_RValue,
3799 RParenLoc);
3800 }
Sebastian Redlc215cfc2009-01-19 00:08:26 +00003801
John McCallbebede42011-02-26 05:39:39 +00003802 unsigned BuiltinID = (FDecl ? FDecl->getBuiltinID() : 0);
3803
3804 // Bail out early if calling a builtin with custom typechecking.
3805 if (BuiltinID && Context.BuiltinInfo.hasCustomTypechecking(BuiltinID))
3806 return CheckBuiltinFunctionCall(BuiltinID, TheCall);
3807
John McCall31996342011-04-07 08:22:57 +00003808 retry:
Steve Naroff8de9c3a2008-09-05 22:11:13 +00003809 const FunctionType *FuncT;
John McCallbebede42011-02-26 05:39:39 +00003810 if (const PointerType *PT = Fn->getType()->getAs<PointerType>()) {
Steve Naroff8de9c3a2008-09-05 22:11:13 +00003811 // C99 6.5.2.2p1 - "The expression that denotes the called function shall
3812 // have type pointer to function".
John McCall9dd450b2009-09-21 23:43:11 +00003813 FuncT = PT->getPointeeType()->getAs<FunctionType>();
John McCallbebede42011-02-26 05:39:39 +00003814 if (FuncT == 0)
3815 return ExprError(Diag(LParenLoc, diag::err_typecheck_call_not_function)
3816 << Fn->getType() << Fn->getSourceRange());
3817 } else if (const BlockPointerType *BPT =
3818 Fn->getType()->getAs<BlockPointerType>()) {
3819 FuncT = BPT->getPointeeType()->castAs<FunctionType>();
3820 } else {
John McCall31996342011-04-07 08:22:57 +00003821 // Handle calls to expressions of unknown-any type.
3822 if (Fn->getType() == Context.UnknownAnyTy) {
John McCall2979fe02011-04-12 00:42:48 +00003823 ExprResult rewrite = rebuildUnknownAnyFunction(*this, Fn);
John McCall31996342011-04-07 08:22:57 +00003824 if (rewrite.isInvalid()) return ExprError();
3825 Fn = rewrite.take();
John McCall39439732011-04-09 22:50:59 +00003826 TheCall->setCallee(Fn);
John McCall31996342011-04-07 08:22:57 +00003827 goto retry;
3828 }
3829
Sebastian Redlc215cfc2009-01-19 00:08:26 +00003830 return ExprError(Diag(LParenLoc, diag::err_typecheck_call_not_function)
3831 << Fn->getType() << Fn->getSourceRange());
John McCallbebede42011-02-26 05:39:39 +00003832 }
Sebastian Redlc215cfc2009-01-19 00:08:26 +00003833
David Blaikiebbafb8a2012-03-11 07:00:24 +00003834 if (getLangOpts().CUDA) {
Peter Collingbourne4b66c472011-02-23 01:53:29 +00003835 if (Config) {
3836 // CUDA: Kernel calls must be to global functions
3837 if (FDecl && !FDecl->hasAttr<CUDAGlobalAttr>())
3838 return ExprError(Diag(LParenLoc,diag::err_kern_call_not_global_function)
3839 << FDecl->getName() << Fn->getSourceRange());
3840
3841 // CUDA: Kernel function must have 'void' return type
3842 if (!FuncT->getResultType()->isVoidType())
3843 return ExprError(Diag(LParenLoc, diag::err_kern_type_not_void_return)
3844 << Fn->getType() << Fn->getSourceRange());
Peter Collingbourne34a20b02011-10-02 23:49:15 +00003845 } else {
3846 // CUDA: Calls to global functions must be configured
3847 if (FDecl && FDecl->hasAttr<CUDAGlobalAttr>())
3848 return ExprError(Diag(LParenLoc, diag::err_global_call_not_config)
3849 << FDecl->getName() << Fn->getSourceRange());
Peter Collingbourne4b66c472011-02-23 01:53:29 +00003850 }
3851 }
3852
Eli Friedman3164fb12009-03-22 22:00:50 +00003853 // Check for a valid return type
Kovarththanan Rajaratnamba2c6522010-03-13 10:17:05 +00003854 if (CheckCallReturnType(FuncT->getResultType(),
Daniel Dunbar62ee6412012-03-09 18:35:03 +00003855 Fn->getLocStart(), TheCall,
Anders Carlsson7f84ed92009-10-09 23:51:55 +00003856 FDecl))
Eli Friedman3164fb12009-03-22 22:00:50 +00003857 return ExprError();
3858
Chris Lattner08464942007-12-28 05:29:59 +00003859 // We know the result type of the call, set it.
Douglas Gregor603d81b2010-07-13 08:18:22 +00003860 TheCall->setType(FuncT->getCallResultType(Context));
John McCall7decc9e2010-11-18 06:31:45 +00003861 TheCall->setValueKind(Expr::getValueKindForType(FuncT->getResultType()));
Sebastian Redlc215cfc2009-01-19 00:08:26 +00003862
Douglas Gregordeaad8c2009-02-26 23:50:07 +00003863 if (const FunctionProtoType *Proto = dyn_cast<FunctionProtoType>(FuncT)) {
John McCallb268a282010-08-23 23:25:46 +00003864 if (ConvertArgumentsForCall(TheCall, Fn, FDecl, Proto, Args, NumArgs,
Peter Collingbourne619a8c72011-10-02 23:49:29 +00003865 RParenLoc, IsExecConfig))
Sebastian Redlc215cfc2009-01-19 00:08:26 +00003866 return ExprError();
Chris Lattner08464942007-12-28 05:29:59 +00003867 } else {
Douglas Gregordeaad8c2009-02-26 23:50:07 +00003868 assert(isa<FunctionNoProtoType>(FuncT) && "Unknown FunctionType!");
Sebastian Redlc215cfc2009-01-19 00:08:26 +00003869
Douglas Gregord8e97de2009-04-02 15:37:10 +00003870 if (FDecl) {
3871 // Check if we have too few/too many template arguments, based
3872 // on our knowledge of the function definition.
3873 const FunctionDecl *Def = 0;
Argyrios Kyrtzidis36ea3222010-07-07 11:31:19 +00003874 if (FDecl->hasBody(Def) && NumArgs != Def->param_size()) {
Douglas Gregor8e09a722010-10-25 20:39:23 +00003875 const FunctionProtoType *Proto
3876 = Def->getType()->getAs<FunctionProtoType>();
3877 if (!Proto || !(Proto->isVariadic() && NumArgs >= Def->param_size()))
Eli Friedmanfcbf7d22009-06-01 09:24:59 +00003878 Diag(RParenLoc, diag::warn_call_wrong_number_of_arguments)
3879 << (NumArgs > Def->param_size()) << FDecl << Fn->getSourceRange();
Eli Friedmanfcbf7d22009-06-01 09:24:59 +00003880 }
Douglas Gregor8e09a722010-10-25 20:39:23 +00003881
3882 // If the function we're calling isn't a function prototype, but we have
3883 // a function prototype from a prior declaratiom, use that prototype.
3884 if (!FDecl->hasPrototype())
3885 Proto = FDecl->getType()->getAs<FunctionProtoType>();
Douglas Gregord8e97de2009-04-02 15:37:10 +00003886 }
3887
Steve Naroff0b661582007-08-28 23:30:39 +00003888 // Promote the arguments (C99 6.5.2.2p6).
Chris Lattner08464942007-12-28 05:29:59 +00003889 for (unsigned i = 0; i != NumArgs; i++) {
3890 Expr *Arg = Args[i];
Douglas Gregor8e09a722010-10-25 20:39:23 +00003891
3892 if (Proto && i < Proto->getNumArgs()) {
Douglas Gregor8e09a722010-10-25 20:39:23 +00003893 InitializedEntity Entity
3894 = InitializedEntity::InitializeParameter(Context,
John McCall31168b02011-06-15 23:02:42 +00003895 Proto->getArgType(i),
3896 Proto->isArgConsumed(i));
Douglas Gregor8e09a722010-10-25 20:39:23 +00003897 ExprResult ArgE = PerformCopyInitialization(Entity,
3898 SourceLocation(),
3899 Owned(Arg));
3900 if (ArgE.isInvalid())
3901 return true;
3902
3903 Arg = ArgE.takeAs<Expr>();
3904
3905 } else {
John Wiegley01296292011-04-08 18:41:53 +00003906 ExprResult ArgE = DefaultArgumentPromotion(Arg);
3907
3908 if (ArgE.isInvalid())
3909 return true;
3910
3911 Arg = ArgE.takeAs<Expr>();
Douglas Gregor8e09a722010-10-25 20:39:23 +00003912 }
3913
Daniel Dunbar62ee6412012-03-09 18:35:03 +00003914 if (RequireCompleteType(Arg->getLocStart(),
Douglas Gregor83025412010-10-26 05:45:40 +00003915 Arg->getType(),
Douglas Gregor7bfb2d02012-05-04 16:32:21 +00003916 diag::err_call_incomplete_argument, Arg))
Douglas Gregor83025412010-10-26 05:45:40 +00003917 return ExprError();
3918
Chris Lattner08464942007-12-28 05:29:59 +00003919 TheCall->setArg(i, Arg);
Steve Naroff0b661582007-08-28 23:30:39 +00003920 }
Steve Naroffae4143e2007-04-26 20:39:23 +00003921 }
Chris Lattner08464942007-12-28 05:29:59 +00003922
Douglas Gregor97fd6e22008-12-22 05:46:06 +00003923 if (CXXMethodDecl *Method = dyn_cast_or_null<CXXMethodDecl>(FDecl))
3924 if (!Method->isStatic())
Sebastian Redlc215cfc2009-01-19 00:08:26 +00003925 return ExprError(Diag(LParenLoc, diag::err_member_call_without_object)
3926 << Fn->getSourceRange());
Douglas Gregor97fd6e22008-12-22 05:46:06 +00003927
Fariborz Jahanian0aa5c452009-05-15 20:33:25 +00003928 // Check for sentinels
3929 if (NDecl)
3930 DiagnoseSentinelCalls(NDecl, LParenLoc, Args, NumArgs);
Mike Stump11289f42009-09-09 15:08:12 +00003931
Chris Lattnerb87b1b32007-08-10 20:18:51 +00003932 // Do special checking on direct calls to functions.
Anders Carlssonbc4c1072009-08-16 01:56:34 +00003933 if (FDecl) {
John McCallb268a282010-08-23 23:25:46 +00003934 if (CheckFunctionCall(FDecl, TheCall))
Anders Carlssonbc4c1072009-08-16 01:56:34 +00003935 return ExprError();
Mike Stump11289f42009-09-09 15:08:12 +00003936
John McCallbebede42011-02-26 05:39:39 +00003937 if (BuiltinID)
Fariborz Jahaniane8473c22010-11-30 17:35:24 +00003938 return CheckBuiltinFunctionCall(BuiltinID, TheCall);
Anders Carlssonbc4c1072009-08-16 01:56:34 +00003939 } else if (NDecl) {
John McCallb268a282010-08-23 23:25:46 +00003940 if (CheckBlockCall(NDecl, TheCall))
Anders Carlssonbc4c1072009-08-16 01:56:34 +00003941 return ExprError();
3942 }
Chris Lattnerb87b1b32007-08-10 20:18:51 +00003943
John McCallb268a282010-08-23 23:25:46 +00003944 return MaybeBindToTemporary(TheCall);
Chris Lattnere168f762006-11-10 05:29:30 +00003945}
3946
John McCalldadc5752010-08-24 06:29:42 +00003947ExprResult
John McCallba7bf592010-08-24 05:47:05 +00003948Sema::ActOnCompoundLiteral(SourceLocation LParenLoc, ParsedType Ty,
John McCallb268a282010-08-23 23:25:46 +00003949 SourceLocation RParenLoc, Expr *InitExpr) {
Steve Naroff83895f72007-09-16 03:34:24 +00003950 assert((Ty != 0) && "ActOnCompoundLiteral(): missing type");
Steve Naroff57eb2c52007-07-19 21:32:11 +00003951 // FIXME: put back this assert when initializers are worked out.
Steve Naroff83895f72007-09-16 03:34:24 +00003952 //assert((InitExpr != 0) && "ActOnCompoundLiteral(): missing expression");
John McCalle15bbff2010-01-18 19:35:47 +00003953
3954 TypeSourceInfo *TInfo;
3955 QualType literalType = GetTypeFromParser(Ty, &TInfo);
3956 if (!TInfo)
3957 TInfo = Context.getTrivialTypeSourceInfo(literalType);
3958
John McCallb268a282010-08-23 23:25:46 +00003959 return BuildCompoundLiteralExpr(LParenLoc, TInfo, RParenLoc, InitExpr);
John McCalle15bbff2010-01-18 19:35:47 +00003960}
3961
John McCalldadc5752010-08-24 06:29:42 +00003962ExprResult
John McCalle15bbff2010-01-18 19:35:47 +00003963Sema::BuildCompoundLiteralExpr(SourceLocation LParenLoc, TypeSourceInfo *TInfo,
Richard Trieuba63ce62011-09-09 01:45:06 +00003964 SourceLocation RParenLoc, Expr *LiteralExpr) {
John McCalle15bbff2010-01-18 19:35:47 +00003965 QualType literalType = TInfo->getType();
Anders Carlsson2c1ec6d2007-12-05 07:24:19 +00003966
Eli Friedman37a186d2008-05-20 05:22:08 +00003967 if (literalType->isArrayType()) {
Argyrios Kyrtzidis85663562010-11-08 19:14:19 +00003968 if (RequireCompleteType(LParenLoc, Context.getBaseElementType(literalType),
Douglas Gregor7bfb2d02012-05-04 16:32:21 +00003969 diag::err_illegal_decl_array_incomplete_type,
3970 SourceRange(LParenLoc,
3971 LiteralExpr->getSourceRange().getEnd())))
Argyrios Kyrtzidis85663562010-11-08 19:14:19 +00003972 return ExprError();
Chris Lattner7adf0762008-08-04 07:31:14 +00003973 if (literalType->isVariableArrayType())
Sebastian Redlb5d49352009-01-19 22:31:54 +00003974 return ExprError(Diag(LParenLoc, diag::err_variable_object_no_init)
Richard Trieuba63ce62011-09-09 01:45:06 +00003975 << SourceRange(LParenLoc, LiteralExpr->getSourceRange().getEnd()));
Douglas Gregor1c37d9e2009-05-21 23:48:18 +00003976 } else if (!literalType->isDependentType() &&
3977 RequireCompleteType(LParenLoc, literalType,
Douglas Gregor7bfb2d02012-05-04 16:32:21 +00003978 diag::err_typecheck_decl_incomplete_type,
3979 SourceRange(LParenLoc, LiteralExpr->getSourceRange().getEnd())))
Sebastian Redlb5d49352009-01-19 22:31:54 +00003980 return ExprError();
Eli Friedman37a186d2008-05-20 05:22:08 +00003981
Douglas Gregor85dabae2009-12-16 01:38:02 +00003982 InitializedEntity Entity
Douglas Gregor1b303932009-12-22 15:35:07 +00003983 = InitializedEntity::InitializeTemporary(literalType);
Douglas Gregor85dabae2009-12-16 01:38:02 +00003984 InitializationKind Kind
John McCall31168b02011-06-15 23:02:42 +00003985 = InitializationKind::CreateCStyleCast(LParenLoc,
Sebastian Redl0501c632012-02-12 16:37:36 +00003986 SourceRange(LParenLoc, RParenLoc),
3987 /*InitList=*/true);
Richard Trieuba63ce62011-09-09 01:45:06 +00003988 InitializationSequence InitSeq(*this, Entity, Kind, &LiteralExpr, 1);
John McCalldadc5752010-08-24 06:29:42 +00003989 ExprResult Result = InitSeq.Perform(*this, Entity, Kind,
Richard Trieuba63ce62011-09-09 01:45:06 +00003990 MultiExprArg(*this, &LiteralExpr, 1),
Eli Friedmana553d4a2009-12-22 02:35:53 +00003991 &literalType);
3992 if (Result.isInvalid())
Sebastian Redlb5d49352009-01-19 22:31:54 +00003993 return ExprError();
Richard Trieuba63ce62011-09-09 01:45:06 +00003994 LiteralExpr = Result.get();
Steve Naroffd32419d2008-01-14 18:19:28 +00003995
Chris Lattner79413952008-12-04 23:50:19 +00003996 bool isFileScope = getCurFunctionOrMethodDecl() == 0;
Steve Naroffd32419d2008-01-14 18:19:28 +00003997 if (isFileScope) { // 6.5.2.5p3
Richard Trieuba63ce62011-09-09 01:45:06 +00003998 if (CheckForConstantInitializer(LiteralExpr, literalType))
Sebastian Redlb5d49352009-01-19 22:31:54 +00003999 return ExprError();
Steve Naroff98f72032008-01-10 22:15:12 +00004000 }
Eli Friedmana553d4a2009-12-22 02:35:53 +00004001
John McCall7decc9e2010-11-18 06:31:45 +00004002 // In C, compound literals are l-values for some reason.
David Blaikiebbafb8a2012-03-11 07:00:24 +00004003 ExprValueKind VK = getLangOpts().CPlusPlus ? VK_RValue : VK_LValue;
John McCall7decc9e2010-11-18 06:31:45 +00004004
Douglas Gregor9b71f0c2011-06-17 04:59:12 +00004005 return MaybeBindToTemporary(
4006 new (Context) CompoundLiteralExpr(LParenLoc, TInfo, literalType,
Richard Trieuba63ce62011-09-09 01:45:06 +00004007 VK, LiteralExpr, isFileScope));
Steve Narofffbd09832007-07-19 01:06:55 +00004008}
4009
John McCalldadc5752010-08-24 06:29:42 +00004010ExprResult
Richard Trieuba63ce62011-09-09 01:45:06 +00004011Sema::ActOnInitList(SourceLocation LBraceLoc, MultiExprArg InitArgList,
Sebastian Redlb5d49352009-01-19 22:31:54 +00004012 SourceLocation RBraceLoc) {
Richard Trieuba63ce62011-09-09 01:45:06 +00004013 unsigned NumInit = InitArgList.size();
4014 Expr **InitList = InitArgList.release();
Anders Carlsson4692db02007-08-31 04:56:16 +00004015
John McCall526ab472011-10-25 17:37:35 +00004016 // Immediately handle non-overload placeholders. Overloads can be
4017 // resolved contextually, but everything else here can't.
4018 for (unsigned I = 0; I != NumInit; ++I) {
John McCalld5c98ae2011-11-15 01:35:18 +00004019 if (InitList[I]->getType()->isNonOverloadPlaceholderType()) {
John McCall526ab472011-10-25 17:37:35 +00004020 ExprResult result = CheckPlaceholderExpr(InitList[I]);
4021
4022 // Ignore failures; dropping the entire initializer list because
4023 // of one failure would be terrible for indexing/etc.
4024 if (result.isInvalid()) continue;
4025
4026 InitList[I] = result.take();
4027 }
4028 }
4029
Steve Naroff30d242c2007-09-15 18:49:24 +00004030 // Semantic analysis for initializers is done by ActOnDeclarator() and
Mike Stump4e1f26a2009-02-19 03:04:26 +00004031 // CheckInitializer() - it requires knowledge of the object being intialized.
Sebastian Redlb5d49352009-01-19 22:31:54 +00004032
Ted Kremenekac034612010-04-13 23:39:13 +00004033 InitListExpr *E = new (Context) InitListExpr(Context, LBraceLoc, InitList,
4034 NumInit, RBraceLoc);
Chris Lattner24d5bfe2008-04-02 04:24:33 +00004035 E->setType(Context.VoidTy); // FIXME: just a place holder for now.
Sebastian Redlb5d49352009-01-19 22:31:54 +00004036 return Owned(E);
Steve Narofffbd09832007-07-19 01:06:55 +00004037}
4038
John McCallcd78e802011-09-10 01:16:55 +00004039/// Do an explicit extend of the given block pointer if we're in ARC.
4040static void maybeExtendBlockObject(Sema &S, ExprResult &E) {
4041 assert(E.get()->getType()->isBlockPointerType());
4042 assert(E.get()->isRValue());
4043
4044 // Only do this in an r-value context.
David Blaikiebbafb8a2012-03-11 07:00:24 +00004045 if (!S.getLangOpts().ObjCAutoRefCount) return;
John McCallcd78e802011-09-10 01:16:55 +00004046
4047 E = ImplicitCastExpr::Create(S.Context, E.get()->getType(),
John McCall2d637d22011-09-10 06:18:15 +00004048 CK_ARCExtendBlockObject, E.get(),
John McCallcd78e802011-09-10 01:16:55 +00004049 /*base path*/ 0, VK_RValue);
4050 S.ExprNeedsCleanups = true;
4051}
4052
4053/// Prepare a conversion of the given expression to an ObjC object
4054/// pointer type.
4055CastKind Sema::PrepareCastToObjCObjectPointer(ExprResult &E) {
4056 QualType type = E.get()->getType();
4057 if (type->isObjCObjectPointerType()) {
4058 return CK_BitCast;
4059 } else if (type->isBlockPointerType()) {
4060 maybeExtendBlockObject(*this, E);
4061 return CK_BlockPointerToObjCPointerCast;
4062 } else {
4063 assert(type->isPointerType());
4064 return CK_CPointerToObjCPointerCast;
4065 }
4066}
4067
John McCalld7646252010-11-14 08:17:51 +00004068/// Prepares for a scalar cast, performing all the necessary stages
4069/// except the final cast and returning the kind required.
John McCall9776e432011-10-06 23:25:11 +00004070CastKind Sema::PrepareScalarCast(ExprResult &Src, QualType DestTy) {
John McCalld7646252010-11-14 08:17:51 +00004071 // Both Src and Dest are scalar types, i.e. arithmetic or pointer.
4072 // Also, callers should have filtered out the invalid cases with
4073 // pointers. Everything else should be possible.
4074
John Wiegley01296292011-04-08 18:41:53 +00004075 QualType SrcTy = Src.get()->getType();
David Chisnallfa35df62012-01-16 17:27:18 +00004076 if (const AtomicType *SrcAtomicTy = SrcTy->getAs<AtomicType>())
4077 SrcTy = SrcAtomicTy->getValueType();
4078 if (const AtomicType *DestAtomicTy = DestTy->getAs<AtomicType>())
4079 DestTy = DestAtomicTy->getValueType();
4080
John McCall9776e432011-10-06 23:25:11 +00004081 if (Context.hasSameUnqualifiedType(SrcTy, DestTy))
John McCalle3027922010-08-25 11:45:40 +00004082 return CK_NoOp;
Anders Carlsson094c4592009-10-18 18:12:03 +00004083
John McCall9320b872011-09-09 05:25:32 +00004084 switch (Type::ScalarTypeKind SrcKind = SrcTy->getScalarTypeKind()) {
John McCall8cb679e2010-11-15 09:13:47 +00004085 case Type::STK_MemberPointer:
4086 llvm_unreachable("member pointer type in C");
Abramo Bagnaraba854972011-01-04 09:50:03 +00004087
John McCall9320b872011-09-09 05:25:32 +00004088 case Type::STK_CPointer:
4089 case Type::STK_BlockPointer:
4090 case Type::STK_ObjCObjectPointer:
John McCall8cb679e2010-11-15 09:13:47 +00004091 switch (DestTy->getScalarTypeKind()) {
John McCall9320b872011-09-09 05:25:32 +00004092 case Type::STK_CPointer:
4093 return CK_BitCast;
4094 case Type::STK_BlockPointer:
4095 return (SrcKind == Type::STK_BlockPointer
4096 ? CK_BitCast : CK_AnyPointerToBlockPointerCast);
4097 case Type::STK_ObjCObjectPointer:
4098 if (SrcKind == Type::STK_ObjCObjectPointer)
4099 return CK_BitCast;
David Blaikie8a40f702012-01-17 06:56:22 +00004100 if (SrcKind == Type::STK_CPointer)
John McCall9320b872011-09-09 05:25:32 +00004101 return CK_CPointerToObjCPointerCast;
David Blaikie8a40f702012-01-17 06:56:22 +00004102 maybeExtendBlockObject(*this, Src);
4103 return CK_BlockPointerToObjCPointerCast;
John McCall8cb679e2010-11-15 09:13:47 +00004104 case Type::STK_Bool:
4105 return CK_PointerToBoolean;
4106 case Type::STK_Integral:
4107 return CK_PointerToIntegral;
4108 case Type::STK_Floating:
4109 case Type::STK_FloatingComplex:
4110 case Type::STK_IntegralComplex:
4111 case Type::STK_MemberPointer:
4112 llvm_unreachable("illegal cast from pointer");
4113 }
David Blaikie8a40f702012-01-17 06:56:22 +00004114 llvm_unreachable("Should have returned before this");
Kovarththanan Rajaratnamba2c6522010-03-13 10:17:05 +00004115
John McCall8cb679e2010-11-15 09:13:47 +00004116 case Type::STK_Bool: // casting from bool is like casting from an integer
4117 case Type::STK_Integral:
4118 switch (DestTy->getScalarTypeKind()) {
John McCall9320b872011-09-09 05:25:32 +00004119 case Type::STK_CPointer:
4120 case Type::STK_ObjCObjectPointer:
4121 case Type::STK_BlockPointer:
John McCall9776e432011-10-06 23:25:11 +00004122 if (Src.get()->isNullPointerConstant(Context,
Richard Trieucfc491d2011-08-02 04:35:43 +00004123 Expr::NPC_ValueDependentIsNull))
John McCalle84af4e2010-11-13 01:35:44 +00004124 return CK_NullToPointer;
John McCalle3027922010-08-25 11:45:40 +00004125 return CK_IntegralToPointer;
John McCall8cb679e2010-11-15 09:13:47 +00004126 case Type::STK_Bool:
4127 return CK_IntegralToBoolean;
4128 case Type::STK_Integral:
John McCalld7646252010-11-14 08:17:51 +00004129 return CK_IntegralCast;
John McCall8cb679e2010-11-15 09:13:47 +00004130 case Type::STK_Floating:
John McCalle3027922010-08-25 11:45:40 +00004131 return CK_IntegralToFloating;
John McCall8cb679e2010-11-15 09:13:47 +00004132 case Type::STK_IntegralComplex:
John McCall9776e432011-10-06 23:25:11 +00004133 Src = ImpCastExprToType(Src.take(),
4134 DestTy->castAs<ComplexType>()->getElementType(),
4135 CK_IntegralCast);
John McCalld7646252010-11-14 08:17:51 +00004136 return CK_IntegralRealToComplex;
John McCall8cb679e2010-11-15 09:13:47 +00004137 case Type::STK_FloatingComplex:
John McCall9776e432011-10-06 23:25:11 +00004138 Src = ImpCastExprToType(Src.take(),
4139 DestTy->castAs<ComplexType>()->getElementType(),
4140 CK_IntegralToFloating);
John McCalld7646252010-11-14 08:17:51 +00004141 return CK_FloatingRealToComplex;
John McCall8cb679e2010-11-15 09:13:47 +00004142 case Type::STK_MemberPointer:
4143 llvm_unreachable("member pointer type in C");
John McCalld7646252010-11-14 08:17:51 +00004144 }
David Blaikie8a40f702012-01-17 06:56:22 +00004145 llvm_unreachable("Should have returned before this");
Kovarththanan Rajaratnamba2c6522010-03-13 10:17:05 +00004146
John McCall8cb679e2010-11-15 09:13:47 +00004147 case Type::STK_Floating:
4148 switch (DestTy->getScalarTypeKind()) {
4149 case Type::STK_Floating:
John McCalle3027922010-08-25 11:45:40 +00004150 return CK_FloatingCast;
John McCall8cb679e2010-11-15 09:13:47 +00004151 case Type::STK_Bool:
4152 return CK_FloatingToBoolean;
4153 case Type::STK_Integral:
John McCalle3027922010-08-25 11:45:40 +00004154 return CK_FloatingToIntegral;
John McCall8cb679e2010-11-15 09:13:47 +00004155 case Type::STK_FloatingComplex:
John McCall9776e432011-10-06 23:25:11 +00004156 Src = ImpCastExprToType(Src.take(),
4157 DestTy->castAs<ComplexType>()->getElementType(),
4158 CK_FloatingCast);
John McCalld7646252010-11-14 08:17:51 +00004159 return CK_FloatingRealToComplex;
John McCall8cb679e2010-11-15 09:13:47 +00004160 case Type::STK_IntegralComplex:
John McCall9776e432011-10-06 23:25:11 +00004161 Src = ImpCastExprToType(Src.take(),
4162 DestTy->castAs<ComplexType>()->getElementType(),
4163 CK_FloatingToIntegral);
John McCalld7646252010-11-14 08:17:51 +00004164 return CK_IntegralRealToComplex;
John McCall9320b872011-09-09 05:25:32 +00004165 case Type::STK_CPointer:
4166 case Type::STK_ObjCObjectPointer:
4167 case Type::STK_BlockPointer:
John McCall8cb679e2010-11-15 09:13:47 +00004168 llvm_unreachable("valid float->pointer cast?");
4169 case Type::STK_MemberPointer:
4170 llvm_unreachable("member pointer type in C");
John McCalld7646252010-11-14 08:17:51 +00004171 }
David Blaikie8a40f702012-01-17 06:56:22 +00004172 llvm_unreachable("Should have returned before this");
John McCalld7646252010-11-14 08:17:51 +00004173
John McCall8cb679e2010-11-15 09:13:47 +00004174 case Type::STK_FloatingComplex:
4175 switch (DestTy->getScalarTypeKind()) {
4176 case Type::STK_FloatingComplex:
John McCalld7646252010-11-14 08:17:51 +00004177 return CK_FloatingComplexCast;
John McCall8cb679e2010-11-15 09:13:47 +00004178 case Type::STK_IntegralComplex:
John McCalld7646252010-11-14 08:17:51 +00004179 return CK_FloatingComplexToIntegralComplex;
John McCallfcef3cf2010-12-14 17:51:41 +00004180 case Type::STK_Floating: {
John McCall9776e432011-10-06 23:25:11 +00004181 QualType ET = SrcTy->castAs<ComplexType>()->getElementType();
4182 if (Context.hasSameType(ET, DestTy))
John McCallfcef3cf2010-12-14 17:51:41 +00004183 return CK_FloatingComplexToReal;
John McCall9776e432011-10-06 23:25:11 +00004184 Src = ImpCastExprToType(Src.take(), ET, CK_FloatingComplexToReal);
John McCallfcef3cf2010-12-14 17:51:41 +00004185 return CK_FloatingCast;
4186 }
John McCall8cb679e2010-11-15 09:13:47 +00004187 case Type::STK_Bool:
John McCalld7646252010-11-14 08:17:51 +00004188 return CK_FloatingComplexToBoolean;
John McCall8cb679e2010-11-15 09:13:47 +00004189 case Type::STK_Integral:
John McCall9776e432011-10-06 23:25:11 +00004190 Src = ImpCastExprToType(Src.take(),
4191 SrcTy->castAs<ComplexType>()->getElementType(),
4192 CK_FloatingComplexToReal);
John McCalld7646252010-11-14 08:17:51 +00004193 return CK_FloatingToIntegral;
John McCall9320b872011-09-09 05:25:32 +00004194 case Type::STK_CPointer:
4195 case Type::STK_ObjCObjectPointer:
4196 case Type::STK_BlockPointer:
John McCall8cb679e2010-11-15 09:13:47 +00004197 llvm_unreachable("valid complex float->pointer cast?");
4198 case Type::STK_MemberPointer:
4199 llvm_unreachable("member pointer type in C");
John McCalld7646252010-11-14 08:17:51 +00004200 }
David Blaikie8a40f702012-01-17 06:56:22 +00004201 llvm_unreachable("Should have returned before this");
John McCalld7646252010-11-14 08:17:51 +00004202
John McCall8cb679e2010-11-15 09:13:47 +00004203 case Type::STK_IntegralComplex:
4204 switch (DestTy->getScalarTypeKind()) {
4205 case Type::STK_FloatingComplex:
John McCalld7646252010-11-14 08:17:51 +00004206 return CK_IntegralComplexToFloatingComplex;
John McCall8cb679e2010-11-15 09:13:47 +00004207 case Type::STK_IntegralComplex:
John McCalld7646252010-11-14 08:17:51 +00004208 return CK_IntegralComplexCast;
John McCallfcef3cf2010-12-14 17:51:41 +00004209 case Type::STK_Integral: {
John McCall9776e432011-10-06 23:25:11 +00004210 QualType ET = SrcTy->castAs<ComplexType>()->getElementType();
4211 if (Context.hasSameType(ET, DestTy))
John McCallfcef3cf2010-12-14 17:51:41 +00004212 return CK_IntegralComplexToReal;
John McCall9776e432011-10-06 23:25:11 +00004213 Src = ImpCastExprToType(Src.take(), ET, CK_IntegralComplexToReal);
John McCallfcef3cf2010-12-14 17:51:41 +00004214 return CK_IntegralCast;
4215 }
John McCall8cb679e2010-11-15 09:13:47 +00004216 case Type::STK_Bool:
John McCalld7646252010-11-14 08:17:51 +00004217 return CK_IntegralComplexToBoolean;
John McCall8cb679e2010-11-15 09:13:47 +00004218 case Type::STK_Floating:
John McCall9776e432011-10-06 23:25:11 +00004219 Src = ImpCastExprToType(Src.take(),
4220 SrcTy->castAs<ComplexType>()->getElementType(),
4221 CK_IntegralComplexToReal);
John McCalld7646252010-11-14 08:17:51 +00004222 return CK_IntegralToFloating;
John McCall9320b872011-09-09 05:25:32 +00004223 case Type::STK_CPointer:
4224 case Type::STK_ObjCObjectPointer:
4225 case Type::STK_BlockPointer:
John McCall8cb679e2010-11-15 09:13:47 +00004226 llvm_unreachable("valid complex int->pointer cast?");
4227 case Type::STK_MemberPointer:
4228 llvm_unreachable("member pointer type in C");
John McCalld7646252010-11-14 08:17:51 +00004229 }
David Blaikie8a40f702012-01-17 06:56:22 +00004230 llvm_unreachable("Should have returned before this");
Anders Carlsson094c4592009-10-18 18:12:03 +00004231 }
Kovarththanan Rajaratnamba2c6522010-03-13 10:17:05 +00004232
John McCalld7646252010-11-14 08:17:51 +00004233 llvm_unreachable("Unhandled scalar cast");
Anders Carlsson094c4592009-10-18 18:12:03 +00004234}
4235
Anders Carlsson525b76b2009-10-16 02:48:28 +00004236bool Sema::CheckVectorCast(SourceRange R, QualType VectorTy, QualType Ty,
John McCalle3027922010-08-25 11:45:40 +00004237 CastKind &Kind) {
Anders Carlssonde71adf2007-11-27 05:51:55 +00004238 assert(VectorTy->isVectorType() && "Not a vector type!");
Mike Stump4e1f26a2009-02-19 03:04:26 +00004239
Anders Carlssonde71adf2007-11-27 05:51:55 +00004240 if (Ty->isVectorType() || Ty->isIntegerType()) {
Chris Lattner37e05872008-03-05 18:54:05 +00004241 if (Context.getTypeSize(VectorTy) != Context.getTypeSize(Ty))
Anders Carlssonde71adf2007-11-27 05:51:55 +00004242 return Diag(R.getBegin(),
Mike Stump4e1f26a2009-02-19 03:04:26 +00004243 Ty->isVectorType() ?
Anders Carlssonde71adf2007-11-27 05:51:55 +00004244 diag::err_invalid_conversion_between_vectors :
Chris Lattner3b054132008-11-19 05:08:23 +00004245 diag::err_invalid_conversion_between_vector_and_integer)
Chris Lattner1e5665e2008-11-24 06:25:27 +00004246 << VectorTy << Ty << R;
Anders Carlssonde71adf2007-11-27 05:51:55 +00004247 } else
4248 return Diag(R.getBegin(),
Chris Lattner3b054132008-11-19 05:08:23 +00004249 diag::err_invalid_conversion_between_vector_and_scalar)
Chris Lattner1e5665e2008-11-24 06:25:27 +00004250 << VectorTy << Ty << R;
Mike Stump4e1f26a2009-02-19 03:04:26 +00004251
John McCalle3027922010-08-25 11:45:40 +00004252 Kind = CK_BitCast;
Anders Carlssonde71adf2007-11-27 05:51:55 +00004253 return false;
4254}
4255
John Wiegley01296292011-04-08 18:41:53 +00004256ExprResult Sema::CheckExtVectorCast(SourceRange R, QualType DestTy,
4257 Expr *CastExpr, CastKind &Kind) {
Nate Begemanc69b7402009-06-26 00:50:28 +00004258 assert(DestTy->isExtVectorType() && "Not an extended vector type!");
Kovarththanan Rajaratnamba2c6522010-03-13 10:17:05 +00004259
Anders Carlsson43d70f82009-10-16 05:23:41 +00004260 QualType SrcTy = CastExpr->getType();
Kovarththanan Rajaratnamba2c6522010-03-13 10:17:05 +00004261
Nate Begemanc8961a42009-06-27 22:05:55 +00004262 // If SrcTy is a VectorType, the total size must match to explicitly cast to
4263 // an ExtVectorType.
Tobias Grosser766bcc22011-09-22 13:03:14 +00004264 // In OpenCL, casts between vectors of different types are not allowed.
4265 // (See OpenCL 6.2).
Nate Begemanc69b7402009-06-26 00:50:28 +00004266 if (SrcTy->isVectorType()) {
Tobias Grosser766bcc22011-09-22 13:03:14 +00004267 if (Context.getTypeSize(DestTy) != Context.getTypeSize(SrcTy)
David Blaikiebbafb8a2012-03-11 07:00:24 +00004268 || (getLangOpts().OpenCL &&
Tobias Grosser766bcc22011-09-22 13:03:14 +00004269 (DestTy.getCanonicalType() != SrcTy.getCanonicalType()))) {
John Wiegley01296292011-04-08 18:41:53 +00004270 Diag(R.getBegin(),diag::err_invalid_conversion_between_ext_vectors)
Nate Begemanc69b7402009-06-26 00:50:28 +00004271 << DestTy << SrcTy << R;
John Wiegley01296292011-04-08 18:41:53 +00004272 return ExprError();
4273 }
John McCalle3027922010-08-25 11:45:40 +00004274 Kind = CK_BitCast;
John Wiegley01296292011-04-08 18:41:53 +00004275 return Owned(CastExpr);
Nate Begemanc69b7402009-06-26 00:50:28 +00004276 }
4277
Nate Begemanbd956c42009-06-28 02:36:38 +00004278 // All non-pointer scalars can be cast to ExtVector type. The appropriate
Nate Begemanc69b7402009-06-26 00:50:28 +00004279 // conversion will take place first from scalar to elt type, and then
4280 // splat from elt type to vector.
Nate Begemanbd956c42009-06-28 02:36:38 +00004281 if (SrcTy->isPointerType())
4282 return Diag(R.getBegin(),
4283 diag::err_invalid_conversion_between_vector_and_scalar)
4284 << DestTy << SrcTy << R;
Eli Friedman06ed2a52009-10-20 08:27:19 +00004285
4286 QualType DestElemTy = DestTy->getAs<ExtVectorType>()->getElementType();
John Wiegley01296292011-04-08 18:41:53 +00004287 ExprResult CastExprRes = Owned(CastExpr);
John McCall9776e432011-10-06 23:25:11 +00004288 CastKind CK = PrepareScalarCast(CastExprRes, DestElemTy);
John Wiegley01296292011-04-08 18:41:53 +00004289 if (CastExprRes.isInvalid())
4290 return ExprError();
4291 CastExpr = ImpCastExprToType(CastExprRes.take(), DestElemTy, CK).take();
Kovarththanan Rajaratnamba2c6522010-03-13 10:17:05 +00004292
John McCalle3027922010-08-25 11:45:40 +00004293 Kind = CK_VectorSplat;
John Wiegley01296292011-04-08 18:41:53 +00004294 return Owned(CastExpr);
Nate Begemanc69b7402009-06-26 00:50:28 +00004295}
4296
John McCalldadc5752010-08-24 06:29:42 +00004297ExprResult
Argyrios Kyrtzidis7192a3b2011-07-01 22:22:59 +00004298Sema::ActOnCastExpr(Scope *S, SourceLocation LParenLoc,
4299 Declarator &D, ParsedType &Ty,
Richard Trieuba63ce62011-09-09 01:45:06 +00004300 SourceLocation RParenLoc, Expr *CastExpr) {
4301 assert(!D.isInvalidType() && (CastExpr != 0) &&
Sebastian Redlb5d49352009-01-19 22:31:54 +00004302 "ActOnCastExpr(): missing type or expr");
Steve Naroff1a2cf6b2007-07-16 23:25:18 +00004303
Richard Trieuba63ce62011-09-09 01:45:06 +00004304 TypeSourceInfo *castTInfo = GetTypeForDeclaratorCast(D, CastExpr->getType());
Argyrios Kyrtzidis7192a3b2011-07-01 22:22:59 +00004305 if (D.isInvalidType())
4306 return ExprError();
4307
David Blaikiebbafb8a2012-03-11 07:00:24 +00004308 if (getLangOpts().CPlusPlus) {
Argyrios Kyrtzidis7192a3b2011-07-01 22:22:59 +00004309 // Check that there are no default arguments (C++ only).
4310 CheckExtraCXXDefaultArguments(D);
4311 }
4312
John McCall42856de2011-10-01 05:17:03 +00004313 checkUnusedDeclAttributes(D);
4314
Argyrios Kyrtzidis7192a3b2011-07-01 22:22:59 +00004315 QualType castType = castTInfo->getType();
4316 Ty = CreateParsedType(castType, castTInfo);
Mike Stump11289f42009-09-09 15:08:12 +00004317
Argyrios Kyrtzidisd8701b62011-07-01 22:22:54 +00004318 bool isVectorLiteral = false;
4319
4320 // Check for an altivec or OpenCL literal,
4321 // i.e. all the elements are integer constants.
Richard Trieuba63ce62011-09-09 01:45:06 +00004322 ParenExpr *PE = dyn_cast<ParenExpr>(CastExpr);
4323 ParenListExpr *PLE = dyn_cast<ParenListExpr>(CastExpr);
David Blaikiebbafb8a2012-03-11 07:00:24 +00004324 if ((getLangOpts().AltiVec || getLangOpts().OpenCL)
Tobias Grosser0a3a22f2011-09-21 18:28:29 +00004325 && castType->isVectorType() && (PE || PLE)) {
Argyrios Kyrtzidisd8701b62011-07-01 22:22:54 +00004326 if (PLE && PLE->getNumExprs() == 0) {
4327 Diag(PLE->getExprLoc(), diag::err_altivec_empty_initializer);
4328 return ExprError();
4329 }
4330 if (PE || PLE->getNumExprs() == 1) {
4331 Expr *E = (PE ? PE->getSubExpr() : PLE->getExpr(0));
4332 if (!E->getType()->isVectorType())
4333 isVectorLiteral = true;
4334 }
4335 else
4336 isVectorLiteral = true;
4337 }
4338
4339 // If this is a vector initializer, '(' type ')' '(' init, ..., init ')'
4340 // then handle it as such.
4341 if (isVectorLiteral)
Richard Trieuba63ce62011-09-09 01:45:06 +00004342 return BuildVectorLiteral(LParenLoc, RParenLoc, CastExpr, castTInfo);
Argyrios Kyrtzidisd8701b62011-07-01 22:22:54 +00004343
Nate Begeman5ec4b312009-08-10 23:49:36 +00004344 // If the Expr being casted is a ParenListExpr, handle it specially.
Argyrios Kyrtzidisd8701b62011-07-01 22:22:54 +00004345 // This is not an AltiVec-style cast, so turn the ParenListExpr into a
4346 // sequence of BinOp comma operators.
Richard Trieuba63ce62011-09-09 01:45:06 +00004347 if (isa<ParenListExpr>(CastExpr)) {
4348 ExprResult Result = MaybeConvertParenListExprToParenExpr(S, CastExpr);
Argyrios Kyrtzidisd8701b62011-07-01 22:22:54 +00004349 if (Result.isInvalid()) return ExprError();
Richard Trieuba63ce62011-09-09 01:45:06 +00004350 CastExpr = Result.take();
Argyrios Kyrtzidisd8701b62011-07-01 22:22:54 +00004351 }
John McCallebe54742010-01-15 18:56:44 +00004352
Richard Trieuba63ce62011-09-09 01:45:06 +00004353 return BuildCStyleCastExpr(LParenLoc, castTInfo, RParenLoc, CastExpr);
John McCallebe54742010-01-15 18:56:44 +00004354}
4355
Argyrios Kyrtzidisd8701b62011-07-01 22:22:54 +00004356ExprResult Sema::BuildVectorLiteral(SourceLocation LParenLoc,
4357 SourceLocation RParenLoc, Expr *E,
4358 TypeSourceInfo *TInfo) {
4359 assert((isa<ParenListExpr>(E) || isa<ParenExpr>(E)) &&
4360 "Expected paren or paren list expression");
4361
4362 Expr **exprs;
4363 unsigned numExprs;
4364 Expr *subExpr;
4365 if (ParenListExpr *PE = dyn_cast<ParenListExpr>(E)) {
4366 exprs = PE->getExprs();
4367 numExprs = PE->getNumExprs();
4368 } else {
4369 subExpr = cast<ParenExpr>(E)->getSubExpr();
4370 exprs = &subExpr;
4371 numExprs = 1;
4372 }
4373
4374 QualType Ty = TInfo->getType();
4375 assert(Ty->isVectorType() && "Expected vector type");
4376
Chris Lattner0e62c1c2011-07-23 10:55:15 +00004377 SmallVector<Expr *, 8> initExprs;
Tanya Lattner83559382011-07-15 23:07:01 +00004378 const VectorType *VTy = Ty->getAs<VectorType>();
4379 unsigned numElems = Ty->getAs<VectorType>()->getNumElements();
4380
Argyrios Kyrtzidisd8701b62011-07-01 22:22:54 +00004381 // '(...)' form of vector initialization in AltiVec: the number of
4382 // initializers must be one or must match the size of the vector.
4383 // If a single value is specified in the initializer then it will be
4384 // replicated to all the components of the vector
Tanya Lattner83559382011-07-15 23:07:01 +00004385 if (VTy->getVectorKind() == VectorType::AltiVecVector) {
Argyrios Kyrtzidisd8701b62011-07-01 22:22:54 +00004386 // The number of initializers must be one or must match the size of the
4387 // vector. If a single value is specified in the initializer then it will
4388 // be replicated to all the components of the vector
4389 if (numExprs == 1) {
4390 QualType ElemTy = Ty->getAs<VectorType>()->getElementType();
Richard Smith01ebacd2011-10-27 23:31:58 +00004391 ExprResult Literal = DefaultLvalueConversion(exprs[0]);
4392 if (Literal.isInvalid())
4393 return ExprError();
Argyrios Kyrtzidisd8701b62011-07-01 22:22:54 +00004394 Literal = ImpCastExprToType(Literal.take(), ElemTy,
John McCall9776e432011-10-06 23:25:11 +00004395 PrepareScalarCast(Literal, ElemTy));
Argyrios Kyrtzidisd8701b62011-07-01 22:22:54 +00004396 return BuildCStyleCastExpr(LParenLoc, TInfo, RParenLoc, Literal.take());
4397 }
4398 else if (numExprs < numElems) {
4399 Diag(E->getExprLoc(),
4400 diag::err_incorrect_number_of_vector_initializers);
4401 return ExprError();
4402 }
4403 else
Benjamin Kramer8001f742012-02-14 12:06:21 +00004404 initExprs.append(exprs, exprs + numExprs);
Argyrios Kyrtzidisd8701b62011-07-01 22:22:54 +00004405 }
Tanya Lattner83559382011-07-15 23:07:01 +00004406 else {
4407 // For OpenCL, when the number of initializers is a single value,
4408 // it will be replicated to all components of the vector.
David Blaikiebbafb8a2012-03-11 07:00:24 +00004409 if (getLangOpts().OpenCL &&
Tanya Lattner83559382011-07-15 23:07:01 +00004410 VTy->getVectorKind() == VectorType::GenericVector &&
4411 numExprs == 1) {
4412 QualType ElemTy = Ty->getAs<VectorType>()->getElementType();
Richard Smith01ebacd2011-10-27 23:31:58 +00004413 ExprResult Literal = DefaultLvalueConversion(exprs[0]);
4414 if (Literal.isInvalid())
4415 return ExprError();
Tanya Lattner83559382011-07-15 23:07:01 +00004416 Literal = ImpCastExprToType(Literal.take(), ElemTy,
John McCall9776e432011-10-06 23:25:11 +00004417 PrepareScalarCast(Literal, ElemTy));
Tanya Lattner83559382011-07-15 23:07:01 +00004418 return BuildCStyleCastExpr(LParenLoc, TInfo, RParenLoc, Literal.take());
4419 }
4420
Benjamin Kramer8001f742012-02-14 12:06:21 +00004421 initExprs.append(exprs, exprs + numExprs);
Tanya Lattner83559382011-07-15 23:07:01 +00004422 }
Argyrios Kyrtzidisd8701b62011-07-01 22:22:54 +00004423 // FIXME: This means that pretty-printing the final AST will produce curly
4424 // braces instead of the original commas.
4425 InitListExpr *initE = new (Context) InitListExpr(Context, LParenLoc,
4426 &initExprs[0],
4427 initExprs.size(), RParenLoc);
4428 initE->setType(Ty);
4429 return BuildCompoundLiteralExpr(LParenLoc, TInfo, RParenLoc, initE);
4430}
4431
Sebastian Redla9351792012-02-11 23:51:47 +00004432/// This is not an AltiVec-style cast or or C++ direct-initialization, so turn
4433/// the ParenListExpr into a sequence of comma binary operators.
John McCalldadc5752010-08-24 06:29:42 +00004434ExprResult
Richard Trieuba63ce62011-09-09 01:45:06 +00004435Sema::MaybeConvertParenListExprToParenExpr(Scope *S, Expr *OrigExpr) {
4436 ParenListExpr *E = dyn_cast<ParenListExpr>(OrigExpr);
Nate Begeman5ec4b312009-08-10 23:49:36 +00004437 if (!E)
Richard Trieuba63ce62011-09-09 01:45:06 +00004438 return Owned(OrigExpr);
Mike Stump11289f42009-09-09 15:08:12 +00004439
John McCalldadc5752010-08-24 06:29:42 +00004440 ExprResult Result(E->getExpr(0));
Mike Stump11289f42009-09-09 15:08:12 +00004441
Nate Begeman5ec4b312009-08-10 23:49:36 +00004442 for (unsigned i = 1, e = E->getNumExprs(); i != e && !Result.isInvalid(); ++i)
John McCallb268a282010-08-23 23:25:46 +00004443 Result = ActOnBinOp(S, E->getExprLoc(), tok::comma, Result.get(),
4444 E->getExpr(i));
Mike Stump11289f42009-09-09 15:08:12 +00004445
John McCallb268a282010-08-23 23:25:46 +00004446 if (Result.isInvalid()) return ExprError();
4447
4448 return ActOnParenExpr(E->getLParenLoc(), E->getRParenLoc(), Result.get());
Nate Begeman5ec4b312009-08-10 23:49:36 +00004449}
4450
Sebastian Redla9351792012-02-11 23:51:47 +00004451ExprResult Sema::ActOnParenListExpr(SourceLocation L,
4452 SourceLocation R,
4453 MultiExprArg Val) {
Nate Begeman5ec4b312009-08-10 23:49:36 +00004454 unsigned nexprs = Val.size();
4455 Expr **exprs = reinterpret_cast<Expr**>(Val.release());
Fariborz Jahanian906d8712009-11-25 01:26:41 +00004456 assert((exprs != 0) && "ActOnParenOrParenListExpr() missing expr list");
Sebastian Redla9351792012-02-11 23:51:47 +00004457 Expr *expr = new (Context) ParenListExpr(Context, L, exprs, nexprs, R);
Nate Begeman5ec4b312009-08-10 23:49:36 +00004458 return Owned(expr);
4459}
4460
Chandler Carrutha8bea4b2011-02-18 23:54:50 +00004461/// \brief Emit a specialized diagnostic when one expression is a null pointer
Richard Trieu27ae4cb2011-09-02 01:51:02 +00004462/// constant and the other is not a pointer. Returns true if a diagnostic is
4463/// emitted.
Richard Trieud33e46e2011-09-06 20:06:39 +00004464bool Sema::DiagnoseConditionalForNull(Expr *LHSExpr, Expr *RHSExpr,
Chandler Carrutha8bea4b2011-02-18 23:54:50 +00004465 SourceLocation QuestionLoc) {
Richard Trieud33e46e2011-09-06 20:06:39 +00004466 Expr *NullExpr = LHSExpr;
4467 Expr *NonPointerExpr = RHSExpr;
Chandler Carrutha8bea4b2011-02-18 23:54:50 +00004468 Expr::NullPointerConstantKind NullKind =
4469 NullExpr->isNullPointerConstant(Context,
4470 Expr::NPC_ValueDependentIsNotNull);
4471
4472 if (NullKind == Expr::NPCK_NotNull) {
Richard Trieud33e46e2011-09-06 20:06:39 +00004473 NullExpr = RHSExpr;
4474 NonPointerExpr = LHSExpr;
Chandler Carrutha8bea4b2011-02-18 23:54:50 +00004475 NullKind =
4476 NullExpr->isNullPointerConstant(Context,
4477 Expr::NPC_ValueDependentIsNotNull);
4478 }
4479
4480 if (NullKind == Expr::NPCK_NotNull)
4481 return false;
4482
4483 if (NullKind == Expr::NPCK_ZeroInteger) {
4484 // In this case, check to make sure that we got here from a "NULL"
4485 // string in the source code.
4486 NullExpr = NullExpr->IgnoreParenImpCasts();
John McCall462c0552011-03-08 07:59:04 +00004487 SourceLocation loc = NullExpr->getExprLoc();
4488 if (!findMacroSpelling(loc, "NULL"))
Chandler Carrutha8bea4b2011-02-18 23:54:50 +00004489 return false;
4490 }
4491
4492 int DiagType = (NullKind == Expr::NPCK_CXX0X_nullptr);
4493 Diag(QuestionLoc, diag::err_typecheck_cond_incompatible_operands_null)
4494 << NonPointerExpr->getType() << DiagType
4495 << NonPointerExpr->getSourceRange();
4496 return true;
4497}
4498
Richard Trieu27ae4cb2011-09-02 01:51:02 +00004499/// \brief Return false if the condition expression is valid, true otherwise.
4500static bool checkCondition(Sema &S, Expr *Cond) {
4501 QualType CondTy = Cond->getType();
4502
4503 // C99 6.5.15p2
4504 if (CondTy->isScalarType()) return false;
4505
4506 // OpenCL: Sec 6.3.i says the condition is allowed to be a vector or scalar.
David Blaikiebbafb8a2012-03-11 07:00:24 +00004507 if (S.getLangOpts().OpenCL && CondTy->isVectorType())
Richard Trieu27ae4cb2011-09-02 01:51:02 +00004508 return false;
4509
4510 // Emit the proper error message.
David Blaikiebbafb8a2012-03-11 07:00:24 +00004511 S.Diag(Cond->getLocStart(), S.getLangOpts().OpenCL ?
Richard Trieu27ae4cb2011-09-02 01:51:02 +00004512 diag::err_typecheck_cond_expect_scalar :
4513 diag::err_typecheck_cond_expect_scalar_or_vector)
4514 << CondTy;
4515 return true;
4516}
4517
4518/// \brief Return false if the two expressions can be converted to a vector,
4519/// true otherwise
4520static bool checkConditionalConvertScalarsToVectors(Sema &S, ExprResult &LHS,
4521 ExprResult &RHS,
4522 QualType CondTy) {
4523 // Both operands should be of scalar type.
4524 if (!LHS.get()->getType()->isScalarType()) {
4525 S.Diag(LHS.get()->getLocStart(), diag::err_typecheck_cond_expect_scalar)
4526 << CondTy;
4527 return true;
4528 }
4529 if (!RHS.get()->getType()->isScalarType()) {
4530 S.Diag(RHS.get()->getLocStart(), diag::err_typecheck_cond_expect_scalar)
4531 << CondTy;
4532 return true;
4533 }
4534
4535 // Implicity convert these scalars to the type of the condition.
4536 LHS = S.ImpCastExprToType(LHS.take(), CondTy, CK_IntegralCast);
4537 RHS = S.ImpCastExprToType(RHS.take(), CondTy, CK_IntegralCast);
4538 return false;
4539}
4540
4541/// \brief Handle when one or both operands are void type.
4542static QualType checkConditionalVoidType(Sema &S, ExprResult &LHS,
4543 ExprResult &RHS) {
4544 Expr *LHSExpr = LHS.get();
4545 Expr *RHSExpr = RHS.get();
4546
4547 if (!LHSExpr->getType()->isVoidType())
4548 S.Diag(RHSExpr->getLocStart(), diag::ext_typecheck_cond_one_void)
4549 << RHSExpr->getSourceRange();
4550 if (!RHSExpr->getType()->isVoidType())
4551 S.Diag(LHSExpr->getLocStart(), diag::ext_typecheck_cond_one_void)
4552 << LHSExpr->getSourceRange();
4553 LHS = S.ImpCastExprToType(LHS.take(), S.Context.VoidTy, CK_ToVoid);
4554 RHS = S.ImpCastExprToType(RHS.take(), S.Context.VoidTy, CK_ToVoid);
4555 return S.Context.VoidTy;
4556}
4557
4558/// \brief Return false if the NullExpr can be promoted to PointerTy,
4559/// true otherwise.
4560static bool checkConditionalNullPointer(Sema &S, ExprResult &NullExpr,
4561 QualType PointerTy) {
4562 if ((!PointerTy->isAnyPointerType() && !PointerTy->isBlockPointerType()) ||
4563 !NullExpr.get()->isNullPointerConstant(S.Context,
4564 Expr::NPC_ValueDependentIsNull))
4565 return true;
4566
4567 NullExpr = S.ImpCastExprToType(NullExpr.take(), PointerTy, CK_NullToPointer);
4568 return false;
4569}
4570
4571/// \brief Checks compatibility between two pointers and return the resulting
4572/// type.
4573static QualType checkConditionalPointerCompatibility(Sema &S, ExprResult &LHS,
4574 ExprResult &RHS,
4575 SourceLocation Loc) {
4576 QualType LHSTy = LHS.get()->getType();
4577 QualType RHSTy = RHS.get()->getType();
4578
4579 if (S.Context.hasSameType(LHSTy, RHSTy)) {
4580 // Two identical pointers types are always compatible.
4581 return LHSTy;
4582 }
4583
4584 QualType lhptee, rhptee;
4585
4586 // Get the pointee types.
John McCall9320b872011-09-09 05:25:32 +00004587 if (const BlockPointerType *LHSBTy = LHSTy->getAs<BlockPointerType>()) {
4588 lhptee = LHSBTy->getPointeeType();
4589 rhptee = RHSTy->castAs<BlockPointerType>()->getPointeeType();
Richard Trieu27ae4cb2011-09-02 01:51:02 +00004590 } else {
John McCall9320b872011-09-09 05:25:32 +00004591 lhptee = LHSTy->castAs<PointerType>()->getPointeeType();
4592 rhptee = RHSTy->castAs<PointerType>()->getPointeeType();
Richard Trieu27ae4cb2011-09-02 01:51:02 +00004593 }
4594
Eli Friedman57a75392012-04-05 22:30:04 +00004595 // C99 6.5.15p6: If both operands are pointers to compatible types or to
4596 // differently qualified versions of compatible types, the result type is
4597 // a pointer to an appropriately qualified version of the composite
4598 // type.
4599
4600 // Only CVR-qualifiers exist in the standard, and the differently-qualified
4601 // clause doesn't make sense for our extensions. E.g. address space 2 should
4602 // be incompatible with address space 3: they may live on different devices or
4603 // anything.
4604 Qualifiers lhQual = lhptee.getQualifiers();
4605 Qualifiers rhQual = rhptee.getQualifiers();
4606
4607 unsigned MergedCVRQual = lhQual.getCVRQualifiers() | rhQual.getCVRQualifiers();
4608 lhQual.removeCVRQualifiers();
4609 rhQual.removeCVRQualifiers();
4610
4611 lhptee = S.Context.getQualifiedType(lhptee.getUnqualifiedType(), lhQual);
4612 rhptee = S.Context.getQualifiedType(rhptee.getUnqualifiedType(), rhQual);
4613
4614 QualType CompositeTy = S.Context.mergeTypes(lhptee, rhptee);
4615
4616 if (CompositeTy.isNull()) {
Richard Trieu27ae4cb2011-09-02 01:51:02 +00004617 S.Diag(Loc, diag::warn_typecheck_cond_incompatible_pointers)
4618 << LHSTy << RHSTy << LHS.get()->getSourceRange()
4619 << RHS.get()->getSourceRange();
4620 // In this situation, we assume void* type. No especially good
4621 // reason, but this is what gcc does, and we do have to pick
4622 // to get a consistent AST.
4623 QualType incompatTy = S.Context.getPointerType(S.Context.VoidTy);
4624 LHS = S.ImpCastExprToType(LHS.take(), incompatTy, CK_BitCast);
4625 RHS = S.ImpCastExprToType(RHS.take(), incompatTy, CK_BitCast);
4626 return incompatTy;
4627 }
4628
4629 // The pointer types are compatible.
Eli Friedman57a75392012-04-05 22:30:04 +00004630 QualType ResultTy = CompositeTy.withCVRQualifiers(MergedCVRQual);
4631 ResultTy = S.Context.getPointerType(ResultTy);
Richard Trieu27ae4cb2011-09-02 01:51:02 +00004632
Eli Friedman57a75392012-04-05 22:30:04 +00004633 LHS = S.ImpCastExprToType(LHS.take(), ResultTy, CK_BitCast);
4634 RHS = S.ImpCastExprToType(RHS.take(), ResultTy, CK_BitCast);
4635 return ResultTy;
Richard Trieu27ae4cb2011-09-02 01:51:02 +00004636}
4637
4638/// \brief Return the resulting type when the operands are both block pointers.
4639static QualType checkConditionalBlockPointerCompatibility(Sema &S,
4640 ExprResult &LHS,
4641 ExprResult &RHS,
4642 SourceLocation Loc) {
4643 QualType LHSTy = LHS.get()->getType();
4644 QualType RHSTy = RHS.get()->getType();
4645
4646 if (!LHSTy->isBlockPointerType() || !RHSTy->isBlockPointerType()) {
4647 if (LHSTy->isVoidPointerType() || RHSTy->isVoidPointerType()) {
4648 QualType destType = S.Context.getPointerType(S.Context.VoidTy);
4649 LHS = S.ImpCastExprToType(LHS.take(), destType, CK_BitCast);
4650 RHS = S.ImpCastExprToType(RHS.take(), destType, CK_BitCast);
4651 return destType;
4652 }
4653 S.Diag(Loc, diag::err_typecheck_cond_incompatible_operands)
4654 << LHSTy << RHSTy << LHS.get()->getSourceRange()
4655 << RHS.get()->getSourceRange();
4656 return QualType();
4657 }
4658
4659 // We have 2 block pointer types.
4660 return checkConditionalPointerCompatibility(S, LHS, RHS, Loc);
4661}
4662
4663/// \brief Return the resulting type when the operands are both pointers.
4664static QualType
4665checkConditionalObjectPointersCompatibility(Sema &S, ExprResult &LHS,
4666 ExprResult &RHS,
4667 SourceLocation Loc) {
4668 // get the pointer types
4669 QualType LHSTy = LHS.get()->getType();
4670 QualType RHSTy = RHS.get()->getType();
4671
4672 // get the "pointed to" types
4673 QualType lhptee = LHSTy->getAs<PointerType>()->getPointeeType();
4674 QualType rhptee = RHSTy->getAs<PointerType>()->getPointeeType();
4675
4676 // ignore qualifiers on void (C99 6.5.15p3, clause 6)
4677 if (lhptee->isVoidType() && rhptee->isIncompleteOrObjectType()) {
4678 // Figure out necessary qualifiers (C99 6.5.15p6)
4679 QualType destPointee
4680 = S.Context.getQualifiedType(lhptee, rhptee.getQualifiers());
4681 QualType destType = S.Context.getPointerType(destPointee);
4682 // Add qualifiers if necessary.
4683 LHS = S.ImpCastExprToType(LHS.take(), destType, CK_NoOp);
4684 // Promote to void*.
4685 RHS = S.ImpCastExprToType(RHS.take(), destType, CK_BitCast);
4686 return destType;
4687 }
4688 if (rhptee->isVoidType() && lhptee->isIncompleteOrObjectType()) {
4689 QualType destPointee
4690 = S.Context.getQualifiedType(rhptee, lhptee.getQualifiers());
4691 QualType destType = S.Context.getPointerType(destPointee);
4692 // Add qualifiers if necessary.
4693 RHS = S.ImpCastExprToType(RHS.take(), destType, CK_NoOp);
4694 // Promote to void*.
4695 LHS = S.ImpCastExprToType(LHS.take(), destType, CK_BitCast);
4696 return destType;
4697 }
4698
4699 return checkConditionalPointerCompatibility(S, LHS, RHS, Loc);
4700}
4701
4702/// \brief Return false if the first expression is not an integer and the second
4703/// expression is not a pointer, true otherwise.
4704static bool checkPointerIntegerMismatch(Sema &S, ExprResult &Int,
4705 Expr* PointerExpr, SourceLocation Loc,
Richard Trieuba63ce62011-09-09 01:45:06 +00004706 bool IsIntFirstExpr) {
Richard Trieu27ae4cb2011-09-02 01:51:02 +00004707 if (!PointerExpr->getType()->isPointerType() ||
4708 !Int.get()->getType()->isIntegerType())
4709 return false;
4710
Richard Trieuba63ce62011-09-09 01:45:06 +00004711 Expr *Expr1 = IsIntFirstExpr ? Int.get() : PointerExpr;
4712 Expr *Expr2 = IsIntFirstExpr ? PointerExpr : Int.get();
Richard Trieu27ae4cb2011-09-02 01:51:02 +00004713
4714 S.Diag(Loc, diag::warn_typecheck_cond_pointer_integer_mismatch)
4715 << Expr1->getType() << Expr2->getType()
4716 << Expr1->getSourceRange() << Expr2->getSourceRange();
4717 Int = S.ImpCastExprToType(Int.take(), PointerExpr->getType(),
4718 CK_IntegralToPointer);
4719 return true;
4720}
4721
Richard Trieud33e46e2011-09-06 20:06:39 +00004722/// Note that LHS is not null here, even if this is the gnu "x ?: y" extension.
4723/// In that case, LHS = cond.
Chris Lattner2c486602009-02-18 04:38:20 +00004724/// C99 6.5.15
Richard Trieucfc491d2011-08-02 04:35:43 +00004725QualType Sema::CheckConditionalOperands(ExprResult &Cond, ExprResult &LHS,
4726 ExprResult &RHS, ExprValueKind &VK,
4727 ExprObjectKind &OK,
Chris Lattner2c486602009-02-18 04:38:20 +00004728 SourceLocation QuestionLoc) {
Douglas Gregor1beec452011-03-12 01:48:56 +00004729
Richard Trieud33e46e2011-09-06 20:06:39 +00004730 ExprResult LHSResult = CheckPlaceholderExpr(LHS.get());
4731 if (!LHSResult.isUsable()) return QualType();
4732 LHS = move(LHSResult);
Douglas Gregor0124e9b2010-11-09 21:07:58 +00004733
Richard Trieud33e46e2011-09-06 20:06:39 +00004734 ExprResult RHSResult = CheckPlaceholderExpr(RHS.get());
4735 if (!RHSResult.isUsable()) return QualType();
4736 RHS = move(RHSResult);
Douglas Gregor0124e9b2010-11-09 21:07:58 +00004737
Sebastian Redl1a99f442009-04-16 17:51:27 +00004738 // C++ is sufficiently different to merit its own checker.
David Blaikiebbafb8a2012-03-11 07:00:24 +00004739 if (getLangOpts().CPlusPlus)
John McCallc07a0c72011-02-17 10:25:35 +00004740 return CXXCheckConditionalOperands(Cond, LHS, RHS, VK, OK, QuestionLoc);
John McCall7decc9e2010-11-18 06:31:45 +00004741
4742 VK = VK_RValue;
John McCall4bc41ae2010-11-18 19:01:18 +00004743 OK = OK_Ordinary;
Sebastian Redl1a99f442009-04-16 17:51:27 +00004744
John Wiegley01296292011-04-08 18:41:53 +00004745 Cond = UsualUnaryConversions(Cond.take());
4746 if (Cond.isInvalid())
4747 return QualType();
4748 LHS = UsualUnaryConversions(LHS.take());
4749 if (LHS.isInvalid())
4750 return QualType();
4751 RHS = UsualUnaryConversions(RHS.take());
4752 if (RHS.isInvalid())
4753 return QualType();
4754
4755 QualType CondTy = Cond.get()->getType();
4756 QualType LHSTy = LHS.get()->getType();
4757 QualType RHSTy = RHS.get()->getType();
Steve Naroff31090012007-07-16 21:54:35 +00004758
Steve Naroffa78fe7e2007-05-16 19:47:19 +00004759 // first, check the condition.
Richard Trieu27ae4cb2011-09-02 01:51:02 +00004760 if (checkCondition(*this, Cond.get()))
4761 return QualType();
Mike Stump4e1f26a2009-02-19 03:04:26 +00004762
Chris Lattnere2949f42008-01-06 22:42:25 +00004763 // Now check the two expressions.
Nate Begeman5ec4b312009-08-10 23:49:36 +00004764 if (LHSTy->isVectorType() || RHSTy->isVectorType())
Eli Friedman1408bc92011-06-23 18:10:35 +00004765 return CheckVectorOperands(LHS, RHS, QuestionLoc, /*isCompAssign*/false);
Douglas Gregor4619e432008-12-05 23:32:09 +00004766
Nate Begemanabb5a732010-09-20 22:41:17 +00004767 // OpenCL: If the condition is a vector, and both operands are scalar,
4768 // attempt to implicity convert them to the vector type to act like the
4769 // built in select.
David Blaikiebbafb8a2012-03-11 07:00:24 +00004770 if (getLangOpts().OpenCL && CondTy->isVectorType())
Richard Trieu27ae4cb2011-09-02 01:51:02 +00004771 if (checkConditionalConvertScalarsToVectors(*this, LHS, RHS, CondTy))
Nate Begemanabb5a732010-09-20 22:41:17 +00004772 return QualType();
Nate Begemanabb5a732010-09-20 22:41:17 +00004773
Chris Lattnere2949f42008-01-06 22:42:25 +00004774 // If both operands have arithmetic type, do the usual arithmetic conversions
4775 // to find a common type: C99 6.5.15p3,5.
Chris Lattner432cff52009-02-18 04:28:32 +00004776 if (LHSTy->isArithmeticType() && RHSTy->isArithmeticType()) {
4777 UsualArithmeticConversions(LHS, RHS);
John Wiegley01296292011-04-08 18:41:53 +00004778 if (LHS.isInvalid() || RHS.isInvalid())
4779 return QualType();
4780 return LHS.get()->getType();
Steve Naroffdbd9e892007-07-17 00:58:39 +00004781 }
Mike Stump4e1f26a2009-02-19 03:04:26 +00004782
Chris Lattnere2949f42008-01-06 22:42:25 +00004783 // If both operands are the same structure or union type, the result is that
4784 // type.
Ted Kremenekc23c7e62009-07-29 21:53:49 +00004785 if (const RecordType *LHSRT = LHSTy->getAs<RecordType>()) { // C99 6.5.15p3
4786 if (const RecordType *RHSRT = RHSTy->getAs<RecordType>())
Chris Lattner2ab40a62007-11-26 01:40:58 +00004787 if (LHSRT->getDecl() == RHSRT->getDecl())
Mike Stump4e1f26a2009-02-19 03:04:26 +00004788 // "If both the operands have structure or union type, the result has
Chris Lattnere2949f42008-01-06 22:42:25 +00004789 // that type." This implies that CV qualifiers are dropped.
Chris Lattner432cff52009-02-18 04:28:32 +00004790 return LHSTy.getUnqualifiedType();
Eli Friedmanba961a92009-03-23 00:24:07 +00004791 // FIXME: Type of conditional expression must be complete in C mode.
Steve Naroffa78fe7e2007-05-16 19:47:19 +00004792 }
Mike Stump4e1f26a2009-02-19 03:04:26 +00004793
Chris Lattnere2949f42008-01-06 22:42:25 +00004794 // C99 6.5.15p5: "If both operands have void type, the result has void type."
Steve Naroffbf1516c2008-05-12 21:44:38 +00004795 // The following || allows only one side to be void (a GCC-ism).
Chris Lattner432cff52009-02-18 04:28:32 +00004796 if (LHSTy->isVoidType() || RHSTy->isVoidType()) {
Richard Trieu27ae4cb2011-09-02 01:51:02 +00004797 return checkConditionalVoidType(*this, LHS, RHS);
Steve Naroffbf1516c2008-05-12 21:44:38 +00004798 }
Richard Trieu27ae4cb2011-09-02 01:51:02 +00004799
Steve Naroff039ad3c2008-01-08 01:11:38 +00004800 // C99 6.5.15p6 - "if one operand is a null pointer constant, the result has
4801 // the type of the other operand."
Richard Trieu27ae4cb2011-09-02 01:51:02 +00004802 if (!checkConditionalNullPointer(*this, RHS, LHSTy)) return LHSTy;
4803 if (!checkConditionalNullPointer(*this, LHS, RHSTy)) return RHSTy;
Kovarththanan Rajaratnamba2c6522010-03-13 10:17:05 +00004804
Fariborz Jahaniana430f712009-12-10 19:47:41 +00004805 // All objective-c pointer type analysis is done here.
4806 QualType compositeType = FindCompositeObjCPointerType(LHS, RHS,
4807 QuestionLoc);
John Wiegley01296292011-04-08 18:41:53 +00004808 if (LHS.isInvalid() || RHS.isInvalid())
4809 return QualType();
Fariborz Jahaniana430f712009-12-10 19:47:41 +00004810 if (!compositeType.isNull())
4811 return compositeType;
Kovarththanan Rajaratnamba2c6522010-03-13 10:17:05 +00004812
4813
Steve Naroff05efa972009-07-01 14:36:47 +00004814 // Handle block pointer types.
Richard Trieu27ae4cb2011-09-02 01:51:02 +00004815 if (LHSTy->isBlockPointerType() || RHSTy->isBlockPointerType())
4816 return checkConditionalBlockPointerCompatibility(*this, LHS, RHS,
4817 QuestionLoc);
Kovarththanan Rajaratnamba2c6522010-03-13 10:17:05 +00004818
Steve Naroff05efa972009-07-01 14:36:47 +00004819 // Check constraints for C object pointers types (C99 6.5.15p3,6).
Richard Trieu27ae4cb2011-09-02 01:51:02 +00004820 if (LHSTy->isPointerType() && RHSTy->isPointerType())
4821 return checkConditionalObjectPointersCompatibility(*this, LHS, RHS,
4822 QuestionLoc);
Mike Stump11289f42009-09-09 15:08:12 +00004823
John McCalle84af4e2010-11-13 01:35:44 +00004824 // GCC compatibility: soften pointer/integer mismatch. Note that
4825 // null pointers have been filtered out by this point.
Richard Trieu27ae4cb2011-09-02 01:51:02 +00004826 if (checkPointerIntegerMismatch(*this, LHS, RHS.get(), QuestionLoc,
4827 /*isIntFirstExpr=*/true))
Steve Naroff05efa972009-07-01 14:36:47 +00004828 return RHSTy;
Richard Trieu27ae4cb2011-09-02 01:51:02 +00004829 if (checkPointerIntegerMismatch(*this, RHS, LHS.get(), QuestionLoc,
4830 /*isIntFirstExpr=*/false))
Steve Naroff05efa972009-07-01 14:36:47 +00004831 return LHSTy;
Daniel Dunbar484603b2008-09-11 23:12:46 +00004832
Chandler Carrutha8bea4b2011-02-18 23:54:50 +00004833 // Emit a better diagnostic if one of the expressions is a null pointer
4834 // constant and the other is not a pointer type. In this case, the user most
4835 // likely forgot to take the address of the other expression.
John Wiegley01296292011-04-08 18:41:53 +00004836 if (DiagnoseConditionalForNull(LHS.get(), RHS.get(), QuestionLoc))
Chandler Carrutha8bea4b2011-02-18 23:54:50 +00004837 return QualType();
4838
Chris Lattnere2949f42008-01-06 22:42:25 +00004839 // Otherwise, the operands are not compatible.
Chris Lattner432cff52009-02-18 04:28:32 +00004840 Diag(QuestionLoc, diag::err_typecheck_cond_incompatible_operands)
Richard Trieucfc491d2011-08-02 04:35:43 +00004841 << LHSTy << RHSTy << LHS.get()->getSourceRange()
4842 << RHS.get()->getSourceRange();
Steve Naroffa78fe7e2007-05-16 19:47:19 +00004843 return QualType();
Steve Narofff8a28c52007-05-15 20:29:32 +00004844}
4845
Fariborz Jahaniana430f712009-12-10 19:47:41 +00004846/// FindCompositeObjCPointerType - Helper method to find composite type of
4847/// two objective-c pointer types of the two input expressions.
John Wiegley01296292011-04-08 18:41:53 +00004848QualType Sema::FindCompositeObjCPointerType(ExprResult &LHS, ExprResult &RHS,
Richard Trieucfc491d2011-08-02 04:35:43 +00004849 SourceLocation QuestionLoc) {
John Wiegley01296292011-04-08 18:41:53 +00004850 QualType LHSTy = LHS.get()->getType();
4851 QualType RHSTy = RHS.get()->getType();
Kovarththanan Rajaratnamba2c6522010-03-13 10:17:05 +00004852
Fariborz Jahaniana430f712009-12-10 19:47:41 +00004853 // Handle things like Class and struct objc_class*. Here we case the result
4854 // to the pseudo-builtin, because that will be implicitly cast back to the
4855 // redefinition type if an attempt is made to access its fields.
4856 if (LHSTy->isObjCClassType() &&
Douglas Gregor97673472011-08-11 20:58:55 +00004857 (Context.hasSameType(RHSTy, Context.getObjCClassRedefinitionType()))) {
John McCall9320b872011-09-09 05:25:32 +00004858 RHS = ImpCastExprToType(RHS.take(), LHSTy, CK_CPointerToObjCPointerCast);
Fariborz Jahaniana430f712009-12-10 19:47:41 +00004859 return LHSTy;
4860 }
4861 if (RHSTy->isObjCClassType() &&
Douglas Gregor97673472011-08-11 20:58:55 +00004862 (Context.hasSameType(LHSTy, Context.getObjCClassRedefinitionType()))) {
John McCall9320b872011-09-09 05:25:32 +00004863 LHS = ImpCastExprToType(LHS.take(), RHSTy, CK_CPointerToObjCPointerCast);
Fariborz Jahaniana430f712009-12-10 19:47:41 +00004864 return RHSTy;
4865 }
4866 // And the same for struct objc_object* / id
4867 if (LHSTy->isObjCIdType() &&
Douglas Gregor97673472011-08-11 20:58:55 +00004868 (Context.hasSameType(RHSTy, Context.getObjCIdRedefinitionType()))) {
John McCall9320b872011-09-09 05:25:32 +00004869 RHS = ImpCastExprToType(RHS.take(), LHSTy, CK_CPointerToObjCPointerCast);
Fariborz Jahaniana430f712009-12-10 19:47:41 +00004870 return LHSTy;
4871 }
4872 if (RHSTy->isObjCIdType() &&
Douglas Gregor97673472011-08-11 20:58:55 +00004873 (Context.hasSameType(LHSTy, Context.getObjCIdRedefinitionType()))) {
John McCall9320b872011-09-09 05:25:32 +00004874 LHS = ImpCastExprToType(LHS.take(), RHSTy, CK_CPointerToObjCPointerCast);
Fariborz Jahaniana430f712009-12-10 19:47:41 +00004875 return RHSTy;
4876 }
4877 // And the same for struct objc_selector* / SEL
4878 if (Context.isObjCSelType(LHSTy) &&
Douglas Gregor97673472011-08-11 20:58:55 +00004879 (Context.hasSameType(RHSTy, Context.getObjCSelRedefinitionType()))) {
John Wiegley01296292011-04-08 18:41:53 +00004880 RHS = ImpCastExprToType(RHS.take(), LHSTy, CK_BitCast);
Fariborz Jahaniana430f712009-12-10 19:47:41 +00004881 return LHSTy;
4882 }
4883 if (Context.isObjCSelType(RHSTy) &&
Douglas Gregor97673472011-08-11 20:58:55 +00004884 (Context.hasSameType(LHSTy, Context.getObjCSelRedefinitionType()))) {
John Wiegley01296292011-04-08 18:41:53 +00004885 LHS = ImpCastExprToType(LHS.take(), RHSTy, CK_BitCast);
Fariborz Jahaniana430f712009-12-10 19:47:41 +00004886 return RHSTy;
4887 }
4888 // Check constraints for Objective-C object pointers types.
4889 if (LHSTy->isObjCObjectPointerType() && RHSTy->isObjCObjectPointerType()) {
Kovarththanan Rajaratnamba2c6522010-03-13 10:17:05 +00004890
Fariborz Jahaniana430f712009-12-10 19:47:41 +00004891 if (Context.getCanonicalType(LHSTy) == Context.getCanonicalType(RHSTy)) {
4892 // Two identical object pointer types are always compatible.
4893 return LHSTy;
4894 }
John McCall9320b872011-09-09 05:25:32 +00004895 const ObjCObjectPointerType *LHSOPT = LHSTy->castAs<ObjCObjectPointerType>();
4896 const ObjCObjectPointerType *RHSOPT = RHSTy->castAs<ObjCObjectPointerType>();
Fariborz Jahaniana430f712009-12-10 19:47:41 +00004897 QualType compositeType = LHSTy;
Kovarththanan Rajaratnamba2c6522010-03-13 10:17:05 +00004898
Fariborz Jahaniana430f712009-12-10 19:47:41 +00004899 // If both operands are interfaces and either operand can be
4900 // assigned to the other, use that type as the composite
4901 // type. This allows
4902 // xxx ? (A*) a : (B*) b
4903 // where B is a subclass of A.
4904 //
4905 // Additionally, as for assignment, if either type is 'id'
4906 // allow silent coercion. Finally, if the types are
4907 // incompatible then make sure to use 'id' as the composite
4908 // type so the result is acceptable for sending messages to.
Kovarththanan Rajaratnamba2c6522010-03-13 10:17:05 +00004909
Fariborz Jahaniana430f712009-12-10 19:47:41 +00004910 // FIXME: Consider unifying with 'areComparableObjCPointerTypes'.
4911 // It could return the composite type.
4912 if (Context.canAssignObjCInterfaces(LHSOPT, RHSOPT)) {
4913 compositeType = RHSOPT->isObjCBuiltinType() ? RHSTy : LHSTy;
4914 } else if (Context.canAssignObjCInterfaces(RHSOPT, LHSOPT)) {
4915 compositeType = LHSOPT->isObjCBuiltinType() ? LHSTy : RHSTy;
4916 } else if ((LHSTy->isObjCQualifiedIdType() ||
4917 RHSTy->isObjCQualifiedIdType()) &&
4918 Context.ObjCQualifiedIdTypesAreCompatible(LHSTy, RHSTy, true)) {
4919 // Need to handle "id<xx>" explicitly.
4920 // GCC allows qualified id and any Objective-C type to devolve to
4921 // id. Currently localizing to here until clear this should be
4922 // part of ObjCQualifiedIdTypesAreCompatible.
4923 compositeType = Context.getObjCIdType();
4924 } else if (LHSTy->isObjCIdType() || RHSTy->isObjCIdType()) {
4925 compositeType = Context.getObjCIdType();
Kovarththanan Rajaratnamba2c6522010-03-13 10:17:05 +00004926 } else if (!(compositeType =
Fariborz Jahaniana430f712009-12-10 19:47:41 +00004927 Context.areCommonBaseCompatible(LHSOPT, RHSOPT)).isNull())
4928 ;
4929 else {
4930 Diag(QuestionLoc, diag::ext_typecheck_cond_incompatible_operands)
4931 << LHSTy << RHSTy
John Wiegley01296292011-04-08 18:41:53 +00004932 << LHS.get()->getSourceRange() << RHS.get()->getSourceRange();
Fariborz Jahaniana430f712009-12-10 19:47:41 +00004933 QualType incompatTy = Context.getObjCIdType();
John Wiegley01296292011-04-08 18:41:53 +00004934 LHS = ImpCastExprToType(LHS.take(), incompatTy, CK_BitCast);
4935 RHS = ImpCastExprToType(RHS.take(), incompatTy, CK_BitCast);
Fariborz Jahaniana430f712009-12-10 19:47:41 +00004936 return incompatTy;
4937 }
4938 // The object pointer types are compatible.
John Wiegley01296292011-04-08 18:41:53 +00004939 LHS = ImpCastExprToType(LHS.take(), compositeType, CK_BitCast);
4940 RHS = ImpCastExprToType(RHS.take(), compositeType, CK_BitCast);
Fariborz Jahaniana430f712009-12-10 19:47:41 +00004941 return compositeType;
4942 }
4943 // Check Objective-C object pointer types and 'void *'
4944 if (LHSTy->isVoidPointerType() && RHSTy->isObjCObjectPointerType()) {
David Blaikiebbafb8a2012-03-11 07:00:24 +00004945 if (getLangOpts().ObjCAutoRefCount) {
Eli Friedman8a78a582012-02-25 00:23:44 +00004946 // ARC forbids the implicit conversion of object pointers to 'void *',
4947 // so these types are not compatible.
4948 Diag(QuestionLoc, diag::err_cond_voidptr_arc) << LHSTy << RHSTy
4949 << LHS.get()->getSourceRange() << RHS.get()->getSourceRange();
4950 LHS = RHS = true;
4951 return QualType();
4952 }
Fariborz Jahaniana430f712009-12-10 19:47:41 +00004953 QualType lhptee = LHSTy->getAs<PointerType>()->getPointeeType();
4954 QualType rhptee = RHSTy->getAs<ObjCObjectPointerType>()->getPointeeType();
4955 QualType destPointee
4956 = Context.getQualifiedType(lhptee, rhptee.getQualifiers());
4957 QualType destType = Context.getPointerType(destPointee);
4958 // Add qualifiers if necessary.
John Wiegley01296292011-04-08 18:41:53 +00004959 LHS = ImpCastExprToType(LHS.take(), destType, CK_NoOp);
Fariborz Jahaniana430f712009-12-10 19:47:41 +00004960 // Promote to void*.
John Wiegley01296292011-04-08 18:41:53 +00004961 RHS = ImpCastExprToType(RHS.take(), destType, CK_BitCast);
Fariborz Jahaniana430f712009-12-10 19:47:41 +00004962 return destType;
4963 }
4964 if (LHSTy->isObjCObjectPointerType() && RHSTy->isVoidPointerType()) {
David Blaikiebbafb8a2012-03-11 07:00:24 +00004965 if (getLangOpts().ObjCAutoRefCount) {
Eli Friedman8a78a582012-02-25 00:23:44 +00004966 // ARC forbids the implicit conversion of object pointers to 'void *',
4967 // so these types are not compatible.
4968 Diag(QuestionLoc, diag::err_cond_voidptr_arc) << LHSTy << RHSTy
4969 << LHS.get()->getSourceRange() << RHS.get()->getSourceRange();
4970 LHS = RHS = true;
4971 return QualType();
4972 }
Fariborz Jahaniana430f712009-12-10 19:47:41 +00004973 QualType lhptee = LHSTy->getAs<ObjCObjectPointerType>()->getPointeeType();
4974 QualType rhptee = RHSTy->getAs<PointerType>()->getPointeeType();
4975 QualType destPointee
4976 = Context.getQualifiedType(rhptee, lhptee.getQualifiers());
4977 QualType destType = Context.getPointerType(destPointee);
4978 // Add qualifiers if necessary.
John Wiegley01296292011-04-08 18:41:53 +00004979 RHS = ImpCastExprToType(RHS.take(), destType, CK_NoOp);
Fariborz Jahaniana430f712009-12-10 19:47:41 +00004980 // Promote to void*.
John Wiegley01296292011-04-08 18:41:53 +00004981 LHS = ImpCastExprToType(LHS.take(), destType, CK_BitCast);
Fariborz Jahaniana430f712009-12-10 19:47:41 +00004982 return destType;
4983 }
4984 return QualType();
4985}
4986
Chandler Carruthb00e8c02011-06-16 01:05:14 +00004987/// SuggestParentheses - Emit a note with a fixit hint that wraps
Hans Wennborgcf9bac42011-06-03 18:00:36 +00004988/// ParenRange in parentheses.
4989static void SuggestParentheses(Sema &Self, SourceLocation Loc,
Chandler Carruthb00e8c02011-06-16 01:05:14 +00004990 const PartialDiagnostic &Note,
4991 SourceRange ParenRange) {
4992 SourceLocation EndLoc = Self.PP.getLocForEndOfToken(ParenRange.getEnd());
4993 if (ParenRange.getBegin().isFileID() && ParenRange.getEnd().isFileID() &&
4994 EndLoc.isValid()) {
4995 Self.Diag(Loc, Note)
4996 << FixItHint::CreateInsertion(ParenRange.getBegin(), "(")
4997 << FixItHint::CreateInsertion(EndLoc, ")");
4998 } else {
4999 // We can't display the parentheses, so just show the bare note.
5000 Self.Diag(Loc, Note) << ParenRange;
Hans Wennborgcf9bac42011-06-03 18:00:36 +00005001 }
Hans Wennborgcf9bac42011-06-03 18:00:36 +00005002}
5003
5004static bool IsArithmeticOp(BinaryOperatorKind Opc) {
5005 return Opc >= BO_Mul && Opc <= BO_Shr;
5006}
5007
Hans Wennborgde2e67e2011-06-09 17:06:51 +00005008/// IsArithmeticBinaryExpr - Returns true if E is an arithmetic binary
5009/// expression, either using a built-in or overloaded operator,
Richard Trieud33e46e2011-09-06 20:06:39 +00005010/// and sets *OpCode to the opcode and *RHSExprs to the right-hand side
5011/// expression.
Hans Wennborgde2e67e2011-06-09 17:06:51 +00005012static bool IsArithmeticBinaryExpr(Expr *E, BinaryOperatorKind *Opcode,
Richard Trieud33e46e2011-09-06 20:06:39 +00005013 Expr **RHSExprs) {
Hans Wennborgbe207b32011-09-12 12:07:30 +00005014 // Don't strip parenthesis: we should not warn if E is in parenthesis.
5015 E = E->IgnoreImpCasts();
Hans Wennborgde2e67e2011-06-09 17:06:51 +00005016 E = E->IgnoreConversionOperator();
Hans Wennborgbe207b32011-09-12 12:07:30 +00005017 E = E->IgnoreImpCasts();
Hans Wennborgde2e67e2011-06-09 17:06:51 +00005018
5019 // Built-in binary operator.
5020 if (BinaryOperator *OP = dyn_cast<BinaryOperator>(E)) {
5021 if (IsArithmeticOp(OP->getOpcode())) {
5022 *Opcode = OP->getOpcode();
Richard Trieud33e46e2011-09-06 20:06:39 +00005023 *RHSExprs = OP->getRHS();
Hans Wennborgde2e67e2011-06-09 17:06:51 +00005024 return true;
5025 }
5026 }
5027
5028 // Overloaded operator.
5029 if (CXXOperatorCallExpr *Call = dyn_cast<CXXOperatorCallExpr>(E)) {
5030 if (Call->getNumArgs() != 2)
5031 return false;
5032
5033 // Make sure this is really a binary operator that is safe to pass into
5034 // BinaryOperator::getOverloadedOpcode(), e.g. it's not a subscript op.
5035 OverloadedOperatorKind OO = Call->getOperator();
5036 if (OO < OO_Plus || OO > OO_Arrow)
5037 return false;
5038
5039 BinaryOperatorKind OpKind = BinaryOperator::getOverloadedOpcode(OO);
5040 if (IsArithmeticOp(OpKind)) {
5041 *Opcode = OpKind;
Richard Trieud33e46e2011-09-06 20:06:39 +00005042 *RHSExprs = Call->getArg(1);
Hans Wennborgde2e67e2011-06-09 17:06:51 +00005043 return true;
5044 }
5045 }
5046
5047 return false;
5048}
5049
Hans Wennborgcf9bac42011-06-03 18:00:36 +00005050static bool IsLogicOp(BinaryOperatorKind Opc) {
5051 return (Opc >= BO_LT && Opc <= BO_NE) || (Opc >= BO_LAnd && Opc <= BO_LOr);
5052}
5053
Hans Wennborgde2e67e2011-06-09 17:06:51 +00005054/// ExprLooksBoolean - Returns true if E looks boolean, i.e. it has boolean type
5055/// or is a logical expression such as (x==y) which has int type, but is
5056/// commonly interpreted as boolean.
5057static bool ExprLooksBoolean(Expr *E) {
5058 E = E->IgnoreParenImpCasts();
5059
5060 if (E->getType()->isBooleanType())
5061 return true;
5062 if (BinaryOperator *OP = dyn_cast<BinaryOperator>(E))
5063 return IsLogicOp(OP->getOpcode());
5064 if (UnaryOperator *OP = dyn_cast<UnaryOperator>(E))
5065 return OP->getOpcode() == UO_LNot;
5066
5067 return false;
5068}
5069
Hans Wennborgcf9bac42011-06-03 18:00:36 +00005070/// DiagnoseConditionalPrecedence - Emit a warning when a conditional operator
5071/// and binary operator are mixed in a way that suggests the programmer assumed
5072/// the conditional operator has higher precedence, for example:
5073/// "int x = a + someBinaryCondition ? 1 : 2".
5074static void DiagnoseConditionalPrecedence(Sema &Self,
5075 SourceLocation OpLoc,
Chandler Carruth08dc2ba2011-06-16 01:05:08 +00005076 Expr *Condition,
Richard Trieud33e46e2011-09-06 20:06:39 +00005077 Expr *LHSExpr,
5078 Expr *RHSExpr) {
Hans Wennborgde2e67e2011-06-09 17:06:51 +00005079 BinaryOperatorKind CondOpcode;
5080 Expr *CondRHS;
Hans Wennborgcf9bac42011-06-03 18:00:36 +00005081
Chandler Carruth08dc2ba2011-06-16 01:05:08 +00005082 if (!IsArithmeticBinaryExpr(Condition, &CondOpcode, &CondRHS))
Hans Wennborgde2e67e2011-06-09 17:06:51 +00005083 return;
5084 if (!ExprLooksBoolean(CondRHS))
5085 return;
Hans Wennborgcf9bac42011-06-03 18:00:36 +00005086
Hans Wennborgde2e67e2011-06-09 17:06:51 +00005087 // The condition is an arithmetic binary expression, with a right-
5088 // hand side that looks boolean, so warn.
Hans Wennborgcf9bac42011-06-03 18:00:36 +00005089
Chandler Carruthb00e8c02011-06-16 01:05:14 +00005090 Self.Diag(OpLoc, diag::warn_precedence_conditional)
Chandler Carruth08dc2ba2011-06-16 01:05:08 +00005091 << Condition->getSourceRange()
Hans Wennborgde2e67e2011-06-09 17:06:51 +00005092 << BinaryOperator::getOpcodeStr(CondOpcode);
Hans Wennborgcf9bac42011-06-03 18:00:36 +00005093
Chandler Carruthb00e8c02011-06-16 01:05:14 +00005094 SuggestParentheses(Self, OpLoc,
5095 Self.PDiag(diag::note_precedence_conditional_silence)
5096 << BinaryOperator::getOpcodeStr(CondOpcode),
5097 SourceRange(Condition->getLocStart(), Condition->getLocEnd()));
Chandler Carruthf51c5a52011-06-21 23:04:18 +00005098
5099 SuggestParentheses(Self, OpLoc,
5100 Self.PDiag(diag::note_precedence_conditional_first),
Richard Trieud33e46e2011-09-06 20:06:39 +00005101 SourceRange(CondRHS->getLocStart(), RHSExpr->getLocEnd()));
Hans Wennborgcf9bac42011-06-03 18:00:36 +00005102}
5103
Steve Naroff83895f72007-09-16 03:34:24 +00005104/// ActOnConditionalOp - Parse a ?: operation. Note that 'LHS' may be null
Chris Lattnere168f762006-11-10 05:29:30 +00005105/// in the case of a the GNU conditional expr extension.
John McCalldadc5752010-08-24 06:29:42 +00005106ExprResult Sema::ActOnConditionalOp(SourceLocation QuestionLoc,
John McCallc07a0c72011-02-17 10:25:35 +00005107 SourceLocation ColonLoc,
5108 Expr *CondExpr, Expr *LHSExpr,
5109 Expr *RHSExpr) {
Chris Lattner2ab40a62007-11-26 01:40:58 +00005110 // If this is the gnu "x ?: y" extension, analyze the types as though the LHS
5111 // was the condition.
John McCallc07a0c72011-02-17 10:25:35 +00005112 OpaqueValueExpr *opaqueValue = 0;
5113 Expr *commonExpr = 0;
5114 if (LHSExpr == 0) {
5115 commonExpr = CondExpr;
5116
5117 // We usually want to apply unary conversions *before* saving, except
5118 // in the special case of a C++ l-value conditional.
David Blaikiebbafb8a2012-03-11 07:00:24 +00005119 if (!(getLangOpts().CPlusPlus
John McCallc07a0c72011-02-17 10:25:35 +00005120 && !commonExpr->isTypeDependent()
5121 && commonExpr->getValueKind() == RHSExpr->getValueKind()
5122 && commonExpr->isGLValue()
5123 && commonExpr->isOrdinaryOrBitFieldObject()
5124 && RHSExpr->isOrdinaryOrBitFieldObject()
5125 && Context.hasSameType(commonExpr->getType(), RHSExpr->getType()))) {
John Wiegley01296292011-04-08 18:41:53 +00005126 ExprResult commonRes = UsualUnaryConversions(commonExpr);
5127 if (commonRes.isInvalid())
5128 return ExprError();
5129 commonExpr = commonRes.take();
John McCallc07a0c72011-02-17 10:25:35 +00005130 }
5131
5132 opaqueValue = new (Context) OpaqueValueExpr(commonExpr->getExprLoc(),
5133 commonExpr->getType(),
5134 commonExpr->getValueKind(),
Douglas Gregor2d5aea02012-02-23 22:17:26 +00005135 commonExpr->getObjectKind(),
5136 commonExpr);
John McCallc07a0c72011-02-17 10:25:35 +00005137 LHSExpr = CondExpr = opaqueValue;
Fariborz Jahanianc6bf0bd2010-08-31 18:02:20 +00005138 }
Sebastian Redlb5d49352009-01-19 22:31:54 +00005139
John McCall7decc9e2010-11-18 06:31:45 +00005140 ExprValueKind VK = VK_RValue;
John McCall4bc41ae2010-11-18 19:01:18 +00005141 ExprObjectKind OK = OK_Ordinary;
John Wiegley01296292011-04-08 18:41:53 +00005142 ExprResult Cond = Owned(CondExpr), LHS = Owned(LHSExpr), RHS = Owned(RHSExpr);
5143 QualType result = CheckConditionalOperands(Cond, LHS, RHS,
John McCallc07a0c72011-02-17 10:25:35 +00005144 VK, OK, QuestionLoc);
John Wiegley01296292011-04-08 18:41:53 +00005145 if (result.isNull() || Cond.isInvalid() || LHS.isInvalid() ||
5146 RHS.isInvalid())
Sebastian Redlb5d49352009-01-19 22:31:54 +00005147 return ExprError();
5148
Hans Wennborgcf9bac42011-06-03 18:00:36 +00005149 DiagnoseConditionalPrecedence(*this, QuestionLoc, Cond.get(), LHS.get(),
5150 RHS.get());
5151
John McCallc07a0c72011-02-17 10:25:35 +00005152 if (!commonExpr)
John Wiegley01296292011-04-08 18:41:53 +00005153 return Owned(new (Context) ConditionalOperator(Cond.take(), QuestionLoc,
5154 LHS.take(), ColonLoc,
5155 RHS.take(), result, VK, OK));
John McCallc07a0c72011-02-17 10:25:35 +00005156
5157 return Owned(new (Context)
John Wiegley01296292011-04-08 18:41:53 +00005158 BinaryConditionalOperator(commonExpr, opaqueValue, Cond.take(), LHS.take(),
Richard Trieucfc491d2011-08-02 04:35:43 +00005159 RHS.take(), QuestionLoc, ColonLoc, result, VK,
5160 OK));
Chris Lattnere168f762006-11-10 05:29:30 +00005161}
5162
John McCallaba90822011-01-31 23:13:11 +00005163// checkPointerTypesForAssignment - This is a very tricky routine (despite
Mike Stump4e1f26a2009-02-19 03:04:26 +00005164// being closely modeled after the C99 spec:-). The odd characteristic of this
Steve Naroff3f597292007-05-11 22:18:03 +00005165// routine is it effectively iqnores the qualifiers on the top level pointee.
5166// This circumvents the usual type rules specified in 6.2.7p1 & 6.7.5.[1-3].
5167// FIXME: add a couple examples in this comment.
John McCallaba90822011-01-31 23:13:11 +00005168static Sema::AssignConvertType
Richard Trieua871b972011-09-06 20:21:22 +00005169checkPointerTypesForAssignment(Sema &S, QualType LHSType, QualType RHSType) {
5170 assert(LHSType.isCanonical() && "LHS not canonicalized!");
5171 assert(RHSType.isCanonical() && "RHS not canonicalized!");
Mike Stump4e1f26a2009-02-19 03:04:26 +00005172
Steve Naroff1f4d7272007-05-11 04:00:31 +00005173 // get the "pointed to" type (ignoring qualifiers at the top level)
John McCall4fff8f62011-02-01 00:10:29 +00005174 const Type *lhptee, *rhptee;
5175 Qualifiers lhq, rhq;
Richard Trieua871b972011-09-06 20:21:22 +00005176 llvm::tie(lhptee, lhq) = cast<PointerType>(LHSType)->getPointeeType().split();
5177 llvm::tie(rhptee, rhq) = cast<PointerType>(RHSType)->getPointeeType().split();
Mike Stump4e1f26a2009-02-19 03:04:26 +00005178
John McCallaba90822011-01-31 23:13:11 +00005179 Sema::AssignConvertType ConvTy = Sema::Compatible;
Mike Stump4e1f26a2009-02-19 03:04:26 +00005180
5181 // C99 6.5.16.1p1: This following citation is common to constraints
5182 // 3 & 4 (below). ...and the type *pointed to* by the left has all the
5183 // qualifiers of the type *pointed to* by the right;
John McCall4fff8f62011-02-01 00:10:29 +00005184 Qualifiers lq;
5185
John McCall31168b02011-06-15 23:02:42 +00005186 // As a special case, 'non-__weak A *' -> 'non-__weak const *' is okay.
5187 if (lhq.getObjCLifetime() != rhq.getObjCLifetime() &&
5188 lhq.compatiblyIncludesObjCLifetime(rhq)) {
5189 // Ignore lifetime for further calculation.
5190 lhq.removeObjCLifetime();
5191 rhq.removeObjCLifetime();
5192 }
5193
John McCall4fff8f62011-02-01 00:10:29 +00005194 if (!lhq.compatiblyIncludes(rhq)) {
5195 // Treat address-space mismatches as fatal. TODO: address subspaces
5196 if (lhq.getAddressSpace() != rhq.getAddressSpace())
5197 ConvTy = Sema::IncompatiblePointerDiscardsQualifiers;
5198
John McCall31168b02011-06-15 23:02:42 +00005199 // It's okay to add or remove GC or lifetime qualifiers when converting to
John McCall78535952011-03-26 02:56:45 +00005200 // and from void*.
John McCall18ce25e2012-02-08 00:46:36 +00005201 else if (lhq.withoutObjCGCAttr().withoutObjCLifetime()
John McCall31168b02011-06-15 23:02:42 +00005202 .compatiblyIncludes(
John McCall18ce25e2012-02-08 00:46:36 +00005203 rhq.withoutObjCGCAttr().withoutObjCLifetime())
John McCall78535952011-03-26 02:56:45 +00005204 && (lhptee->isVoidType() || rhptee->isVoidType()))
5205 ; // keep old
5206
John McCall31168b02011-06-15 23:02:42 +00005207 // Treat lifetime mismatches as fatal.
5208 else if (lhq.getObjCLifetime() != rhq.getObjCLifetime())
5209 ConvTy = Sema::IncompatiblePointerDiscardsQualifiers;
5210
John McCall4fff8f62011-02-01 00:10:29 +00005211 // For GCC compatibility, other qualifier mismatches are treated
5212 // as still compatible in C.
5213 else ConvTy = Sema::CompatiblePointerDiscardsQualifiers;
5214 }
Steve Naroff3f597292007-05-11 22:18:03 +00005215
Mike Stump4e1f26a2009-02-19 03:04:26 +00005216 // C99 6.5.16.1p1 (constraint 4): If one operand is a pointer to an object or
5217 // incomplete type and the other is a pointer to a qualified or unqualified
Steve Naroff3f597292007-05-11 22:18:03 +00005218 // version of void...
Chris Lattner0a788432008-01-03 22:56:36 +00005219 if (lhptee->isVoidType()) {
Chris Lattnerb3a176d2008-04-02 06:59:01 +00005220 if (rhptee->isIncompleteOrObjectType())
Chris Lattner9bad62c2008-01-04 18:04:52 +00005221 return ConvTy;
Mike Stump4e1f26a2009-02-19 03:04:26 +00005222
Chris Lattner0a788432008-01-03 22:56:36 +00005223 // As an extension, we allow cast to/from void* to function pointer.
Chris Lattnerb3a176d2008-04-02 06:59:01 +00005224 assert(rhptee->isFunctionType());
John McCallaba90822011-01-31 23:13:11 +00005225 return Sema::FunctionVoidPointer;
Chris Lattner0a788432008-01-03 22:56:36 +00005226 }
Mike Stump4e1f26a2009-02-19 03:04:26 +00005227
Chris Lattner0a788432008-01-03 22:56:36 +00005228 if (rhptee->isVoidType()) {
Chris Lattnerb3a176d2008-04-02 06:59:01 +00005229 if (lhptee->isIncompleteOrObjectType())
Chris Lattner9bad62c2008-01-04 18:04:52 +00005230 return ConvTy;
Chris Lattner0a788432008-01-03 22:56:36 +00005231
5232 // As an extension, we allow cast to/from void* to function pointer.
Chris Lattnerb3a176d2008-04-02 06:59:01 +00005233 assert(lhptee->isFunctionType());
John McCallaba90822011-01-31 23:13:11 +00005234 return Sema::FunctionVoidPointer;
Chris Lattner0a788432008-01-03 22:56:36 +00005235 }
John McCall4fff8f62011-02-01 00:10:29 +00005236
Mike Stump4e1f26a2009-02-19 03:04:26 +00005237 // C99 6.5.16.1p1 (constraint 3): both operands are pointers to qualified or
Steve Naroff3f597292007-05-11 22:18:03 +00005238 // unqualified versions of compatible types, ...
John McCall4fff8f62011-02-01 00:10:29 +00005239 QualType ltrans = QualType(lhptee, 0), rtrans = QualType(rhptee, 0);
5240 if (!S.Context.typesAreCompatible(ltrans, rtrans)) {
Eli Friedman80160bd2009-03-22 23:59:44 +00005241 // Check if the pointee types are compatible ignoring the sign.
5242 // We explicitly check for char so that we catch "char" vs
5243 // "unsigned char" on systems where "char" is unsigned.
Chris Lattnerec3a1562009-10-17 20:33:28 +00005244 if (lhptee->isCharType())
John McCall4fff8f62011-02-01 00:10:29 +00005245 ltrans = S.Context.UnsignedCharTy;
Douglas Gregor5cc2c8b2010-07-23 15:58:24 +00005246 else if (lhptee->hasSignedIntegerRepresentation())
John McCall4fff8f62011-02-01 00:10:29 +00005247 ltrans = S.Context.getCorrespondingUnsignedType(ltrans);
Kovarththanan Rajaratnamba2c6522010-03-13 10:17:05 +00005248
Chris Lattnerec3a1562009-10-17 20:33:28 +00005249 if (rhptee->isCharType())
John McCall4fff8f62011-02-01 00:10:29 +00005250 rtrans = S.Context.UnsignedCharTy;
Douglas Gregor5cc2c8b2010-07-23 15:58:24 +00005251 else if (rhptee->hasSignedIntegerRepresentation())
John McCall4fff8f62011-02-01 00:10:29 +00005252 rtrans = S.Context.getCorrespondingUnsignedType(rtrans);
Chris Lattnerec3a1562009-10-17 20:33:28 +00005253
John McCall4fff8f62011-02-01 00:10:29 +00005254 if (ltrans == rtrans) {
Eli Friedman80160bd2009-03-22 23:59:44 +00005255 // Types are compatible ignoring the sign. Qualifier incompatibility
5256 // takes priority over sign incompatibility because the sign
5257 // warning can be disabled.
John McCallaba90822011-01-31 23:13:11 +00005258 if (ConvTy != Sema::Compatible)
Eli Friedman80160bd2009-03-22 23:59:44 +00005259 return ConvTy;
John McCall4fff8f62011-02-01 00:10:29 +00005260
John McCallaba90822011-01-31 23:13:11 +00005261 return Sema::IncompatiblePointerSign;
Eli Friedman80160bd2009-03-22 23:59:44 +00005262 }
Kovarththanan Rajaratnamba2c6522010-03-13 10:17:05 +00005263
Fariborz Jahaniand7aa9d82009-11-07 20:20:40 +00005264 // If we are a multi-level pointer, it's possible that our issue is simply
5265 // one of qualification - e.g. char ** -> const char ** is not allowed. If
5266 // the eventual target type is the same and the pointers have the same
5267 // level of indirection, this must be the issue.
John McCallaba90822011-01-31 23:13:11 +00005268 if (isa<PointerType>(lhptee) && isa<PointerType>(rhptee)) {
Fariborz Jahaniand7aa9d82009-11-07 20:20:40 +00005269 do {
John McCall4fff8f62011-02-01 00:10:29 +00005270 lhptee = cast<PointerType>(lhptee)->getPointeeType().getTypePtr();
5271 rhptee = cast<PointerType>(rhptee)->getPointeeType().getTypePtr();
John McCallaba90822011-01-31 23:13:11 +00005272 } while (isa<PointerType>(lhptee) && isa<PointerType>(rhptee));
Kovarththanan Rajaratnamba2c6522010-03-13 10:17:05 +00005273
John McCall4fff8f62011-02-01 00:10:29 +00005274 if (lhptee == rhptee)
John McCallaba90822011-01-31 23:13:11 +00005275 return Sema::IncompatibleNestedPointerQualifiers;
Fariborz Jahaniand7aa9d82009-11-07 20:20:40 +00005276 }
Kovarththanan Rajaratnamba2c6522010-03-13 10:17:05 +00005277
Eli Friedman80160bd2009-03-22 23:59:44 +00005278 // General pointer incompatibility takes priority over qualifiers.
John McCallaba90822011-01-31 23:13:11 +00005279 return Sema::IncompatiblePointer;
Eli Friedman80160bd2009-03-22 23:59:44 +00005280 }
David Blaikiebbafb8a2012-03-11 07:00:24 +00005281 if (!S.getLangOpts().CPlusPlus &&
Fariborz Jahanian48c69102011-10-05 00:05:34 +00005282 S.IsNoReturnConversion(ltrans, rtrans, ltrans))
5283 return Sema::IncompatiblePointer;
Chris Lattner9bad62c2008-01-04 18:04:52 +00005284 return ConvTy;
Steve Naroff1f4d7272007-05-11 04:00:31 +00005285}
5286
John McCallaba90822011-01-31 23:13:11 +00005287/// checkBlockPointerTypesForAssignment - This routine determines whether two
Steve Naroff081c7422008-09-04 15:10:53 +00005288/// block pointer types are compatible or whether a block and normal pointer
5289/// are compatible. It is more restrict than comparing two function pointer
5290// types.
John McCallaba90822011-01-31 23:13:11 +00005291static Sema::AssignConvertType
Richard Trieua871b972011-09-06 20:21:22 +00005292checkBlockPointerTypesForAssignment(Sema &S, QualType LHSType,
5293 QualType RHSType) {
5294 assert(LHSType.isCanonical() && "LHS not canonicalized!");
5295 assert(RHSType.isCanonical() && "RHS not canonicalized!");
John McCallaba90822011-01-31 23:13:11 +00005296
Steve Naroff081c7422008-09-04 15:10:53 +00005297 QualType lhptee, rhptee;
Mike Stump4e1f26a2009-02-19 03:04:26 +00005298
Steve Naroff081c7422008-09-04 15:10:53 +00005299 // get the "pointed to" type (ignoring qualifiers at the top level)
Richard Trieua871b972011-09-06 20:21:22 +00005300 lhptee = cast<BlockPointerType>(LHSType)->getPointeeType();
5301 rhptee = cast<BlockPointerType>(RHSType)->getPointeeType();
Mike Stump4e1f26a2009-02-19 03:04:26 +00005302
John McCallaba90822011-01-31 23:13:11 +00005303 // In C++, the types have to match exactly.
David Blaikiebbafb8a2012-03-11 07:00:24 +00005304 if (S.getLangOpts().CPlusPlus)
John McCallaba90822011-01-31 23:13:11 +00005305 return Sema::IncompatibleBlockPointer;
Mike Stump4e1f26a2009-02-19 03:04:26 +00005306
John McCallaba90822011-01-31 23:13:11 +00005307 Sema::AssignConvertType ConvTy = Sema::Compatible;
Mike Stump4e1f26a2009-02-19 03:04:26 +00005308
Steve Naroff081c7422008-09-04 15:10:53 +00005309 // For blocks we enforce that qualifiers are identical.
John McCallaba90822011-01-31 23:13:11 +00005310 if (lhptee.getLocalQualifiers() != rhptee.getLocalQualifiers())
5311 ConvTy = Sema::CompatiblePointerDiscardsQualifiers;
Mike Stump4e1f26a2009-02-19 03:04:26 +00005312
Richard Trieua871b972011-09-06 20:21:22 +00005313 if (!S.Context.typesAreBlockPointerCompatible(LHSType, RHSType))
John McCallaba90822011-01-31 23:13:11 +00005314 return Sema::IncompatibleBlockPointer;
5315
Steve Naroff081c7422008-09-04 15:10:53 +00005316 return ConvTy;
5317}
5318
John McCallaba90822011-01-31 23:13:11 +00005319/// checkObjCPointerTypesForAssignment - Compares two objective-c pointer types
Fariborz Jahanian410f2eb2009-12-08 18:24:49 +00005320/// for assignment compatibility.
John McCallaba90822011-01-31 23:13:11 +00005321static Sema::AssignConvertType
Richard Trieua871b972011-09-06 20:21:22 +00005322checkObjCPointerTypesForAssignment(Sema &S, QualType LHSType,
5323 QualType RHSType) {
5324 assert(LHSType.isCanonical() && "LHS was not canonicalized!");
5325 assert(RHSType.isCanonical() && "RHS was not canonicalized!");
John McCallaba90822011-01-31 23:13:11 +00005326
Richard Trieua871b972011-09-06 20:21:22 +00005327 if (LHSType->isObjCBuiltinType()) {
Fariborz Jahaniand5bb8cb2010-03-19 18:06:10 +00005328 // Class is not compatible with ObjC object pointers.
Richard Trieua871b972011-09-06 20:21:22 +00005329 if (LHSType->isObjCClassType() && !RHSType->isObjCBuiltinType() &&
5330 !RHSType->isObjCQualifiedClassType())
John McCallaba90822011-01-31 23:13:11 +00005331 return Sema::IncompatiblePointer;
5332 return Sema::Compatible;
Fariborz Jahaniand5bb8cb2010-03-19 18:06:10 +00005333 }
Richard Trieua871b972011-09-06 20:21:22 +00005334 if (RHSType->isObjCBuiltinType()) {
Richard Trieua871b972011-09-06 20:21:22 +00005335 if (RHSType->isObjCClassType() && !LHSType->isObjCBuiltinType() &&
5336 !LHSType->isObjCQualifiedClassType())
Fariborz Jahaniand923eb02011-09-15 20:40:18 +00005337 return Sema::IncompatiblePointer;
John McCallaba90822011-01-31 23:13:11 +00005338 return Sema::Compatible;
Fariborz Jahaniand5bb8cb2010-03-19 18:06:10 +00005339 }
Richard Trieua871b972011-09-06 20:21:22 +00005340 QualType lhptee = LHSType->getAs<ObjCObjectPointerType>()->getPointeeType();
5341 QualType rhptee = RHSType->getAs<ObjCObjectPointerType>()->getPointeeType();
Kovarththanan Rajaratnamba2c6522010-03-13 10:17:05 +00005342
Fariborz Jahaniane74d47e2012-01-12 22:12:08 +00005343 if (!lhptee.isAtLeastAsQualifiedAs(rhptee) &&
5344 // make an exception for id<P>
5345 !LHSType->isObjCQualifiedIdType())
John McCallaba90822011-01-31 23:13:11 +00005346 return Sema::CompatiblePointerDiscardsQualifiers;
5347
Richard Trieua871b972011-09-06 20:21:22 +00005348 if (S.Context.typesAreCompatible(LHSType, RHSType))
John McCallaba90822011-01-31 23:13:11 +00005349 return Sema::Compatible;
Richard Trieua871b972011-09-06 20:21:22 +00005350 if (LHSType->isObjCQualifiedIdType() || RHSType->isObjCQualifiedIdType())
John McCallaba90822011-01-31 23:13:11 +00005351 return Sema::IncompatibleObjCQualifiedId;
5352 return Sema::IncompatiblePointer;
Fariborz Jahanian410f2eb2009-12-08 18:24:49 +00005353}
5354
John McCall29600e12010-11-16 02:32:08 +00005355Sema::AssignConvertType
Douglas Gregorc03a1082011-01-28 02:26:04 +00005356Sema::CheckAssignmentConstraints(SourceLocation Loc,
Richard Trieua871b972011-09-06 20:21:22 +00005357 QualType LHSType, QualType RHSType) {
John McCall29600e12010-11-16 02:32:08 +00005358 // Fake up an opaque expression. We don't actually care about what
5359 // cast operations are required, so if CheckAssignmentConstraints
5360 // adds casts to this they'll be wasted, but fortunately that doesn't
5361 // usually happen on valid code.
Richard Trieua871b972011-09-06 20:21:22 +00005362 OpaqueValueExpr RHSExpr(Loc, RHSType, VK_RValue);
5363 ExprResult RHSPtr = &RHSExpr;
John McCall29600e12010-11-16 02:32:08 +00005364 CastKind K = CK_Invalid;
5365
Richard Trieua871b972011-09-06 20:21:22 +00005366 return CheckAssignmentConstraints(LHSType, RHSPtr, K);
John McCall29600e12010-11-16 02:32:08 +00005367}
5368
Mike Stump4e1f26a2009-02-19 03:04:26 +00005369/// CheckAssignmentConstraints (C99 6.5.16) - This routine currently
5370/// has code to accommodate several GCC extensions when type checking
Steve Naroff17f76e02007-05-03 21:03:48 +00005371/// pointers. Here are some objectionable examples that GCC considers warnings:
5372///
5373/// int a, *pint;
5374/// short *pshort;
5375/// struct foo *pfoo;
5376///
5377/// pint = pshort; // warning: assignment from incompatible pointer type
5378/// a = pint; // warning: assignment makes integer from pointer without a cast
5379/// pint = a; // warning: assignment makes pointer from integer without a cast
5380/// pint = pfoo; // warning: assignment from incompatible pointer type
5381///
5382/// As a result, the code for dealing with pointers is more complex than the
Mike Stump4e1f26a2009-02-19 03:04:26 +00005383/// C99 spec dictates.
Steve Naroff17f76e02007-05-03 21:03:48 +00005384///
John McCall8cb679e2010-11-15 09:13:47 +00005385/// Sets 'Kind' for any result kind except Incompatible.
Chris Lattner9bad62c2008-01-04 18:04:52 +00005386Sema::AssignConvertType
Richard Trieude4958f2011-09-06 20:30:53 +00005387Sema::CheckAssignmentConstraints(QualType LHSType, ExprResult &RHS,
John McCall8cb679e2010-11-15 09:13:47 +00005388 CastKind &Kind) {
Richard Trieude4958f2011-09-06 20:30:53 +00005389 QualType RHSType = RHS.get()->getType();
5390 QualType OrigLHSType = LHSType;
John McCall29600e12010-11-16 02:32:08 +00005391
Chris Lattnera52c2f22008-01-04 23:18:45 +00005392 // Get canonical types. We're not formatting these types, just comparing
5393 // them.
Richard Trieude4958f2011-09-06 20:30:53 +00005394 LHSType = Context.getCanonicalType(LHSType).getUnqualifiedType();
5395 RHSType = Context.getCanonicalType(RHSType).getUnqualifiedType();
Eli Friedman3360d892008-05-30 18:07:22 +00005396
Eli Friedman0dfb8892011-10-06 23:00:33 +00005397
John McCalle5255932011-01-31 22:28:28 +00005398 // Common case: no conversion required.
Richard Trieude4958f2011-09-06 20:30:53 +00005399 if (LHSType == RHSType) {
John McCall8cb679e2010-11-15 09:13:47 +00005400 Kind = CK_NoOp;
John McCall8cb679e2010-11-15 09:13:47 +00005401 return Compatible;
David Chisnall9f57c292009-08-17 16:35:33 +00005402 }
5403
David Chisnallfa35df62012-01-16 17:27:18 +00005404 if (const AtomicType *AtomicTy = dyn_cast<AtomicType>(LHSType)) {
5405 if (AtomicTy->getValueType() == RHSType) {
5406 Kind = CK_NonAtomicToAtomic;
5407 return Compatible;
5408 }
5409 }
5410
5411 if (const AtomicType *AtomicTy = dyn_cast<AtomicType>(RHSType)) {
5412 if (AtomicTy->getValueType() == LHSType) {
5413 Kind = CK_AtomicToNonAtomic;
5414 return Compatible;
5415 }
5416 }
5417
5418
Douglas Gregor6b754842008-10-28 00:22:11 +00005419 // If the left-hand side is a reference type, then we are in a
5420 // (rare!) case where we've allowed the use of references in C,
5421 // e.g., as a parameter type in a built-in function. In this case,
5422 // just make sure that the type referenced is compatible with the
5423 // right-hand side type. The caller is responsible for adjusting
Richard Trieude4958f2011-09-06 20:30:53 +00005424 // LHSType so that the resulting expression does not have reference
Douglas Gregor6b754842008-10-28 00:22:11 +00005425 // type.
Richard Trieude4958f2011-09-06 20:30:53 +00005426 if (const ReferenceType *LHSTypeRef = LHSType->getAs<ReferenceType>()) {
5427 if (Context.typesAreCompatible(LHSTypeRef->getPointeeType(), RHSType)) {
John McCall8cb679e2010-11-15 09:13:47 +00005428 Kind = CK_LValueBitCast;
Anders Carlsson24ebce62007-10-12 23:56:29 +00005429 return Compatible;
John McCall8cb679e2010-11-15 09:13:47 +00005430 }
Chris Lattnera52c2f22008-01-04 23:18:45 +00005431 return Incompatible;
Fariborz Jahaniana1e34202007-12-19 17:45:58 +00005432 }
John McCalle5255932011-01-31 22:28:28 +00005433
Nate Begemanbd956c42009-06-28 02:36:38 +00005434 // Allow scalar to ExtVector assignments, and assignments of an ExtVector type
5435 // to the same ExtVector type.
Richard Trieude4958f2011-09-06 20:30:53 +00005436 if (LHSType->isExtVectorType()) {
5437 if (RHSType->isExtVectorType())
John McCall8cb679e2010-11-15 09:13:47 +00005438 return Incompatible;
Richard Trieude4958f2011-09-06 20:30:53 +00005439 if (RHSType->isArithmeticType()) {
John McCall29600e12010-11-16 02:32:08 +00005440 // CK_VectorSplat does T -> vector T, so first cast to the
5441 // element type.
Richard Trieude4958f2011-09-06 20:30:53 +00005442 QualType elType = cast<ExtVectorType>(LHSType)->getElementType();
5443 if (elType != RHSType) {
John McCall9776e432011-10-06 23:25:11 +00005444 Kind = PrepareScalarCast(RHS, elType);
Richard Trieude4958f2011-09-06 20:30:53 +00005445 RHS = ImpCastExprToType(RHS.take(), elType, Kind);
John McCall29600e12010-11-16 02:32:08 +00005446 }
5447 Kind = CK_VectorSplat;
Nate Begemanbd956c42009-06-28 02:36:38 +00005448 return Compatible;
John McCall8cb679e2010-11-15 09:13:47 +00005449 }
Nate Begemanbd956c42009-06-28 02:36:38 +00005450 }
Mike Stump11289f42009-09-09 15:08:12 +00005451
John McCalle5255932011-01-31 22:28:28 +00005452 // Conversions to or from vector type.
Richard Trieude4958f2011-09-06 20:30:53 +00005453 if (LHSType->isVectorType() || RHSType->isVectorType()) {
5454 if (LHSType->isVectorType() && RHSType->isVectorType()) {
Bob Wilson01856f32010-12-02 00:25:15 +00005455 // Allow assignments of an AltiVec vector type to an equivalent GCC
5456 // vector type and vice versa
Richard Trieude4958f2011-09-06 20:30:53 +00005457 if (Context.areCompatibleVectorTypes(LHSType, RHSType)) {
Bob Wilson01856f32010-12-02 00:25:15 +00005458 Kind = CK_BitCast;
5459 return Compatible;
5460 }
5461
Douglas Gregor59e8b3b2010-08-06 10:14:59 +00005462 // If we are allowing lax vector conversions, and LHS and RHS are both
5463 // vectors, the total size only needs to be the same. This is a bitcast;
5464 // no bits are changed but the result type is different.
David Blaikiebbafb8a2012-03-11 07:00:24 +00005465 if (getLangOpts().LaxVectorConversions &&
Richard Trieude4958f2011-09-06 20:30:53 +00005466 (Context.getTypeSize(LHSType) == Context.getTypeSize(RHSType))) {
John McCall3065d042010-11-15 10:08:00 +00005467 Kind = CK_BitCast;
Anders Carlssondb5a9b62009-01-30 23:17:46 +00005468 return IncompatibleVectors;
John McCall8cb679e2010-11-15 09:13:47 +00005469 }
Chris Lattner881a2122008-01-04 23:32:24 +00005470 }
5471 return Incompatible;
Mike Stump4e1f26a2009-02-19 03:04:26 +00005472 }
Eli Friedman3360d892008-05-30 18:07:22 +00005473
John McCalle5255932011-01-31 22:28:28 +00005474 // Arithmetic conversions.
Richard Trieude4958f2011-09-06 20:30:53 +00005475 if (LHSType->isArithmeticType() && RHSType->isArithmeticType() &&
David Blaikiebbafb8a2012-03-11 07:00:24 +00005476 !(getLangOpts().CPlusPlus && LHSType->isEnumeralType())) {
John McCall9776e432011-10-06 23:25:11 +00005477 Kind = PrepareScalarCast(RHS, LHSType);
Steve Naroff98cf3e92007-06-06 18:38:38 +00005478 return Compatible;
John McCall8cb679e2010-11-15 09:13:47 +00005479 }
Eli Friedman3360d892008-05-30 18:07:22 +00005480
John McCalle5255932011-01-31 22:28:28 +00005481 // Conversions to normal pointers.
Richard Trieude4958f2011-09-06 20:30:53 +00005482 if (const PointerType *LHSPointer = dyn_cast<PointerType>(LHSType)) {
John McCalle5255932011-01-31 22:28:28 +00005483 // U* -> T*
Richard Trieude4958f2011-09-06 20:30:53 +00005484 if (isa<PointerType>(RHSType)) {
John McCall8cb679e2010-11-15 09:13:47 +00005485 Kind = CK_BitCast;
Richard Trieude4958f2011-09-06 20:30:53 +00005486 return checkPointerTypesForAssignment(*this, LHSType, RHSType);
John McCall8cb679e2010-11-15 09:13:47 +00005487 }
Mike Stump4e1f26a2009-02-19 03:04:26 +00005488
John McCalle5255932011-01-31 22:28:28 +00005489 // int -> T*
Richard Trieude4958f2011-09-06 20:30:53 +00005490 if (RHSType->isIntegerType()) {
John McCalle5255932011-01-31 22:28:28 +00005491 Kind = CK_IntegralToPointer; // FIXME: null?
5492 return IntToPointer;
Steve Naroff7cae42b2009-07-10 23:34:53 +00005493 }
John McCalle5255932011-01-31 22:28:28 +00005494
5495 // C pointers are not compatible with ObjC object pointers,
5496 // with two exceptions:
Richard Trieude4958f2011-09-06 20:30:53 +00005497 if (isa<ObjCObjectPointerType>(RHSType)) {
John McCalle5255932011-01-31 22:28:28 +00005498 // - conversions to void*
Richard Trieude4958f2011-09-06 20:30:53 +00005499 if (LHSPointer->getPointeeType()->isVoidType()) {
John McCall9320b872011-09-09 05:25:32 +00005500 Kind = CK_BitCast;
John McCalle5255932011-01-31 22:28:28 +00005501 return Compatible;
5502 }
5503
5504 // - conversions from 'Class' to the redefinition type
Richard Trieude4958f2011-09-06 20:30:53 +00005505 if (RHSType->isObjCClassType() &&
5506 Context.hasSameType(LHSType,
Douglas Gregor97673472011-08-11 20:58:55 +00005507 Context.getObjCClassRedefinitionType())) {
John McCall8cb679e2010-11-15 09:13:47 +00005508 Kind = CK_BitCast;
Douglas Gregore7dd1452008-11-27 00:44:28 +00005509 return Compatible;
John McCall8cb679e2010-11-15 09:13:47 +00005510 }
Douglas Gregor486b74e2011-09-27 16:10:05 +00005511
John McCalle5255932011-01-31 22:28:28 +00005512 Kind = CK_BitCast;
5513 return IncompatiblePointer;
5514 }
5515
5516 // U^ -> void*
Richard Trieude4958f2011-09-06 20:30:53 +00005517 if (RHSType->getAs<BlockPointerType>()) {
5518 if (LHSPointer->getPointeeType()->isVoidType()) {
John McCalle5255932011-01-31 22:28:28 +00005519 Kind = CK_BitCast;
Steve Naroff32d072c2008-09-29 18:10:17 +00005520 return Compatible;
John McCall8cb679e2010-11-15 09:13:47 +00005521 }
Steve Naroff32d072c2008-09-29 18:10:17 +00005522 }
John McCalle5255932011-01-31 22:28:28 +00005523
Steve Naroff081c7422008-09-04 15:10:53 +00005524 return Incompatible;
5525 }
5526
John McCalle5255932011-01-31 22:28:28 +00005527 // Conversions to block pointers.
Richard Trieude4958f2011-09-06 20:30:53 +00005528 if (isa<BlockPointerType>(LHSType)) {
John McCalle5255932011-01-31 22:28:28 +00005529 // U^ -> T^
Richard Trieude4958f2011-09-06 20:30:53 +00005530 if (RHSType->isBlockPointerType()) {
John McCall9320b872011-09-09 05:25:32 +00005531 Kind = CK_BitCast;
Richard Trieude4958f2011-09-06 20:30:53 +00005532 return checkBlockPointerTypesForAssignment(*this, LHSType, RHSType);
John McCalle5255932011-01-31 22:28:28 +00005533 }
5534
5535 // int or null -> T^
Richard Trieude4958f2011-09-06 20:30:53 +00005536 if (RHSType->isIntegerType()) {
John McCall8cb679e2010-11-15 09:13:47 +00005537 Kind = CK_IntegralToPointer; // FIXME: null
Eli Friedman8163b7a2009-02-25 04:20:42 +00005538 return IntToBlockPointer;
John McCall8cb679e2010-11-15 09:13:47 +00005539 }
5540
John McCalle5255932011-01-31 22:28:28 +00005541 // id -> T^
David Blaikiebbafb8a2012-03-11 07:00:24 +00005542 if (getLangOpts().ObjC1 && RHSType->isObjCIdType()) {
John McCalle5255932011-01-31 22:28:28 +00005543 Kind = CK_AnyPointerToBlockPointerCast;
Steve Naroff32d072c2008-09-29 18:10:17 +00005544 return Compatible;
John McCalle5255932011-01-31 22:28:28 +00005545 }
Steve Naroff32d072c2008-09-29 18:10:17 +00005546
John McCalle5255932011-01-31 22:28:28 +00005547 // void* -> T^
Richard Trieude4958f2011-09-06 20:30:53 +00005548 if (const PointerType *RHSPT = RHSType->getAs<PointerType>())
John McCalle5255932011-01-31 22:28:28 +00005549 if (RHSPT->getPointeeType()->isVoidType()) {
5550 Kind = CK_AnyPointerToBlockPointerCast;
Douglas Gregore7dd1452008-11-27 00:44:28 +00005551 return Compatible;
John McCalle5255932011-01-31 22:28:28 +00005552 }
John McCall8cb679e2010-11-15 09:13:47 +00005553
Chris Lattnera52c2f22008-01-04 23:18:45 +00005554 return Incompatible;
5555 }
5556
John McCalle5255932011-01-31 22:28:28 +00005557 // Conversions to Objective-C pointers.
Richard Trieude4958f2011-09-06 20:30:53 +00005558 if (isa<ObjCObjectPointerType>(LHSType)) {
John McCalle5255932011-01-31 22:28:28 +00005559 // A* -> B*
Richard Trieude4958f2011-09-06 20:30:53 +00005560 if (RHSType->isObjCObjectPointerType()) {
John McCalle5255932011-01-31 22:28:28 +00005561 Kind = CK_BitCast;
Fariborz Jahanian6f472e82011-07-07 18:55:47 +00005562 Sema::AssignConvertType result =
Richard Trieude4958f2011-09-06 20:30:53 +00005563 checkObjCPointerTypesForAssignment(*this, LHSType, RHSType);
David Blaikiebbafb8a2012-03-11 07:00:24 +00005564 if (getLangOpts().ObjCAutoRefCount &&
Fariborz Jahanian6f472e82011-07-07 18:55:47 +00005565 result == Compatible &&
Richard Trieude4958f2011-09-06 20:30:53 +00005566 !CheckObjCARCUnavailableWeakConversion(OrigLHSType, RHSType))
Fariborz Jahanian7fcce682011-07-07 23:04:17 +00005567 result = IncompatibleObjCWeakRef;
Fariborz Jahanian6f472e82011-07-07 18:55:47 +00005568 return result;
John McCalle5255932011-01-31 22:28:28 +00005569 }
5570
5571 // int or null -> A*
Richard Trieude4958f2011-09-06 20:30:53 +00005572 if (RHSType->isIntegerType()) {
John McCall8cb679e2010-11-15 09:13:47 +00005573 Kind = CK_IntegralToPointer; // FIXME: null
Steve Naroff7cae42b2009-07-10 23:34:53 +00005574 return IntToPointer;
John McCall8cb679e2010-11-15 09:13:47 +00005575 }
5576
John McCalle5255932011-01-31 22:28:28 +00005577 // In general, C pointers are not compatible with ObjC object pointers,
5578 // with two exceptions:
Richard Trieude4958f2011-09-06 20:30:53 +00005579 if (isa<PointerType>(RHSType)) {
John McCall9320b872011-09-09 05:25:32 +00005580 Kind = CK_CPointerToObjCPointerCast;
5581
John McCalle5255932011-01-31 22:28:28 +00005582 // - conversions from 'void*'
Richard Trieude4958f2011-09-06 20:30:53 +00005583 if (RHSType->isVoidPointerType()) {
Steve Naroffaccc4882009-07-20 17:56:53 +00005584 return Compatible;
John McCalle5255932011-01-31 22:28:28 +00005585 }
5586
5587 // - conversions to 'Class' from its redefinition type
Richard Trieude4958f2011-09-06 20:30:53 +00005588 if (LHSType->isObjCClassType() &&
5589 Context.hasSameType(RHSType,
Douglas Gregor97673472011-08-11 20:58:55 +00005590 Context.getObjCClassRedefinitionType())) {
John McCalle5255932011-01-31 22:28:28 +00005591 return Compatible;
5592 }
5593
Steve Naroffaccc4882009-07-20 17:56:53 +00005594 return IncompatiblePointer;
Steve Naroff7cae42b2009-07-10 23:34:53 +00005595 }
John McCalle5255932011-01-31 22:28:28 +00005596
5597 // T^ -> A*
Richard Trieude4958f2011-09-06 20:30:53 +00005598 if (RHSType->isBlockPointerType()) {
John McCallcd78e802011-09-10 01:16:55 +00005599 maybeExtendBlockObject(*this, RHS);
John McCall9320b872011-09-09 05:25:32 +00005600 Kind = CK_BlockPointerToObjCPointerCast;
Steve Naroff7cae42b2009-07-10 23:34:53 +00005601 return Compatible;
John McCalle5255932011-01-31 22:28:28 +00005602 }
5603
Steve Naroff7cae42b2009-07-10 23:34:53 +00005604 return Incompatible;
5605 }
John McCalle5255932011-01-31 22:28:28 +00005606
5607 // Conversions from pointers that are not covered by the above.
Richard Trieude4958f2011-09-06 20:30:53 +00005608 if (isa<PointerType>(RHSType)) {
John McCalle5255932011-01-31 22:28:28 +00005609 // T* -> _Bool
Richard Trieude4958f2011-09-06 20:30:53 +00005610 if (LHSType == Context.BoolTy) {
John McCall8cb679e2010-11-15 09:13:47 +00005611 Kind = CK_PointerToBoolean;
Eli Friedman3360d892008-05-30 18:07:22 +00005612 return Compatible;
John McCall8cb679e2010-11-15 09:13:47 +00005613 }
Eli Friedman3360d892008-05-30 18:07:22 +00005614
John McCalle5255932011-01-31 22:28:28 +00005615 // T* -> int
Richard Trieude4958f2011-09-06 20:30:53 +00005616 if (LHSType->isIntegerType()) {
John McCall8cb679e2010-11-15 09:13:47 +00005617 Kind = CK_PointerToIntegral;
Chris Lattner940cfeb2008-01-04 18:22:42 +00005618 return PointerToInt;
John McCall8cb679e2010-11-15 09:13:47 +00005619 }
Mike Stump4e1f26a2009-02-19 03:04:26 +00005620
Chris Lattnera52c2f22008-01-04 23:18:45 +00005621 return Incompatible;
Chris Lattnera52c2f22008-01-04 23:18:45 +00005622 }
John McCalle5255932011-01-31 22:28:28 +00005623
5624 // Conversions from Objective-C pointers that are not covered by the above.
Richard Trieude4958f2011-09-06 20:30:53 +00005625 if (isa<ObjCObjectPointerType>(RHSType)) {
John McCalle5255932011-01-31 22:28:28 +00005626 // T* -> _Bool
Richard Trieude4958f2011-09-06 20:30:53 +00005627 if (LHSType == Context.BoolTy) {
John McCall8cb679e2010-11-15 09:13:47 +00005628 Kind = CK_PointerToBoolean;
Steve Naroff7cae42b2009-07-10 23:34:53 +00005629 return Compatible;
John McCall8cb679e2010-11-15 09:13:47 +00005630 }
Steve Naroff7cae42b2009-07-10 23:34:53 +00005631
John McCalle5255932011-01-31 22:28:28 +00005632 // T* -> int
Richard Trieude4958f2011-09-06 20:30:53 +00005633 if (LHSType->isIntegerType()) {
John McCall8cb679e2010-11-15 09:13:47 +00005634 Kind = CK_PointerToIntegral;
Steve Naroff7cae42b2009-07-10 23:34:53 +00005635 return PointerToInt;
John McCall8cb679e2010-11-15 09:13:47 +00005636 }
5637
Steve Naroff7cae42b2009-07-10 23:34:53 +00005638 return Incompatible;
5639 }
Eli Friedman3360d892008-05-30 18:07:22 +00005640
John McCalle5255932011-01-31 22:28:28 +00005641 // struct A -> struct B
Richard Trieude4958f2011-09-06 20:30:53 +00005642 if (isa<TagType>(LHSType) && isa<TagType>(RHSType)) {
5643 if (Context.typesAreCompatible(LHSType, RHSType)) {
John McCall8cb679e2010-11-15 09:13:47 +00005644 Kind = CK_NoOp;
Steve Naroff98cf3e92007-06-06 18:38:38 +00005645 return Compatible;
John McCall8cb679e2010-11-15 09:13:47 +00005646 }
Bill Wendling216423b2007-05-30 06:30:29 +00005647 }
John McCalle5255932011-01-31 22:28:28 +00005648
Steve Naroff98cf3e92007-06-06 18:38:38 +00005649 return Incompatible;
Steve Naroff9eb24652007-05-02 21:58:15 +00005650}
5651
Douglas Gregor0cfbdab2009-04-29 22:16:16 +00005652/// \brief Constructs a transparent union from an expression that is
5653/// used to initialize the transparent union.
Richard Trieucfc491d2011-08-02 04:35:43 +00005654static void ConstructTransparentUnion(Sema &S, ASTContext &C,
5655 ExprResult &EResult, QualType UnionType,
5656 FieldDecl *Field) {
Douglas Gregor0cfbdab2009-04-29 22:16:16 +00005657 // Build an initializer list that designates the appropriate member
5658 // of the transparent union.
John Wiegley01296292011-04-08 18:41:53 +00005659 Expr *E = EResult.take();
Ted Kremenekac034612010-04-13 23:39:13 +00005660 InitListExpr *Initializer = new (C) InitListExpr(C, SourceLocation(),
Ted Kremenek013041e2010-02-19 01:50:18 +00005661 &E, 1,
Douglas Gregor0cfbdab2009-04-29 22:16:16 +00005662 SourceLocation());
5663 Initializer->setType(UnionType);
5664 Initializer->setInitializedFieldInUnion(Field);
5665
5666 // Build a compound literal constructing a value of the transparent
5667 // union type from this initializer list.
John McCalle15bbff2010-01-18 19:35:47 +00005668 TypeSourceInfo *unionTInfo = C.getTrivialTypeSourceInfo(UnionType);
John Wiegley01296292011-04-08 18:41:53 +00005669 EResult = S.Owned(
5670 new (C) CompoundLiteralExpr(SourceLocation(), unionTInfo, UnionType,
5671 VK_RValue, Initializer, false));
Douglas Gregor0cfbdab2009-04-29 22:16:16 +00005672}
5673
5674Sema::AssignConvertType
Richard Trieucfc491d2011-08-02 04:35:43 +00005675Sema::CheckTransparentUnionArgumentConstraints(QualType ArgType,
Richard Trieueb299142011-09-06 20:40:12 +00005676 ExprResult &RHS) {
5677 QualType RHSType = RHS.get()->getType();
Douglas Gregor0cfbdab2009-04-29 22:16:16 +00005678
Mike Stump11289f42009-09-09 15:08:12 +00005679 // If the ArgType is a Union type, we want to handle a potential
Douglas Gregor0cfbdab2009-04-29 22:16:16 +00005680 // transparent_union GCC extension.
5681 const RecordType *UT = ArgType->getAsUnionType();
Argyrios Kyrtzidisb4b64ca2009-06-30 02:34:44 +00005682 if (!UT || !UT->getDecl()->hasAttr<TransparentUnionAttr>())
Douglas Gregor0cfbdab2009-04-29 22:16:16 +00005683 return Incompatible;
5684
5685 // The field to initialize within the transparent union.
5686 RecordDecl *UD = UT->getDecl();
5687 FieldDecl *InitField = 0;
5688 // It's compatible if the expression matches any of the fields.
Argyrios Kyrtzidiscfbfe782009-06-30 02:36:12 +00005689 for (RecordDecl::field_iterator it = UD->field_begin(),
5690 itend = UD->field_end();
Douglas Gregor0cfbdab2009-04-29 22:16:16 +00005691 it != itend; ++it) {
5692 if (it->getType()->isPointerType()) {
5693 // If the transparent union contains a pointer type, we allow:
5694 // 1) void pointer
5695 // 2) null pointer constant
Richard Trieueb299142011-09-06 20:40:12 +00005696 if (RHSType->isPointerType())
John McCall9320b872011-09-09 05:25:32 +00005697 if (RHSType->castAs<PointerType>()->getPointeeType()->isVoidType()) {
Richard Trieueb299142011-09-06 20:40:12 +00005698 RHS = ImpCastExprToType(RHS.take(), it->getType(), CK_BitCast);
David Blaikie2d7c57e2012-04-30 02:36:29 +00005699 InitField = &*it;
Douglas Gregor0cfbdab2009-04-29 22:16:16 +00005700 break;
5701 }
Mike Stump11289f42009-09-09 15:08:12 +00005702
Richard Trieueb299142011-09-06 20:40:12 +00005703 if (RHS.get()->isNullPointerConstant(Context,
5704 Expr::NPC_ValueDependentIsNull)) {
5705 RHS = ImpCastExprToType(RHS.take(), it->getType(),
5706 CK_NullToPointer);
David Blaikie2d7c57e2012-04-30 02:36:29 +00005707 InitField = &*it;
Douglas Gregor0cfbdab2009-04-29 22:16:16 +00005708 break;
5709 }
5710 }
5711
John McCall8cb679e2010-11-15 09:13:47 +00005712 CastKind Kind = CK_Invalid;
Richard Trieueb299142011-09-06 20:40:12 +00005713 if (CheckAssignmentConstraints(it->getType(), RHS, Kind)
Douglas Gregor0cfbdab2009-04-29 22:16:16 +00005714 == Compatible) {
Richard Trieueb299142011-09-06 20:40:12 +00005715 RHS = ImpCastExprToType(RHS.take(), it->getType(), Kind);
David Blaikie2d7c57e2012-04-30 02:36:29 +00005716 InitField = &*it;
Douglas Gregor0cfbdab2009-04-29 22:16:16 +00005717 break;
5718 }
5719 }
5720
5721 if (!InitField)
5722 return Incompatible;
5723
Richard Trieueb299142011-09-06 20:40:12 +00005724 ConstructTransparentUnion(*this, Context, RHS, ArgType, InitField);
Douglas Gregor0cfbdab2009-04-29 22:16:16 +00005725 return Compatible;
5726}
5727
Chris Lattner9bad62c2008-01-04 18:04:52 +00005728Sema::AssignConvertType
Sebastian Redlb49c46c2011-09-24 17:48:00 +00005729Sema::CheckSingleAssignmentConstraints(QualType LHSType, ExprResult &RHS,
5730 bool Diagnose) {
David Blaikiebbafb8a2012-03-11 07:00:24 +00005731 if (getLangOpts().CPlusPlus) {
Eli Friedman0dfb8892011-10-06 23:00:33 +00005732 if (!LHSType->isRecordType() && !LHSType->isAtomicType()) {
Douglas Gregor9a657932008-10-21 23:43:52 +00005733 // C++ 5.17p3: If the left operand is not of class type, the
5734 // expression is implicitly converted (C++ 4) to the
5735 // cv-unqualified type of the left operand.
Sebastian Redlcc152642011-10-16 18:19:06 +00005736 ExprResult Res;
5737 if (Diagnose) {
5738 Res = PerformImplicitConversion(RHS.get(), LHSType.getUnqualifiedType(),
5739 AA_Assigning);
5740 } else {
5741 ImplicitConversionSequence ICS =
5742 TryImplicitConversion(RHS.get(), LHSType.getUnqualifiedType(),
5743 /*SuppressUserConversions=*/false,
5744 /*AllowExplicit=*/false,
5745 /*InOverloadResolution=*/false,
5746 /*CStyle=*/false,
5747 /*AllowObjCWritebackConversion=*/false);
5748 if (ICS.isFailure())
5749 return Incompatible;
5750 Res = PerformImplicitConversion(RHS.get(), LHSType.getUnqualifiedType(),
5751 ICS, AA_Assigning);
5752 }
John Wiegley01296292011-04-08 18:41:53 +00005753 if (Res.isInvalid())
Douglas Gregor9a657932008-10-21 23:43:52 +00005754 return Incompatible;
Fariborz Jahanian7fcce682011-07-07 23:04:17 +00005755 Sema::AssignConvertType result = Compatible;
David Blaikiebbafb8a2012-03-11 07:00:24 +00005756 if (getLangOpts().ObjCAutoRefCount &&
Richard Trieueb299142011-09-06 20:40:12 +00005757 !CheckObjCARCUnavailableWeakConversion(LHSType,
5758 RHS.get()->getType()))
Fariborz Jahanian7fcce682011-07-07 23:04:17 +00005759 result = IncompatibleObjCWeakRef;
Richard Trieueb299142011-09-06 20:40:12 +00005760 RHS = move(Res);
Fariborz Jahanian7fcce682011-07-07 23:04:17 +00005761 return result;
Douglas Gregor9a657932008-10-21 23:43:52 +00005762 }
5763
5764 // FIXME: Currently, we fall through and treat C++ classes like C
5765 // structures.
Eli Friedman0dfb8892011-10-06 23:00:33 +00005766 // FIXME: We also fall through for atomics; not sure what should
5767 // happen there, though.
Sebastian Redlb49c46c2011-09-24 17:48:00 +00005768 }
Douglas Gregor9a657932008-10-21 23:43:52 +00005769
Steve Naroff0ee0b0a2007-11-27 17:58:44 +00005770 // C99 6.5.16.1p1: the left operand is a pointer and the right is
5771 // a null pointer constant.
Richard Trieueb299142011-09-06 20:40:12 +00005772 if ((LHSType->isPointerType() ||
5773 LHSType->isObjCObjectPointerType() ||
5774 LHSType->isBlockPointerType())
5775 && RHS.get()->isNullPointerConstant(Context,
5776 Expr::NPC_ValueDependentIsNull)) {
5777 RHS = ImpCastExprToType(RHS.take(), LHSType, CK_NullToPointer);
Steve Naroff0ee0b0a2007-11-27 17:58:44 +00005778 return Compatible;
5779 }
Mike Stump4e1f26a2009-02-19 03:04:26 +00005780
Chris Lattnere6dcd502007-10-16 02:55:40 +00005781 // This check seems unnatural, however it is necessary to ensure the proper
Steve Naroffb8ea4fb2007-07-13 23:32:42 +00005782 // conversion of functions/arrays. If the conversion were done for all
Douglas Gregora121b752009-11-03 16:56:39 +00005783 // DeclExpr's (created by ActOnIdExpression), it would mess up the unary
Nick Lewyckyef7c0ff2010-08-05 06:27:49 +00005784 // expressions that suppress this implicit conversion (&, sizeof).
Chris Lattnere6dcd502007-10-16 02:55:40 +00005785 //
Mike Stump4e1f26a2009-02-19 03:04:26 +00005786 // Suppress this for references: C++ 8.5.3p5.
Richard Trieueb299142011-09-06 20:40:12 +00005787 if (!LHSType->isReferenceType()) {
5788 RHS = DefaultFunctionArrayLvalueConversion(RHS.take());
5789 if (RHS.isInvalid())
John Wiegley01296292011-04-08 18:41:53 +00005790 return Incompatible;
5791 }
Steve Naroff0c1c7ed2007-08-24 22:33:52 +00005792
John McCall8cb679e2010-11-15 09:13:47 +00005793 CastKind Kind = CK_Invalid;
Chris Lattner9bad62c2008-01-04 18:04:52 +00005794 Sema::AssignConvertType result =
Richard Trieueb299142011-09-06 20:40:12 +00005795 CheckAssignmentConstraints(LHSType, RHS, Kind);
Mike Stump4e1f26a2009-02-19 03:04:26 +00005796
Steve Naroff0c1c7ed2007-08-24 22:33:52 +00005797 // C99 6.5.16.1p2: The value of the right operand is converted to the
5798 // type of the assignment expression.
Douglas Gregor6b754842008-10-28 00:22:11 +00005799 // CheckAssignmentConstraints allows the left-hand side to be a reference,
5800 // so that we can use references in built-in functions even in C.
5801 // The getNonReferenceType() call makes sure that the resulting expression
5802 // does not have reference type.
Richard Trieueb299142011-09-06 20:40:12 +00005803 if (result != Incompatible && RHS.get()->getType() != LHSType)
5804 RHS = ImpCastExprToType(RHS.take(),
5805 LHSType.getNonLValueExprType(Context), Kind);
Steve Naroff0c1c7ed2007-08-24 22:33:52 +00005806 return result;
Steve Naroffb8ea4fb2007-07-13 23:32:42 +00005807}
5808
Richard Trieueb299142011-09-06 20:40:12 +00005809QualType Sema::InvalidOperands(SourceLocation Loc, ExprResult &LHS,
5810 ExprResult &RHS) {
Chris Lattner377d1f82008-11-18 22:52:51 +00005811 Diag(Loc, diag::err_typecheck_invalid_operands)
Richard Trieueb299142011-09-06 20:40:12 +00005812 << LHS.get()->getType() << RHS.get()->getType()
5813 << LHS.get()->getSourceRange() << RHS.get()->getSourceRange();
Chris Lattner5c11c412007-12-12 05:47:28 +00005814 return QualType();
Steve Naroff6f49f5d2007-05-29 14:23:36 +00005815}
5816
Richard Trieu859d23f2011-09-06 21:01:04 +00005817QualType Sema::CheckVectorOperands(ExprResult &LHS, ExprResult &RHS,
Richard Trieuba63ce62011-09-09 01:45:06 +00005818 SourceLocation Loc, bool IsCompAssign) {
Richard Smith508ebf32011-10-28 03:31:48 +00005819 if (!IsCompAssign) {
5820 LHS = DefaultFunctionArrayLvalueConversion(LHS.take());
5821 if (LHS.isInvalid())
5822 return QualType();
5823 }
5824 RHS = DefaultFunctionArrayLvalueConversion(RHS.take());
5825 if (RHS.isInvalid())
5826 return QualType();
5827
Mike Stump4e1f26a2009-02-19 03:04:26 +00005828 // For conversion purposes, we ignore any qualifiers.
Nate Begeman002e4bd2008-04-04 01:30:25 +00005829 // For example, "const float" and "float" are equivalent.
Richard Trieu859d23f2011-09-06 21:01:04 +00005830 QualType LHSType =
5831 Context.getCanonicalType(LHS.get()->getType()).getUnqualifiedType();
5832 QualType RHSType =
5833 Context.getCanonicalType(RHS.get()->getType()).getUnqualifiedType();
Mike Stump4e1f26a2009-02-19 03:04:26 +00005834
Nate Begeman191a6b12008-07-14 18:02:46 +00005835 // If the vector types are identical, return.
Richard Trieu859d23f2011-09-06 21:01:04 +00005836 if (LHSType == RHSType)
5837 return LHSType;
Nate Begeman330aaa72007-12-30 02:59:45 +00005838
Douglas Gregor59e8b3b2010-08-06 10:14:59 +00005839 // Handle the case of equivalent AltiVec and GCC vector types
Richard Trieu859d23f2011-09-06 21:01:04 +00005840 if (LHSType->isVectorType() && RHSType->isVectorType() &&
5841 Context.areCompatibleVectorTypes(LHSType, RHSType)) {
5842 if (LHSType->isExtVectorType()) {
5843 RHS = ImpCastExprToType(RHS.take(), LHSType, CK_BitCast);
5844 return LHSType;
Eli Friedman1408bc92011-06-23 18:10:35 +00005845 }
5846
Richard Trieuba63ce62011-09-09 01:45:06 +00005847 if (!IsCompAssign)
Richard Trieu859d23f2011-09-06 21:01:04 +00005848 LHS = ImpCastExprToType(LHS.take(), RHSType, CK_BitCast);
5849 return RHSType;
Douglas Gregor59e8b3b2010-08-06 10:14:59 +00005850 }
5851
David Blaikiebbafb8a2012-03-11 07:00:24 +00005852 if (getLangOpts().LaxVectorConversions &&
Richard Trieu859d23f2011-09-06 21:01:04 +00005853 Context.getTypeSize(LHSType) == Context.getTypeSize(RHSType)) {
Eli Friedman1408bc92011-06-23 18:10:35 +00005854 // If we are allowing lax vector conversions, and LHS and RHS are both
5855 // vectors, the total size only needs to be the same. This is a
5856 // bitcast; no bits are changed but the result type is different.
5857 // FIXME: Should we really be allowing this?
Richard Trieu859d23f2011-09-06 21:01:04 +00005858 RHS = ImpCastExprToType(RHS.take(), LHSType, CK_BitCast);
5859 return LHSType;
Eli Friedman1408bc92011-06-23 18:10:35 +00005860 }
5861
Nate Begemanbd956c42009-06-28 02:36:38 +00005862 // Canonicalize the ExtVector to the LHS, remember if we swapped so we can
5863 // swap back (so that we don't reverse the inputs to a subtract, for instance.
5864 bool swapped = false;
Richard Trieuba63ce62011-09-09 01:45:06 +00005865 if (RHSType->isExtVectorType() && !IsCompAssign) {
Nate Begemanbd956c42009-06-28 02:36:38 +00005866 swapped = true;
Richard Trieu859d23f2011-09-06 21:01:04 +00005867 std::swap(RHS, LHS);
5868 std::swap(RHSType, LHSType);
Nate Begemanbd956c42009-06-28 02:36:38 +00005869 }
Mike Stump11289f42009-09-09 15:08:12 +00005870
Nate Begeman886448d2009-06-28 19:12:57 +00005871 // Handle the case of an ext vector and scalar.
Richard Trieu859d23f2011-09-06 21:01:04 +00005872 if (const ExtVectorType *LV = LHSType->getAs<ExtVectorType>()) {
Nate Begemanbd956c42009-06-28 02:36:38 +00005873 QualType EltTy = LV->getElementType();
Richard Trieu859d23f2011-09-06 21:01:04 +00005874 if (EltTy->isIntegralType(Context) && RHSType->isIntegralType(Context)) {
5875 int order = Context.getIntegerTypeOrder(EltTy, RHSType);
John McCall8cb679e2010-11-15 09:13:47 +00005876 if (order > 0)
Richard Trieu859d23f2011-09-06 21:01:04 +00005877 RHS = ImpCastExprToType(RHS.take(), EltTy, CK_IntegralCast);
John McCall8cb679e2010-11-15 09:13:47 +00005878 if (order >= 0) {
Richard Trieu859d23f2011-09-06 21:01:04 +00005879 RHS = ImpCastExprToType(RHS.take(), LHSType, CK_VectorSplat);
5880 if (swapped) std::swap(RHS, LHS);
5881 return LHSType;
Nate Begemanbd956c42009-06-28 02:36:38 +00005882 }
5883 }
Richard Trieu859d23f2011-09-06 21:01:04 +00005884 if (EltTy->isRealFloatingType() && RHSType->isScalarType() &&
5885 RHSType->isRealFloatingType()) {
5886 int order = Context.getFloatingTypeOrder(EltTy, RHSType);
John McCall8cb679e2010-11-15 09:13:47 +00005887 if (order > 0)
Richard Trieu859d23f2011-09-06 21:01:04 +00005888 RHS = ImpCastExprToType(RHS.take(), EltTy, CK_FloatingCast);
John McCall8cb679e2010-11-15 09:13:47 +00005889 if (order >= 0) {
Richard Trieu859d23f2011-09-06 21:01:04 +00005890 RHS = ImpCastExprToType(RHS.take(), LHSType, CK_VectorSplat);
5891 if (swapped) std::swap(RHS, LHS);
5892 return LHSType;
Nate Begemanbd956c42009-06-28 02:36:38 +00005893 }
Nate Begeman330aaa72007-12-30 02:59:45 +00005894 }
5895 }
Mike Stump11289f42009-09-09 15:08:12 +00005896
Nate Begeman886448d2009-06-28 19:12:57 +00005897 // Vectors of different size or scalar and non-ext-vector are errors.
Richard Trieu859d23f2011-09-06 21:01:04 +00005898 if (swapped) std::swap(RHS, LHS);
Chris Lattner377d1f82008-11-18 22:52:51 +00005899 Diag(Loc, diag::err_typecheck_vector_not_convertable)
Richard Trieu859d23f2011-09-06 21:01:04 +00005900 << LHS.get()->getType() << RHS.get()->getType()
5901 << LHS.get()->getSourceRange() << RHS.get()->getSourceRange();
Steve Naroff84ff4b42007-07-09 21:31:10 +00005902 return QualType();
Sebastian Redl112a97662009-02-07 00:15:38 +00005903}
5904
Richard Trieuf8916e12011-09-16 00:53:10 +00005905// checkArithmeticNull - Detect when a NULL constant is used improperly in an
5906// expression. These are mainly cases where the null pointer is used as an
5907// integer instead of a pointer.
5908static void checkArithmeticNull(Sema &S, ExprResult &LHS, ExprResult &RHS,
5909 SourceLocation Loc, bool IsCompare) {
5910 // The canonical way to check for a GNU null is with isNullPointerConstant,
5911 // but we use a bit of a hack here for speed; this is a relatively
5912 // hot path, and isNullPointerConstant is slow.
5913 bool LHSNull = isa<GNUNullExpr>(LHS.get()->IgnoreParenImpCasts());
5914 bool RHSNull = isa<GNUNullExpr>(RHS.get()->IgnoreParenImpCasts());
5915
5916 QualType NonNullType = LHSNull ? RHS.get()->getType() : LHS.get()->getType();
5917
5918 // Avoid analyzing cases where the result will either be invalid (and
5919 // diagnosed as such) or entirely valid and not something to warn about.
5920 if ((!LHSNull && !RHSNull) || NonNullType->isBlockPointerType() ||
5921 NonNullType->isMemberPointerType() || NonNullType->isFunctionType())
5922 return;
5923
5924 // Comparison operations would not make sense with a null pointer no matter
5925 // what the other expression is.
5926 if (!IsCompare) {
5927 S.Diag(Loc, diag::warn_null_in_arithmetic_operation)
5928 << (LHSNull ? LHS.get()->getSourceRange() : SourceRange())
5929 << (RHSNull ? RHS.get()->getSourceRange() : SourceRange());
5930 return;
5931 }
5932
5933 // The rest of the operations only make sense with a null pointer
5934 // if the other expression is a pointer.
5935 if (LHSNull == RHSNull || NonNullType->isAnyPointerType() ||
5936 NonNullType->canDecayToPointerType())
5937 return;
5938
5939 S.Diag(Loc, diag::warn_null_in_comparison_operation)
5940 << LHSNull /* LHS is NULL */ << NonNullType
5941 << LHS.get()->getSourceRange() << RHS.get()->getSourceRange();
5942}
5943
Richard Trieu859d23f2011-09-06 21:01:04 +00005944QualType Sema::CheckMultiplyDivideOperands(ExprResult &LHS, ExprResult &RHS,
Richard Trieucfc491d2011-08-02 04:35:43 +00005945 SourceLocation Loc,
Richard Trieuba63ce62011-09-09 01:45:06 +00005946 bool IsCompAssign, bool IsDiv) {
Richard Trieuf8916e12011-09-16 00:53:10 +00005947 checkArithmeticNull(*this, LHS, RHS, Loc, /*isCompare=*/false);
5948
Richard Trieu859d23f2011-09-06 21:01:04 +00005949 if (LHS.get()->getType()->isVectorType() ||
5950 RHS.get()->getType()->isVectorType())
Richard Trieuba63ce62011-09-09 01:45:06 +00005951 return CheckVectorOperands(LHS, RHS, Loc, IsCompAssign);
Mike Stump4e1f26a2009-02-19 03:04:26 +00005952
Richard Trieuba63ce62011-09-09 01:45:06 +00005953 QualType compType = UsualArithmeticConversions(LHS, RHS, IsCompAssign);
Richard Trieu859d23f2011-09-06 21:01:04 +00005954 if (LHS.isInvalid() || RHS.isInvalid())
John Wiegley01296292011-04-08 18:41:53 +00005955 return QualType();
Mike Stump4e1f26a2009-02-19 03:04:26 +00005956
David Chisnallfa35df62012-01-16 17:27:18 +00005957
Richard Trieu859d23f2011-09-06 21:01:04 +00005958 if (!LHS.get()->getType()->isArithmeticType() ||
David Chisnallfa35df62012-01-16 17:27:18 +00005959 !RHS.get()->getType()->isArithmeticType()) {
5960 if (IsCompAssign &&
5961 LHS.get()->getType()->isAtomicType() &&
5962 RHS.get()->getType()->isArithmeticType())
5963 return compType;
Richard Trieu859d23f2011-09-06 21:01:04 +00005964 return InvalidOperands(Loc, LHS, RHS);
David Chisnallfa35df62012-01-16 17:27:18 +00005965 }
Kovarththanan Rajaratnamba2c6522010-03-13 10:17:05 +00005966
Chris Lattnerfaa54172010-01-12 21:23:57 +00005967 // Check for division by zero.
Richard Trieuba63ce62011-09-09 01:45:06 +00005968 if (IsDiv &&
Richard Trieu859d23f2011-09-06 21:01:04 +00005969 RHS.get()->isNullPointerConstant(Context,
Richard Trieucfc491d2011-08-02 04:35:43 +00005970 Expr::NPC_ValueDependentIsNotNull))
Richard Trieu859d23f2011-09-06 21:01:04 +00005971 DiagRuntimeBehavior(Loc, RHS.get(), PDiag(diag::warn_division_by_zero)
5972 << RHS.get()->getSourceRange());
Kovarththanan Rajaratnamba2c6522010-03-13 10:17:05 +00005973
Chris Lattnerfaa54172010-01-12 21:23:57 +00005974 return compType;
Steve Naroff26c8ea52007-03-21 21:08:52 +00005975}
5976
Chris Lattnerfaa54172010-01-12 21:23:57 +00005977QualType Sema::CheckRemainderOperands(
Richard Trieuba63ce62011-09-09 01:45:06 +00005978 ExprResult &LHS, ExprResult &RHS, SourceLocation Loc, bool IsCompAssign) {
Richard Trieuf8916e12011-09-16 00:53:10 +00005979 checkArithmeticNull(*this, LHS, RHS, Loc, /*isCompare=*/false);
5980
Richard Trieu859d23f2011-09-06 21:01:04 +00005981 if (LHS.get()->getType()->isVectorType() ||
5982 RHS.get()->getType()->isVectorType()) {
5983 if (LHS.get()->getType()->hasIntegerRepresentation() &&
5984 RHS.get()->getType()->hasIntegerRepresentation())
Richard Trieuba63ce62011-09-09 01:45:06 +00005985 return CheckVectorOperands(LHS, RHS, Loc, IsCompAssign);
Richard Trieu859d23f2011-09-06 21:01:04 +00005986 return InvalidOperands(Loc, LHS, RHS);
Daniel Dunbar0d2bfec2009-01-05 22:55:36 +00005987 }
Steve Naroffb8ea4fb2007-07-13 23:32:42 +00005988
Richard Trieuba63ce62011-09-09 01:45:06 +00005989 QualType compType = UsualArithmeticConversions(LHS, RHS, IsCompAssign);
Richard Trieu859d23f2011-09-06 21:01:04 +00005990 if (LHS.isInvalid() || RHS.isInvalid())
John Wiegley01296292011-04-08 18:41:53 +00005991 return QualType();
Mike Stump4e1f26a2009-02-19 03:04:26 +00005992
Richard Trieu859d23f2011-09-06 21:01:04 +00005993 if (!LHS.get()->getType()->isIntegerType() ||
5994 !RHS.get()->getType()->isIntegerType())
5995 return InvalidOperands(Loc, LHS, RHS);
Kovarththanan Rajaratnamba2c6522010-03-13 10:17:05 +00005996
Chris Lattnerfaa54172010-01-12 21:23:57 +00005997 // Check for remainder by zero.
Richard Trieu859d23f2011-09-06 21:01:04 +00005998 if (RHS.get()->isNullPointerConstant(Context,
Richard Trieucfc491d2011-08-02 04:35:43 +00005999 Expr::NPC_ValueDependentIsNotNull))
Richard Trieu859d23f2011-09-06 21:01:04 +00006000 DiagRuntimeBehavior(Loc, RHS.get(), PDiag(diag::warn_remainder_by_zero)
6001 << RHS.get()->getSourceRange());
Kovarththanan Rajaratnamba2c6522010-03-13 10:17:05 +00006002
Chris Lattnerfaa54172010-01-12 21:23:57 +00006003 return compType;
Steve Naroff218bc2b2007-05-04 21:54:46 +00006004}
6005
Chandler Carruthc9332212011-06-27 08:02:19 +00006006/// \brief Diagnose invalid arithmetic on two void pointers.
6007static void diagnoseArithmeticOnTwoVoidPointers(Sema &S, SourceLocation Loc,
Richard Trieu4ae7e972011-09-06 21:13:51 +00006008 Expr *LHSExpr, Expr *RHSExpr) {
David Blaikiebbafb8a2012-03-11 07:00:24 +00006009 S.Diag(Loc, S.getLangOpts().CPlusPlus
Chandler Carruthc9332212011-06-27 08:02:19 +00006010 ? diag::err_typecheck_pointer_arith_void_type
6011 : diag::ext_gnu_void_ptr)
Richard Trieu4ae7e972011-09-06 21:13:51 +00006012 << 1 /* two pointers */ << LHSExpr->getSourceRange()
6013 << RHSExpr->getSourceRange();
Chandler Carruthc9332212011-06-27 08:02:19 +00006014}
6015
6016/// \brief Diagnose invalid arithmetic on a void pointer.
6017static void diagnoseArithmeticOnVoidPointer(Sema &S, SourceLocation Loc,
6018 Expr *Pointer) {
David Blaikiebbafb8a2012-03-11 07:00:24 +00006019 S.Diag(Loc, S.getLangOpts().CPlusPlus
Chandler Carruthc9332212011-06-27 08:02:19 +00006020 ? diag::err_typecheck_pointer_arith_void_type
6021 : diag::ext_gnu_void_ptr)
6022 << 0 /* one pointer */ << Pointer->getSourceRange();
6023}
6024
6025/// \brief Diagnose invalid arithmetic on two function pointers.
6026static void diagnoseArithmeticOnTwoFunctionPointers(Sema &S, SourceLocation Loc,
6027 Expr *LHS, Expr *RHS) {
6028 assert(LHS->getType()->isAnyPointerType());
6029 assert(RHS->getType()->isAnyPointerType());
David Blaikiebbafb8a2012-03-11 07:00:24 +00006030 S.Diag(Loc, S.getLangOpts().CPlusPlus
Chandler Carruthc9332212011-06-27 08:02:19 +00006031 ? diag::err_typecheck_pointer_arith_function_type
6032 : diag::ext_gnu_ptr_func_arith)
6033 << 1 /* two pointers */ << LHS->getType()->getPointeeType()
6034 // We only show the second type if it differs from the first.
6035 << (unsigned)!S.Context.hasSameUnqualifiedType(LHS->getType(),
6036 RHS->getType())
6037 << RHS->getType()->getPointeeType()
6038 << LHS->getSourceRange() << RHS->getSourceRange();
6039}
6040
6041/// \brief Diagnose invalid arithmetic on a function pointer.
6042static void diagnoseArithmeticOnFunctionPointer(Sema &S, SourceLocation Loc,
6043 Expr *Pointer) {
6044 assert(Pointer->getType()->isAnyPointerType());
David Blaikiebbafb8a2012-03-11 07:00:24 +00006045 S.Diag(Loc, S.getLangOpts().CPlusPlus
Chandler Carruthc9332212011-06-27 08:02:19 +00006046 ? diag::err_typecheck_pointer_arith_function_type
6047 : diag::ext_gnu_ptr_func_arith)
6048 << 0 /* one pointer */ << Pointer->getType()->getPointeeType()
6049 << 0 /* one pointer, so only one type */
6050 << Pointer->getSourceRange();
6051}
6052
Richard Trieu993f3ab2011-09-12 18:08:02 +00006053/// \brief Emit error if Operand is incomplete pointer type
Richard Trieuaba22802011-09-02 02:15:37 +00006054///
6055/// \returns True if pointer has incomplete type
6056static bool checkArithmeticIncompletePointerType(Sema &S, SourceLocation Loc,
6057 Expr *Operand) {
6058 if ((Operand->getType()->isPointerType() &&
6059 !Operand->getType()->isDependentType()) ||
6060 Operand->getType()->isObjCObjectPointerType()) {
6061 QualType PointeeTy = Operand->getType()->getPointeeType();
6062 if (S.RequireCompleteType(
6063 Loc, PointeeTy,
Douglas Gregor7bfb2d02012-05-04 16:32:21 +00006064 diag::err_typecheck_arithmetic_incomplete_type,
6065 PointeeTy, Operand->getSourceRange()))
Richard Trieuaba22802011-09-02 02:15:37 +00006066 return true;
6067 }
6068 return false;
6069}
6070
Chandler Carruthc9332212011-06-27 08:02:19 +00006071/// \brief Check the validity of an arithmetic pointer operand.
6072///
6073/// If the operand has pointer type, this code will check for pointer types
6074/// which are invalid in arithmetic operations. These will be diagnosed
6075/// appropriately, including whether or not the use is supported as an
6076/// extension.
6077///
6078/// \returns True when the operand is valid to use (even if as an extension).
6079static bool checkArithmeticOpPointerOperand(Sema &S, SourceLocation Loc,
6080 Expr *Operand) {
6081 if (!Operand->getType()->isAnyPointerType()) return true;
6082
6083 QualType PointeeTy = Operand->getType()->getPointeeType();
6084 if (PointeeTy->isVoidType()) {
6085 diagnoseArithmeticOnVoidPointer(S, Loc, Operand);
David Blaikiebbafb8a2012-03-11 07:00:24 +00006086 return !S.getLangOpts().CPlusPlus;
Chandler Carruthc9332212011-06-27 08:02:19 +00006087 }
6088 if (PointeeTy->isFunctionType()) {
6089 diagnoseArithmeticOnFunctionPointer(S, Loc, Operand);
David Blaikiebbafb8a2012-03-11 07:00:24 +00006090 return !S.getLangOpts().CPlusPlus;
Chandler Carruthc9332212011-06-27 08:02:19 +00006091 }
6092
Richard Trieuaba22802011-09-02 02:15:37 +00006093 if (checkArithmeticIncompletePointerType(S, Loc, Operand)) return false;
Chandler Carruthc9332212011-06-27 08:02:19 +00006094
6095 return true;
6096}
6097
6098/// \brief Check the validity of a binary arithmetic operation w.r.t. pointer
6099/// operands.
6100///
6101/// This routine will diagnose any invalid arithmetic on pointer operands much
6102/// like \see checkArithmeticOpPointerOperand. However, it has special logic
6103/// for emitting a single diagnostic even for operations where both LHS and RHS
6104/// are (potentially problematic) pointers.
6105///
6106/// \returns True when the operand is valid to use (even if as an extension).
6107static bool checkArithmeticBinOpPointerOperands(Sema &S, SourceLocation Loc,
Richard Trieu4ae7e972011-09-06 21:13:51 +00006108 Expr *LHSExpr, Expr *RHSExpr) {
6109 bool isLHSPointer = LHSExpr->getType()->isAnyPointerType();
6110 bool isRHSPointer = RHSExpr->getType()->isAnyPointerType();
Chandler Carruthc9332212011-06-27 08:02:19 +00006111 if (!isLHSPointer && !isRHSPointer) return true;
6112
6113 QualType LHSPointeeTy, RHSPointeeTy;
Richard Trieu4ae7e972011-09-06 21:13:51 +00006114 if (isLHSPointer) LHSPointeeTy = LHSExpr->getType()->getPointeeType();
6115 if (isRHSPointer) RHSPointeeTy = RHSExpr->getType()->getPointeeType();
Chandler Carruthc9332212011-06-27 08:02:19 +00006116
6117 // Check for arithmetic on pointers to incomplete types.
6118 bool isLHSVoidPtr = isLHSPointer && LHSPointeeTy->isVoidType();
6119 bool isRHSVoidPtr = isRHSPointer && RHSPointeeTy->isVoidType();
6120 if (isLHSVoidPtr || isRHSVoidPtr) {
Richard Trieu4ae7e972011-09-06 21:13:51 +00006121 if (!isRHSVoidPtr) diagnoseArithmeticOnVoidPointer(S, Loc, LHSExpr);
6122 else if (!isLHSVoidPtr) diagnoseArithmeticOnVoidPointer(S, Loc, RHSExpr);
6123 else diagnoseArithmeticOnTwoVoidPointers(S, Loc, LHSExpr, RHSExpr);
Chandler Carruthc9332212011-06-27 08:02:19 +00006124
David Blaikiebbafb8a2012-03-11 07:00:24 +00006125 return !S.getLangOpts().CPlusPlus;
Chandler Carruthc9332212011-06-27 08:02:19 +00006126 }
6127
6128 bool isLHSFuncPtr = isLHSPointer && LHSPointeeTy->isFunctionType();
6129 bool isRHSFuncPtr = isRHSPointer && RHSPointeeTy->isFunctionType();
6130 if (isLHSFuncPtr || isRHSFuncPtr) {
Richard Trieu4ae7e972011-09-06 21:13:51 +00006131 if (!isRHSFuncPtr) diagnoseArithmeticOnFunctionPointer(S, Loc, LHSExpr);
6132 else if (!isLHSFuncPtr) diagnoseArithmeticOnFunctionPointer(S, Loc,
6133 RHSExpr);
6134 else diagnoseArithmeticOnTwoFunctionPointers(S, Loc, LHSExpr, RHSExpr);
Chandler Carruthc9332212011-06-27 08:02:19 +00006135
David Blaikiebbafb8a2012-03-11 07:00:24 +00006136 return !S.getLangOpts().CPlusPlus;
Chandler Carruthc9332212011-06-27 08:02:19 +00006137 }
6138
Richard Trieu4ae7e972011-09-06 21:13:51 +00006139 if (checkArithmeticIncompletePointerType(S, Loc, LHSExpr)) return false;
6140 if (checkArithmeticIncompletePointerType(S, Loc, RHSExpr)) return false;
Richard Trieuaba22802011-09-02 02:15:37 +00006141
Chandler Carruthc9332212011-06-27 08:02:19 +00006142 return true;
6143}
6144
Richard Trieub10c6312011-09-01 22:53:23 +00006145/// \brief Check bad cases where we step over interface counts.
6146static bool checkArithmethicPointerOnNonFragileABI(Sema &S,
6147 SourceLocation OpLoc,
6148 Expr *Op) {
6149 assert(Op->getType()->isAnyPointerType());
6150 QualType PointeeTy = Op->getType()->getPointeeType();
6151 if (!PointeeTy->isObjCObjectType() || !S.LangOpts.ObjCNonFragileABI)
6152 return true;
6153
6154 S.Diag(OpLoc, diag::err_arithmetic_nonfragile_interface)
6155 << PointeeTy << Op->getSourceRange();
6156 return false;
6157}
6158
Nico Weberccec40d2012-03-02 22:01:22 +00006159/// diagnoseStringPlusInt - Emit a warning when adding an integer to a string
6160/// literal.
6161static void diagnoseStringPlusInt(Sema &Self, SourceLocation OpLoc,
6162 Expr *LHSExpr, Expr *RHSExpr) {
6163 StringLiteral* StrExpr = dyn_cast<StringLiteral>(LHSExpr->IgnoreImpCasts());
6164 Expr* IndexExpr = RHSExpr;
6165 if (!StrExpr) {
6166 StrExpr = dyn_cast<StringLiteral>(RHSExpr->IgnoreImpCasts());
6167 IndexExpr = LHSExpr;
6168 }
6169
6170 bool IsStringPlusInt = StrExpr &&
6171 IndexExpr->getType()->isIntegralOrUnscopedEnumerationType();
6172 if (!IsStringPlusInt)
6173 return;
6174
6175 llvm::APSInt index;
6176 if (IndexExpr->EvaluateAsInt(index, Self.getASTContext())) {
6177 unsigned StrLenWithNull = StrExpr->getLength() + 1;
6178 if (index.isNonNegative() &&
6179 index <= llvm::APSInt(llvm::APInt(index.getBitWidth(), StrLenWithNull),
6180 index.isUnsigned()))
6181 return;
6182 }
6183
6184 SourceRange DiagRange(LHSExpr->getLocStart(), RHSExpr->getLocEnd());
6185 Self.Diag(OpLoc, diag::warn_string_plus_int)
6186 << DiagRange << IndexExpr->IgnoreImpCasts()->getType();
6187
6188 // Only print a fixit for "str" + int, not for int + "str".
6189 if (IndexExpr == RHSExpr) {
6190 SourceLocation EndLoc = Self.PP.getLocForEndOfToken(RHSExpr->getLocEnd());
6191 Self.Diag(OpLoc, diag::note_string_plus_int_silence)
6192 << FixItHint::CreateInsertion(LHSExpr->getLocStart(), "&")
6193 << FixItHint::CreateReplacement(SourceRange(OpLoc), "[")
6194 << FixItHint::CreateInsertion(EndLoc, "]");
6195 } else
6196 Self.Diag(OpLoc, diag::note_string_plus_int_silence);
6197}
6198
Richard Trieu993f3ab2011-09-12 18:08:02 +00006199/// \brief Emit error when two pointers are incompatible.
Richard Trieub10c6312011-09-01 22:53:23 +00006200static void diagnosePointerIncompatibility(Sema &S, SourceLocation Loc,
Richard Trieu4ae7e972011-09-06 21:13:51 +00006201 Expr *LHSExpr, Expr *RHSExpr) {
6202 assert(LHSExpr->getType()->isAnyPointerType());
6203 assert(RHSExpr->getType()->isAnyPointerType());
Richard Trieub10c6312011-09-01 22:53:23 +00006204 S.Diag(Loc, diag::err_typecheck_sub_ptr_compatible)
Richard Trieu4ae7e972011-09-06 21:13:51 +00006205 << LHSExpr->getType() << RHSExpr->getType() << LHSExpr->getSourceRange()
6206 << RHSExpr->getSourceRange();
Richard Trieub10c6312011-09-01 22:53:23 +00006207}
6208
Chris Lattnerfaa54172010-01-12 21:23:57 +00006209QualType Sema::CheckAdditionOperands( // C99 6.5.6
Nico Weberccec40d2012-03-02 22:01:22 +00006210 ExprResult &LHS, ExprResult &RHS, SourceLocation Loc, unsigned Opc,
6211 QualType* CompLHSTy) {
Richard Trieuf8916e12011-09-16 00:53:10 +00006212 checkArithmeticNull(*this, LHS, RHS, Loc, /*isCompare=*/false);
6213
Richard Trieu4ae7e972011-09-06 21:13:51 +00006214 if (LHS.get()->getType()->isVectorType() ||
6215 RHS.get()->getType()->isVectorType()) {
6216 QualType compType = CheckVectorOperands(LHS, RHS, Loc, CompLHSTy);
Eli Friedman8b7b1b12009-03-28 01:22:36 +00006217 if (CompLHSTy) *CompLHSTy = compType;
6218 return compType;
6219 }
Steve Naroff7a5af782007-07-13 16:58:59 +00006220
Richard Trieu4ae7e972011-09-06 21:13:51 +00006221 QualType compType = UsualArithmeticConversions(LHS, RHS, CompLHSTy);
6222 if (LHS.isInvalid() || RHS.isInvalid())
John Wiegley01296292011-04-08 18:41:53 +00006223 return QualType();
Eli Friedman8e122982008-05-18 18:08:51 +00006224
Nico Weberccec40d2012-03-02 22:01:22 +00006225 // Diagnose "string literal" '+' int.
6226 if (Opc == BO_Add)
6227 diagnoseStringPlusInt(*this, Loc, LHS.get(), RHS.get());
6228
Steve Naroffe4718892007-04-27 18:30:00 +00006229 // handle the common case first (both operands are arithmetic).
Richard Trieu4ae7e972011-09-06 21:13:51 +00006230 if (LHS.get()->getType()->isArithmeticType() &&
6231 RHS.get()->getType()->isArithmeticType()) {
Eli Friedman8b7b1b12009-03-28 01:22:36 +00006232 if (CompLHSTy) *CompLHSTy = compType;
Steve Naroffbe4c4d12007-08-24 19:07:16 +00006233 return compType;
Eli Friedman8b7b1b12009-03-28 01:22:36 +00006234 }
Steve Naroff218bc2b2007-05-04 21:54:46 +00006235
David Chisnallfa35df62012-01-16 17:27:18 +00006236 if (LHS.get()->getType()->isAtomicType() &&
6237 RHS.get()->getType()->isArithmeticType()) {
6238 *CompLHSTy = LHS.get()->getType();
6239 return compType;
6240 }
6241
Eli Friedman8e122982008-05-18 18:08:51 +00006242 // Put any potential pointer into PExp
Richard Trieu4ae7e972011-09-06 21:13:51 +00006243 Expr* PExp = LHS.get(), *IExp = RHS.get();
Steve Naroff6b712a72009-07-14 18:25:06 +00006244 if (IExp->getType()->isAnyPointerType())
Eli Friedman8e122982008-05-18 18:08:51 +00006245 std::swap(PExp, IExp);
6246
Richard Trieub420bca2011-09-12 18:37:54 +00006247 if (!PExp->getType()->isAnyPointerType())
6248 return InvalidOperands(Loc, LHS, RHS);
Chandler Carruthc9332212011-06-27 08:02:19 +00006249
Richard Trieub420bca2011-09-12 18:37:54 +00006250 if (!IExp->getType()->isIntegerType())
6251 return InvalidOperands(Loc, LHS, RHS);
Mike Stump11289f42009-09-09 15:08:12 +00006252
Richard Trieub420bca2011-09-12 18:37:54 +00006253 if (!checkArithmeticOpPointerOperand(*this, Loc, PExp))
6254 return QualType();
Kaelyn Uhrain2e7aa5a2011-08-05 23:18:04 +00006255
Richard Trieub420bca2011-09-12 18:37:54 +00006256 // Diagnose bad cases where we step over interface counts.
6257 if (!checkArithmethicPointerOnNonFragileABI(*this, Loc, PExp))
6258 return QualType();
6259
6260 // Check array bounds for pointer arithemtic
6261 CheckArrayAccess(PExp, IExp);
6262
6263 if (CompLHSTy) {
6264 QualType LHSTy = Context.isPromotableBitField(LHS.get());
6265 if (LHSTy.isNull()) {
6266 LHSTy = LHS.get()->getType();
6267 if (LHSTy->isPromotableIntegerType())
6268 LHSTy = Context.getPromotedIntegerType(LHSTy);
Eli Friedman8e122982008-05-18 18:08:51 +00006269 }
Richard Trieub420bca2011-09-12 18:37:54 +00006270 *CompLHSTy = LHSTy;
Eli Friedman8e122982008-05-18 18:08:51 +00006271 }
6272
Richard Trieub420bca2011-09-12 18:37:54 +00006273 return PExp->getType();
Steve Naroff26c8ea52007-03-21 21:08:52 +00006274}
6275
Chris Lattner2a3569b2008-04-07 05:30:13 +00006276// C99 6.5.6
Richard Trieu4ae7e972011-09-06 21:13:51 +00006277QualType Sema::CheckSubtractionOperands(ExprResult &LHS, ExprResult &RHS,
Richard Trieucfc491d2011-08-02 04:35:43 +00006278 SourceLocation Loc,
6279 QualType* CompLHSTy) {
Richard Trieuf8916e12011-09-16 00:53:10 +00006280 checkArithmeticNull(*this, LHS, RHS, Loc, /*isCompare=*/false);
6281
Richard Trieu4ae7e972011-09-06 21:13:51 +00006282 if (LHS.get()->getType()->isVectorType() ||
6283 RHS.get()->getType()->isVectorType()) {
6284 QualType compType = CheckVectorOperands(LHS, RHS, Loc, CompLHSTy);
Eli Friedman8b7b1b12009-03-28 01:22:36 +00006285 if (CompLHSTy) *CompLHSTy = compType;
6286 return compType;
6287 }
Mike Stump4e1f26a2009-02-19 03:04:26 +00006288
Richard Trieu4ae7e972011-09-06 21:13:51 +00006289 QualType compType = UsualArithmeticConversions(LHS, RHS, CompLHSTy);
6290 if (LHS.isInvalid() || RHS.isInvalid())
John Wiegley01296292011-04-08 18:41:53 +00006291 return QualType();
Mike Stump4e1f26a2009-02-19 03:04:26 +00006292
Chris Lattner4d62f422007-12-09 21:53:25 +00006293 // Enforce type constraints: C99 6.5.6p3.
Mike Stump4e1f26a2009-02-19 03:04:26 +00006294
Chris Lattner4d62f422007-12-09 21:53:25 +00006295 // Handle the common case first (both operands are arithmetic).
Richard Trieu4ae7e972011-09-06 21:13:51 +00006296 if (LHS.get()->getType()->isArithmeticType() &&
6297 RHS.get()->getType()->isArithmeticType()) {
Eli Friedman8b7b1b12009-03-28 01:22:36 +00006298 if (CompLHSTy) *CompLHSTy = compType;
Steve Naroffbe4c4d12007-08-24 19:07:16 +00006299 return compType;
Eli Friedman8b7b1b12009-03-28 01:22:36 +00006300 }
Mike Stump11289f42009-09-09 15:08:12 +00006301
David Chisnallfa35df62012-01-16 17:27:18 +00006302 if (LHS.get()->getType()->isAtomicType() &&
6303 RHS.get()->getType()->isArithmeticType()) {
6304 *CompLHSTy = LHS.get()->getType();
6305 return compType;
6306 }
6307
Chris Lattner4d62f422007-12-09 21:53:25 +00006308 // Either ptr - int or ptr - ptr.
Richard Trieu4ae7e972011-09-06 21:13:51 +00006309 if (LHS.get()->getType()->isAnyPointerType()) {
6310 QualType lpointee = LHS.get()->getType()->getPointeeType();
Mike Stump4e1f26a2009-02-19 03:04:26 +00006311
Chris Lattner12bdebb2009-04-24 23:50:08 +00006312 // Diagnose bad cases where we step over interface counts.
Richard Trieu4ae7e972011-09-06 21:13:51 +00006313 if (!checkArithmethicPointerOnNonFragileABI(*this, Loc, LHS.get()))
Chris Lattner12bdebb2009-04-24 23:50:08 +00006314 return QualType();
Mike Stump11289f42009-09-09 15:08:12 +00006315
Chris Lattner4d62f422007-12-09 21:53:25 +00006316 // The result type of a pointer-int computation is the pointer type.
Richard Trieu4ae7e972011-09-06 21:13:51 +00006317 if (RHS.get()->getType()->isIntegerType()) {
6318 if (!checkArithmeticOpPointerOperand(*this, Loc, LHS.get()))
Chandler Carruthc9332212011-06-27 08:02:19 +00006319 return QualType();
Douglas Gregorac1fb652009-03-24 19:52:54 +00006320
Kaelyn Uhrain2e7aa5a2011-08-05 23:18:04 +00006321 // Check array bounds for pointer arithemtic
Richard Smith13f67182011-12-16 19:31:14 +00006322 CheckArrayAccess(LHS.get(), RHS.get(), /*ArraySubscriptExpr*/0,
6323 /*AllowOnePastEnd*/true, /*IndexNegated*/true);
Kaelyn Uhrain2e7aa5a2011-08-05 23:18:04 +00006324
Richard Trieu4ae7e972011-09-06 21:13:51 +00006325 if (CompLHSTy) *CompLHSTy = LHS.get()->getType();
6326 return LHS.get()->getType();
Douglas Gregorac1fb652009-03-24 19:52:54 +00006327 }
Mike Stump4e1f26a2009-02-19 03:04:26 +00006328
Chris Lattner4d62f422007-12-09 21:53:25 +00006329 // Handle pointer-pointer subtractions.
Richard Trieucfc491d2011-08-02 04:35:43 +00006330 if (const PointerType *RHSPTy
Richard Trieu4ae7e972011-09-06 21:13:51 +00006331 = RHS.get()->getType()->getAs<PointerType>()) {
Eli Friedman1974e532008-02-08 01:19:44 +00006332 QualType rpointee = RHSPTy->getPointeeType();
Mike Stump4e1f26a2009-02-19 03:04:26 +00006333
David Blaikiebbafb8a2012-03-11 07:00:24 +00006334 if (getLangOpts().CPlusPlus) {
Eli Friedman168fe152009-05-16 13:54:38 +00006335 // Pointee types must be the same: C++ [expr.add]
6336 if (!Context.hasSameUnqualifiedType(lpointee, rpointee)) {
Richard Trieu4ae7e972011-09-06 21:13:51 +00006337 diagnosePointerIncompatibility(*this, Loc, LHS.get(), RHS.get());
Eli Friedman168fe152009-05-16 13:54:38 +00006338 }
6339 } else {
6340 // Pointee types must be compatible C99 6.5.6p3
6341 if (!Context.typesAreCompatible(
6342 Context.getCanonicalType(lpointee).getUnqualifiedType(),
6343 Context.getCanonicalType(rpointee).getUnqualifiedType())) {
Richard Trieu4ae7e972011-09-06 21:13:51 +00006344 diagnosePointerIncompatibility(*this, Loc, LHS.get(), RHS.get());
Eli Friedman168fe152009-05-16 13:54:38 +00006345 return QualType();
6346 }
Chris Lattner4d62f422007-12-09 21:53:25 +00006347 }
Mike Stump4e1f26a2009-02-19 03:04:26 +00006348
Chandler Carruthc9332212011-06-27 08:02:19 +00006349 if (!checkArithmeticBinOpPointerOperands(*this, Loc,
Richard Trieu4ae7e972011-09-06 21:13:51 +00006350 LHS.get(), RHS.get()))
Chandler Carruthc9332212011-06-27 08:02:19 +00006351 return QualType();
Eli Friedman8b7b1b12009-03-28 01:22:36 +00006352
Richard Trieu4ae7e972011-09-06 21:13:51 +00006353 if (CompLHSTy) *CompLHSTy = LHS.get()->getType();
Chris Lattner4d62f422007-12-09 21:53:25 +00006354 return Context.getPointerDiffType();
6355 }
6356 }
Mike Stump4e1f26a2009-02-19 03:04:26 +00006357
Richard Trieu4ae7e972011-09-06 21:13:51 +00006358 return InvalidOperands(Loc, LHS, RHS);
Steve Naroff218bc2b2007-05-04 21:54:46 +00006359}
6360
Douglas Gregor0bf31402010-10-08 23:50:27 +00006361static bool isScopedEnumerationType(QualType T) {
6362 if (const EnumType *ET = dyn_cast<EnumType>(T))
6363 return ET->getDecl()->isScoped();
6364 return false;
6365}
6366
Richard Trieue4a19fb2011-09-06 21:21:28 +00006367static void DiagnoseBadShiftValues(Sema& S, ExprResult &LHS, ExprResult &RHS,
Chandler Carruth4c6fdca2011-02-23 23:34:11 +00006368 SourceLocation Loc, unsigned Opc,
Richard Trieue4a19fb2011-09-06 21:21:28 +00006369 QualType LHSType) {
Chandler Carruth4c6fdca2011-02-23 23:34:11 +00006370 llvm::APSInt Right;
6371 // Check right/shifter operand
Richard Trieue4a19fb2011-09-06 21:21:28 +00006372 if (RHS.get()->isValueDependent() ||
6373 !RHS.get()->isIntegerConstantExpr(Right, S.Context))
Chandler Carruth4c6fdca2011-02-23 23:34:11 +00006374 return;
6375
6376 if (Right.isNegative()) {
Richard Trieue4a19fb2011-09-06 21:21:28 +00006377 S.DiagRuntimeBehavior(Loc, RHS.get(),
Ted Kremenek63657fe2011-03-01 18:09:31 +00006378 S.PDiag(diag::warn_shift_negative)
Richard Trieue4a19fb2011-09-06 21:21:28 +00006379 << RHS.get()->getSourceRange());
Chandler Carruth4c6fdca2011-02-23 23:34:11 +00006380 return;
6381 }
6382 llvm::APInt LeftBits(Right.getBitWidth(),
Richard Trieue4a19fb2011-09-06 21:21:28 +00006383 S.Context.getTypeSize(LHS.get()->getType()));
Chandler Carruth4c6fdca2011-02-23 23:34:11 +00006384 if (Right.uge(LeftBits)) {
Richard Trieue4a19fb2011-09-06 21:21:28 +00006385 S.DiagRuntimeBehavior(Loc, RHS.get(),
Ted Kremenek26bbc3d2011-03-01 19:13:22 +00006386 S.PDiag(diag::warn_shift_gt_typewidth)
Richard Trieue4a19fb2011-09-06 21:21:28 +00006387 << RHS.get()->getSourceRange());
Chandler Carruth4c6fdca2011-02-23 23:34:11 +00006388 return;
6389 }
6390 if (Opc != BO_Shl)
6391 return;
6392
6393 // When left shifting an ICE which is signed, we can check for overflow which
6394 // according to C++ has undefined behavior ([expr.shift] 5.8/2). Unsigned
6395 // integers have defined behavior modulo one more than the maximum value
6396 // representable in the result type, so never warn for those.
6397 llvm::APSInt Left;
Richard Trieue4a19fb2011-09-06 21:21:28 +00006398 if (LHS.get()->isValueDependent() ||
6399 !LHS.get()->isIntegerConstantExpr(Left, S.Context) ||
6400 LHSType->hasUnsignedIntegerRepresentation())
Chandler Carruth4c6fdca2011-02-23 23:34:11 +00006401 return;
6402 llvm::APInt ResultBits =
6403 static_cast<llvm::APInt&>(Right) + Left.getMinSignedBits();
6404 if (LeftBits.uge(ResultBits))
6405 return;
6406 llvm::APSInt Result = Left.extend(ResultBits.getLimitedValue());
6407 Result = Result.shl(Right);
6408
Ted Kremenek70f05fd2011-06-15 00:54:52 +00006409 // Print the bit representation of the signed integer as an unsigned
6410 // hexadecimal number.
Dylan Noblesmith2c1dd272012-02-05 02:13:05 +00006411 SmallString<40> HexResult;
Ted Kremenek70f05fd2011-06-15 00:54:52 +00006412 Result.toString(HexResult, 16, /*Signed =*/false, /*Literal =*/true);
6413
Chandler Carruth4c6fdca2011-02-23 23:34:11 +00006414 // If we are only missing a sign bit, this is less likely to result in actual
6415 // bugs -- if the result is cast back to an unsigned type, it will have the
6416 // expected value. Thus we place this behind a different warning that can be
6417 // turned off separately if needed.
6418 if (LeftBits == ResultBits - 1) {
Ted Kremenek70f05fd2011-06-15 00:54:52 +00006419 S.Diag(Loc, diag::warn_shift_result_sets_sign_bit)
Richard Trieue4a19fb2011-09-06 21:21:28 +00006420 << HexResult.str() << LHSType
6421 << LHS.get()->getSourceRange() << RHS.get()->getSourceRange();
Chandler Carruth4c6fdca2011-02-23 23:34:11 +00006422 return;
6423 }
6424
6425 S.Diag(Loc, diag::warn_shift_result_gt_typewidth)
Richard Trieue4a19fb2011-09-06 21:21:28 +00006426 << HexResult.str() << Result.getMinSignedBits() << LHSType
6427 << Left.getBitWidth() << LHS.get()->getSourceRange()
6428 << RHS.get()->getSourceRange();
Chandler Carruth4c6fdca2011-02-23 23:34:11 +00006429}
6430
Chris Lattner2a3569b2008-04-07 05:30:13 +00006431// C99 6.5.7
Richard Trieue4a19fb2011-09-06 21:21:28 +00006432QualType Sema::CheckShiftOperands(ExprResult &LHS, ExprResult &RHS,
Richard Trieucfc491d2011-08-02 04:35:43 +00006433 SourceLocation Loc, unsigned Opc,
Richard Trieuba63ce62011-09-09 01:45:06 +00006434 bool IsCompAssign) {
Richard Trieuf8916e12011-09-16 00:53:10 +00006435 checkArithmeticNull(*this, LHS, RHS, Loc, /*isCompare=*/false);
6436
Chris Lattner5c11c412007-12-12 05:47:28 +00006437 // C99 6.5.7p2: Each of the operands shall have integer type.
Richard Trieue4a19fb2011-09-06 21:21:28 +00006438 if (!LHS.get()->getType()->hasIntegerRepresentation() ||
6439 !RHS.get()->getType()->hasIntegerRepresentation())
6440 return InvalidOperands(Loc, LHS, RHS);
Mike Stump4e1f26a2009-02-19 03:04:26 +00006441
Douglas Gregor0bf31402010-10-08 23:50:27 +00006442 // C++0x: Don't allow scoped enums. FIXME: Use something better than
6443 // hasIntegerRepresentation() above instead of this.
Richard Trieue4a19fb2011-09-06 21:21:28 +00006444 if (isScopedEnumerationType(LHS.get()->getType()) ||
6445 isScopedEnumerationType(RHS.get()->getType())) {
6446 return InvalidOperands(Loc, LHS, RHS);
Douglas Gregor0bf31402010-10-08 23:50:27 +00006447 }
6448
Nate Begemane46ee9a2009-10-25 02:26:48 +00006449 // Vector shifts promote their scalar inputs to vector type.
Richard Trieue4a19fb2011-09-06 21:21:28 +00006450 if (LHS.get()->getType()->isVectorType() ||
6451 RHS.get()->getType()->isVectorType())
Richard Trieuba63ce62011-09-09 01:45:06 +00006452 return CheckVectorOperands(LHS, RHS, Loc, IsCompAssign);
Nate Begemane46ee9a2009-10-25 02:26:48 +00006453
Chris Lattner5c11c412007-12-12 05:47:28 +00006454 // Shifts don't perform usual arithmetic conversions, they just do integer
6455 // promotions on each operand. C99 6.5.7p3
Eli Friedman8b7b1b12009-03-28 01:22:36 +00006456
John McCall57cdd882010-12-16 19:28:59 +00006457 // For the LHS, do usual unary conversions, but then reset them away
6458 // if this is a compound assignment.
Richard Trieue4a19fb2011-09-06 21:21:28 +00006459 ExprResult OldLHS = LHS;
6460 LHS = UsualUnaryConversions(LHS.take());
6461 if (LHS.isInvalid())
John Wiegley01296292011-04-08 18:41:53 +00006462 return QualType();
Richard Trieue4a19fb2011-09-06 21:21:28 +00006463 QualType LHSType = LHS.get()->getType();
Richard Trieuba63ce62011-09-09 01:45:06 +00006464 if (IsCompAssign) LHS = OldLHS;
John McCall57cdd882010-12-16 19:28:59 +00006465
6466 // The RHS is simpler.
Richard Trieue4a19fb2011-09-06 21:21:28 +00006467 RHS = UsualUnaryConversions(RHS.take());
6468 if (RHS.isInvalid())
John Wiegley01296292011-04-08 18:41:53 +00006469 return QualType();
Mike Stump4e1f26a2009-02-19 03:04:26 +00006470
Ryan Flynnf53fab82009-08-07 16:20:20 +00006471 // Sanity-check shift operands
Richard Trieue4a19fb2011-09-06 21:21:28 +00006472 DiagnoseBadShiftValues(*this, LHS, RHS, Loc, Opc, LHSType);
Ryan Flynnf53fab82009-08-07 16:20:20 +00006473
Chris Lattner5c11c412007-12-12 05:47:28 +00006474 // "The type of the result is that of the promoted left operand."
Richard Trieue4a19fb2011-09-06 21:21:28 +00006475 return LHSType;
Steve Naroff26c8ea52007-03-21 21:08:52 +00006476}
6477
Chandler Carruth17773fc2010-07-10 12:30:03 +00006478static bool IsWithinTemplateSpecialization(Decl *D) {
6479 if (DeclContext *DC = D->getDeclContext()) {
6480 if (isa<ClassTemplateSpecializationDecl>(DC))
6481 return true;
6482 if (FunctionDecl *FD = dyn_cast<FunctionDecl>(DC))
6483 return FD->isFunctionTemplateSpecialization();
6484 }
6485 return false;
6486}
6487
Richard Trieueea56f72011-09-02 03:48:46 +00006488/// If two different enums are compared, raise a warning.
Richard Trieu1762d7c2011-09-06 21:27:33 +00006489static void checkEnumComparison(Sema &S, SourceLocation Loc, ExprResult &LHS,
6490 ExprResult &RHS) {
6491 QualType LHSStrippedType = LHS.get()->IgnoreParenImpCasts()->getType();
6492 QualType RHSStrippedType = RHS.get()->IgnoreParenImpCasts()->getType();
Richard Trieueea56f72011-09-02 03:48:46 +00006493
6494 const EnumType *LHSEnumType = LHSStrippedType->getAs<EnumType>();
6495 if (!LHSEnumType)
6496 return;
6497 const EnumType *RHSEnumType = RHSStrippedType->getAs<EnumType>();
6498 if (!RHSEnumType)
6499 return;
6500
6501 // Ignore anonymous enums.
6502 if (!LHSEnumType->getDecl()->getIdentifier())
6503 return;
6504 if (!RHSEnumType->getDecl()->getIdentifier())
6505 return;
6506
6507 if (S.Context.hasSameUnqualifiedType(LHSStrippedType, RHSStrippedType))
6508 return;
6509
6510 S.Diag(Loc, diag::warn_comparison_of_mixed_enum_types)
6511 << LHSStrippedType << RHSStrippedType
Richard Trieu1762d7c2011-09-06 21:27:33 +00006512 << LHS.get()->getSourceRange() << RHS.get()->getSourceRange();
Richard Trieueea56f72011-09-02 03:48:46 +00006513}
6514
Richard Trieudd82a5c2011-09-02 02:55:45 +00006515/// \brief Diagnose bad pointer comparisons.
6516static void diagnoseDistinctPointerComparison(Sema &S, SourceLocation Loc,
Richard Trieu1762d7c2011-09-06 21:27:33 +00006517 ExprResult &LHS, ExprResult &RHS,
Richard Trieuba63ce62011-09-09 01:45:06 +00006518 bool IsError) {
6519 S.Diag(Loc, IsError ? diag::err_typecheck_comparison_of_distinct_pointers
Richard Trieudd82a5c2011-09-02 02:55:45 +00006520 : diag::ext_typecheck_comparison_of_distinct_pointers)
Richard Trieu1762d7c2011-09-06 21:27:33 +00006521 << LHS.get()->getType() << RHS.get()->getType()
6522 << LHS.get()->getSourceRange() << RHS.get()->getSourceRange();
Richard Trieudd82a5c2011-09-02 02:55:45 +00006523}
6524
6525/// \brief Returns false if the pointers are converted to a composite type,
6526/// true otherwise.
6527static bool convertPointersToCompositeType(Sema &S, SourceLocation Loc,
Richard Trieu1762d7c2011-09-06 21:27:33 +00006528 ExprResult &LHS, ExprResult &RHS) {
Richard Trieudd82a5c2011-09-02 02:55:45 +00006529 // C++ [expr.rel]p2:
6530 // [...] Pointer conversions (4.10) and qualification
6531 // conversions (4.4) are performed on pointer operands (or on
6532 // a pointer operand and a null pointer constant) to bring
6533 // them to their composite pointer type. [...]
6534 //
6535 // C++ [expr.eq]p1 uses the same notion for (in)equality
6536 // comparisons of pointers.
6537
6538 // C++ [expr.eq]p2:
6539 // In addition, pointers to members can be compared, or a pointer to
6540 // member and a null pointer constant. Pointer to member conversions
6541 // (4.11) and qualification conversions (4.4) are performed to bring
6542 // them to a common type. If one operand is a null pointer constant,
6543 // the common type is the type of the other operand. Otherwise, the
6544 // common type is a pointer to member type similar (4.4) to the type
6545 // of one of the operands, with a cv-qualification signature (4.4)
6546 // that is the union of the cv-qualification signatures of the operand
6547 // types.
6548
Richard Trieu1762d7c2011-09-06 21:27:33 +00006549 QualType LHSType = LHS.get()->getType();
6550 QualType RHSType = RHS.get()->getType();
6551 assert((LHSType->isPointerType() && RHSType->isPointerType()) ||
6552 (LHSType->isMemberPointerType() && RHSType->isMemberPointerType()));
Richard Trieudd82a5c2011-09-02 02:55:45 +00006553
6554 bool NonStandardCompositeType = false;
Richard Trieu48277e52011-09-02 21:44:27 +00006555 bool *BoolPtr = S.isSFINAEContext() ? 0 : &NonStandardCompositeType;
Richard Trieu1762d7c2011-09-06 21:27:33 +00006556 QualType T = S.FindCompositePointerType(Loc, LHS, RHS, BoolPtr);
Richard Trieudd82a5c2011-09-02 02:55:45 +00006557 if (T.isNull()) {
Richard Trieu1762d7c2011-09-06 21:27:33 +00006558 diagnoseDistinctPointerComparison(S, Loc, LHS, RHS, /*isError*/true);
Richard Trieudd82a5c2011-09-02 02:55:45 +00006559 return true;
6560 }
6561
6562 if (NonStandardCompositeType)
6563 S.Diag(Loc, diag::ext_typecheck_comparison_of_distinct_pointers_nonstandard)
Richard Trieu1762d7c2011-09-06 21:27:33 +00006564 << LHSType << RHSType << T << LHS.get()->getSourceRange()
6565 << RHS.get()->getSourceRange();
Richard Trieudd82a5c2011-09-02 02:55:45 +00006566
Richard Trieu1762d7c2011-09-06 21:27:33 +00006567 LHS = S.ImpCastExprToType(LHS.take(), T, CK_BitCast);
6568 RHS = S.ImpCastExprToType(RHS.take(), T, CK_BitCast);
Richard Trieudd82a5c2011-09-02 02:55:45 +00006569 return false;
6570}
6571
6572static void diagnoseFunctionPointerToVoidComparison(Sema &S, SourceLocation Loc,
Richard Trieu1762d7c2011-09-06 21:27:33 +00006573 ExprResult &LHS,
6574 ExprResult &RHS,
Richard Trieuba63ce62011-09-09 01:45:06 +00006575 bool IsError) {
6576 S.Diag(Loc, IsError ? diag::err_typecheck_comparison_of_fptr_to_void
6577 : diag::ext_typecheck_comparison_of_fptr_to_void)
Richard Trieu1762d7c2011-09-06 21:27:33 +00006578 << LHS.get()->getType() << RHS.get()->getType()
6579 << LHS.get()->getSourceRange() << RHS.get()->getSourceRange();
Richard Trieudd82a5c2011-09-02 02:55:45 +00006580}
6581
Douglas Gregor5b07c7e2009-05-04 06:07:12 +00006582// C99 6.5.8, C++ [expr.rel]
Richard Trieub80728f2011-09-06 21:43:51 +00006583QualType Sema::CheckCompareOperands(ExprResult &LHS, ExprResult &RHS,
Richard Trieucfc491d2011-08-02 04:35:43 +00006584 SourceLocation Loc, unsigned OpaqueOpc,
Richard Trieuba63ce62011-09-09 01:45:06 +00006585 bool IsRelational) {
Richard Trieuf8916e12011-09-16 00:53:10 +00006586 checkArithmeticNull(*this, LHS, RHS, Loc, /*isCompare=*/true);
6587
John McCalle3027922010-08-25 11:45:40 +00006588 BinaryOperatorKind Opc = (BinaryOperatorKind) OpaqueOpc;
Douglas Gregor7a5bc762009-04-06 18:45:53 +00006589
Chris Lattner9a152e22009-12-05 05:40:13 +00006590 // Handle vector comparisons separately.
Richard Trieub80728f2011-09-06 21:43:51 +00006591 if (LHS.get()->getType()->isVectorType() ||
6592 RHS.get()->getType()->isVectorType())
Richard Trieuba63ce62011-09-09 01:45:06 +00006593 return CheckVectorCompareOperands(LHS, RHS, Loc, IsRelational);
Mike Stump4e1f26a2009-02-19 03:04:26 +00006594
Richard Trieub80728f2011-09-06 21:43:51 +00006595 QualType LHSType = LHS.get()->getType();
6596 QualType RHSType = RHS.get()->getType();
Benjamin Kramera66aaa92011-09-03 08:46:20 +00006597
Richard Trieub80728f2011-09-06 21:43:51 +00006598 Expr *LHSStripped = LHS.get()->IgnoreParenImpCasts();
6599 Expr *RHSStripped = RHS.get()->IgnoreParenImpCasts();
Chandler Carruth712563b2011-02-17 08:37:06 +00006600
Richard Trieub80728f2011-09-06 21:43:51 +00006601 checkEnumComparison(*this, Loc, LHS, RHS);
Chandler Carruth712563b2011-02-17 08:37:06 +00006602
Richard Trieub80728f2011-09-06 21:43:51 +00006603 if (!LHSType->hasFloatingRepresentation() &&
Richard Trieuba63ce62011-09-09 01:45:06 +00006604 !(LHSType->isBlockPointerType() && IsRelational) &&
Richard Trieub80728f2011-09-06 21:43:51 +00006605 !LHS.get()->getLocStart().isMacroID() &&
6606 !RHS.get()->getLocStart().isMacroID()) {
Chris Lattner222b8bd2009-03-08 19:39:53 +00006607 // For non-floating point types, check for self-comparisons of the form
6608 // x == x, x != x, x < x, etc. These always evaluate to a constant, and
6609 // often indicate logic errors in the program.
Chandler Carruth65a38182010-07-12 06:23:38 +00006610 //
6611 // NOTE: Don't warn about comparison expressions resulting from macro
6612 // expansion. Also don't warn about comparisons which are only self
6613 // comparisons within a template specialization. The warnings should catch
6614 // obvious cases in the definition of the template anyways. The idea is to
6615 // warn when the typed comparison operator will always evaluate to the same
6616 // result.
Chandler Carruth17773fc2010-07-10 12:30:03 +00006617 if (DeclRefExpr* DRL = dyn_cast<DeclRefExpr>(LHSStripped)) {
Douglas Gregorec170db2010-06-08 19:50:34 +00006618 if (DeclRefExpr* DRR = dyn_cast<DeclRefExpr>(RHSStripped)) {
Ted Kremenek853734e2010-09-16 00:03:01 +00006619 if (DRL->getDecl() == DRR->getDecl() &&
Chandler Carruth17773fc2010-07-10 12:30:03 +00006620 !IsWithinTemplateSpecialization(DRL->getDecl())) {
Ted Kremenek3427fac2011-02-23 01:52:04 +00006621 DiagRuntimeBehavior(Loc, 0, PDiag(diag::warn_comparison_always)
Douglas Gregorec170db2010-06-08 19:50:34 +00006622 << 0 // self-
John McCalle3027922010-08-25 11:45:40 +00006623 << (Opc == BO_EQ
6624 || Opc == BO_LE
6625 || Opc == BO_GE));
Richard Trieub80728f2011-09-06 21:43:51 +00006626 } else if (LHSType->isArrayType() && RHSType->isArrayType() &&
Douglas Gregorec170db2010-06-08 19:50:34 +00006627 !DRL->getDecl()->getType()->isReferenceType() &&
6628 !DRR->getDecl()->getType()->isReferenceType()) {
6629 // what is it always going to eval to?
6630 char always_evals_to;
6631 switch(Opc) {
John McCalle3027922010-08-25 11:45:40 +00006632 case BO_EQ: // e.g. array1 == array2
Douglas Gregorec170db2010-06-08 19:50:34 +00006633 always_evals_to = 0; // false
6634 break;
John McCalle3027922010-08-25 11:45:40 +00006635 case BO_NE: // e.g. array1 != array2
Douglas Gregorec170db2010-06-08 19:50:34 +00006636 always_evals_to = 1; // true
6637 break;
6638 default:
6639 // best we can say is 'a constant'
6640 always_evals_to = 2; // e.g. array1 <= array2
6641 break;
6642 }
Ted Kremenek3427fac2011-02-23 01:52:04 +00006643 DiagRuntimeBehavior(Loc, 0, PDiag(diag::warn_comparison_always)
Douglas Gregorec170db2010-06-08 19:50:34 +00006644 << 1 // array
6645 << always_evals_to);
6646 }
6647 }
Chandler Carruth17773fc2010-07-10 12:30:03 +00006648 }
Mike Stump11289f42009-09-09 15:08:12 +00006649
Chris Lattner222b8bd2009-03-08 19:39:53 +00006650 if (isa<CastExpr>(LHSStripped))
6651 LHSStripped = LHSStripped->IgnoreParenCasts();
6652 if (isa<CastExpr>(RHSStripped))
6653 RHSStripped = RHSStripped->IgnoreParenCasts();
Mike Stump11289f42009-09-09 15:08:12 +00006654
Chris Lattner222b8bd2009-03-08 19:39:53 +00006655 // Warn about comparisons against a string constant (unless the other
6656 // operand is null), the user probably wants strcmp.
Douglas Gregor7a5bc762009-04-06 18:45:53 +00006657 Expr *literalString = 0;
6658 Expr *literalStringStripped = 0;
Chris Lattner222b8bd2009-03-08 19:39:53 +00006659 if ((isa<StringLiteral>(LHSStripped) || isa<ObjCEncodeExpr>(LHSStripped)) &&
Kovarththanan Rajaratnamba2c6522010-03-13 10:17:05 +00006660 !RHSStripped->isNullPointerConstant(Context,
Douglas Gregor56751b52009-09-25 04:25:58 +00006661 Expr::NPC_ValueDependentIsNull)) {
Richard Trieub80728f2011-09-06 21:43:51 +00006662 literalString = LHS.get();
Douglas Gregor7a5bc762009-04-06 18:45:53 +00006663 literalStringStripped = LHSStripped;
Mike Stump12b8ce12009-08-04 21:02:39 +00006664 } else if ((isa<StringLiteral>(RHSStripped) ||
6665 isa<ObjCEncodeExpr>(RHSStripped)) &&
Kovarththanan Rajaratnamba2c6522010-03-13 10:17:05 +00006666 !LHSStripped->isNullPointerConstant(Context,
Douglas Gregor56751b52009-09-25 04:25:58 +00006667 Expr::NPC_ValueDependentIsNull)) {
Richard Trieub80728f2011-09-06 21:43:51 +00006668 literalString = RHS.get();
Douglas Gregor7a5bc762009-04-06 18:45:53 +00006669 literalStringStripped = RHSStripped;
6670 }
6671
6672 if (literalString) {
6673 std::string resultComparison;
6674 switch (Opc) {
John McCalle3027922010-08-25 11:45:40 +00006675 case BO_LT: resultComparison = ") < 0"; break;
6676 case BO_GT: resultComparison = ") > 0"; break;
6677 case BO_LE: resultComparison = ") <= 0"; break;
6678 case BO_GE: resultComparison = ") >= 0"; break;
6679 case BO_EQ: resultComparison = ") == 0"; break;
6680 case BO_NE: resultComparison = ") != 0"; break;
David Blaikie83d382b2011-09-23 05:06:16 +00006681 default: llvm_unreachable("Invalid comparison operator");
Douglas Gregor7a5bc762009-04-06 18:45:53 +00006682 }
Kovarththanan Rajaratnamba2c6522010-03-13 10:17:05 +00006683
Ted Kremenek3427fac2011-02-23 01:52:04 +00006684 DiagRuntimeBehavior(Loc, 0,
Douglas Gregor49862b82010-01-12 23:18:54 +00006685 PDiag(diag::warn_stringcompare)
6686 << isa<ObjCEncodeExpr>(literalStringStripped)
Ted Kremenek800b66b2010-04-09 20:26:53 +00006687 << literalString->getSourceRange());
Douglas Gregor7a5bc762009-04-06 18:45:53 +00006688 }
Ted Kremeneke451eae2007-10-29 16:58:49 +00006689 }
Mike Stump4e1f26a2009-02-19 03:04:26 +00006690
Douglas Gregorec170db2010-06-08 19:50:34 +00006691 // C99 6.5.8p3 / C99 6.5.9p4
Richard Trieub80728f2011-09-06 21:43:51 +00006692 if (LHS.get()->getType()->isArithmeticType() &&
6693 RHS.get()->getType()->isArithmeticType()) {
6694 UsualArithmeticConversions(LHS, RHS);
6695 if (LHS.isInvalid() || RHS.isInvalid())
John Wiegley01296292011-04-08 18:41:53 +00006696 return QualType();
6697 }
Douglas Gregorec170db2010-06-08 19:50:34 +00006698 else {
Richard Trieub80728f2011-09-06 21:43:51 +00006699 LHS = UsualUnaryConversions(LHS.take());
6700 if (LHS.isInvalid())
John Wiegley01296292011-04-08 18:41:53 +00006701 return QualType();
6702
Richard Trieub80728f2011-09-06 21:43:51 +00006703 RHS = UsualUnaryConversions(RHS.take());
6704 if (RHS.isInvalid())
John Wiegley01296292011-04-08 18:41:53 +00006705 return QualType();
Douglas Gregorec170db2010-06-08 19:50:34 +00006706 }
6707
Richard Trieub80728f2011-09-06 21:43:51 +00006708 LHSType = LHS.get()->getType();
6709 RHSType = RHS.get()->getType();
Douglas Gregorec170db2010-06-08 19:50:34 +00006710
Douglas Gregorca63811b2008-11-19 03:25:36 +00006711 // The result of comparisons is 'bool' in C++, 'int' in C.
Argyrios Kyrtzidis1bdd6882011-02-18 20:55:15 +00006712 QualType ResultTy = Context.getLogicalOperationType();
Douglas Gregorca63811b2008-11-19 03:25:36 +00006713
Richard Trieuba63ce62011-09-09 01:45:06 +00006714 if (IsRelational) {
Richard Trieub80728f2011-09-06 21:43:51 +00006715 if (LHSType->isRealType() && RHSType->isRealType())
Douglas Gregorca63811b2008-11-19 03:25:36 +00006716 return ResultTy;
Chris Lattnerb620c342007-08-26 01:18:55 +00006717 } else {
Ted Kremeneke2763b02007-10-29 17:13:39 +00006718 // Check for comparisons of floating point operands using != and ==.
Richard Trieub80728f2011-09-06 21:43:51 +00006719 if (LHSType->hasFloatingRepresentation())
6720 CheckFloatComparison(Loc, LHS.get(), RHS.get());
Mike Stump4e1f26a2009-02-19 03:04:26 +00006721
Richard Trieub80728f2011-09-06 21:43:51 +00006722 if (LHSType->isArithmeticType() && RHSType->isArithmeticType())
Douglas Gregorca63811b2008-11-19 03:25:36 +00006723 return ResultTy;
Chris Lattnerb620c342007-08-26 01:18:55 +00006724 }
Mike Stump4e1f26a2009-02-19 03:04:26 +00006725
Richard Trieub80728f2011-09-06 21:43:51 +00006726 bool LHSIsNull = LHS.get()->isNullPointerConstant(Context,
Douglas Gregor56751b52009-09-25 04:25:58 +00006727 Expr::NPC_ValueDependentIsNull);
Richard Trieub80728f2011-09-06 21:43:51 +00006728 bool RHSIsNull = RHS.get()->isNullPointerConstant(Context,
Douglas Gregor56751b52009-09-25 04:25:58 +00006729 Expr::NPC_ValueDependentIsNull);
Mike Stump4e1f26a2009-02-19 03:04:26 +00006730
Douglas Gregorf267edd2010-06-15 21:38:40 +00006731 // All of the following pointer-related warnings are GCC extensions, except
6732 // when handling null pointer constants.
Richard Trieub80728f2011-09-06 21:43:51 +00006733 if (LHSType->isPointerType() && RHSType->isPointerType()) { // C99 6.5.8p2
Chris Lattner3a0702e2008-04-03 05:07:25 +00006734 QualType LCanPointeeTy =
John McCall9320b872011-09-09 05:25:32 +00006735 LHSType->castAs<PointerType>()->getPointeeType().getCanonicalType();
Chris Lattner3a0702e2008-04-03 05:07:25 +00006736 QualType RCanPointeeTy =
John McCall9320b872011-09-09 05:25:32 +00006737 RHSType->castAs<PointerType>()->getPointeeType().getCanonicalType();
Mike Stump4e1f26a2009-02-19 03:04:26 +00006738
David Blaikiebbafb8a2012-03-11 07:00:24 +00006739 if (getLangOpts().CPlusPlus) {
Eli Friedman16c209612009-08-23 00:27:47 +00006740 if (LCanPointeeTy == RCanPointeeTy)
6741 return ResultTy;
Richard Trieuba63ce62011-09-09 01:45:06 +00006742 if (!IsRelational &&
Fariborz Jahanianffc420c2009-12-21 18:19:17 +00006743 (LCanPointeeTy->isVoidType() || RCanPointeeTy->isVoidType())) {
6744 // Valid unless comparison between non-null pointer and function pointer
6745 // This is a gcc extension compatibility comparison.
Douglas Gregorf267edd2010-06-15 21:38:40 +00006746 // In a SFINAE context, we treat this as a hard error to maintain
6747 // conformance with the C++ standard.
Fariborz Jahanianffc420c2009-12-21 18:19:17 +00006748 if ((LCanPointeeTy->isFunctionType() || RCanPointeeTy->isFunctionType())
6749 && !LHSIsNull && !RHSIsNull) {
Richard Trieudd82a5c2011-09-02 02:55:45 +00006750 diagnoseFunctionPointerToVoidComparison(
Richard Trieub80728f2011-09-06 21:43:51 +00006751 *this, Loc, LHS, RHS, /*isError*/ isSFINAEContext());
Douglas Gregorf267edd2010-06-15 21:38:40 +00006752
6753 if (isSFINAEContext())
6754 return QualType();
6755
Richard Trieub80728f2011-09-06 21:43:51 +00006756 RHS = ImpCastExprToType(RHS.take(), LHSType, CK_BitCast);
Fariborz Jahanianffc420c2009-12-21 18:19:17 +00006757 return ResultTy;
6758 }
6759 }
Anders Carlssona95069c2010-11-04 03:17:43 +00006760
Richard Trieub80728f2011-09-06 21:43:51 +00006761 if (convertPointersToCompositeType(*this, Loc, LHS, RHS))
Douglas Gregor5b07c7e2009-05-04 06:07:12 +00006762 return QualType();
Richard Trieudd82a5c2011-09-02 02:55:45 +00006763 else
6764 return ResultTy;
Douglas Gregor5b07c7e2009-05-04 06:07:12 +00006765 }
Eli Friedman16c209612009-08-23 00:27:47 +00006766 // C99 6.5.9p2 and C99 6.5.8p2
6767 if (Context.typesAreCompatible(LCanPointeeTy.getUnqualifiedType(),
6768 RCanPointeeTy.getUnqualifiedType())) {
6769 // Valid unless a relational comparison of function pointers
Richard Trieuba63ce62011-09-09 01:45:06 +00006770 if (IsRelational && LCanPointeeTy->isFunctionType()) {
Eli Friedman16c209612009-08-23 00:27:47 +00006771 Diag(Loc, diag::ext_typecheck_ordered_comparison_of_function_pointers)
Richard Trieub80728f2011-09-06 21:43:51 +00006772 << LHSType << RHSType << LHS.get()->getSourceRange()
6773 << RHS.get()->getSourceRange();
Eli Friedman16c209612009-08-23 00:27:47 +00006774 }
Richard Trieuba63ce62011-09-09 01:45:06 +00006775 } else if (!IsRelational &&
Eli Friedman16c209612009-08-23 00:27:47 +00006776 (LCanPointeeTy->isVoidType() || RCanPointeeTy->isVoidType())) {
6777 // Valid unless comparison between non-null pointer and function pointer
6778 if ((LCanPointeeTy->isFunctionType() || RCanPointeeTy->isFunctionType())
Richard Trieudd82a5c2011-09-02 02:55:45 +00006779 && !LHSIsNull && !RHSIsNull)
Richard Trieub80728f2011-09-06 21:43:51 +00006780 diagnoseFunctionPointerToVoidComparison(*this, Loc, LHS, RHS,
Richard Trieudd82a5c2011-09-02 02:55:45 +00006781 /*isError*/false);
Eli Friedman16c209612009-08-23 00:27:47 +00006782 } else {
6783 // Invalid
Richard Trieub80728f2011-09-06 21:43:51 +00006784 diagnoseDistinctPointerComparison(*this, Loc, LHS, RHS, /*isError*/false);
Steve Naroff75c17232007-06-13 21:41:08 +00006785 }
John McCall7684dde2011-03-11 04:25:25 +00006786 if (LCanPointeeTy != RCanPointeeTy) {
6787 if (LHSIsNull && !RHSIsNull)
Richard Trieub80728f2011-09-06 21:43:51 +00006788 LHS = ImpCastExprToType(LHS.take(), RHSType, CK_BitCast);
John McCall7684dde2011-03-11 04:25:25 +00006789 else
Richard Trieub80728f2011-09-06 21:43:51 +00006790 RHS = ImpCastExprToType(RHS.take(), LHSType, CK_BitCast);
John McCall7684dde2011-03-11 04:25:25 +00006791 }
Douglas Gregorca63811b2008-11-19 03:25:36 +00006792 return ResultTy;
Steve Naroffcdee44c2007-08-16 21:48:38 +00006793 }
Mike Stump11289f42009-09-09 15:08:12 +00006794
David Blaikiebbafb8a2012-03-11 07:00:24 +00006795 if (getLangOpts().CPlusPlus) {
Anders Carlssona95069c2010-11-04 03:17:43 +00006796 // Comparison of nullptr_t with itself.
Richard Trieub80728f2011-09-06 21:43:51 +00006797 if (LHSType->isNullPtrType() && RHSType->isNullPtrType())
Anders Carlssona95069c2010-11-04 03:17:43 +00006798 return ResultTy;
6799
Mike Stump11289f42009-09-09 15:08:12 +00006800 // Comparison of pointers with null pointer constants and equality
Douglas Gregorb00b10e2009-08-24 17:42:35 +00006801 // comparisons of member pointers to null pointer constants.
Mike Stump11289f42009-09-09 15:08:12 +00006802 if (RHSIsNull &&
Richard Trieub80728f2011-09-06 21:43:51 +00006803 ((LHSType->isAnyPointerType() || LHSType->isNullPtrType()) ||
Richard Trieuba63ce62011-09-09 01:45:06 +00006804 (!IsRelational &&
Richard Trieub80728f2011-09-06 21:43:51 +00006805 (LHSType->isMemberPointerType() || LHSType->isBlockPointerType())))) {
6806 RHS = ImpCastExprToType(RHS.take(), LHSType,
6807 LHSType->isMemberPointerType()
John McCalle3027922010-08-25 11:45:40 +00006808 ? CK_NullToMemberPointer
John McCalle84af4e2010-11-13 01:35:44 +00006809 : CK_NullToPointer);
Sebastian Redl576fd422009-05-10 18:38:11 +00006810 return ResultTy;
6811 }
Douglas Gregorb00b10e2009-08-24 17:42:35 +00006812 if (LHSIsNull &&
Richard Trieub80728f2011-09-06 21:43:51 +00006813 ((RHSType->isAnyPointerType() || RHSType->isNullPtrType()) ||
Richard Trieuba63ce62011-09-09 01:45:06 +00006814 (!IsRelational &&
Richard Trieub80728f2011-09-06 21:43:51 +00006815 (RHSType->isMemberPointerType() || RHSType->isBlockPointerType())))) {
6816 LHS = ImpCastExprToType(LHS.take(), RHSType,
6817 RHSType->isMemberPointerType()
John McCalle3027922010-08-25 11:45:40 +00006818 ? CK_NullToMemberPointer
John McCalle84af4e2010-11-13 01:35:44 +00006819 : CK_NullToPointer);
Sebastian Redl576fd422009-05-10 18:38:11 +00006820 return ResultTy;
6821 }
Douglas Gregorb00b10e2009-08-24 17:42:35 +00006822
6823 // Comparison of member pointers.
Richard Trieuba63ce62011-09-09 01:45:06 +00006824 if (!IsRelational &&
Richard Trieub80728f2011-09-06 21:43:51 +00006825 LHSType->isMemberPointerType() && RHSType->isMemberPointerType()) {
6826 if (convertPointersToCompositeType(*this, Loc, LHS, RHS))
Douglas Gregorb00b10e2009-08-24 17:42:35 +00006827 return QualType();
Richard Trieudd82a5c2011-09-02 02:55:45 +00006828 else
6829 return ResultTy;
Douglas Gregorb00b10e2009-08-24 17:42:35 +00006830 }
Douglas Gregor48e6bbf2011-03-01 17:16:20 +00006831
6832 // Handle scoped enumeration types specifically, since they don't promote
6833 // to integers.
Richard Trieub80728f2011-09-06 21:43:51 +00006834 if (LHS.get()->getType()->isEnumeralType() &&
6835 Context.hasSameUnqualifiedType(LHS.get()->getType(),
6836 RHS.get()->getType()))
Douglas Gregor48e6bbf2011-03-01 17:16:20 +00006837 return ResultTy;
Sebastian Redl576fd422009-05-10 18:38:11 +00006838 }
Mike Stump11289f42009-09-09 15:08:12 +00006839
Steve Naroff081c7422008-09-04 15:10:53 +00006840 // Handle block pointer types.
Richard Trieuba63ce62011-09-09 01:45:06 +00006841 if (!IsRelational && LHSType->isBlockPointerType() &&
Richard Trieub80728f2011-09-06 21:43:51 +00006842 RHSType->isBlockPointerType()) {
John McCall9320b872011-09-09 05:25:32 +00006843 QualType lpointee = LHSType->castAs<BlockPointerType>()->getPointeeType();
6844 QualType rpointee = RHSType->castAs<BlockPointerType>()->getPointeeType();
Mike Stump4e1f26a2009-02-19 03:04:26 +00006845
Steve Naroff081c7422008-09-04 15:10:53 +00006846 if (!LHSIsNull && !RHSIsNull &&
Eli Friedmana6638ca2009-06-08 05:08:54 +00006847 !Context.typesAreCompatible(lpointee, rpointee)) {
Chris Lattner377d1f82008-11-18 22:52:51 +00006848 Diag(Loc, diag::err_typecheck_comparison_of_distinct_blocks)
Richard Trieub80728f2011-09-06 21:43:51 +00006849 << LHSType << RHSType << LHS.get()->getSourceRange()
6850 << RHS.get()->getSourceRange();
Steve Naroff081c7422008-09-04 15:10:53 +00006851 }
Richard Trieub80728f2011-09-06 21:43:51 +00006852 RHS = ImpCastExprToType(RHS.take(), LHSType, CK_BitCast);
Douglas Gregorca63811b2008-11-19 03:25:36 +00006853 return ResultTy;
Steve Naroff081c7422008-09-04 15:10:53 +00006854 }
John Wiegley01296292011-04-08 18:41:53 +00006855
Steve Naroffe18f94c2008-09-28 01:11:11 +00006856 // Allow block pointers to be compared with null pointer constants.
Richard Trieuba63ce62011-09-09 01:45:06 +00006857 if (!IsRelational
Richard Trieub80728f2011-09-06 21:43:51 +00006858 && ((LHSType->isBlockPointerType() && RHSType->isPointerType())
6859 || (LHSType->isPointerType() && RHSType->isBlockPointerType()))) {
Steve Naroffe18f94c2008-09-28 01:11:11 +00006860 if (!LHSIsNull && !RHSIsNull) {
Richard Trieub80728f2011-09-06 21:43:51 +00006861 if (!((RHSType->isPointerType() && RHSType->castAs<PointerType>()
Mike Stump1b821b42009-05-07 03:14:14 +00006862 ->getPointeeType()->isVoidType())
Richard Trieub80728f2011-09-06 21:43:51 +00006863 || (LHSType->isPointerType() && LHSType->castAs<PointerType>()
Mike Stump1b821b42009-05-07 03:14:14 +00006864 ->getPointeeType()->isVoidType())))
6865 Diag(Loc, diag::err_typecheck_comparison_of_distinct_blocks)
Richard Trieub80728f2011-09-06 21:43:51 +00006866 << LHSType << RHSType << LHS.get()->getSourceRange()
6867 << RHS.get()->getSourceRange();
Steve Naroffe18f94c2008-09-28 01:11:11 +00006868 }
John McCall7684dde2011-03-11 04:25:25 +00006869 if (LHSIsNull && !RHSIsNull)
John McCall9320b872011-09-09 05:25:32 +00006870 LHS = ImpCastExprToType(LHS.take(), RHSType,
6871 RHSType->isPointerType() ? CK_BitCast
6872 : CK_AnyPointerToBlockPointerCast);
John McCall7684dde2011-03-11 04:25:25 +00006873 else
John McCall9320b872011-09-09 05:25:32 +00006874 RHS = ImpCastExprToType(RHS.take(), LHSType,
6875 LHSType->isPointerType() ? CK_BitCast
6876 : CK_AnyPointerToBlockPointerCast);
Douglas Gregorca63811b2008-11-19 03:25:36 +00006877 return ResultTy;
Steve Naroffe18f94c2008-09-28 01:11:11 +00006878 }
Steve Naroff081c7422008-09-04 15:10:53 +00006879
Richard Trieub80728f2011-09-06 21:43:51 +00006880 if (LHSType->isObjCObjectPointerType() ||
6881 RHSType->isObjCObjectPointerType()) {
6882 const PointerType *LPT = LHSType->getAs<PointerType>();
6883 const PointerType *RPT = RHSType->getAs<PointerType>();
John McCall7684dde2011-03-11 04:25:25 +00006884 if (LPT || RPT) {
6885 bool LPtrToVoid = LPT ? LPT->getPointeeType()->isVoidType() : false;
6886 bool RPtrToVoid = RPT ? RPT->getPointeeType()->isVoidType() : false;
Mike Stump4e1f26a2009-02-19 03:04:26 +00006887
Steve Naroff753567f2008-11-17 19:49:16 +00006888 if (!LPtrToVoid && !RPtrToVoid &&
Richard Trieub80728f2011-09-06 21:43:51 +00006889 !Context.typesAreCompatible(LHSType, RHSType)) {
6890 diagnoseDistinctPointerComparison(*this, Loc, LHS, RHS,
Richard Trieudd82a5c2011-09-02 02:55:45 +00006891 /*isError*/false);
Steve Naroff1d4a9a32008-10-27 10:33:19 +00006892 }
John McCall7684dde2011-03-11 04:25:25 +00006893 if (LHSIsNull && !RHSIsNull)
John McCall9320b872011-09-09 05:25:32 +00006894 LHS = ImpCastExprToType(LHS.take(), RHSType,
6895 RPT ? CK_BitCast :CK_CPointerToObjCPointerCast);
John McCall7684dde2011-03-11 04:25:25 +00006896 else
John McCall9320b872011-09-09 05:25:32 +00006897 RHS = ImpCastExprToType(RHS.take(), LHSType,
6898 LPT ? CK_BitCast :CK_CPointerToObjCPointerCast);
Douglas Gregorca63811b2008-11-19 03:25:36 +00006899 return ResultTy;
Steve Naroffea54d9e2008-10-20 18:19:10 +00006900 }
Richard Trieub80728f2011-09-06 21:43:51 +00006901 if (LHSType->isObjCObjectPointerType() &&
6902 RHSType->isObjCObjectPointerType()) {
6903 if (!Context.areComparableObjCPointerTypes(LHSType, RHSType))
6904 diagnoseDistinctPointerComparison(*this, Loc, LHS, RHS,
Richard Trieudd82a5c2011-09-02 02:55:45 +00006905 /*isError*/false);
John McCall7684dde2011-03-11 04:25:25 +00006906 if (LHSIsNull && !RHSIsNull)
Richard Trieub80728f2011-09-06 21:43:51 +00006907 LHS = ImpCastExprToType(LHS.take(), RHSType, CK_BitCast);
John McCall7684dde2011-03-11 04:25:25 +00006908 else
Richard Trieub80728f2011-09-06 21:43:51 +00006909 RHS = ImpCastExprToType(RHS.take(), LHSType, CK_BitCast);
Douglas Gregorca63811b2008-11-19 03:25:36 +00006910 return ResultTy;
Steve Naroffb788d9b2008-06-03 14:04:54 +00006911 }
Fariborz Jahanian134cbef2007-12-20 01:06:58 +00006912 }
Richard Trieub80728f2011-09-06 21:43:51 +00006913 if ((LHSType->isAnyPointerType() && RHSType->isIntegerType()) ||
6914 (LHSType->isIntegerType() && RHSType->isAnyPointerType())) {
Chris Lattnerd99bd522009-08-23 00:03:44 +00006915 unsigned DiagID = 0;
Douglas Gregorf267edd2010-06-15 21:38:40 +00006916 bool isError = false;
Richard Trieub80728f2011-09-06 21:43:51 +00006917 if ((LHSIsNull && LHSType->isIntegerType()) ||
6918 (RHSIsNull && RHSType->isIntegerType())) {
David Blaikiebbafb8a2012-03-11 07:00:24 +00006919 if (IsRelational && !getLangOpts().CPlusPlus)
Chris Lattnerd99bd522009-08-23 00:03:44 +00006920 DiagID = diag::ext_typecheck_ordered_comparison_of_pointer_and_zero;
David Blaikiebbafb8a2012-03-11 07:00:24 +00006921 } else if (IsRelational && !getLangOpts().CPlusPlus)
Chris Lattnerd99bd522009-08-23 00:03:44 +00006922 DiagID = diag::ext_typecheck_ordered_comparison_of_pointer_integer;
David Blaikiebbafb8a2012-03-11 07:00:24 +00006923 else if (getLangOpts().CPlusPlus) {
Douglas Gregorf267edd2010-06-15 21:38:40 +00006924 DiagID = diag::err_typecheck_comparison_of_pointer_integer;
6925 isError = true;
6926 } else
Chris Lattnerd99bd522009-08-23 00:03:44 +00006927 DiagID = diag::ext_typecheck_comparison_of_pointer_integer;
Mike Stump11289f42009-09-09 15:08:12 +00006928
Chris Lattnerd99bd522009-08-23 00:03:44 +00006929 if (DiagID) {
Chris Lattnerf8344db2009-08-22 18:58:31 +00006930 Diag(Loc, DiagID)
Richard Trieub80728f2011-09-06 21:43:51 +00006931 << LHSType << RHSType << LHS.get()->getSourceRange()
6932 << RHS.get()->getSourceRange();
Douglas Gregorf267edd2010-06-15 21:38:40 +00006933 if (isError)
6934 return QualType();
Chris Lattnerf8344db2009-08-22 18:58:31 +00006935 }
Douglas Gregorf267edd2010-06-15 21:38:40 +00006936
Richard Trieub80728f2011-09-06 21:43:51 +00006937 if (LHSType->isIntegerType())
6938 LHS = ImpCastExprToType(LHS.take(), RHSType,
John McCalle84af4e2010-11-13 01:35:44 +00006939 LHSIsNull ? CK_NullToPointer : CK_IntegralToPointer);
Chris Lattnerd99bd522009-08-23 00:03:44 +00006940 else
Richard Trieub80728f2011-09-06 21:43:51 +00006941 RHS = ImpCastExprToType(RHS.take(), LHSType,
John McCalle84af4e2010-11-13 01:35:44 +00006942 RHSIsNull ? CK_NullToPointer : CK_IntegralToPointer);
Douglas Gregorca63811b2008-11-19 03:25:36 +00006943 return ResultTy;
Steve Naroff043d45d2007-05-15 02:32:35 +00006944 }
Douglas Gregorf267edd2010-06-15 21:38:40 +00006945
Steve Naroff4b191572008-09-04 16:56:14 +00006946 // Handle block pointers.
Richard Trieuba63ce62011-09-09 01:45:06 +00006947 if (!IsRelational && RHSIsNull
Richard Trieub80728f2011-09-06 21:43:51 +00006948 && LHSType->isBlockPointerType() && RHSType->isIntegerType()) {
6949 RHS = ImpCastExprToType(RHS.take(), LHSType, CK_NullToPointer);
Douglas Gregorca63811b2008-11-19 03:25:36 +00006950 return ResultTy;
Steve Naroff4b191572008-09-04 16:56:14 +00006951 }
Richard Trieuba63ce62011-09-09 01:45:06 +00006952 if (!IsRelational && LHSIsNull
Richard Trieub80728f2011-09-06 21:43:51 +00006953 && LHSType->isIntegerType() && RHSType->isBlockPointerType()) {
6954 LHS = ImpCastExprToType(LHS.take(), RHSType, CK_NullToPointer);
Douglas Gregorca63811b2008-11-19 03:25:36 +00006955 return ResultTy;
Steve Naroff4b191572008-09-04 16:56:14 +00006956 }
Douglas Gregor48e6bbf2011-03-01 17:16:20 +00006957
Richard Trieub80728f2011-09-06 21:43:51 +00006958 return InvalidOperands(Loc, LHS, RHS);
Steve Naroff26c8ea52007-03-21 21:08:52 +00006959}
6960
Tanya Lattner20248222012-01-16 21:02:28 +00006961
6962// Return a signed type that is of identical size and number of elements.
6963// For floating point vectors, return an integer type of identical size
6964// and number of elements.
6965QualType Sema::GetSignedVectorType(QualType V) {
6966 const VectorType *VTy = V->getAs<VectorType>();
6967 unsigned TypeSize = Context.getTypeSize(VTy->getElementType());
6968 if (TypeSize == Context.getTypeSize(Context.CharTy))
6969 return Context.getExtVectorType(Context.CharTy, VTy->getNumElements());
6970 else if (TypeSize == Context.getTypeSize(Context.ShortTy))
6971 return Context.getExtVectorType(Context.ShortTy, VTy->getNumElements());
6972 else if (TypeSize == Context.getTypeSize(Context.IntTy))
6973 return Context.getExtVectorType(Context.IntTy, VTy->getNumElements());
6974 else if (TypeSize == Context.getTypeSize(Context.LongTy))
6975 return Context.getExtVectorType(Context.LongTy, VTy->getNumElements());
6976 assert(TypeSize == Context.getTypeSize(Context.LongLongTy) &&
6977 "Unhandled vector element size in vector compare");
6978 return Context.getExtVectorType(Context.LongLongTy, VTy->getNumElements());
6979}
6980
Nate Begeman191a6b12008-07-14 18:02:46 +00006981/// CheckVectorCompareOperands - vector comparisons are a clang extension that
Mike Stump4e1f26a2009-02-19 03:04:26 +00006982/// operates on extended vector types. Instead of producing an IntTy result,
Nate Begeman191a6b12008-07-14 18:02:46 +00006983/// like a scalar comparison, a vector comparison produces a vector of integer
6984/// types.
Richard Trieubcce2f72011-09-07 01:19:57 +00006985QualType Sema::CheckVectorCompareOperands(ExprResult &LHS, ExprResult &RHS,
Chris Lattner326f7572008-11-18 01:30:42 +00006986 SourceLocation Loc,
Richard Trieuba63ce62011-09-09 01:45:06 +00006987 bool IsRelational) {
Nate Begeman191a6b12008-07-14 18:02:46 +00006988 // Check to make sure we're operating on vectors of the same type and width,
6989 // Allowing one side to be a scalar of element type.
Richard Trieubcce2f72011-09-07 01:19:57 +00006990 QualType vType = CheckVectorOperands(LHS, RHS, Loc, /*isCompAssign*/false);
Nate Begeman191a6b12008-07-14 18:02:46 +00006991 if (vType.isNull())
6992 return vType;
Mike Stump4e1f26a2009-02-19 03:04:26 +00006993
Richard Trieubcce2f72011-09-07 01:19:57 +00006994 QualType LHSType = LHS.get()->getType();
Mike Stump4e1f26a2009-02-19 03:04:26 +00006995
Anton Yartsev530deb92011-03-27 15:36:07 +00006996 // If AltiVec, the comparison results in a numeric type, i.e.
6997 // bool for C++, int for C
Anton Yartsev93900c72011-03-28 21:00:05 +00006998 if (vType->getAs<VectorType>()->getVectorKind() == VectorType::AltiVecVector)
Anton Yartsev530deb92011-03-27 15:36:07 +00006999 return Context.getLogicalOperationType();
7000
Nate Begeman191a6b12008-07-14 18:02:46 +00007001 // For non-floating point types, check for self-comparisons of the form
7002 // x == x, x != x, x < x, etc. These always evaluate to a constant, and
7003 // often indicate logic errors in the program.
Richard Trieubcce2f72011-09-07 01:19:57 +00007004 if (!LHSType->hasFloatingRepresentation()) {
Richard Smith508ebf32011-10-28 03:31:48 +00007005 if (DeclRefExpr* DRL
7006 = dyn_cast<DeclRefExpr>(LHS.get()->IgnoreParenImpCasts()))
7007 if (DeclRefExpr* DRR
7008 = dyn_cast<DeclRefExpr>(RHS.get()->IgnoreParenImpCasts()))
Nate Begeman191a6b12008-07-14 18:02:46 +00007009 if (DRL->getDecl() == DRR->getDecl())
Ted Kremenek3427fac2011-02-23 01:52:04 +00007010 DiagRuntimeBehavior(Loc, 0,
Douglas Gregorec170db2010-06-08 19:50:34 +00007011 PDiag(diag::warn_comparison_always)
7012 << 0 // self-
7013 << 2 // "a constant"
7014 );
Nate Begeman191a6b12008-07-14 18:02:46 +00007015 }
Mike Stump4e1f26a2009-02-19 03:04:26 +00007016
Nate Begeman191a6b12008-07-14 18:02:46 +00007017 // Check for comparisons of floating point operands using != and ==.
Richard Trieuba63ce62011-09-09 01:45:06 +00007018 if (!IsRelational && LHSType->hasFloatingRepresentation()) {
David Blaikieca043222012-01-16 05:16:03 +00007019 assert (RHS.get()->getType()->hasFloatingRepresentation());
Richard Trieubcce2f72011-09-07 01:19:57 +00007020 CheckFloatComparison(Loc, LHS.get(), RHS.get());
Nate Begeman191a6b12008-07-14 18:02:46 +00007021 }
Tanya Lattner20248222012-01-16 21:02:28 +00007022
7023 // Return a signed type for the vector.
7024 return GetSignedVectorType(LHSType);
7025}
Mike Stump4e1f26a2009-02-19 03:04:26 +00007026
Tanya Lattner3dd33b22012-01-19 01:16:16 +00007027QualType Sema::CheckVectorLogicalOperands(ExprResult &LHS, ExprResult &RHS,
7028 SourceLocation Loc) {
Tanya Lattner20248222012-01-16 21:02:28 +00007029 // Ensure that either both operands are of the same vector type, or
7030 // one operand is of a vector type and the other is of its element type.
7031 QualType vType = CheckVectorOperands(LHS, RHS, Loc, false);
7032 if (vType.isNull() || vType->isFloatingType())
7033 return InvalidOperands(Loc, LHS, RHS);
7034
7035 return GetSignedVectorType(LHS.get()->getType());
Nate Begeman191a6b12008-07-14 18:02:46 +00007036}
7037
Steve Naroff218bc2b2007-05-04 21:54:46 +00007038inline QualType Sema::CheckBitwiseOperands(
Richard Trieuba63ce62011-09-09 01:45:06 +00007039 ExprResult &LHS, ExprResult &RHS, SourceLocation Loc, bool IsCompAssign) {
Richard Trieuf8916e12011-09-16 00:53:10 +00007040 checkArithmeticNull(*this, LHS, RHS, Loc, /*isCompare=*/false);
7041
Richard Trieubcce2f72011-09-07 01:19:57 +00007042 if (LHS.get()->getType()->isVectorType() ||
7043 RHS.get()->getType()->isVectorType()) {
7044 if (LHS.get()->getType()->hasIntegerRepresentation() &&
7045 RHS.get()->getType()->hasIntegerRepresentation())
Richard Trieuba63ce62011-09-09 01:45:06 +00007046 return CheckVectorOperands(LHS, RHS, Loc, IsCompAssign);
Douglas Gregor5cc2c8b2010-07-23 15:58:24 +00007047
Richard Trieubcce2f72011-09-07 01:19:57 +00007048 return InvalidOperands(Loc, LHS, RHS);
Douglas Gregor5cc2c8b2010-07-23 15:58:24 +00007049 }
Steve Naroffb8ea4fb2007-07-13 23:32:42 +00007050
Richard Trieubcce2f72011-09-07 01:19:57 +00007051 ExprResult LHSResult = Owned(LHS), RHSResult = Owned(RHS);
7052 QualType compType = UsualArithmeticConversions(LHSResult, RHSResult,
Richard Trieuba63ce62011-09-09 01:45:06 +00007053 IsCompAssign);
Richard Trieubcce2f72011-09-07 01:19:57 +00007054 if (LHSResult.isInvalid() || RHSResult.isInvalid())
John Wiegley01296292011-04-08 18:41:53 +00007055 return QualType();
Richard Trieubcce2f72011-09-07 01:19:57 +00007056 LHS = LHSResult.take();
7057 RHS = RHSResult.take();
Mike Stump4e1f26a2009-02-19 03:04:26 +00007058
Richard Trieubcce2f72011-09-07 01:19:57 +00007059 if (LHS.get()->getType()->isIntegralOrUnscopedEnumerationType() &&
7060 RHS.get()->getType()->isIntegralOrUnscopedEnumerationType())
Steve Naroffbe4c4d12007-08-24 19:07:16 +00007061 return compType;
Richard Trieubcce2f72011-09-07 01:19:57 +00007062 return InvalidOperands(Loc, LHS, RHS);
Steve Naroff26c8ea52007-03-21 21:08:52 +00007063}
7064
Steve Naroff218bc2b2007-05-04 21:54:46 +00007065inline QualType Sema::CheckLogicalOperands( // C99 6.5.[13,14]
Richard Trieubcce2f72011-09-07 01:19:57 +00007066 ExprResult &LHS, ExprResult &RHS, SourceLocation Loc, unsigned Opc) {
Chris Lattner8406c512010-07-13 19:41:32 +00007067
Tanya Lattner20248222012-01-16 21:02:28 +00007068 // Check vector operands differently.
7069 if (LHS.get()->getType()->isVectorType() || RHS.get()->getType()->isVectorType())
7070 return CheckVectorLogicalOperands(LHS, RHS, Loc);
7071
Chris Lattner8406c512010-07-13 19:41:32 +00007072 // Diagnose cases where the user write a logical and/or but probably meant a
7073 // bitwise one. We do this when the LHS is a non-bool integer and the RHS
7074 // is a constant.
Richard Trieubcce2f72011-09-07 01:19:57 +00007075 if (LHS.get()->getType()->isIntegerType() &&
7076 !LHS.get()->getType()->isBooleanType() &&
7077 RHS.get()->getType()->isIntegerType() && !RHS.get()->isValueDependent() &&
Richard Trieucfe39262011-07-15 00:00:51 +00007078 // Don't warn in macros or template instantiations.
7079 !Loc.isMacroID() && ActiveTemplateInstantiations.empty()) {
Chris Lattner938533d2010-07-24 01:10:11 +00007080 // If the RHS can be constant folded, and if it constant folds to something
7081 // that isn't 0 or 1 (which indicate a potential logical operation that
7082 // happened to fold to true/false) then warn.
Chandler Carruthe54ff6c2011-05-31 05:41:42 +00007083 // Parens on the RHS are ignored.
Richard Smith00ab3ae2011-10-16 23:01:09 +00007084 llvm::APSInt Result;
7085 if (RHS.get()->EvaluateAsInt(Result, Context))
David Blaikiebbafb8a2012-03-11 07:00:24 +00007086 if ((getLangOpts().Bool && !RHS.get()->getType()->isBooleanType()) ||
Richard Smith00ab3ae2011-10-16 23:01:09 +00007087 (Result != 0 && Result != 1)) {
Chandler Carruthe54ff6c2011-05-31 05:41:42 +00007088 Diag(Loc, diag::warn_logical_instead_of_bitwise)
Richard Trieubcce2f72011-09-07 01:19:57 +00007089 << RHS.get()->getSourceRange()
Matt Beaumont-Gay0a0ba9d2011-08-15 17:50:06 +00007090 << (Opc == BO_LAnd ? "&&" : "||");
7091 // Suggest replacing the logical operator with the bitwise version
7092 Diag(Loc, diag::note_logical_instead_of_bitwise_change_operator)
7093 << (Opc == BO_LAnd ? "&" : "|")
7094 << FixItHint::CreateReplacement(SourceRange(
7095 Loc, Lexer::getLocForEndOfToken(Loc, 0, getSourceManager(),
David Blaikiebbafb8a2012-03-11 07:00:24 +00007096 getLangOpts())),
Matt Beaumont-Gay0a0ba9d2011-08-15 17:50:06 +00007097 Opc == BO_LAnd ? "&" : "|");
7098 if (Opc == BO_LAnd)
7099 // Suggest replacing "Foo() && kNonZero" with "Foo()"
7100 Diag(Loc, diag::note_logical_instead_of_bitwise_remove_constant)
7101 << FixItHint::CreateRemoval(
7102 SourceRange(
Richard Trieubcce2f72011-09-07 01:19:57 +00007103 Lexer::getLocForEndOfToken(LHS.get()->getLocEnd(),
Matt Beaumont-Gay0a0ba9d2011-08-15 17:50:06 +00007104 0, getSourceManager(),
David Blaikiebbafb8a2012-03-11 07:00:24 +00007105 getLangOpts()),
Richard Trieubcce2f72011-09-07 01:19:57 +00007106 RHS.get()->getLocEnd()));
Matt Beaumont-Gay0a0ba9d2011-08-15 17:50:06 +00007107 }
Chris Lattner938533d2010-07-24 01:10:11 +00007108 }
Chris Lattner8406c512010-07-13 19:41:32 +00007109
David Blaikiebbafb8a2012-03-11 07:00:24 +00007110 if (!Context.getLangOpts().CPlusPlus) {
Richard Trieubcce2f72011-09-07 01:19:57 +00007111 LHS = UsualUnaryConversions(LHS.take());
7112 if (LHS.isInvalid())
John Wiegley01296292011-04-08 18:41:53 +00007113 return QualType();
Mike Stump4e1f26a2009-02-19 03:04:26 +00007114
Richard Trieubcce2f72011-09-07 01:19:57 +00007115 RHS = UsualUnaryConversions(RHS.take());
7116 if (RHS.isInvalid())
John Wiegley01296292011-04-08 18:41:53 +00007117 return QualType();
7118
Richard Trieubcce2f72011-09-07 01:19:57 +00007119 if (!LHS.get()->getType()->isScalarType() ||
7120 !RHS.get()->getType()->isScalarType())
7121 return InvalidOperands(Loc, LHS, RHS);
Kovarththanan Rajaratnamba2c6522010-03-13 10:17:05 +00007122
Anders Carlsson2e7bc112009-11-23 21:47:44 +00007123 return Context.IntTy;
Anders Carlsson35a99d92009-10-16 01:44:21 +00007124 }
Kovarththanan Rajaratnamba2c6522010-03-13 10:17:05 +00007125
John McCall4a2429a2010-06-04 00:29:51 +00007126 // The following is safe because we only use this method for
7127 // non-overloadable operands.
7128
Anders Carlsson2e7bc112009-11-23 21:47:44 +00007129 // C++ [expr.log.and]p1
7130 // C++ [expr.log.or]p1
John McCall4a2429a2010-06-04 00:29:51 +00007131 // The operands are both contextually converted to type bool.
Richard Trieubcce2f72011-09-07 01:19:57 +00007132 ExprResult LHSRes = PerformContextuallyConvertToBool(LHS.get());
7133 if (LHSRes.isInvalid())
7134 return InvalidOperands(Loc, LHS, RHS);
7135 LHS = move(LHSRes);
John Wiegley01296292011-04-08 18:41:53 +00007136
Richard Trieubcce2f72011-09-07 01:19:57 +00007137 ExprResult RHSRes = PerformContextuallyConvertToBool(RHS.get());
7138 if (RHSRes.isInvalid())
7139 return InvalidOperands(Loc, LHS, RHS);
7140 RHS = move(RHSRes);
Kovarththanan Rajaratnamba2c6522010-03-13 10:17:05 +00007141
Anders Carlsson2e7bc112009-11-23 21:47:44 +00007142 // C++ [expr.log.and]p2
7143 // C++ [expr.log.or]p2
7144 // The result is a bool.
7145 return Context.BoolTy;
Steve Naroffae4143e2007-04-26 20:39:23 +00007146}
7147
Fariborz Jahanian8e1555c2009-01-12 19:55:42 +00007148/// IsReadonlyProperty - Verify that otherwise a valid l-value expression
7149/// is a read-only property; return true if so. A readonly property expression
7150/// depends on various declarations and thus must be treated specially.
7151///
Mike Stump11289f42009-09-09 15:08:12 +00007152static bool IsReadonlyProperty(Expr *E, Sema &S) {
John McCall526ab472011-10-25 17:37:35 +00007153 const ObjCPropertyRefExpr *PropExpr = dyn_cast<ObjCPropertyRefExpr>(E);
7154 if (!PropExpr) return false;
7155 if (PropExpr->isImplicitProperty()) return false;
John McCallb7bd14f2010-12-02 01:19:52 +00007156
John McCall526ab472011-10-25 17:37:35 +00007157 ObjCPropertyDecl *PDecl = PropExpr->getExplicitProperty();
7158 QualType BaseType = PropExpr->isSuperReceiver() ?
John McCallb7bd14f2010-12-02 01:19:52 +00007159 PropExpr->getSuperReceiverType() :
Fariborz Jahanian681c0752010-10-14 16:04:05 +00007160 PropExpr->getBase()->getType();
7161
John McCall526ab472011-10-25 17:37:35 +00007162 if (const ObjCObjectPointerType *OPT =
7163 BaseType->getAsObjCInterfacePointerType())
7164 if (ObjCInterfaceDecl *IFace = OPT->getInterfaceDecl())
7165 if (S.isPropertyReadonly(PDecl, IFace))
7166 return true;
Fariborz Jahanian8e1555c2009-01-12 19:55:42 +00007167 return false;
7168}
7169
Fariborz Jahanian071caef2011-03-26 19:48:30 +00007170static bool IsReadonlyMessage(Expr *E, Sema &S) {
John McCall526ab472011-10-25 17:37:35 +00007171 const MemberExpr *ME = dyn_cast<MemberExpr>(E);
7172 if (!ME) return false;
7173 if (!isa<FieldDecl>(ME->getMemberDecl())) return false;
7174 ObjCMessageExpr *Base =
7175 dyn_cast<ObjCMessageExpr>(ME->getBase()->IgnoreParenImpCasts());
7176 if (!Base) return false;
7177 return Base->getMethodDecl() != 0;
Fariborz Jahanian071caef2011-03-26 19:48:30 +00007178}
7179
John McCall5fa2ef42012-03-13 00:37:01 +00007180/// Is the given expression (which must be 'const') a reference to a
7181/// variable which was originally non-const, but which has become
7182/// 'const' due to being captured within a block?
7183enum NonConstCaptureKind { NCCK_None, NCCK_Block, NCCK_Lambda };
7184static NonConstCaptureKind isReferenceToNonConstCapture(Sema &S, Expr *E) {
7185 assert(E->isLValue() && E->getType().isConstQualified());
7186 E = E->IgnoreParens();
7187
7188 // Must be a reference to a declaration from an enclosing scope.
7189 DeclRefExpr *DRE = dyn_cast<DeclRefExpr>(E);
7190 if (!DRE) return NCCK_None;
7191 if (!DRE->refersToEnclosingLocal()) return NCCK_None;
7192
7193 // The declaration must be a variable which is not declared 'const'.
7194 VarDecl *var = dyn_cast<VarDecl>(DRE->getDecl());
7195 if (!var) return NCCK_None;
7196 if (var->getType().isConstQualified()) return NCCK_None;
7197 assert(var->hasLocalStorage() && "capture added 'const' to non-local?");
7198
7199 // Decide whether the first capture was for a block or a lambda.
7200 DeclContext *DC = S.CurContext;
7201 while (DC->getParent() != var->getDeclContext())
7202 DC = DC->getParent();
7203 return (isa<BlockDecl>(DC) ? NCCK_Block : NCCK_Lambda);
7204}
7205
Chris Lattner30bd3272008-11-18 01:22:49 +00007206/// CheckForModifiableLvalue - Verify that E is a modifiable lvalue. If not,
7207/// emit an error and return true. If so, return false.
7208static bool CheckForModifiableLvalue(Expr *E, SourceLocation Loc, Sema &S) {
Fariborz Jahanianca5c5972012-04-10 17:30:10 +00007209 assert(!E->hasPlaceholderType(BuiltinType::PseudoObject));
Daniel Dunbarc2223ab2009-04-15 00:08:05 +00007210 SourceLocation OrigLoc = Loc;
Mike Stump11289f42009-09-09 15:08:12 +00007211 Expr::isModifiableLvalueResult IsLV = E->isModifiableLvalue(S.Context,
Daniel Dunbarc2223ab2009-04-15 00:08:05 +00007212 &Loc);
Fariborz Jahanian8e1555c2009-01-12 19:55:42 +00007213 if (IsLV == Expr::MLV_Valid && IsReadonlyProperty(E, S))
7214 IsLV = Expr::MLV_ReadonlyProperty;
Fariborz Jahanian071caef2011-03-26 19:48:30 +00007215 else if (IsLV == Expr::MLV_ClassTemporary && IsReadonlyMessage(E, S))
7216 IsLV = Expr::MLV_InvalidMessageExpression;
Chris Lattner30bd3272008-11-18 01:22:49 +00007217 if (IsLV == Expr::MLV_Valid)
7218 return false;
Mike Stump4e1f26a2009-02-19 03:04:26 +00007219
Chris Lattner30bd3272008-11-18 01:22:49 +00007220 unsigned Diag = 0;
7221 bool NeedType = false;
7222 switch (IsLV) { // C99 6.5.16p2
John McCall31168b02011-06-15 23:02:42 +00007223 case Expr::MLV_ConstQualified:
7224 Diag = diag::err_typecheck_assign_const;
7225
John McCall5fa2ef42012-03-13 00:37:01 +00007226 // Use a specialized diagnostic when we're assigning to an object
7227 // from an enclosing function or block.
7228 if (NonConstCaptureKind NCCK = isReferenceToNonConstCapture(S, E)) {
7229 if (NCCK == NCCK_Block)
7230 Diag = diag::err_block_decl_ref_not_modifiable_lvalue;
7231 else
7232 Diag = diag::err_lambda_decl_ref_not_modifiable_lvalue;
7233 break;
7234 }
7235
John McCalld4631322011-06-17 06:42:21 +00007236 // In ARC, use some specialized diagnostics for occasions where we
7237 // infer 'const'. These are always pseudo-strong variables.
David Blaikiebbafb8a2012-03-11 07:00:24 +00007238 if (S.getLangOpts().ObjCAutoRefCount) {
John McCall31168b02011-06-15 23:02:42 +00007239 DeclRefExpr *declRef = dyn_cast<DeclRefExpr>(E->IgnoreParenCasts());
7240 if (declRef && isa<VarDecl>(declRef->getDecl())) {
7241 VarDecl *var = cast<VarDecl>(declRef->getDecl());
7242
John McCalld4631322011-06-17 06:42:21 +00007243 // Use the normal diagnostic if it's pseudo-__strong but the
7244 // user actually wrote 'const'.
7245 if (var->isARCPseudoStrong() &&
7246 (!var->getTypeSourceInfo() ||
7247 !var->getTypeSourceInfo()->getType().isConstQualified())) {
7248 // There are two pseudo-strong cases:
7249 // - self
John McCall31168b02011-06-15 23:02:42 +00007250 ObjCMethodDecl *method = S.getCurMethodDecl();
7251 if (method && var == method->getSelfDecl())
Ted Kremenek1fcdaa92011-11-14 21:59:25 +00007252 Diag = method->isClassMethod()
7253 ? diag::err_typecheck_arc_assign_self_class_method
7254 : diag::err_typecheck_arc_assign_self;
John McCalld4631322011-06-17 06:42:21 +00007255
7256 // - fast enumeration variables
7257 else
John McCall31168b02011-06-15 23:02:42 +00007258 Diag = diag::err_typecheck_arr_assign_enumeration;
John McCalld4631322011-06-17 06:42:21 +00007259
John McCall31168b02011-06-15 23:02:42 +00007260 SourceRange Assign;
7261 if (Loc != OrigLoc)
7262 Assign = SourceRange(OrigLoc, OrigLoc);
7263 S.Diag(Loc, Diag) << E->getSourceRange() << Assign;
7264 // We need to preserve the AST regardless, so migration tool
7265 // can do its job.
7266 return false;
7267 }
7268 }
7269 }
7270
7271 break;
Mike Stump4e1f26a2009-02-19 03:04:26 +00007272 case Expr::MLV_ArrayType:
Chris Lattner30bd3272008-11-18 01:22:49 +00007273 Diag = diag::err_typecheck_array_not_modifiable_lvalue;
7274 NeedType = true;
7275 break;
Mike Stump4e1f26a2009-02-19 03:04:26 +00007276 case Expr::MLV_NotObjectType:
Chris Lattner30bd3272008-11-18 01:22:49 +00007277 Diag = diag::err_typecheck_non_object_not_modifiable_lvalue;
7278 NeedType = true;
7279 break;
Chris Lattner9b3bbe92008-11-17 19:51:54 +00007280 case Expr::MLV_LValueCast:
Chris Lattner30bd3272008-11-18 01:22:49 +00007281 Diag = diag::err_typecheck_lvalue_casts_not_supported;
7282 break;
Douglas Gregorb154fdc2010-02-16 21:39:57 +00007283 case Expr::MLV_Valid:
7284 llvm_unreachable("did not take early return for MLV_Valid");
Chris Lattner9bad62c2008-01-04 18:04:52 +00007285 case Expr::MLV_InvalidExpression:
Douglas Gregorb154fdc2010-02-16 21:39:57 +00007286 case Expr::MLV_MemberFunction:
7287 case Expr::MLV_ClassTemporary:
Chris Lattner30bd3272008-11-18 01:22:49 +00007288 Diag = diag::err_typecheck_expression_not_modifiable_lvalue;
7289 break;
Chris Lattner9bad62c2008-01-04 18:04:52 +00007290 case Expr::MLV_IncompleteType:
7291 case Expr::MLV_IncompleteVoidType:
Douglas Gregored0cfbd2009-03-09 16:13:40 +00007292 return S.RequireCompleteType(Loc, E->getType(),
Douglas Gregor7bfb2d02012-05-04 16:32:21 +00007293 diag::err_typecheck_incomplete_type_not_modifiable_lvalue, E);
Chris Lattner9bad62c2008-01-04 18:04:52 +00007294 case Expr::MLV_DuplicateVectorComponents:
Chris Lattner30bd3272008-11-18 01:22:49 +00007295 Diag = diag::err_typecheck_duplicate_vector_components_not_mlvalue;
7296 break;
Fariborz Jahanian8a1810f2008-11-22 18:39:36 +00007297 case Expr::MLV_ReadonlyProperty:
Fariborz Jahanian5118c412008-11-22 20:25:50 +00007298 case Expr::MLV_NoSetterProperty:
John McCall526ab472011-10-25 17:37:35 +00007299 llvm_unreachable("readonly properties should be processed differently");
Fariborz Jahanian071caef2011-03-26 19:48:30 +00007300 case Expr::MLV_InvalidMessageExpression:
7301 Diag = diag::error_readonly_message_assignment;
7302 break;
Fariborz Jahaniane8d28902009-12-15 23:59:41 +00007303 case Expr::MLV_SubObjCPropertySetting:
7304 Diag = diag::error_no_subobject_property_setting;
7305 break;
Steve Naroff218bc2b2007-05-04 21:54:46 +00007306 }
Steve Naroffad373bd2007-07-31 12:34:36 +00007307
Daniel Dunbarc2223ab2009-04-15 00:08:05 +00007308 SourceRange Assign;
7309 if (Loc != OrigLoc)
7310 Assign = SourceRange(OrigLoc, OrigLoc);
Chris Lattner30bd3272008-11-18 01:22:49 +00007311 if (NeedType)
Daniel Dunbarc2223ab2009-04-15 00:08:05 +00007312 S.Diag(Loc, Diag) << E->getType() << E->getSourceRange() << Assign;
Chris Lattner30bd3272008-11-18 01:22:49 +00007313 else
Mike Stump11289f42009-09-09 15:08:12 +00007314 S.Diag(Loc, Diag) << E->getSourceRange() << Assign;
Chris Lattner30bd3272008-11-18 01:22:49 +00007315 return true;
7316}
7317
7318
7319
7320// C99 6.5.16.1
Richard Trieuda4f43a62011-09-07 01:33:52 +00007321QualType Sema::CheckAssignmentOperands(Expr *LHSExpr, ExprResult &RHS,
Chris Lattner326f7572008-11-18 01:30:42 +00007322 SourceLocation Loc,
7323 QualType CompoundType) {
John McCall526ab472011-10-25 17:37:35 +00007324 assert(!LHSExpr->hasPlaceholderType(BuiltinType::PseudoObject));
7325
Chris Lattner326f7572008-11-18 01:30:42 +00007326 // Verify that LHS is a modifiable lvalue, and emit error if not.
Richard Trieuda4f43a62011-09-07 01:33:52 +00007327 if (CheckForModifiableLvalue(LHSExpr, Loc, *this))
Chris Lattner30bd3272008-11-18 01:22:49 +00007328 return QualType();
Chris Lattner326f7572008-11-18 01:30:42 +00007329
Richard Trieuda4f43a62011-09-07 01:33:52 +00007330 QualType LHSType = LHSExpr->getType();
Richard Trieucfc491d2011-08-02 04:35:43 +00007331 QualType RHSType = CompoundType.isNull() ? RHS.get()->getType() :
7332 CompoundType;
Chris Lattner9bad62c2008-01-04 18:04:52 +00007333 AssignConvertType ConvTy;
Chris Lattner326f7572008-11-18 01:30:42 +00007334 if (CompoundType.isNull()) {
Fariborz Jahanianbe21aa32010-06-07 22:02:01 +00007335 QualType LHSTy(LHSType);
Fariborz Jahanianbe21aa32010-06-07 22:02:01 +00007336 ConvTy = CheckSingleAssignmentConstraints(LHSTy, RHS);
John Wiegley01296292011-04-08 18:41:53 +00007337 if (RHS.isInvalid())
7338 return QualType();
Fariborz Jahanian255c0952009-01-13 23:34:40 +00007339 // Special case of NSObject attributes on c-style pointer types.
7340 if (ConvTy == IncompatiblePointer &&
7341 ((Context.isObjCNSObjectType(LHSType) &&
Steve Naroff79d12152009-07-16 15:41:00 +00007342 RHSType->isObjCObjectPointerType()) ||
Fariborz Jahanian255c0952009-01-13 23:34:40 +00007343 (Context.isObjCNSObjectType(RHSType) &&
Steve Naroff79d12152009-07-16 15:41:00 +00007344 LHSType->isObjCObjectPointerType())))
Fariborz Jahanian255c0952009-01-13 23:34:40 +00007345 ConvTy = Compatible;
Mike Stump4e1f26a2009-02-19 03:04:26 +00007346
John McCall7decc9e2010-11-18 06:31:45 +00007347 if (ConvTy == Compatible &&
Fariborz Jahaniane2a77762012-01-24 19:40:13 +00007348 LHSType->isObjCObjectType())
Fariborz Jahanian3c4225a2012-01-24 18:05:45 +00007349 Diag(Loc, diag::err_objc_object_assignment)
7350 << LHSType;
John McCall7decc9e2010-11-18 06:31:45 +00007351
Chris Lattnerea714382008-08-21 18:04:13 +00007352 // If the RHS is a unary plus or minus, check to see if they = and + are
7353 // right next to each other. If so, the user may have typo'd "x =+ 4"
7354 // instead of "x += 4".
John Wiegley01296292011-04-08 18:41:53 +00007355 Expr *RHSCheck = RHS.get();
Chris Lattnerea714382008-08-21 18:04:13 +00007356 if (ImplicitCastExpr *ICE = dyn_cast<ImplicitCastExpr>(RHSCheck))
7357 RHSCheck = ICE->getSubExpr();
7358 if (UnaryOperator *UO = dyn_cast<UnaryOperator>(RHSCheck)) {
John McCalle3027922010-08-25 11:45:40 +00007359 if ((UO->getOpcode() == UO_Plus ||
7360 UO->getOpcode() == UO_Minus) &&
Chris Lattner326f7572008-11-18 01:30:42 +00007361 Loc.isFileID() && UO->getOperatorLoc().isFileID() &&
Chris Lattnerea714382008-08-21 18:04:13 +00007362 // Only if the two operators are exactly adjacent.
Argyrios Kyrtzidise6e67de2011-09-19 20:40:19 +00007363 Loc.getLocWithOffset(1) == UO->getOperatorLoc() &&
Chris Lattner36c39c92009-03-08 06:51:10 +00007364 // And there is a space or other character before the subexpr of the
7365 // unary +/-. We don't want to warn on "x=-1".
Argyrios Kyrtzidise6e67de2011-09-19 20:40:19 +00007366 Loc.getLocWithOffset(2) != UO->getSubExpr()->getLocStart() &&
Chris Lattnered9f14c2009-03-09 07:11:10 +00007367 UO->getSubExpr()->getLocStart().isFileID()) {
Chris Lattner29e812b2008-11-20 06:06:08 +00007368 Diag(Loc, diag::warn_not_compound_assign)
John McCalle3027922010-08-25 11:45:40 +00007369 << (UO->getOpcode() == UO_Plus ? "+" : "-")
Chris Lattner29e812b2008-11-20 06:06:08 +00007370 << SourceRange(UO->getOperatorLoc(), UO->getOperatorLoc());
Chris Lattner36c39c92009-03-08 06:51:10 +00007371 }
Chris Lattnerea714382008-08-21 18:04:13 +00007372 }
John McCall31168b02011-06-15 23:02:42 +00007373
7374 if (ConvTy == Compatible) {
7375 if (LHSType.getObjCLifetime() == Qualifiers::OCL_Strong)
Richard Trieuda4f43a62011-09-07 01:33:52 +00007376 checkRetainCycles(LHSExpr, RHS.get());
David Blaikiebbafb8a2012-03-11 07:00:24 +00007377 else if (getLangOpts().ObjCAutoRefCount)
Richard Trieuda4f43a62011-09-07 01:33:52 +00007378 checkUnsafeExprAssigns(Loc, LHSExpr, RHS.get());
John McCall31168b02011-06-15 23:02:42 +00007379 }
Chris Lattnerea714382008-08-21 18:04:13 +00007380 } else {
7381 // Compound assignment "x += y"
Douglas Gregorc03a1082011-01-28 02:26:04 +00007382 ConvTy = CheckAssignmentConstraints(Loc, LHSType, RHSType);
Chris Lattnerea714382008-08-21 18:04:13 +00007383 }
Chris Lattner9bad62c2008-01-04 18:04:52 +00007384
Chris Lattner326f7572008-11-18 01:30:42 +00007385 if (DiagnoseAssignmentResult(ConvTy, Loc, LHSType, RHSType,
John Wiegley01296292011-04-08 18:41:53 +00007386 RHS.get(), AA_Assigning))
Chris Lattner9bad62c2008-01-04 18:04:52 +00007387 return QualType();
Mike Stump4e1f26a2009-02-19 03:04:26 +00007388
Richard Trieuda4f43a62011-09-07 01:33:52 +00007389 CheckForNullPointerDereference(*this, LHSExpr);
Kaelyn Uhrain2e7aa5a2011-08-05 23:18:04 +00007390
Steve Naroff98cf3e92007-06-06 18:38:38 +00007391 // C99 6.5.16p3: The type of an assignment expression is the type of the
7392 // left operand unless the left operand has qualified type, in which case
Mike Stump4e1f26a2009-02-19 03:04:26 +00007393 // it is the unqualified version of the type of the left operand.
Steve Naroff98cf3e92007-06-06 18:38:38 +00007394 // C99 6.5.16.1p2: In simple assignment, the value of the right operand
7395 // is converted to the type of the assignment expression (above).
Chris Lattnerf17bd422007-08-30 17:45:32 +00007396 // C++ 5.17p1: the type of the assignment expression is that of its left
Douglas Gregord2c2d172009-05-02 00:36:19 +00007397 // operand.
David Blaikiebbafb8a2012-03-11 07:00:24 +00007398 return (getLangOpts().CPlusPlus
John McCall01cbf2d2010-10-12 02:19:57 +00007399 ? LHSType : LHSType.getUnqualifiedType());
Steve Naroffae4143e2007-04-26 20:39:23 +00007400}
7401
Chris Lattner326f7572008-11-18 01:30:42 +00007402// C99 6.5.17
John Wiegley01296292011-04-08 18:41:53 +00007403static QualType CheckCommaOperands(Sema &S, ExprResult &LHS, ExprResult &RHS,
John McCall4bc41ae2010-11-18 19:01:18 +00007404 SourceLocation Loc) {
John Wiegley01296292011-04-08 18:41:53 +00007405 S.DiagnoseUnusedExprResult(LHS.get());
Argyrios Kyrtzidis639ffb02010-06-30 10:53:14 +00007406
John McCall3aef3d82011-04-10 19:13:55 +00007407 LHS = S.CheckPlaceholderExpr(LHS.take());
7408 RHS = S.CheckPlaceholderExpr(RHS.take());
John Wiegley01296292011-04-08 18:41:53 +00007409 if (LHS.isInvalid() || RHS.isInvalid())
Douglas Gregor0124e9b2010-11-09 21:07:58 +00007410 return QualType();
7411
John McCall73d36182010-10-12 07:14:40 +00007412 // C's comma performs lvalue conversion (C99 6.3.2.1) on both its
7413 // operands, but not unary promotions.
7414 // C++'s comma does not do any conversions at all (C++ [expr.comma]p1).
Eli Friedmanba961a92009-03-23 00:24:07 +00007415
John McCall34376a62010-12-04 03:47:34 +00007416 // So we treat the LHS as a ignored value, and in C++ we allow the
7417 // containing site to determine what should be done with the RHS.
John Wiegley01296292011-04-08 18:41:53 +00007418 LHS = S.IgnoredValueConversions(LHS.take());
7419 if (LHS.isInvalid())
7420 return QualType();
John McCall34376a62010-12-04 03:47:34 +00007421
David Blaikiebbafb8a2012-03-11 07:00:24 +00007422 if (!S.getLangOpts().CPlusPlus) {
John Wiegley01296292011-04-08 18:41:53 +00007423 RHS = S.DefaultFunctionArrayLvalueConversion(RHS.take());
7424 if (RHS.isInvalid())
7425 return QualType();
7426 if (!RHS.get()->getType()->isVoidType())
Richard Trieucfc491d2011-08-02 04:35:43 +00007427 S.RequireCompleteType(Loc, RHS.get()->getType(),
7428 diag::err_incomplete_type);
John McCall73d36182010-10-12 07:14:40 +00007429 }
Eli Friedmanba961a92009-03-23 00:24:07 +00007430
John Wiegley01296292011-04-08 18:41:53 +00007431 return RHS.get()->getType();
Steve Naroff95af0132007-03-30 23:47:58 +00007432}
7433
Steve Naroff7a5af782007-07-13 16:58:59 +00007434/// CheckIncrementDecrementOperand - unlike most "Check" methods, this routine
7435/// doesn't need to call UsualUnaryConversions or UsualArithmeticConversions.
John McCall4bc41ae2010-11-18 19:01:18 +00007436static QualType CheckIncrementDecrementOperand(Sema &S, Expr *Op,
7437 ExprValueKind &VK,
7438 SourceLocation OpLoc,
Richard Trieuba63ce62011-09-09 01:45:06 +00007439 bool IsInc, bool IsPrefix) {
Sebastian Redl8d2ccae2009-02-26 14:39:58 +00007440 if (Op->isTypeDependent())
John McCall4bc41ae2010-11-18 19:01:18 +00007441 return S.Context.DependentTy;
Sebastian Redl8d2ccae2009-02-26 14:39:58 +00007442
Chris Lattner6b0cf142008-11-21 07:05:48 +00007443 QualType ResType = Op->getType();
David Chisnallfa35df62012-01-16 17:27:18 +00007444 // Atomic types can be used for increment / decrement where the non-atomic
7445 // versions can, so ignore the _Atomic() specifier for the purpose of
7446 // checking.
7447 if (const AtomicType *ResAtomicType = ResType->getAs<AtomicType>())
7448 ResType = ResAtomicType->getValueType();
7449
Chris Lattner6b0cf142008-11-21 07:05:48 +00007450 assert(!ResType.isNull() && "no type for increment/decrement expression");
Steve Naroffd50c88e2007-04-05 21:15:20 +00007451
David Blaikiebbafb8a2012-03-11 07:00:24 +00007452 if (S.getLangOpts().CPlusPlus && ResType->isBooleanType()) {
Sebastian Redle10c2c32008-12-20 09:35:34 +00007453 // Decrement of bool is not allowed.
Richard Trieuba63ce62011-09-09 01:45:06 +00007454 if (!IsInc) {
John McCall4bc41ae2010-11-18 19:01:18 +00007455 S.Diag(OpLoc, diag::err_decrement_bool) << Op->getSourceRange();
Sebastian Redle10c2c32008-12-20 09:35:34 +00007456 return QualType();
7457 }
7458 // Increment of bool sets it to true, but is deprecated.
John McCall4bc41ae2010-11-18 19:01:18 +00007459 S.Diag(OpLoc, diag::warn_increment_bool) << Op->getSourceRange();
Sebastian Redle10c2c32008-12-20 09:35:34 +00007460 } else if (ResType->isRealType()) {
Chris Lattner6b0cf142008-11-21 07:05:48 +00007461 // OK!
Steve Naroff6b712a72009-07-14 18:25:06 +00007462 } else if (ResType->isAnyPointerType()) {
Chris Lattner6b0cf142008-11-21 07:05:48 +00007463 // C99 6.5.2.4p2, 6.5.6p2
Chandler Carruthc9332212011-06-27 08:02:19 +00007464 if (!checkArithmeticOpPointerOperand(S, OpLoc, Op))
Douglas Gregordd430f72009-01-19 19:26:10 +00007465 return QualType();
Chandler Carruthc9332212011-06-27 08:02:19 +00007466
Fariborz Jahanianca75db72009-07-16 17:59:14 +00007467 // Diagnose bad cases where we step over interface counts.
Richard Trieub10c6312011-09-01 22:53:23 +00007468 else if (!checkArithmethicPointerOnNonFragileABI(S, OpLoc, Op))
Fariborz Jahanianca75db72009-07-16 17:59:14 +00007469 return QualType();
Eli Friedman090addd2010-01-03 00:20:48 +00007470 } else if (ResType->isAnyComplexType()) {
Chris Lattner6b0cf142008-11-21 07:05:48 +00007471 // C99 does not support ++/-- on complex types, we allow as an extension.
John McCall4bc41ae2010-11-18 19:01:18 +00007472 S.Diag(OpLoc, diag::ext_integer_increment_complex)
Chris Lattner1e5665e2008-11-24 06:25:27 +00007473 << ResType << Op->getSourceRange();
John McCall36226622010-10-12 02:09:17 +00007474 } else if (ResType->isPlaceholderType()) {
John McCall3aef3d82011-04-10 19:13:55 +00007475 ExprResult PR = S.CheckPlaceholderExpr(Op);
John McCall36226622010-10-12 02:09:17 +00007476 if (PR.isInvalid()) return QualType();
John McCall4bc41ae2010-11-18 19:01:18 +00007477 return CheckIncrementDecrementOperand(S, PR.take(), VK, OpLoc,
Richard Trieuba63ce62011-09-09 01:45:06 +00007478 IsInc, IsPrefix);
David Blaikiebbafb8a2012-03-11 07:00:24 +00007479 } else if (S.getLangOpts().AltiVec && ResType->isVectorType()) {
Anton Yartsev85129b82011-02-07 02:17:30 +00007480 // OK! ( C/C++ Language Extensions for CBEA(Version 2.6) 10.3 )
Chris Lattner6b0cf142008-11-21 07:05:48 +00007481 } else {
John McCall4bc41ae2010-11-18 19:01:18 +00007482 S.Diag(OpLoc, diag::err_typecheck_illegal_increment_decrement)
Richard Trieuba63ce62011-09-09 01:45:06 +00007483 << ResType << int(IsInc) << Op->getSourceRange();
Chris Lattner6b0cf142008-11-21 07:05:48 +00007484 return QualType();
Steve Naroff46ba1eb2007-04-03 23:13:13 +00007485 }
Mike Stump4e1f26a2009-02-19 03:04:26 +00007486 // At this point, we know we have a real, complex or pointer type.
Steve Naroff9e1e5512007-08-23 21:37:33 +00007487 // Now make sure the operand is a modifiable lvalue.
John McCall4bc41ae2010-11-18 19:01:18 +00007488 if (CheckForModifiableLvalue(Op, OpLoc, S))
Steve Naroff35d85152007-05-07 00:24:15 +00007489 return QualType();
Alexis Huntc46382e2010-04-28 23:02:27 +00007490 // In C++, a prefix increment is the same type as the operand. Otherwise
7491 // (in C or with postfix), the increment is the unqualified type of the
7492 // operand.
David Blaikiebbafb8a2012-03-11 07:00:24 +00007493 if (IsPrefix && S.getLangOpts().CPlusPlus) {
John McCall4bc41ae2010-11-18 19:01:18 +00007494 VK = VK_LValue;
7495 return ResType;
7496 } else {
7497 VK = VK_RValue;
7498 return ResType.getUnqualifiedType();
7499 }
Steve Naroff26c8ea52007-03-21 21:08:52 +00007500}
Fariborz Jahanian805b74e2010-09-14 23:02:38 +00007501
7502
Anders Carlsson806700f2008-02-01 07:15:58 +00007503/// getPrimaryDecl - Helper function for CheckAddressOfOperand().
Steve Naroff47500512007-04-19 23:00:49 +00007504/// This routine allows us to typecheck complex/recursive expressions
Daniel Dunbarb692ef42008-08-04 20:02:37 +00007505/// where the declaration is needed for type checking. We only need to
7506/// handle cases when the expression references a function designator
7507/// or is an lvalue. Here are some examples:
7508/// - &(x) => x
7509/// - &*****f => f for f a function designator.
7510/// - &s.xx => s
7511/// - &s.zz[1].yy -> s, if zz is an array
7512/// - *(x + 1) -> x, if x is an array
7513/// - &"123"[2] -> 0
7514/// - & __real__ x -> x
John McCallf3a88602011-02-03 08:15:49 +00007515static ValueDecl *getPrimaryDecl(Expr *E) {
Chris Lattner24d5bfe2008-04-02 04:24:33 +00007516 switch (E->getStmtClass()) {
Steve Naroff47500512007-04-19 23:00:49 +00007517 case Stmt::DeclRefExprClass:
Chris Lattner24d5bfe2008-04-02 04:24:33 +00007518 return cast<DeclRefExpr>(E)->getDecl();
Steve Naroff47500512007-04-19 23:00:49 +00007519 case Stmt::MemberExprClass:
Eli Friedman3a1e6922009-04-20 08:23:18 +00007520 // If this is an arrow operator, the address is an offset from
7521 // the base's value, so the object the base refers to is
7522 // irrelevant.
Chris Lattner24d5bfe2008-04-02 04:24:33 +00007523 if (cast<MemberExpr>(E)->isArrow())
Chris Lattner48d52842007-11-16 17:46:48 +00007524 return 0;
Eli Friedman3a1e6922009-04-20 08:23:18 +00007525 // Otherwise, the expression refers to a part of the base
Chris Lattner24d5bfe2008-04-02 04:24:33 +00007526 return getPrimaryDecl(cast<MemberExpr>(E)->getBase());
Anders Carlsson806700f2008-02-01 07:15:58 +00007527 case Stmt::ArraySubscriptExprClass: {
Mike Stump87c57ac2009-05-16 07:39:55 +00007528 // FIXME: This code shouldn't be necessary! We should catch the implicit
7529 // promotion of register arrays earlier.
Eli Friedman3a1e6922009-04-20 08:23:18 +00007530 Expr* Base = cast<ArraySubscriptExpr>(E)->getBase();
7531 if (ImplicitCastExpr* ICE = dyn_cast<ImplicitCastExpr>(Base)) {
7532 if (ICE->getSubExpr()->getType()->isArrayType())
7533 return getPrimaryDecl(ICE->getSubExpr());
7534 }
7535 return 0;
Anders Carlsson806700f2008-02-01 07:15:58 +00007536 }
Daniel Dunbarb692ef42008-08-04 20:02:37 +00007537 case Stmt::UnaryOperatorClass: {
7538 UnaryOperator *UO = cast<UnaryOperator>(E);
Mike Stump4e1f26a2009-02-19 03:04:26 +00007539
Daniel Dunbarb692ef42008-08-04 20:02:37 +00007540 switch(UO->getOpcode()) {
John McCalle3027922010-08-25 11:45:40 +00007541 case UO_Real:
7542 case UO_Imag:
7543 case UO_Extension:
Daniel Dunbarb692ef42008-08-04 20:02:37 +00007544 return getPrimaryDecl(UO->getSubExpr());
7545 default:
7546 return 0;
7547 }
7548 }
Steve Naroff47500512007-04-19 23:00:49 +00007549 case Stmt::ParenExprClass:
Chris Lattner24d5bfe2008-04-02 04:24:33 +00007550 return getPrimaryDecl(cast<ParenExpr>(E)->getSubExpr());
Chris Lattner48d52842007-11-16 17:46:48 +00007551 case Stmt::ImplicitCastExprClass:
Eli Friedman3a1e6922009-04-20 08:23:18 +00007552 // If the result of an implicit cast is an l-value, we care about
7553 // the sub-expression; otherwise, the result here doesn't matter.
Chris Lattner24d5bfe2008-04-02 04:24:33 +00007554 return getPrimaryDecl(cast<ImplicitCastExpr>(E)->getSubExpr());
Steve Naroff47500512007-04-19 23:00:49 +00007555 default:
7556 return 0;
7557 }
7558}
7559
Richard Trieu5f376f62011-09-07 21:46:33 +00007560namespace {
7561 enum {
7562 AO_Bit_Field = 0,
7563 AO_Vector_Element = 1,
7564 AO_Property_Expansion = 2,
7565 AO_Register_Variable = 3,
7566 AO_No_Error = 4
7567 };
7568}
Richard Trieu3fd7bb82011-09-02 00:47:55 +00007569/// \brief Diagnose invalid operand for address of operations.
7570///
7571/// \param Type The type of operand which cannot have its address taken.
Richard Trieu3fd7bb82011-09-02 00:47:55 +00007572static void diagnoseAddressOfInvalidType(Sema &S, SourceLocation Loc,
7573 Expr *E, unsigned Type) {
7574 S.Diag(Loc, diag::err_typecheck_address_of) << Type << E->getSourceRange();
7575}
7576
Steve Naroff47500512007-04-19 23:00:49 +00007577/// CheckAddressOfOperand - The operand of & must be either a function
Mike Stump4e1f26a2009-02-19 03:04:26 +00007578/// designator or an lvalue designating an object. If it is an lvalue, the
Steve Naroff47500512007-04-19 23:00:49 +00007579/// object cannot be declared with storage class register or be a bit field.
Mike Stump4e1f26a2009-02-19 03:04:26 +00007580/// Note: The usual conversions are *not* applied to the operand of the &
Steve Naroffa78fe7e2007-05-16 19:47:19 +00007581/// operator (C99 6.3.2.1p[2-4]), and its result is never an lvalue.
Mike Stump4e1f26a2009-02-19 03:04:26 +00007582/// In C++, the operand might be an overloaded function name, in which case
Douglas Gregorcd695e52008-11-10 20:40:00 +00007583/// we allow the '&' but retain the overloaded-function type.
John McCall526ab472011-10-25 17:37:35 +00007584static QualType CheckAddressOfOperand(Sema &S, ExprResult &OrigOp,
John McCall4bc41ae2010-11-18 19:01:18 +00007585 SourceLocation OpLoc) {
John McCall526ab472011-10-25 17:37:35 +00007586 if (const BuiltinType *PTy = OrigOp.get()->getType()->getAsPlaceholderType()){
7587 if (PTy->getKind() == BuiltinType::Overload) {
7588 if (!isa<OverloadExpr>(OrigOp.get()->IgnoreParens())) {
7589 S.Diag(OpLoc, diag::err_typecheck_invalid_lvalue_addrof)
7590 << OrigOp.get()->getSourceRange();
7591 return QualType();
7592 }
7593
7594 return S.Context.OverloadTy;
7595 }
7596
7597 if (PTy->getKind() == BuiltinType::UnknownAny)
7598 return S.Context.UnknownAnyTy;
7599
7600 if (PTy->getKind() == BuiltinType::BoundMember) {
7601 S.Diag(OpLoc, diag::err_invalid_form_pointer_member_function)
7602 << OrigOp.get()->getSourceRange();
Douglas Gregor668d3622011-10-09 19:10:41 +00007603 return QualType();
7604 }
John McCall526ab472011-10-25 17:37:35 +00007605
7606 OrigOp = S.CheckPlaceholderExpr(OrigOp.take());
7607 if (OrigOp.isInvalid()) return QualType();
John McCall0009fcc2011-04-26 20:42:42 +00007608 }
John McCall8d08b9b2010-08-27 09:08:28 +00007609
John McCall526ab472011-10-25 17:37:35 +00007610 if (OrigOp.get()->isTypeDependent())
7611 return S.Context.DependentTy;
7612
7613 assert(!OrigOp.get()->getType()->isPlaceholderType());
John McCall36226622010-10-12 02:09:17 +00007614
John McCall8d08b9b2010-08-27 09:08:28 +00007615 // Make sure to ignore parentheses in subsequent checks
John McCall526ab472011-10-25 17:37:35 +00007616 Expr *op = OrigOp.get()->IgnoreParens();
Douglas Gregor19b8c4f2008-12-17 22:52:20 +00007617
David Blaikiebbafb8a2012-03-11 07:00:24 +00007618 if (S.getLangOpts().C99) {
Steve Naroff826e91a2008-01-13 17:10:08 +00007619 // Implement C99-only parts of addressof rules.
7620 if (UnaryOperator* uOp = dyn_cast<UnaryOperator>(op)) {
John McCalle3027922010-08-25 11:45:40 +00007621 if (uOp->getOpcode() == UO_Deref)
Steve Naroff826e91a2008-01-13 17:10:08 +00007622 // Per C99 6.5.3.2, the address of a deref always returns a valid result
7623 // (assuming the deref expression is valid).
7624 return uOp->getSubExpr()->getType();
7625 }
7626 // Technically, there should be a check for array subscript
7627 // expressions here, but the result of one is always an lvalue anyway.
7628 }
John McCallf3a88602011-02-03 08:15:49 +00007629 ValueDecl *dcl = getPrimaryDecl(op);
John McCall086a4642010-11-24 05:12:34 +00007630 Expr::LValueClassification lval = op->ClassifyLValue(S.Context);
Richard Trieu5f376f62011-09-07 21:46:33 +00007631 unsigned AddressOfError = AO_No_Error;
Nuno Lopes17f345f2008-12-16 22:59:47 +00007632
Fariborz Jahanian071caef2011-03-26 19:48:30 +00007633 if (lval == Expr::LV_ClassTemporary) {
John McCall4bc41ae2010-11-18 19:01:18 +00007634 bool sfinae = S.isSFINAEContext();
7635 S.Diag(OpLoc, sfinae ? diag::err_typecheck_addrof_class_temporary
7636 : diag::ext_typecheck_addrof_class_temporary)
Douglas Gregorb154fdc2010-02-16 21:39:57 +00007637 << op->getType() << op->getSourceRange();
John McCall4bc41ae2010-11-18 19:01:18 +00007638 if (sfinae)
Douglas Gregorb154fdc2010-02-16 21:39:57 +00007639 return QualType();
John McCall8d08b9b2010-08-27 09:08:28 +00007640 } else if (isa<ObjCSelectorExpr>(op)) {
John McCall4bc41ae2010-11-18 19:01:18 +00007641 return S.Context.getPointerType(op->getType());
John McCall8d08b9b2010-08-27 09:08:28 +00007642 } else if (lval == Expr::LV_MemberFunction) {
7643 // If it's an instance method, make a member pointer.
7644 // The expression must have exactly the form &A::foo.
7645
7646 // If the underlying expression isn't a decl ref, give up.
7647 if (!isa<DeclRefExpr>(op)) {
John McCall4bc41ae2010-11-18 19:01:18 +00007648 S.Diag(OpLoc, diag::err_invalid_form_pointer_member_function)
John McCall526ab472011-10-25 17:37:35 +00007649 << OrigOp.get()->getSourceRange();
John McCall8d08b9b2010-08-27 09:08:28 +00007650 return QualType();
7651 }
7652 DeclRefExpr *DRE = cast<DeclRefExpr>(op);
7653 CXXMethodDecl *MD = cast<CXXMethodDecl>(DRE->getDecl());
7654
7655 // The id-expression was parenthesized.
John McCall526ab472011-10-25 17:37:35 +00007656 if (OrigOp.get() != DRE) {
John McCall4bc41ae2010-11-18 19:01:18 +00007657 S.Diag(OpLoc, diag::err_parens_pointer_member_function)
John McCall526ab472011-10-25 17:37:35 +00007658 << OrigOp.get()->getSourceRange();
John McCall8d08b9b2010-08-27 09:08:28 +00007659
7660 // The method was named without a qualifier.
7661 } else if (!DRE->getQualifier()) {
John McCall4bc41ae2010-11-18 19:01:18 +00007662 S.Diag(OpLoc, diag::err_unqualified_pointer_member_function)
John McCall8d08b9b2010-08-27 09:08:28 +00007663 << op->getSourceRange();
7664 }
7665
John McCall4bc41ae2010-11-18 19:01:18 +00007666 return S.Context.getMemberPointerType(op->getType(),
7667 S.Context.getTypeDeclType(MD->getParent()).getTypePtr());
John McCall8d08b9b2010-08-27 09:08:28 +00007668 } else if (lval != Expr::LV_Valid && lval != Expr::LV_IncompleteVoidType) {
Eli Friedmance7f9002009-05-16 23:27:50 +00007669 // C99 6.5.3.2p1
Eli Friedman3a1e6922009-04-20 08:23:18 +00007670 // The operand must be either an l-value or a function designator
Eli Friedmance7f9002009-05-16 23:27:50 +00007671 if (!op->getType()->isFunctionType()) {
John McCall526ab472011-10-25 17:37:35 +00007672 // Use a special diagnostic for loads from property references.
John McCallfe96e0b2011-11-06 09:01:30 +00007673 if (isa<PseudoObjectExpr>(op)) {
John McCall526ab472011-10-25 17:37:35 +00007674 AddressOfError = AO_Property_Expansion;
7675 } else {
7676 // FIXME: emit more specific diag...
7677 S.Diag(OpLoc, diag::err_typecheck_invalid_lvalue_addrof)
7678 << op->getSourceRange();
7679 return QualType();
7680 }
Steve Naroff35d85152007-05-07 00:24:15 +00007681 }
John McCall086a4642010-11-24 05:12:34 +00007682 } else if (op->getObjectKind() == OK_BitField) { // C99 6.5.3.2p1
Eli Friedman3a1e6922009-04-20 08:23:18 +00007683 // The operand cannot be a bit-field
Richard Trieu5f376f62011-09-07 21:46:33 +00007684 AddressOfError = AO_Bit_Field;
John McCall086a4642010-11-24 05:12:34 +00007685 } else if (op->getObjectKind() == OK_VectorComponent) {
Eli Friedman3a1e6922009-04-20 08:23:18 +00007686 // The operand cannot be an element of a vector
Richard Trieu5f376f62011-09-07 21:46:33 +00007687 AddressOfError = AO_Vector_Element;
Steve Naroffb96e4ab62008-02-29 23:30:25 +00007688 } else if (dcl) { // C99 6.5.3.2p1
Mike Stump4e1f26a2009-02-19 03:04:26 +00007689 // We have an lvalue with a decl. Make sure the decl is not declared
Steve Naroff47500512007-04-19 23:00:49 +00007690 // with the register storage-class specifier.
7691 if (const VarDecl *vd = dyn_cast<VarDecl>(dcl)) {
Fariborz Jahaniane0fd5a92010-08-24 22:21:48 +00007692 // in C++ it is not error to take address of a register
7693 // variable (c++03 7.1.1P3)
John McCall8e7d6562010-08-26 03:08:43 +00007694 if (vd->getStorageClass() == SC_Register &&
David Blaikiebbafb8a2012-03-11 07:00:24 +00007695 !S.getLangOpts().CPlusPlus) {
Richard Trieu5f376f62011-09-07 21:46:33 +00007696 AddressOfError = AO_Register_Variable;
Steve Naroff35d85152007-05-07 00:24:15 +00007697 }
John McCalld14a8642009-11-21 08:51:07 +00007698 } else if (isa<FunctionTemplateDecl>(dcl)) {
John McCall4bc41ae2010-11-18 19:01:18 +00007699 return S.Context.OverloadTy;
John McCallf3a88602011-02-03 08:15:49 +00007700 } else if (isa<FieldDecl>(dcl) || isa<IndirectFieldDecl>(dcl)) {
Douglas Gregor9aa8b552008-12-10 21:26:49 +00007701 // Okay: we can take the address of a field.
Sebastian Redl3d3f75a2009-02-03 20:19:35 +00007702 // Could be a pointer to member, though, if there is an explicit
7703 // scope qualifier for the class.
Douglas Gregor4bd90e52009-10-23 18:54:35 +00007704 if (isa<DeclRefExpr>(op) && cast<DeclRefExpr>(op)->getQualifier()) {
Sebastian Redl3d3f75a2009-02-03 20:19:35 +00007705 DeclContext *Ctx = dcl->getDeclContext();
Anders Carlsson0b675f52009-07-08 21:45:58 +00007706 if (Ctx && Ctx->isRecord()) {
John McCallf3a88602011-02-03 08:15:49 +00007707 if (dcl->getType()->isReferenceType()) {
John McCall4bc41ae2010-11-18 19:01:18 +00007708 S.Diag(OpLoc,
7709 diag::err_cannot_form_pointer_to_member_of_reference_type)
John McCallf3a88602011-02-03 08:15:49 +00007710 << dcl->getDeclName() << dcl->getType();
Anders Carlsson0b675f52009-07-08 21:45:58 +00007711 return QualType();
7712 }
Mike Stump11289f42009-09-09 15:08:12 +00007713
Argyrios Kyrtzidis8322b422011-01-31 07:04:29 +00007714 while (cast<RecordDecl>(Ctx)->isAnonymousStructOrUnion())
7715 Ctx = Ctx->getParent();
John McCall4bc41ae2010-11-18 19:01:18 +00007716 return S.Context.getMemberPointerType(op->getType(),
7717 S.Context.getTypeDeclType(cast<RecordDecl>(Ctx)).getTypePtr());
Anders Carlsson0b675f52009-07-08 21:45:58 +00007718 }
Sebastian Redl3d3f75a2009-02-03 20:19:35 +00007719 }
Eli Friedman755c0c92011-08-26 20:28:17 +00007720 } else if (!isa<FunctionDecl>(dcl) && !isa<NonTypeTemplateParmDecl>(dcl))
David Blaikie83d382b2011-09-23 05:06:16 +00007721 llvm_unreachable("Unknown/unexpected decl type");
Steve Naroff47500512007-04-19 23:00:49 +00007722 }
Sebastian Redl18f8ff62009-02-04 21:23:32 +00007723
Richard Trieu5f376f62011-09-07 21:46:33 +00007724 if (AddressOfError != AO_No_Error) {
7725 diagnoseAddressOfInvalidType(S, OpLoc, op, AddressOfError);
7726 return QualType();
7727 }
7728
Eli Friedmance7f9002009-05-16 23:27:50 +00007729 if (lval == Expr::LV_IncompleteVoidType) {
7730 // Taking the address of a void variable is technically illegal, but we
7731 // allow it in cases which are otherwise valid.
7732 // Example: "extern void x; void* y = &x;".
John McCall4bc41ae2010-11-18 19:01:18 +00007733 S.Diag(OpLoc, diag::ext_typecheck_addrof_void) << op->getSourceRange();
Eli Friedmance7f9002009-05-16 23:27:50 +00007734 }
7735
Steve Naroff47500512007-04-19 23:00:49 +00007736 // If the operand has type "type", the result has type "pointer to type".
Douglas Gregor0bdcb8a2010-07-29 16:05:45 +00007737 if (op->getType()->isObjCObjectType())
John McCall4bc41ae2010-11-18 19:01:18 +00007738 return S.Context.getObjCObjectPointerType(op->getType());
7739 return S.Context.getPointerType(op->getType());
Steve Naroff47500512007-04-19 23:00:49 +00007740}
7741
Chris Lattner9156f1b2010-07-05 19:17:26 +00007742/// CheckIndirectionOperand - Type check unary indirection (prefix '*').
John McCall4bc41ae2010-11-18 19:01:18 +00007743static QualType CheckIndirectionOperand(Sema &S, Expr *Op, ExprValueKind &VK,
7744 SourceLocation OpLoc) {
Sebastian Redl8d2ccae2009-02-26 14:39:58 +00007745 if (Op->isTypeDependent())
John McCall4bc41ae2010-11-18 19:01:18 +00007746 return S.Context.DependentTy;
Sebastian Redl8d2ccae2009-02-26 14:39:58 +00007747
John Wiegley01296292011-04-08 18:41:53 +00007748 ExprResult ConvResult = S.UsualUnaryConversions(Op);
7749 if (ConvResult.isInvalid())
7750 return QualType();
7751 Op = ConvResult.take();
Chris Lattner9156f1b2010-07-05 19:17:26 +00007752 QualType OpTy = Op->getType();
7753 QualType Result;
Argyrios Kyrtzidis69a2c922011-05-02 18:21:19 +00007754
7755 if (isa<CXXReinterpretCastExpr>(Op)) {
7756 QualType OpOrigType = Op->IgnoreParenCasts()->getType();
7757 S.CheckCompatibleReinterpretCast(OpOrigType, OpTy, /*IsDereference*/true,
7758 Op->getSourceRange());
7759 }
7760
Chris Lattner9156f1b2010-07-05 19:17:26 +00007761 // Note that per both C89 and C99, indirection is always legal, even if OpTy
7762 // is an incomplete type or void. It would be possible to warn about
7763 // dereferencing a void pointer, but it's completely well-defined, and such a
7764 // warning is unlikely to catch any mistakes.
7765 if (const PointerType *PT = OpTy->getAs<PointerType>())
7766 Result = PT->getPointeeType();
7767 else if (const ObjCObjectPointerType *OPT =
7768 OpTy->getAs<ObjCObjectPointerType>())
7769 Result = OPT->getPointeeType();
John McCall36226622010-10-12 02:09:17 +00007770 else {
John McCall3aef3d82011-04-10 19:13:55 +00007771 ExprResult PR = S.CheckPlaceholderExpr(Op);
John McCall36226622010-10-12 02:09:17 +00007772 if (PR.isInvalid()) return QualType();
John McCall4bc41ae2010-11-18 19:01:18 +00007773 if (PR.take() != Op)
7774 return CheckIndirectionOperand(S, PR.take(), VK, OpLoc);
John McCall36226622010-10-12 02:09:17 +00007775 }
Mike Stump4e1f26a2009-02-19 03:04:26 +00007776
Chris Lattner9156f1b2010-07-05 19:17:26 +00007777 if (Result.isNull()) {
John McCall4bc41ae2010-11-18 19:01:18 +00007778 S.Diag(OpLoc, diag::err_typecheck_indirection_requires_pointer)
Chris Lattner9156f1b2010-07-05 19:17:26 +00007779 << OpTy << Op->getSourceRange();
7780 return QualType();
7781 }
John McCall4bc41ae2010-11-18 19:01:18 +00007782
7783 // Dereferences are usually l-values...
7784 VK = VK_LValue;
7785
7786 // ...except that certain expressions are never l-values in C.
David Blaikiebbafb8a2012-03-11 07:00:24 +00007787 if (!S.getLangOpts().CPlusPlus && Result.isCForbiddenLValueType())
John McCall4bc41ae2010-11-18 19:01:18 +00007788 VK = VK_RValue;
Chris Lattner9156f1b2010-07-05 19:17:26 +00007789
7790 return Result;
Steve Naroff1926c832007-04-24 00:23:05 +00007791}
Steve Naroff218bc2b2007-05-04 21:54:46 +00007792
John McCalle3027922010-08-25 11:45:40 +00007793static inline BinaryOperatorKind ConvertTokenKindToBinaryOpcode(
Steve Naroff218bc2b2007-05-04 21:54:46 +00007794 tok::TokenKind Kind) {
John McCalle3027922010-08-25 11:45:40 +00007795 BinaryOperatorKind Opc;
Steve Naroff218bc2b2007-05-04 21:54:46 +00007796 switch (Kind) {
David Blaikie83d382b2011-09-23 05:06:16 +00007797 default: llvm_unreachable("Unknown binop!");
John McCalle3027922010-08-25 11:45:40 +00007798 case tok::periodstar: Opc = BO_PtrMemD; break;
7799 case tok::arrowstar: Opc = BO_PtrMemI; break;
7800 case tok::star: Opc = BO_Mul; break;
7801 case tok::slash: Opc = BO_Div; break;
7802 case tok::percent: Opc = BO_Rem; break;
7803 case tok::plus: Opc = BO_Add; break;
7804 case tok::minus: Opc = BO_Sub; break;
7805 case tok::lessless: Opc = BO_Shl; break;
7806 case tok::greatergreater: Opc = BO_Shr; break;
7807 case tok::lessequal: Opc = BO_LE; break;
7808 case tok::less: Opc = BO_LT; break;
7809 case tok::greaterequal: Opc = BO_GE; break;
7810 case tok::greater: Opc = BO_GT; break;
7811 case tok::exclaimequal: Opc = BO_NE; break;
7812 case tok::equalequal: Opc = BO_EQ; break;
7813 case tok::amp: Opc = BO_And; break;
7814 case tok::caret: Opc = BO_Xor; break;
7815 case tok::pipe: Opc = BO_Or; break;
7816 case tok::ampamp: Opc = BO_LAnd; break;
7817 case tok::pipepipe: Opc = BO_LOr; break;
7818 case tok::equal: Opc = BO_Assign; break;
7819 case tok::starequal: Opc = BO_MulAssign; break;
7820 case tok::slashequal: Opc = BO_DivAssign; break;
7821 case tok::percentequal: Opc = BO_RemAssign; break;
7822 case tok::plusequal: Opc = BO_AddAssign; break;
7823 case tok::minusequal: Opc = BO_SubAssign; break;
7824 case tok::lesslessequal: Opc = BO_ShlAssign; break;
7825 case tok::greatergreaterequal: Opc = BO_ShrAssign; break;
7826 case tok::ampequal: Opc = BO_AndAssign; break;
7827 case tok::caretequal: Opc = BO_XorAssign; break;
7828 case tok::pipeequal: Opc = BO_OrAssign; break;
7829 case tok::comma: Opc = BO_Comma; break;
Steve Naroff218bc2b2007-05-04 21:54:46 +00007830 }
7831 return Opc;
7832}
7833
John McCalle3027922010-08-25 11:45:40 +00007834static inline UnaryOperatorKind ConvertTokenKindToUnaryOpcode(
Steve Naroff35d85152007-05-07 00:24:15 +00007835 tok::TokenKind Kind) {
John McCalle3027922010-08-25 11:45:40 +00007836 UnaryOperatorKind Opc;
Steve Naroff35d85152007-05-07 00:24:15 +00007837 switch (Kind) {
David Blaikie83d382b2011-09-23 05:06:16 +00007838 default: llvm_unreachable("Unknown unary op!");
John McCalle3027922010-08-25 11:45:40 +00007839 case tok::plusplus: Opc = UO_PreInc; break;
7840 case tok::minusminus: Opc = UO_PreDec; break;
7841 case tok::amp: Opc = UO_AddrOf; break;
7842 case tok::star: Opc = UO_Deref; break;
7843 case tok::plus: Opc = UO_Plus; break;
7844 case tok::minus: Opc = UO_Minus; break;
7845 case tok::tilde: Opc = UO_Not; break;
7846 case tok::exclaim: Opc = UO_LNot; break;
7847 case tok::kw___real: Opc = UO_Real; break;
7848 case tok::kw___imag: Opc = UO_Imag; break;
7849 case tok::kw___extension__: Opc = UO_Extension; break;
Steve Naroff35d85152007-05-07 00:24:15 +00007850 }
7851 return Opc;
7852}
7853
Chandler Carruthe0cee6a2011-01-04 06:52:15 +00007854/// DiagnoseSelfAssignment - Emits a warning if a value is assigned to itself.
7855/// This warning is only emitted for builtin assignment operations. It is also
7856/// suppressed in the event of macro expansions.
Richard Trieuda4f43a62011-09-07 01:33:52 +00007857static void DiagnoseSelfAssignment(Sema &S, Expr *LHSExpr, Expr *RHSExpr,
Chandler Carruthe0cee6a2011-01-04 06:52:15 +00007858 SourceLocation OpLoc) {
7859 if (!S.ActiveTemplateInstantiations.empty())
7860 return;
7861 if (OpLoc.isInvalid() || OpLoc.isMacroID())
7862 return;
Richard Trieuda4f43a62011-09-07 01:33:52 +00007863 LHSExpr = LHSExpr->IgnoreParenImpCasts();
7864 RHSExpr = RHSExpr->IgnoreParenImpCasts();
7865 const DeclRefExpr *LHSDeclRef = dyn_cast<DeclRefExpr>(LHSExpr);
7866 const DeclRefExpr *RHSDeclRef = dyn_cast<DeclRefExpr>(RHSExpr);
7867 if (!LHSDeclRef || !RHSDeclRef ||
7868 LHSDeclRef->getLocation().isMacroID() ||
7869 RHSDeclRef->getLocation().isMacroID())
Chandler Carruthe0cee6a2011-01-04 06:52:15 +00007870 return;
Richard Trieuda4f43a62011-09-07 01:33:52 +00007871 const ValueDecl *LHSDecl =
7872 cast<ValueDecl>(LHSDeclRef->getDecl()->getCanonicalDecl());
7873 const ValueDecl *RHSDecl =
7874 cast<ValueDecl>(RHSDeclRef->getDecl()->getCanonicalDecl());
7875 if (LHSDecl != RHSDecl)
Chandler Carruthe0cee6a2011-01-04 06:52:15 +00007876 return;
Richard Trieuda4f43a62011-09-07 01:33:52 +00007877 if (LHSDecl->getType().isVolatileQualified())
Chandler Carruthe0cee6a2011-01-04 06:52:15 +00007878 return;
Richard Trieuda4f43a62011-09-07 01:33:52 +00007879 if (const ReferenceType *RefTy = LHSDecl->getType()->getAs<ReferenceType>())
Chandler Carruthe0cee6a2011-01-04 06:52:15 +00007880 if (RefTy->getPointeeType().isVolatileQualified())
7881 return;
7882
7883 S.Diag(OpLoc, diag::warn_self_assignment)
Richard Trieuda4f43a62011-09-07 01:33:52 +00007884 << LHSDeclRef->getType()
7885 << LHSExpr->getSourceRange() << RHSExpr->getSourceRange();
Chandler Carruthe0cee6a2011-01-04 06:52:15 +00007886}
7887
Douglas Gregor7d5fc7e2008-11-06 23:29:22 +00007888/// CreateBuiltinBinOp - Creates a new built-in binary operation with
7889/// operator @p Opc at location @c TokLoc. This routine only supports
7890/// built-in operations; ActOnBinOp handles overloaded operators.
John McCalldadc5752010-08-24 06:29:42 +00007891ExprResult Sema::CreateBuiltinBinOp(SourceLocation OpLoc,
Argyrios Kyrtzidis7a808c02011-01-05 20:09:36 +00007892 BinaryOperatorKind Opc,
Richard Trieu4a287fb2011-09-07 01:49:20 +00007893 Expr *LHSExpr, Expr *RHSExpr) {
David Blaikiebbafb8a2012-03-11 07:00:24 +00007894 if (getLangOpts().CPlusPlus0x && isa<InitListExpr>(RHSExpr)) {
Sebastian Redl67766732012-02-27 20:34:02 +00007895 // The syntax only allows initializer lists on the RHS of assignment,
7896 // so we don't need to worry about accepting invalid code for
7897 // non-assignment operators.
7898 // C++11 5.17p9:
7899 // The meaning of x = {v} [...] is that of x = T(v) [...]. The meaning
7900 // of x = {} is x = T().
7901 InitializationKind Kind =
7902 InitializationKind::CreateDirectList(RHSExpr->getLocStart());
7903 InitializedEntity Entity =
7904 InitializedEntity::InitializeTemporary(LHSExpr->getType());
7905 InitializationSequence InitSeq(*this, Entity, Kind, &RHSExpr, 1);
7906 ExprResult Init = InitSeq.Perform(*this, Entity, Kind,
7907 MultiExprArg(&RHSExpr, 1));
7908 if (Init.isInvalid())
7909 return Init;
7910 RHSExpr = Init.take();
7911 }
7912
Richard Trieu4a287fb2011-09-07 01:49:20 +00007913 ExprResult LHS = Owned(LHSExpr), RHS = Owned(RHSExpr);
Eli Friedman8b7b1b12009-03-28 01:22:36 +00007914 QualType ResultTy; // Result type of the binary operator.
Eli Friedman8b7b1b12009-03-28 01:22:36 +00007915 // The following two variables are used for compound assignment operators
7916 QualType CompLHSTy; // Type of LHS after promotions for computation
7917 QualType CompResultTy; // Type of computation result
John McCall7decc9e2010-11-18 06:31:45 +00007918 ExprValueKind VK = VK_RValue;
7919 ExprObjectKind OK = OK_Ordinary;
Douglas Gregor7d5fc7e2008-11-06 23:29:22 +00007920
7921 switch (Opc) {
John McCalle3027922010-08-25 11:45:40 +00007922 case BO_Assign:
Richard Trieu4a287fb2011-09-07 01:49:20 +00007923 ResultTy = CheckAssignmentOperands(LHS.get(), RHS, OpLoc, QualType());
David Blaikiebbafb8a2012-03-11 07:00:24 +00007924 if (getLangOpts().CPlusPlus &&
Richard Trieu4a287fb2011-09-07 01:49:20 +00007925 LHS.get()->getObjectKind() != OK_ObjCProperty) {
7926 VK = LHS.get()->getValueKind();
7927 OK = LHS.get()->getObjectKind();
John McCall7decc9e2010-11-18 06:31:45 +00007928 }
Chandler Carruthe0cee6a2011-01-04 06:52:15 +00007929 if (!ResultTy.isNull())
Richard Trieu4a287fb2011-09-07 01:49:20 +00007930 DiagnoseSelfAssignment(*this, LHS.get(), RHS.get(), OpLoc);
Douglas Gregor7d5fc7e2008-11-06 23:29:22 +00007931 break;
John McCalle3027922010-08-25 11:45:40 +00007932 case BO_PtrMemD:
7933 case BO_PtrMemI:
Richard Trieu4a287fb2011-09-07 01:49:20 +00007934 ResultTy = CheckPointerToMemberOperands(LHS, RHS, VK, OpLoc,
John McCalle3027922010-08-25 11:45:40 +00007935 Opc == BO_PtrMemI);
Sebastian Redl112a97662009-02-07 00:15:38 +00007936 break;
John McCalle3027922010-08-25 11:45:40 +00007937 case BO_Mul:
7938 case BO_Div:
Richard Trieu4a287fb2011-09-07 01:49:20 +00007939 ResultTy = CheckMultiplyDivideOperands(LHS, RHS, OpLoc, false,
John McCalle3027922010-08-25 11:45:40 +00007940 Opc == BO_Div);
Douglas Gregor7d5fc7e2008-11-06 23:29:22 +00007941 break;
John McCalle3027922010-08-25 11:45:40 +00007942 case BO_Rem:
Richard Trieu4a287fb2011-09-07 01:49:20 +00007943 ResultTy = CheckRemainderOperands(LHS, RHS, OpLoc);
Douglas Gregor7d5fc7e2008-11-06 23:29:22 +00007944 break;
John McCalle3027922010-08-25 11:45:40 +00007945 case BO_Add:
Nico Weberccec40d2012-03-02 22:01:22 +00007946 ResultTy = CheckAdditionOperands(LHS, RHS, OpLoc, Opc);
Douglas Gregor7d5fc7e2008-11-06 23:29:22 +00007947 break;
John McCalle3027922010-08-25 11:45:40 +00007948 case BO_Sub:
Richard Trieu4a287fb2011-09-07 01:49:20 +00007949 ResultTy = CheckSubtractionOperands(LHS, RHS, OpLoc);
Douglas Gregor7d5fc7e2008-11-06 23:29:22 +00007950 break;
John McCalle3027922010-08-25 11:45:40 +00007951 case BO_Shl:
7952 case BO_Shr:
Richard Trieu4a287fb2011-09-07 01:49:20 +00007953 ResultTy = CheckShiftOperands(LHS, RHS, OpLoc, Opc);
Douglas Gregor7d5fc7e2008-11-06 23:29:22 +00007954 break;
John McCalle3027922010-08-25 11:45:40 +00007955 case BO_LE:
7956 case BO_LT:
7957 case BO_GE:
7958 case BO_GT:
Richard Trieu4a287fb2011-09-07 01:49:20 +00007959 ResultTy = CheckCompareOperands(LHS, RHS, OpLoc, Opc, true);
Douglas Gregor7d5fc7e2008-11-06 23:29:22 +00007960 break;
John McCalle3027922010-08-25 11:45:40 +00007961 case BO_EQ:
7962 case BO_NE:
Richard Trieu4a287fb2011-09-07 01:49:20 +00007963 ResultTy = CheckCompareOperands(LHS, RHS, OpLoc, Opc, false);
Douglas Gregor7d5fc7e2008-11-06 23:29:22 +00007964 break;
John McCalle3027922010-08-25 11:45:40 +00007965 case BO_And:
7966 case BO_Xor:
7967 case BO_Or:
Richard Trieu4a287fb2011-09-07 01:49:20 +00007968 ResultTy = CheckBitwiseOperands(LHS, RHS, OpLoc);
Douglas Gregor7d5fc7e2008-11-06 23:29:22 +00007969 break;
John McCalle3027922010-08-25 11:45:40 +00007970 case BO_LAnd:
7971 case BO_LOr:
Richard Trieu4a287fb2011-09-07 01:49:20 +00007972 ResultTy = CheckLogicalOperands(LHS, RHS, OpLoc, Opc);
Douglas Gregor7d5fc7e2008-11-06 23:29:22 +00007973 break;
John McCalle3027922010-08-25 11:45:40 +00007974 case BO_MulAssign:
7975 case BO_DivAssign:
Richard Trieu4a287fb2011-09-07 01:49:20 +00007976 CompResultTy = CheckMultiplyDivideOperands(LHS, RHS, OpLoc, true,
John McCall7decc9e2010-11-18 06:31:45 +00007977 Opc == BO_DivAssign);
Eli Friedman8b7b1b12009-03-28 01:22:36 +00007978 CompLHSTy = CompResultTy;
Richard Trieu4a287fb2011-09-07 01:49:20 +00007979 if (!CompResultTy.isNull() && !LHS.isInvalid() && !RHS.isInvalid())
7980 ResultTy = CheckAssignmentOperands(LHS.get(), RHS, OpLoc, CompResultTy);
Douglas Gregor7d5fc7e2008-11-06 23:29:22 +00007981 break;
John McCalle3027922010-08-25 11:45:40 +00007982 case BO_RemAssign:
Richard Trieu4a287fb2011-09-07 01:49:20 +00007983 CompResultTy = CheckRemainderOperands(LHS, RHS, OpLoc, true);
Eli Friedman8b7b1b12009-03-28 01:22:36 +00007984 CompLHSTy = CompResultTy;
Richard Trieu4a287fb2011-09-07 01:49:20 +00007985 if (!CompResultTy.isNull() && !LHS.isInvalid() && !RHS.isInvalid())
7986 ResultTy = CheckAssignmentOperands(LHS.get(), RHS, OpLoc, CompResultTy);
Douglas Gregor7d5fc7e2008-11-06 23:29:22 +00007987 break;
John McCalle3027922010-08-25 11:45:40 +00007988 case BO_AddAssign:
Nico Weberccec40d2012-03-02 22:01:22 +00007989 CompResultTy = CheckAdditionOperands(LHS, RHS, OpLoc, Opc, &CompLHSTy);
Richard Trieu4a287fb2011-09-07 01:49:20 +00007990 if (!CompResultTy.isNull() && !LHS.isInvalid() && !RHS.isInvalid())
7991 ResultTy = CheckAssignmentOperands(LHS.get(), RHS, OpLoc, CompResultTy);
Douglas Gregor7d5fc7e2008-11-06 23:29:22 +00007992 break;
John McCalle3027922010-08-25 11:45:40 +00007993 case BO_SubAssign:
Richard Trieu4a287fb2011-09-07 01:49:20 +00007994 CompResultTy = CheckSubtractionOperands(LHS, RHS, OpLoc, &CompLHSTy);
7995 if (!CompResultTy.isNull() && !LHS.isInvalid() && !RHS.isInvalid())
7996 ResultTy = CheckAssignmentOperands(LHS.get(), RHS, OpLoc, CompResultTy);
Douglas Gregor7d5fc7e2008-11-06 23:29:22 +00007997 break;
John McCalle3027922010-08-25 11:45:40 +00007998 case BO_ShlAssign:
7999 case BO_ShrAssign:
Richard Trieu4a287fb2011-09-07 01:49:20 +00008000 CompResultTy = CheckShiftOperands(LHS, RHS, OpLoc, Opc, true);
Eli Friedman8b7b1b12009-03-28 01:22:36 +00008001 CompLHSTy = CompResultTy;
Richard Trieu4a287fb2011-09-07 01:49:20 +00008002 if (!CompResultTy.isNull() && !LHS.isInvalid() && !RHS.isInvalid())
8003 ResultTy = CheckAssignmentOperands(LHS.get(), RHS, OpLoc, CompResultTy);
Douglas Gregor7d5fc7e2008-11-06 23:29:22 +00008004 break;
John McCalle3027922010-08-25 11:45:40 +00008005 case BO_AndAssign:
8006 case BO_XorAssign:
8007 case BO_OrAssign:
Richard Trieu4a287fb2011-09-07 01:49:20 +00008008 CompResultTy = CheckBitwiseOperands(LHS, RHS, OpLoc, true);
Eli Friedman8b7b1b12009-03-28 01:22:36 +00008009 CompLHSTy = CompResultTy;
Richard Trieu4a287fb2011-09-07 01:49:20 +00008010 if (!CompResultTy.isNull() && !LHS.isInvalid() && !RHS.isInvalid())
8011 ResultTy = CheckAssignmentOperands(LHS.get(), RHS, OpLoc, CompResultTy);
Douglas Gregor7d5fc7e2008-11-06 23:29:22 +00008012 break;
John McCalle3027922010-08-25 11:45:40 +00008013 case BO_Comma:
Richard Trieu4a287fb2011-09-07 01:49:20 +00008014 ResultTy = CheckCommaOperands(*this, LHS, RHS, OpLoc);
David Blaikiebbafb8a2012-03-11 07:00:24 +00008015 if (getLangOpts().CPlusPlus && !RHS.isInvalid()) {
Richard Trieu4a287fb2011-09-07 01:49:20 +00008016 VK = RHS.get()->getValueKind();
8017 OK = RHS.get()->getObjectKind();
John McCall7decc9e2010-11-18 06:31:45 +00008018 }
Douglas Gregor7d5fc7e2008-11-06 23:29:22 +00008019 break;
8020 }
Richard Trieu4a287fb2011-09-07 01:49:20 +00008021 if (ResultTy.isNull() || LHS.isInvalid() || RHS.isInvalid())
Sebastian Redlb5d49352009-01-19 22:31:54 +00008022 return ExprError();
Kaelyn Uhrain2e7aa5a2011-08-05 23:18:04 +00008023
8024 // Check for array bounds violations for both sides of the BinaryOperator
Richard Trieu4a287fb2011-09-07 01:49:20 +00008025 CheckArrayAccess(LHS.get());
8026 CheckArrayAccess(RHS.get());
Kaelyn Uhrain2e7aa5a2011-08-05 23:18:04 +00008027
Eli Friedman8b7b1b12009-03-28 01:22:36 +00008028 if (CompResultTy.isNull())
Richard Trieu4a287fb2011-09-07 01:49:20 +00008029 return Owned(new (Context) BinaryOperator(LHS.take(), RHS.take(), Opc,
John Wiegley01296292011-04-08 18:41:53 +00008030 ResultTy, VK, OK, OpLoc));
David Blaikiebbafb8a2012-03-11 07:00:24 +00008031 if (getLangOpts().CPlusPlus && LHS.get()->getObjectKind() !=
Richard Trieucfc491d2011-08-02 04:35:43 +00008032 OK_ObjCProperty) {
John McCall7decc9e2010-11-18 06:31:45 +00008033 VK = VK_LValue;
Richard Trieu4a287fb2011-09-07 01:49:20 +00008034 OK = LHS.get()->getObjectKind();
John McCall7decc9e2010-11-18 06:31:45 +00008035 }
Richard Trieu4a287fb2011-09-07 01:49:20 +00008036 return Owned(new (Context) CompoundAssignOperator(LHS.take(), RHS.take(), Opc,
John Wiegley01296292011-04-08 18:41:53 +00008037 ResultTy, VK, OK, CompLHSTy,
John McCall7decc9e2010-11-18 06:31:45 +00008038 CompResultTy, OpLoc));
Douglas Gregor7d5fc7e2008-11-06 23:29:22 +00008039}
8040
Sebastian Redl44615072009-10-27 12:10:02 +00008041/// DiagnoseBitwisePrecedence - Emit a warning when bitwise and comparison
8042/// operators are mixed in a way that suggests that the programmer forgot that
8043/// comparison operators have higher precedence. The most typical example of
8044/// such code is "flags & 0x0020 != 0", which is equivalent to "flags & 1".
John McCalle3027922010-08-25 11:45:40 +00008045static void DiagnoseBitwisePrecedence(Sema &Self, BinaryOperatorKind Opc,
Richard Trieu4a287fb2011-09-07 01:49:20 +00008046 SourceLocation OpLoc, Expr *LHSExpr,
8047 Expr *RHSExpr) {
Sebastian Redl44615072009-10-27 12:10:02 +00008048 typedef BinaryOperator BinOp;
Richard Trieu4a287fb2011-09-07 01:49:20 +00008049 BinOp::Opcode LHSopc = static_cast<BinOp::Opcode>(-1),
8050 RHSopc = static_cast<BinOp::Opcode>(-1);
8051 if (BinOp *BO = dyn_cast<BinOp>(LHSExpr))
8052 LHSopc = BO->getOpcode();
8053 if (BinOp *BO = dyn_cast<BinOp>(RHSExpr))
8054 RHSopc = BO->getOpcode();
Sebastian Redl43028242009-10-26 15:24:15 +00008055
8056 // Subs are not binary operators.
Richard Trieu4a287fb2011-09-07 01:49:20 +00008057 if (LHSopc == -1 && RHSopc == -1)
Sebastian Redl43028242009-10-26 15:24:15 +00008058 return;
8059
8060 // Bitwise operations are sometimes used as eager logical ops.
8061 // Don't diagnose this.
Richard Trieu4a287fb2011-09-07 01:49:20 +00008062 if ((BinOp::isComparisonOp(LHSopc) || BinOp::isBitwiseOp(LHSopc)) &&
8063 (BinOp::isComparisonOp(RHSopc) || BinOp::isBitwiseOp(RHSopc)))
Sebastian Redl43028242009-10-26 15:24:15 +00008064 return;
8065
Richard Trieu4a287fb2011-09-07 01:49:20 +00008066 bool isLeftComp = BinOp::isComparisonOp(LHSopc);
8067 bool isRightComp = BinOp::isComparisonOp(RHSopc);
Richard Trieu73088052011-08-10 22:41:34 +00008068 if (!isLeftComp && !isRightComp) return;
8069
Richard Trieu4a287fb2011-09-07 01:49:20 +00008070 SourceRange DiagRange = isLeftComp ? SourceRange(LHSExpr->getLocStart(),
8071 OpLoc)
8072 : SourceRange(OpLoc, RHSExpr->getLocEnd());
8073 std::string OpStr = isLeftComp ? BinOp::getOpcodeStr(LHSopc)
8074 : BinOp::getOpcodeStr(RHSopc);
Richard Trieu73088052011-08-10 22:41:34 +00008075 SourceRange ParensRange = isLeftComp ?
Richard Trieu4a287fb2011-09-07 01:49:20 +00008076 SourceRange(cast<BinOp>(LHSExpr)->getRHS()->getLocStart(),
8077 RHSExpr->getLocEnd())
8078 : SourceRange(LHSExpr->getLocStart(),
8079 cast<BinOp>(RHSExpr)->getLHS()->getLocStart());
Richard Trieu73088052011-08-10 22:41:34 +00008080
8081 Self.Diag(OpLoc, diag::warn_precedence_bitwise_rel)
8082 << DiagRange << BinOp::getOpcodeStr(Opc) << OpStr;
8083 SuggestParentheses(Self, OpLoc,
8084 Self.PDiag(diag::note_precedence_bitwise_silence) << OpStr,
Richard Trieu4a287fb2011-09-07 01:49:20 +00008085 RHSExpr->getSourceRange());
Richard Trieu73088052011-08-10 22:41:34 +00008086 SuggestParentheses(Self, OpLoc,
8087 Self.PDiag(diag::note_precedence_bitwise_first) << BinOp::getOpcodeStr(Opc),
8088 ParensRange);
Sebastian Redl43028242009-10-26 15:24:15 +00008089}
8090
Argyrios Kyrtzidis01bf7772011-06-20 18:41:26 +00008091/// \brief It accepts a '&' expr that is inside a '|' one.
8092/// Emit a diagnostic together with a fixit hint that wraps the '&' expression
8093/// in parentheses.
8094static void
8095EmitDiagnosticForBitwiseAndInBitwiseOr(Sema &Self, SourceLocation OpLoc,
8096 BinaryOperator *Bop) {
8097 assert(Bop->getOpcode() == BO_And);
8098 Self.Diag(Bop->getOperatorLoc(), diag::warn_bitwise_and_in_bitwise_or)
8099 << Bop->getSourceRange() << OpLoc;
8100 SuggestParentheses(Self, Bop->getOperatorLoc(),
8101 Self.PDiag(diag::note_bitwise_and_in_bitwise_or_silence),
8102 Bop->getSourceRange());
8103}
8104
Argyrios Kyrtzidis14a96622010-11-17 18:26:36 +00008105/// \brief It accepts a '&&' expr that is inside a '||' one.
8106/// Emit a diagnostic together with a fixit hint that wraps the '&&' expression
8107/// in parentheses.
8108static void
8109EmitDiagnosticForLogicalAndInLogicalOr(Sema &Self, SourceLocation OpLoc,
Argyrios Kyrtzidisad8b4d42011-04-22 19:16:27 +00008110 BinaryOperator *Bop) {
8111 assert(Bop->getOpcode() == BO_LAnd);
Chandler Carruthb00e8c02011-06-16 01:05:14 +00008112 Self.Diag(Bop->getOperatorLoc(), diag::warn_logical_and_in_logical_or)
8113 << Bop->getSourceRange() << OpLoc;
Argyrios Kyrtzidisad8b4d42011-04-22 19:16:27 +00008114 SuggestParentheses(Self, Bop->getOperatorLoc(),
Argyrios Kyrtzidis14a96622010-11-17 18:26:36 +00008115 Self.PDiag(diag::note_logical_and_in_logical_or_silence),
Chandler Carruthb00e8c02011-06-16 01:05:14 +00008116 Bop->getSourceRange());
Argyrios Kyrtzidis14a96622010-11-17 18:26:36 +00008117}
8118
8119/// \brief Returns true if the given expression can be evaluated as a constant
8120/// 'true'.
8121static bool EvaluatesAsTrue(Sema &S, Expr *E) {
8122 bool Res;
8123 return E->EvaluateAsBooleanCondition(Res, S.getASTContext()) && Res;
8124}
8125
Argyrios Kyrtzidis56e879d2010-11-17 19:18:19 +00008126/// \brief Returns true if the given expression can be evaluated as a constant
8127/// 'false'.
8128static bool EvaluatesAsFalse(Sema &S, Expr *E) {
8129 bool Res;
8130 return E->EvaluateAsBooleanCondition(Res, S.getASTContext()) && !Res;
8131}
8132
Argyrios Kyrtzidis14a96622010-11-17 18:26:36 +00008133/// \brief Look for '&&' in the left hand of a '||' expr.
8134static void DiagnoseLogicalAndInLogicalOrLHS(Sema &S, SourceLocation OpLoc,
Richard Trieuf9bd0f52011-09-07 02:02:10 +00008135 Expr *LHSExpr, Expr *RHSExpr) {
8136 if (BinaryOperator *Bop = dyn_cast<BinaryOperator>(LHSExpr)) {
Argyrios Kyrtzidisf89a56c2010-11-16 21:00:12 +00008137 if (Bop->getOpcode() == BO_LAnd) {
Argyrios Kyrtzidis56e879d2010-11-17 19:18:19 +00008138 // If it's "a && b || 0" don't warn since the precedence doesn't matter.
Richard Trieuf9bd0f52011-09-07 02:02:10 +00008139 if (EvaluatesAsFalse(S, RHSExpr))
Argyrios Kyrtzidis56e879d2010-11-17 19:18:19 +00008140 return;
Argyrios Kyrtzidis14a96622010-11-17 18:26:36 +00008141 // If it's "1 && a || b" don't warn since the precedence doesn't matter.
8142 if (!EvaluatesAsTrue(S, Bop->getLHS()))
8143 return EmitDiagnosticForLogicalAndInLogicalOr(S, OpLoc, Bop);
8144 } else if (Bop->getOpcode() == BO_LOr) {
8145 if (BinaryOperator *RBop = dyn_cast<BinaryOperator>(Bop->getRHS())) {
8146 // If it's "a || b && 1 || c" we didn't warn earlier for
8147 // "a || b && 1", but warn now.
8148 if (RBop->getOpcode() == BO_LAnd && EvaluatesAsTrue(S, RBop->getRHS()))
8149 return EmitDiagnosticForLogicalAndInLogicalOr(S, OpLoc, RBop);
8150 }
8151 }
8152 }
8153}
8154
8155/// \brief Look for '&&' in the right hand of a '||' expr.
8156static void DiagnoseLogicalAndInLogicalOrRHS(Sema &S, SourceLocation OpLoc,
Richard Trieuf9bd0f52011-09-07 02:02:10 +00008157 Expr *LHSExpr, Expr *RHSExpr) {
8158 if (BinaryOperator *Bop = dyn_cast<BinaryOperator>(RHSExpr)) {
Argyrios Kyrtzidis14a96622010-11-17 18:26:36 +00008159 if (Bop->getOpcode() == BO_LAnd) {
Argyrios Kyrtzidis56e879d2010-11-17 19:18:19 +00008160 // If it's "0 || a && b" don't warn since the precedence doesn't matter.
Richard Trieuf9bd0f52011-09-07 02:02:10 +00008161 if (EvaluatesAsFalse(S, LHSExpr))
Argyrios Kyrtzidis56e879d2010-11-17 19:18:19 +00008162 return;
Argyrios Kyrtzidis14a96622010-11-17 18:26:36 +00008163 // If it's "a || b && 1" don't warn since the precedence doesn't matter.
8164 if (!EvaluatesAsTrue(S, Bop->getRHS()))
8165 return EmitDiagnosticForLogicalAndInLogicalOr(S, OpLoc, Bop);
Argyrios Kyrtzidisf89a56c2010-11-16 21:00:12 +00008166 }
8167 }
8168}
8169
Argyrios Kyrtzidis01bf7772011-06-20 18:41:26 +00008170/// \brief Look for '&' in the left or right hand of a '|' expr.
8171static void DiagnoseBitwiseAndInBitwiseOr(Sema &S, SourceLocation OpLoc,
8172 Expr *OrArg) {
8173 if (BinaryOperator *Bop = dyn_cast<BinaryOperator>(OrArg)) {
8174 if (Bop->getOpcode() == BO_And)
8175 return EmitDiagnosticForBitwiseAndInBitwiseOr(S, OpLoc, Bop);
8176 }
8177}
8178
Sebastian Redl43028242009-10-26 15:24:15 +00008179/// DiagnoseBinOpPrecedence - Emit warnings for expressions with tricky
Argyrios Kyrtzidisf89a56c2010-11-16 21:00:12 +00008180/// precedence.
John McCalle3027922010-08-25 11:45:40 +00008181static void DiagnoseBinOpPrecedence(Sema &Self, BinaryOperatorKind Opc,
Richard Trieuf9bd0f52011-09-07 02:02:10 +00008182 SourceLocation OpLoc, Expr *LHSExpr,
8183 Expr *RHSExpr){
Argyrios Kyrtzidisf89a56c2010-11-16 21:00:12 +00008184 // Diagnose "arg1 'bitwise' arg2 'eq' arg3".
Sebastian Redl44615072009-10-27 12:10:02 +00008185 if (BinaryOperator::isBitwiseOp(Opc))
Richard Trieuf9bd0f52011-09-07 02:02:10 +00008186 DiagnoseBitwisePrecedence(Self, Opc, OpLoc, LHSExpr, RHSExpr);
Argyrios Kyrtzidis01bf7772011-06-20 18:41:26 +00008187
8188 // Diagnose "arg1 & arg2 | arg3"
8189 if (Opc == BO_Or && !OpLoc.isMacroID()/* Don't warn in macros. */) {
Richard Trieuf9bd0f52011-09-07 02:02:10 +00008190 DiagnoseBitwiseAndInBitwiseOr(Self, OpLoc, LHSExpr);
8191 DiagnoseBitwiseAndInBitwiseOr(Self, OpLoc, RHSExpr);
Argyrios Kyrtzidis01bf7772011-06-20 18:41:26 +00008192 }
Argyrios Kyrtzidisf89a56c2010-11-16 21:00:12 +00008193
Argyrios Kyrtzidis14a96622010-11-17 18:26:36 +00008194 // Warn about arg1 || arg2 && arg3, as GCC 4.3+ does.
8195 // We don't warn for 'assert(a || b && "bad")' since this is safe.
Argyrios Kyrtzidisb94e5a32010-11-17 18:54:22 +00008196 if (Opc == BO_LOr && !OpLoc.isMacroID()/* Don't warn in macros. */) {
Richard Trieuf9bd0f52011-09-07 02:02:10 +00008197 DiagnoseLogicalAndInLogicalOrLHS(Self, OpLoc, LHSExpr, RHSExpr);
8198 DiagnoseLogicalAndInLogicalOrRHS(Self, OpLoc, LHSExpr, RHSExpr);
Argyrios Kyrtzidisf89a56c2010-11-16 21:00:12 +00008199 }
Sebastian Redl43028242009-10-26 15:24:15 +00008200}
8201
Steve Naroff218bc2b2007-05-04 21:54:46 +00008202// Binary Operators. 'Tok' is the token for the operator.
John McCalldadc5752010-08-24 06:29:42 +00008203ExprResult Sema::ActOnBinOp(Scope *S, SourceLocation TokLoc,
John McCalle3027922010-08-25 11:45:40 +00008204 tok::TokenKind Kind,
Richard Trieuf9bd0f52011-09-07 02:02:10 +00008205 Expr *LHSExpr, Expr *RHSExpr) {
John McCalle3027922010-08-25 11:45:40 +00008206 BinaryOperatorKind Opc = ConvertTokenKindToBinaryOpcode(Kind);
Richard Trieuf9bd0f52011-09-07 02:02:10 +00008207 assert((LHSExpr != 0) && "ActOnBinOp(): missing left expression");
8208 assert((RHSExpr != 0) && "ActOnBinOp(): missing right expression");
Steve Naroff218bc2b2007-05-04 21:54:46 +00008209
Sebastian Redl43028242009-10-26 15:24:15 +00008210 // Emit warnings for tricky precedence issues, e.g. "bitfield & 0x4 == 0"
Richard Trieuf9bd0f52011-09-07 02:02:10 +00008211 DiagnoseBinOpPrecedence(*this, Opc, TokLoc, LHSExpr, RHSExpr);
Sebastian Redl43028242009-10-26 15:24:15 +00008212
Richard Trieuf9bd0f52011-09-07 02:02:10 +00008213 return BuildBinOp(S, TokLoc, Opc, LHSExpr, RHSExpr);
Douglas Gregor5287f092009-11-05 00:51:44 +00008214}
8215
John McCall526ab472011-10-25 17:37:35 +00008216/// Build an overloaded binary operator expression in the given scope.
8217static ExprResult BuildOverloadedBinOp(Sema &S, Scope *Sc, SourceLocation OpLoc,
8218 BinaryOperatorKind Opc,
8219 Expr *LHS, Expr *RHS) {
8220 // Find all of the overloaded operators visible from this
8221 // point. We perform both an operator-name lookup from the local
8222 // scope and an argument-dependent lookup based on the types of
8223 // the arguments.
8224 UnresolvedSet<16> Functions;
8225 OverloadedOperatorKind OverOp
8226 = BinaryOperator::getOverloadedOperator(Opc);
8227 if (Sc && OverOp != OO_None)
8228 S.LookupOverloadedOperatorName(OverOp, Sc, LHS->getType(),
8229 RHS->getType(), Functions);
8230
8231 // Build the (potentially-overloaded, potentially-dependent)
8232 // binary operation.
8233 return S.CreateOverloadedBinOp(OpLoc, Opc, Functions, LHS, RHS);
8234}
8235
John McCalldadc5752010-08-24 06:29:42 +00008236ExprResult Sema::BuildBinOp(Scope *S, SourceLocation OpLoc,
John McCalle3027922010-08-25 11:45:40 +00008237 BinaryOperatorKind Opc,
Richard Trieuf9bd0f52011-09-07 02:02:10 +00008238 Expr *LHSExpr, Expr *RHSExpr) {
John McCall9a43e122011-10-28 01:04:34 +00008239 // We want to end up calling one of checkPseudoObjectAssignment
8240 // (if the LHS is a pseudo-object), BuildOverloadedBinOp (if
8241 // both expressions are overloadable or either is type-dependent),
8242 // or CreateBuiltinBinOp (in any other case). We also want to get
8243 // any placeholder types out of the way.
8244
John McCall526ab472011-10-25 17:37:35 +00008245 // Handle pseudo-objects in the LHS.
8246 if (const BuiltinType *pty = LHSExpr->getType()->getAsPlaceholderType()) {
8247 // Assignments with a pseudo-object l-value need special analysis.
8248 if (pty->getKind() == BuiltinType::PseudoObject &&
8249 BinaryOperator::isAssignmentOp(Opc))
8250 return checkPseudoObjectAssignment(S, OpLoc, Opc, LHSExpr, RHSExpr);
8251
8252 // Don't resolve overloads if the other type is overloadable.
8253 if (pty->getKind() == BuiltinType::Overload) {
8254 // We can't actually test that if we still have a placeholder,
8255 // though. Fortunately, none of the exceptions we see in that
John McCall9a43e122011-10-28 01:04:34 +00008256 // code below are valid when the LHS is an overload set. Note
8257 // that an overload set can be dependently-typed, but it never
8258 // instantiates to having an overloadable type.
John McCall526ab472011-10-25 17:37:35 +00008259 ExprResult resolvedRHS = CheckPlaceholderExpr(RHSExpr);
8260 if (resolvedRHS.isInvalid()) return ExprError();
8261 RHSExpr = resolvedRHS.take();
8262
John McCall9a43e122011-10-28 01:04:34 +00008263 if (RHSExpr->isTypeDependent() ||
8264 RHSExpr->getType()->isOverloadableType())
John McCall526ab472011-10-25 17:37:35 +00008265 return BuildOverloadedBinOp(*this, S, OpLoc, Opc, LHSExpr, RHSExpr);
8266 }
8267
8268 ExprResult LHS = CheckPlaceholderExpr(LHSExpr);
8269 if (LHS.isInvalid()) return ExprError();
8270 LHSExpr = LHS.take();
8271 }
8272
8273 // Handle pseudo-objects in the RHS.
8274 if (const BuiltinType *pty = RHSExpr->getType()->getAsPlaceholderType()) {
8275 // An overload in the RHS can potentially be resolved by the type
8276 // being assigned to.
John McCall9a43e122011-10-28 01:04:34 +00008277 if (Opc == BO_Assign && pty->getKind() == BuiltinType::Overload) {
8278 if (LHSExpr->isTypeDependent() || RHSExpr->isTypeDependent())
8279 return BuildOverloadedBinOp(*this, S, OpLoc, Opc, LHSExpr, RHSExpr);
8280
Eli Friedman419b1ff2012-01-17 21:27:43 +00008281 if (LHSExpr->getType()->isOverloadableType())
8282 return BuildOverloadedBinOp(*this, S, OpLoc, Opc, LHSExpr, RHSExpr);
8283
John McCall526ab472011-10-25 17:37:35 +00008284 return CreateBuiltinBinOp(OpLoc, Opc, LHSExpr, RHSExpr);
John McCall9a43e122011-10-28 01:04:34 +00008285 }
John McCall526ab472011-10-25 17:37:35 +00008286
8287 // Don't resolve overloads if the other type is overloadable.
8288 if (pty->getKind() == BuiltinType::Overload &&
8289 LHSExpr->getType()->isOverloadableType())
8290 return BuildOverloadedBinOp(*this, S, OpLoc, Opc, LHSExpr, RHSExpr);
8291
8292 ExprResult resolvedRHS = CheckPlaceholderExpr(RHSExpr);
8293 if (!resolvedRHS.isUsable()) return ExprError();
8294 RHSExpr = resolvedRHS.take();
8295 }
8296
David Blaikiebbafb8a2012-03-11 07:00:24 +00008297 if (getLangOpts().CPlusPlus) {
John McCall9a43e122011-10-28 01:04:34 +00008298 // If either expression is type-dependent, always build an
8299 // overloaded op.
8300 if (LHSExpr->isTypeDependent() || RHSExpr->isTypeDependent())
8301 return BuildOverloadedBinOp(*this, S, OpLoc, Opc, LHSExpr, RHSExpr);
Kovarththanan Rajaratnamba2c6522010-03-13 10:17:05 +00008302
John McCall9a43e122011-10-28 01:04:34 +00008303 // Otherwise, build an overloaded op if either expression has an
8304 // overloadable type.
8305 if (LHSExpr->getType()->isOverloadableType() ||
8306 RHSExpr->getType()->isOverloadableType())
John McCall526ab472011-10-25 17:37:35 +00008307 return BuildOverloadedBinOp(*this, S, OpLoc, Opc, LHSExpr, RHSExpr);
Sebastian Redlb5d49352009-01-19 22:31:54 +00008308 }
Kovarththanan Rajaratnamba2c6522010-03-13 10:17:05 +00008309
Douglas Gregor7d5fc7e2008-11-06 23:29:22 +00008310 // Build a built-in binary operation.
Richard Trieuf9bd0f52011-09-07 02:02:10 +00008311 return CreateBuiltinBinOp(OpLoc, Opc, LHSExpr, RHSExpr);
Steve Naroff218bc2b2007-05-04 21:54:46 +00008312}
8313
John McCalldadc5752010-08-24 06:29:42 +00008314ExprResult Sema::CreateBuiltinUnaryOp(SourceLocation OpLoc,
Argyrios Kyrtzidis7a808c02011-01-05 20:09:36 +00008315 UnaryOperatorKind Opc,
John Wiegley01296292011-04-08 18:41:53 +00008316 Expr *InputExpr) {
8317 ExprResult Input = Owned(InputExpr);
John McCall7decc9e2010-11-18 06:31:45 +00008318 ExprValueKind VK = VK_RValue;
8319 ExprObjectKind OK = OK_Ordinary;
Steve Naroff35d85152007-05-07 00:24:15 +00008320 QualType resultType;
8321 switch (Opc) {
John McCalle3027922010-08-25 11:45:40 +00008322 case UO_PreInc:
8323 case UO_PreDec:
8324 case UO_PostInc:
8325 case UO_PostDec:
John Wiegley01296292011-04-08 18:41:53 +00008326 resultType = CheckIncrementDecrementOperand(*this, Input.get(), VK, OpLoc,
John McCalle3027922010-08-25 11:45:40 +00008327 Opc == UO_PreInc ||
8328 Opc == UO_PostInc,
8329 Opc == UO_PreInc ||
8330 Opc == UO_PreDec);
Steve Naroff35d85152007-05-07 00:24:15 +00008331 break;
John McCalle3027922010-08-25 11:45:40 +00008332 case UO_AddrOf:
John McCall526ab472011-10-25 17:37:35 +00008333 resultType = CheckAddressOfOperand(*this, Input, OpLoc);
Steve Naroff35d85152007-05-07 00:24:15 +00008334 break;
John McCall31996342011-04-07 08:22:57 +00008335 case UO_Deref: {
John Wiegley01296292011-04-08 18:41:53 +00008336 Input = DefaultFunctionArrayLvalueConversion(Input.take());
8337 resultType = CheckIndirectionOperand(*this, Input.get(), VK, OpLoc);
Steve Naroff35d85152007-05-07 00:24:15 +00008338 break;
John McCall31996342011-04-07 08:22:57 +00008339 }
John McCalle3027922010-08-25 11:45:40 +00008340 case UO_Plus:
8341 case UO_Minus:
John Wiegley01296292011-04-08 18:41:53 +00008342 Input = UsualUnaryConversions(Input.take());
8343 if (Input.isInvalid()) return ExprError();
8344 resultType = Input.get()->getType();
Sebastian Redl8d2ccae2009-02-26 14:39:58 +00008345 if (resultType->isDependentType())
8346 break;
Douglas Gregora3208f92010-06-22 23:41:02 +00008347 if (resultType->isArithmeticType() || // C99 6.5.3.3p1
8348 resultType->isVectorType())
Douglas Gregord08452f2008-11-19 15:42:04 +00008349 break;
David Blaikiebbafb8a2012-03-11 07:00:24 +00008350 else if (getLangOpts().CPlusPlus && // C++ [expr.unary.op]p6-7
Douglas Gregord08452f2008-11-19 15:42:04 +00008351 resultType->isEnumeralType())
8352 break;
David Blaikiebbafb8a2012-03-11 07:00:24 +00008353 else if (getLangOpts().CPlusPlus && // C++ [expr.unary.op]p6
John McCalle3027922010-08-25 11:45:40 +00008354 Opc == UO_Plus &&
Douglas Gregord08452f2008-11-19 15:42:04 +00008355 resultType->isPointerType())
8356 break;
8357
Sebastian Redlc215cfc2009-01-19 00:08:26 +00008358 return ExprError(Diag(OpLoc, diag::err_typecheck_unary_expr)
John Wiegley01296292011-04-08 18:41:53 +00008359 << resultType << Input.get()->getSourceRange());
8360
John McCalle3027922010-08-25 11:45:40 +00008361 case UO_Not: // bitwise complement
John Wiegley01296292011-04-08 18:41:53 +00008362 Input = UsualUnaryConversions(Input.take());
8363 if (Input.isInvalid()) return ExprError();
8364 resultType = Input.get()->getType();
Sebastian Redl8d2ccae2009-02-26 14:39:58 +00008365 if (resultType->isDependentType())
8366 break;
Chris Lattner0d707612008-07-25 23:52:49 +00008367 // C99 6.5.3.3p1. We allow complex int and float as a GCC extension.
8368 if (resultType->isComplexType() || resultType->isComplexIntegerType())
8369 // C99 does not support '~' for complex conjugation.
Chris Lattner29e812b2008-11-20 06:06:08 +00008370 Diag(OpLoc, diag::ext_integer_complement_complex)
John Wiegley01296292011-04-08 18:41:53 +00008371 << resultType << Input.get()->getSourceRange();
John McCall36226622010-10-12 02:09:17 +00008372 else if (resultType->hasIntegerRepresentation())
8373 break;
John McCall526ab472011-10-25 17:37:35 +00008374 else {
Sebastian Redlc215cfc2009-01-19 00:08:26 +00008375 return ExprError(Diag(OpLoc, diag::err_typecheck_unary_expr)
John Wiegley01296292011-04-08 18:41:53 +00008376 << resultType << Input.get()->getSourceRange());
John McCall36226622010-10-12 02:09:17 +00008377 }
Steve Naroff35d85152007-05-07 00:24:15 +00008378 break;
John Wiegley01296292011-04-08 18:41:53 +00008379
John McCalle3027922010-08-25 11:45:40 +00008380 case UO_LNot: // logical negation
Steve Naroff71b59a92007-06-04 22:22:31 +00008381 // Unlike +/-/~, integer promotions aren't done here (C99 6.5.3.3p5).
John Wiegley01296292011-04-08 18:41:53 +00008382 Input = DefaultFunctionArrayLvalueConversion(Input.take());
8383 if (Input.isInvalid()) return ExprError();
8384 resultType = Input.get()->getType();
Anton Korobeynikovf0c267e2011-10-14 23:23:15 +00008385
8386 // Though we still have to promote half FP to float...
8387 if (resultType->isHalfType()) {
8388 Input = ImpCastExprToType(Input.take(), Context.FloatTy, CK_FloatingCast).take();
8389 resultType = Context.FloatTy;
8390 }
8391
Sebastian Redl8d2ccae2009-02-26 14:39:58 +00008392 if (resultType->isDependentType())
8393 break;
Abramo Bagnara7ccce982011-04-07 09:26:19 +00008394 if (resultType->isScalarType()) {
8395 // C99 6.5.3.3p1: ok, fallthrough;
David Blaikiebbafb8a2012-03-11 07:00:24 +00008396 if (Context.getLangOpts().CPlusPlus) {
Abramo Bagnara7ccce982011-04-07 09:26:19 +00008397 // C++03 [expr.unary.op]p8, C++0x [expr.unary.op]p9:
8398 // operand contextually converted to bool.
John Wiegley01296292011-04-08 18:41:53 +00008399 Input = ImpCastExprToType(Input.take(), Context.BoolTy,
8400 ScalarTypeToBooleanCastKind(resultType));
Abramo Bagnara7ccce982011-04-07 09:26:19 +00008401 }
Tanya Lattner3dd33b22012-01-19 01:16:16 +00008402 } else if (resultType->isExtVectorType()) {
Tanya Lattner20248222012-01-16 21:02:28 +00008403 // Vector logical not returns the signed variant of the operand type.
8404 resultType = GetSignedVectorType(resultType);
8405 break;
John McCall36226622010-10-12 02:09:17 +00008406 } else {
Sebastian Redlc215cfc2009-01-19 00:08:26 +00008407 return ExprError(Diag(OpLoc, diag::err_typecheck_unary_expr)
John Wiegley01296292011-04-08 18:41:53 +00008408 << resultType << Input.get()->getSourceRange());
John McCall36226622010-10-12 02:09:17 +00008409 }
Douglas Gregordb8c6fd2010-09-20 17:13:33 +00008410
Chris Lattnerbe31ed82007-06-02 19:11:33 +00008411 // LNot always has type int. C99 6.5.3.3p5.
Sebastian Redlc215cfc2009-01-19 00:08:26 +00008412 // In C++, it's bool. C++ 5.3.1p8
Argyrios Kyrtzidis1bdd6882011-02-18 20:55:15 +00008413 resultType = Context.getLogicalOperationType();
Steve Naroff35d85152007-05-07 00:24:15 +00008414 break;
John McCalle3027922010-08-25 11:45:40 +00008415 case UO_Real:
8416 case UO_Imag:
John McCall4bc41ae2010-11-18 19:01:18 +00008417 resultType = CheckRealImagOperand(*this, Input, OpLoc, Opc == UO_Real);
Richard Smith0b6b8e42012-02-18 20:53:32 +00008418 // _Real maps ordinary l-values into ordinary l-values. _Imag maps ordinary
8419 // complex l-values to ordinary l-values and all other values to r-values.
John Wiegley01296292011-04-08 18:41:53 +00008420 if (Input.isInvalid()) return ExprError();
Richard Smith0b6b8e42012-02-18 20:53:32 +00008421 if (Opc == UO_Real || Input.get()->getType()->isAnyComplexType()) {
8422 if (Input.get()->getValueKind() != VK_RValue &&
8423 Input.get()->getObjectKind() == OK_Ordinary)
8424 VK = Input.get()->getValueKind();
David Blaikiebbafb8a2012-03-11 07:00:24 +00008425 } else if (!getLangOpts().CPlusPlus) {
Richard Smith0b6b8e42012-02-18 20:53:32 +00008426 // In C, a volatile scalar is read by __imag. In C++, it is not.
8427 Input = DefaultLvalueConversion(Input.take());
8428 }
Chris Lattner30b5dd02007-08-24 21:16:53 +00008429 break;
John McCalle3027922010-08-25 11:45:40 +00008430 case UO_Extension:
John Wiegley01296292011-04-08 18:41:53 +00008431 resultType = Input.get()->getType();
8432 VK = Input.get()->getValueKind();
8433 OK = Input.get()->getObjectKind();
Steve Naroff043d45d2007-05-15 02:32:35 +00008434 break;
Steve Naroff35d85152007-05-07 00:24:15 +00008435 }
John Wiegley01296292011-04-08 18:41:53 +00008436 if (resultType.isNull() || Input.isInvalid())
Sebastian Redlc215cfc2009-01-19 00:08:26 +00008437 return ExprError();
Douglas Gregor084d8552009-03-13 23:49:33 +00008438
Kaelyn Uhrain2e7aa5a2011-08-05 23:18:04 +00008439 // Check for array bounds violations in the operand of the UnaryOperator,
8440 // except for the '*' and '&' operators that have to be handled specially
8441 // by CheckArrayAccess (as there are special cases like &array[arraysize]
8442 // that are explicitly defined as valid by the standard).
8443 if (Opc != UO_AddrOf && Opc != UO_Deref)
8444 CheckArrayAccess(Input.get());
8445
John Wiegley01296292011-04-08 18:41:53 +00008446 return Owned(new (Context) UnaryOperator(Input.take(), Opc, resultType,
John McCall7decc9e2010-11-18 06:31:45 +00008447 VK, OK, OpLoc));
Steve Naroff35d85152007-05-07 00:24:15 +00008448}
Chris Lattnereefa10e2007-05-28 06:56:27 +00008449
Douglas Gregor72341032011-12-14 21:23:13 +00008450/// \brief Determine whether the given expression is a qualified member
8451/// access expression, of a form that could be turned into a pointer to member
8452/// with the address-of operator.
8453static bool isQualifiedMemberAccess(Expr *E) {
8454 if (DeclRefExpr *DRE = dyn_cast<DeclRefExpr>(E)) {
8455 if (!DRE->getQualifier())
8456 return false;
8457
8458 ValueDecl *VD = DRE->getDecl();
8459 if (!VD->isCXXClassMember())
8460 return false;
8461
8462 if (isa<FieldDecl>(VD) || isa<IndirectFieldDecl>(VD))
8463 return true;
8464 if (CXXMethodDecl *Method = dyn_cast<CXXMethodDecl>(VD))
8465 return Method->isInstance();
8466
8467 return false;
8468 }
8469
8470 if (UnresolvedLookupExpr *ULE = dyn_cast<UnresolvedLookupExpr>(E)) {
8471 if (!ULE->getQualifier())
8472 return false;
8473
8474 for (UnresolvedLookupExpr::decls_iterator D = ULE->decls_begin(),
8475 DEnd = ULE->decls_end();
8476 D != DEnd; ++D) {
8477 if (CXXMethodDecl *Method = dyn_cast<CXXMethodDecl>(*D)) {
8478 if (Method->isInstance())
8479 return true;
8480 } else {
8481 // Overload set does not contain methods.
8482 break;
8483 }
8484 }
8485
8486 return false;
8487 }
8488
8489 return false;
8490}
8491
John McCalldadc5752010-08-24 06:29:42 +00008492ExprResult Sema::BuildUnaryOp(Scope *S, SourceLocation OpLoc,
Richard Trieuba63ce62011-09-09 01:45:06 +00008493 UnaryOperatorKind Opc, Expr *Input) {
John McCall526ab472011-10-25 17:37:35 +00008494 // First things first: handle placeholders so that the
8495 // overloaded-operator check considers the right type.
8496 if (const BuiltinType *pty = Input->getType()->getAsPlaceholderType()) {
8497 // Increment and decrement of pseudo-object references.
8498 if (pty->getKind() == BuiltinType::PseudoObject &&
8499 UnaryOperator::isIncrementDecrementOp(Opc))
8500 return checkPseudoObjectIncDec(S, OpLoc, Opc, Input);
8501
8502 // extension is always a builtin operator.
8503 if (Opc == UO_Extension)
8504 return CreateBuiltinUnaryOp(OpLoc, Opc, Input);
8505
8506 // & gets special logic for several kinds of placeholder.
8507 // The builtin code knows what to do.
8508 if (Opc == UO_AddrOf &&
8509 (pty->getKind() == BuiltinType::Overload ||
8510 pty->getKind() == BuiltinType::UnknownAny ||
8511 pty->getKind() == BuiltinType::BoundMember))
8512 return CreateBuiltinUnaryOp(OpLoc, Opc, Input);
8513
8514 // Anything else needs to be handled now.
8515 ExprResult Result = CheckPlaceholderExpr(Input);
8516 if (Result.isInvalid()) return ExprError();
8517 Input = Result.take();
8518 }
8519
David Blaikiebbafb8a2012-03-11 07:00:24 +00008520 if (getLangOpts().CPlusPlus && Input->getType()->isOverloadableType() &&
Douglas Gregor72341032011-12-14 21:23:13 +00008521 UnaryOperator::getOverloadedOperator(Opc) != OO_None &&
8522 !(Opc == UO_AddrOf && isQualifiedMemberAccess(Input))) {
Douglas Gregor084d8552009-03-13 23:49:33 +00008523 // Find all of the overloaded operators visible from this
8524 // point. We perform both an operator-name lookup from the local
8525 // scope and an argument-dependent lookup based on the types of
8526 // the arguments.
John McCall4c4c1df2010-01-26 03:27:55 +00008527 UnresolvedSet<16> Functions;
Douglas Gregor084d8552009-03-13 23:49:33 +00008528 OverloadedOperatorKind OverOp = UnaryOperator::getOverloadedOperator(Opc);
John McCall4c4c1df2010-01-26 03:27:55 +00008529 if (S && OverOp != OO_None)
8530 LookupOverloadedOperatorName(OverOp, S, Input->getType(), QualType(),
8531 Functions);
Kovarththanan Rajaratnamba2c6522010-03-13 10:17:05 +00008532
John McCallb268a282010-08-23 23:25:46 +00008533 return CreateOverloadedUnaryOp(OpLoc, Opc, Functions, Input);
Douglas Gregor084d8552009-03-13 23:49:33 +00008534 }
Kovarththanan Rajaratnamba2c6522010-03-13 10:17:05 +00008535
John McCallb268a282010-08-23 23:25:46 +00008536 return CreateBuiltinUnaryOp(OpLoc, Opc, Input);
Douglas Gregor084d8552009-03-13 23:49:33 +00008537}
8538
Douglas Gregor5287f092009-11-05 00:51:44 +00008539// Unary Operators. 'Tok' is the token for the operator.
John McCalldadc5752010-08-24 06:29:42 +00008540ExprResult Sema::ActOnUnaryOp(Scope *S, SourceLocation OpLoc,
John McCall424cec92011-01-19 06:33:43 +00008541 tok::TokenKind Op, Expr *Input) {
John McCallb268a282010-08-23 23:25:46 +00008542 return BuildUnaryOp(S, OpLoc, ConvertTokenKindToUnaryOpcode(Op), Input);
Douglas Gregor5287f092009-11-05 00:51:44 +00008543}
8544
Steve Naroff66356bd2007-09-16 14:56:35 +00008545/// ActOnAddrLabel - Parse the GNU address of label extension: "&&foo".
Chris Lattnerc8e630e2011-02-17 07:39:24 +00008546ExprResult Sema::ActOnAddrLabel(SourceLocation OpLoc, SourceLocation LabLoc,
Chris Lattnercab02a62011-02-17 20:34:02 +00008547 LabelDecl *TheDecl) {
Chris Lattnerc8e630e2011-02-17 07:39:24 +00008548 TheDecl->setUsed();
Chris Lattnereefa10e2007-05-28 06:56:27 +00008549 // Create the AST node. The address of a label always has type 'void*'.
Chris Lattnerc8e630e2011-02-17 07:39:24 +00008550 return Owned(new (Context) AddrLabelExpr(OpLoc, LabLoc, TheDecl,
Sebastian Redl6d4256c2009-03-15 17:47:39 +00008551 Context.getPointerType(Context.VoidTy)));
Chris Lattnereefa10e2007-05-28 06:56:27 +00008552}
8553
John McCall31168b02011-06-15 23:02:42 +00008554/// Given the last statement in a statement-expression, check whether
8555/// the result is a producing expression (like a call to an
8556/// ns_returns_retained function) and, if so, rebuild it to hoist the
8557/// release out of the full-expression. Otherwise, return null.
8558/// Cannot fail.
Richard Trieuba63ce62011-09-09 01:45:06 +00008559static Expr *maybeRebuildARCConsumingStmt(Stmt *Statement) {
John McCall31168b02011-06-15 23:02:42 +00008560 // Should always be wrapped with one of these.
Richard Trieuba63ce62011-09-09 01:45:06 +00008561 ExprWithCleanups *cleanups = dyn_cast<ExprWithCleanups>(Statement);
John McCall31168b02011-06-15 23:02:42 +00008562 if (!cleanups) return 0;
8563
8564 ImplicitCastExpr *cast = dyn_cast<ImplicitCastExpr>(cleanups->getSubExpr());
John McCall2d637d22011-09-10 06:18:15 +00008565 if (!cast || cast->getCastKind() != CK_ARCConsumeObject)
John McCall31168b02011-06-15 23:02:42 +00008566 return 0;
8567
8568 // Splice out the cast. This shouldn't modify any interesting
8569 // features of the statement.
8570 Expr *producer = cast->getSubExpr();
8571 assert(producer->getType() == cast->getType());
8572 assert(producer->getValueKind() == cast->getValueKind());
8573 cleanups->setSubExpr(producer);
8574 return cleanups;
8575}
8576
John McCall3abee492012-04-04 01:27:53 +00008577void Sema::ActOnStartStmtExpr() {
8578 PushExpressionEvaluationContext(ExprEvalContexts.back().Context);
8579}
8580
8581void Sema::ActOnStmtExprError() {
John McCalled7b2782012-04-06 18:20:53 +00008582 // Note that function is also called by TreeTransform when leaving a
8583 // StmtExpr scope without rebuilding anything.
8584
John McCall3abee492012-04-04 01:27:53 +00008585 DiscardCleanupsInEvaluationContext();
8586 PopExpressionEvaluationContext();
8587}
8588
John McCalldadc5752010-08-24 06:29:42 +00008589ExprResult
John McCallb268a282010-08-23 23:25:46 +00008590Sema::ActOnStmtExpr(SourceLocation LPLoc, Stmt *SubStmt,
Sebastian Redl6d4256c2009-03-15 17:47:39 +00008591 SourceLocation RPLoc) { // "({..})"
Chris Lattner366727f2007-07-24 16:58:17 +00008592 assert(SubStmt && isa<CompoundStmt>(SubStmt) && "Invalid action invocation!");
8593 CompoundStmt *Compound = cast<CompoundStmt>(SubStmt);
8594
John McCall3abee492012-04-04 01:27:53 +00008595 if (hasAnyUnrecoverableErrorsInThisFunction())
8596 DiscardCleanupsInEvaluationContext();
8597 assert(!ExprNeedsCleanups && "cleanups within StmtExpr not correctly bound!");
8598 PopExpressionEvaluationContext();
8599
Douglas Gregor6cf3f3c2010-03-10 04:54:39 +00008600 bool isFileScope
8601 = (getCurFunctionOrMethodDecl() == 0) && (getCurBlock() == 0);
Chris Lattnera69b0762009-04-25 19:11:05 +00008602 if (isFileScope)
Sebastian Redl6d4256c2009-03-15 17:47:39 +00008603 return ExprError(Diag(LPLoc, diag::err_stmtexpr_file_scope));
Eli Friedman52cc0162009-01-24 23:09:00 +00008604
Chris Lattner366727f2007-07-24 16:58:17 +00008605 // FIXME: there are a variety of strange constraints to enforce here, for
8606 // example, it is not possible to goto into a stmt expression apparently.
8607 // More semantic analysis is needed.
Mike Stump4e1f26a2009-02-19 03:04:26 +00008608
Chris Lattner366727f2007-07-24 16:58:17 +00008609 // If there are sub stmts in the compound stmt, take the type of the last one
8610 // as the type of the stmtexpr.
8611 QualType Ty = Context.VoidTy;
Fariborz Jahanian56143ae2010-10-25 23:27:26 +00008612 bool StmtExprMayBindToTemp = false;
Chris Lattner944d3062008-07-26 19:51:01 +00008613 if (!Compound->body_empty()) {
8614 Stmt *LastStmt = Compound->body_back();
Fariborz Jahanian56143ae2010-10-25 23:27:26 +00008615 LabelStmt *LastLabelStmt = 0;
Chris Lattner944d3062008-07-26 19:51:01 +00008616 // If LastStmt is a label, skip down through into the body.
Fariborz Jahanian56143ae2010-10-25 23:27:26 +00008617 while (LabelStmt *Label = dyn_cast<LabelStmt>(LastStmt)) {
8618 LastLabelStmt = Label;
Chris Lattner944d3062008-07-26 19:51:01 +00008619 LastStmt = Label->getSubStmt();
Fariborz Jahanian56143ae2010-10-25 23:27:26 +00008620 }
John McCall31168b02011-06-15 23:02:42 +00008621
John Wiegley01296292011-04-08 18:41:53 +00008622 if (Expr *LastE = dyn_cast<Expr>(LastStmt)) {
John McCall34376a62010-12-04 03:47:34 +00008623 // Do function/array conversion on the last expression, but not
8624 // lvalue-to-rvalue. However, initialize an unqualified type.
John Wiegley01296292011-04-08 18:41:53 +00008625 ExprResult LastExpr = DefaultFunctionArrayConversion(LastE);
8626 if (LastExpr.isInvalid())
8627 return ExprError();
8628 Ty = LastExpr.get()->getType().getUnqualifiedType();
John McCall34376a62010-12-04 03:47:34 +00008629
John Wiegley01296292011-04-08 18:41:53 +00008630 if (!Ty->isDependentType() && !LastExpr.get()->isTypeDependent()) {
John McCall31168b02011-06-15 23:02:42 +00008631 // In ARC, if the final expression ends in a consume, splice
8632 // the consume out and bind it later. In the alternate case
8633 // (when dealing with a retainable type), the result
8634 // initialization will create a produce. In both cases the
8635 // result will be +1, and we'll need to balance that out with
8636 // a bind.
8637 if (Expr *rebuiltLastStmt
8638 = maybeRebuildARCConsumingStmt(LastExpr.get())) {
8639 LastExpr = rebuiltLastStmt;
8640 } else {
8641 LastExpr = PerformCopyInitialization(
Fariborz Jahanian56143ae2010-10-25 23:27:26 +00008642 InitializedEntity::InitializeResult(LPLoc,
8643 Ty,
8644 false),
8645 SourceLocation(),
John McCall31168b02011-06-15 23:02:42 +00008646 LastExpr);
8647 }
8648
John Wiegley01296292011-04-08 18:41:53 +00008649 if (LastExpr.isInvalid())
Fariborz Jahanian56143ae2010-10-25 23:27:26 +00008650 return ExprError();
John Wiegley01296292011-04-08 18:41:53 +00008651 if (LastExpr.get() != 0) {
Fariborz Jahanian56143ae2010-10-25 23:27:26 +00008652 if (!LastLabelStmt)
John Wiegley01296292011-04-08 18:41:53 +00008653 Compound->setLastStmt(LastExpr.take());
Fariborz Jahanian56143ae2010-10-25 23:27:26 +00008654 else
John Wiegley01296292011-04-08 18:41:53 +00008655 LastLabelStmt->setSubStmt(LastExpr.take());
Fariborz Jahanian56143ae2010-10-25 23:27:26 +00008656 StmtExprMayBindToTemp = true;
8657 }
8658 }
8659 }
Chris Lattner944d3062008-07-26 19:51:01 +00008660 }
Mike Stump4e1f26a2009-02-19 03:04:26 +00008661
Eli Friedmanba961a92009-03-23 00:24:07 +00008662 // FIXME: Check that expression type is complete/non-abstract; statement
8663 // expressions are not lvalues.
Fariborz Jahanian56143ae2010-10-25 23:27:26 +00008664 Expr *ResStmtExpr = new (Context) StmtExpr(Compound, Ty, LPLoc, RPLoc);
8665 if (StmtExprMayBindToTemp)
8666 return MaybeBindToTemporary(ResStmtExpr);
8667 return Owned(ResStmtExpr);
Chris Lattner366727f2007-07-24 16:58:17 +00008668}
Steve Naroff78864672007-08-01 22:05:33 +00008669
John McCalldadc5752010-08-24 06:29:42 +00008670ExprResult Sema::BuildBuiltinOffsetOf(SourceLocation BuiltinLoc,
John McCall36226622010-10-12 02:09:17 +00008671 TypeSourceInfo *TInfo,
8672 OffsetOfComponent *CompPtr,
8673 unsigned NumComponents,
8674 SourceLocation RParenLoc) {
Douglas Gregor882211c2010-04-28 22:16:22 +00008675 QualType ArgTy = TInfo->getType();
Sebastian Redl8d2ccae2009-02-26 14:39:58 +00008676 bool Dependent = ArgTy->isDependentType();
Abramo Bagnara1108e7b2010-05-20 10:00:11 +00008677 SourceRange TypeRange = TInfo->getTypeLoc().getLocalSourceRange();
Douglas Gregor882211c2010-04-28 22:16:22 +00008678
Chris Lattnerf17bd422007-08-30 17:45:32 +00008679 // We must have at least one component that refers to the type, and the first
8680 // one is known to be a field designator. Verify that the ArgTy represents
8681 // a struct/union/class.
Sebastian Redl8d2ccae2009-02-26 14:39:58 +00008682 if (!Dependent && !ArgTy->isRecordType())
Douglas Gregor882211c2010-04-28 22:16:22 +00008683 return ExprError(Diag(BuiltinLoc, diag::err_offsetof_record_type)
8684 << ArgTy << TypeRange);
8685
8686 // Type must be complete per C99 7.17p3 because a declaring a variable
8687 // with an incomplete type would be ill-formed.
8688 if (!Dependent
8689 && RequireCompleteType(BuiltinLoc, ArgTy,
Douglas Gregor7bfb2d02012-05-04 16:32:21 +00008690 diag::err_offsetof_incomplete_type, TypeRange))
Douglas Gregor882211c2010-04-28 22:16:22 +00008691 return ExprError();
8692
Chris Lattner78502cf2007-08-31 21:49:13 +00008693 // offsetof with non-identifier designators (e.g. "offsetof(x, a.b[c])") are a
8694 // GCC extension, diagnose them.
Eli Friedman988a16b2009-02-27 06:44:11 +00008695 // FIXME: This diagnostic isn't actually visible because the location is in
8696 // a system header!
Chris Lattner78502cf2007-08-31 21:49:13 +00008697 if (NumComponents != 1)
Chris Lattnerf490e152008-11-19 05:27:50 +00008698 Diag(BuiltinLoc, diag::ext_offsetof_extended_field_designator)
8699 << SourceRange(CompPtr[1].LocStart, CompPtr[NumComponents-1].LocEnd);
Douglas Gregor882211c2010-04-28 22:16:22 +00008700
8701 bool DidWarnAboutNonPOD = false;
8702 QualType CurrentType = ArgTy;
8703 typedef OffsetOfExpr::OffsetOfNode OffsetOfNode;
Chris Lattner0e62c1c2011-07-23 10:55:15 +00008704 SmallVector<OffsetOfNode, 4> Comps;
8705 SmallVector<Expr*, 4> Exprs;
Douglas Gregor882211c2010-04-28 22:16:22 +00008706 for (unsigned i = 0; i != NumComponents; ++i) {
8707 const OffsetOfComponent &OC = CompPtr[i];
8708 if (OC.isBrackets) {
8709 // Offset of an array sub-field. TODO: Should we allow vector elements?
8710 if (!CurrentType->isDependentType()) {
8711 const ArrayType *AT = Context.getAsArrayType(CurrentType);
8712 if(!AT)
8713 return ExprError(Diag(OC.LocEnd, diag::err_offsetof_array_type)
8714 << CurrentType);
8715 CurrentType = AT->getElementType();
8716 } else
8717 CurrentType = Context.DependentTy;
8718
Richard Smith9fcc5c32011-10-17 23:29:39 +00008719 ExprResult IdxRval = DefaultLvalueConversion(static_cast<Expr*>(OC.U.E));
8720 if (IdxRval.isInvalid())
8721 return ExprError();
8722 Expr *Idx = IdxRval.take();
8723
Douglas Gregor882211c2010-04-28 22:16:22 +00008724 // The expression must be an integral expression.
8725 // FIXME: An integral constant expression?
Douglas Gregor882211c2010-04-28 22:16:22 +00008726 if (!Idx->isTypeDependent() && !Idx->isValueDependent() &&
8727 !Idx->getType()->isIntegerType())
8728 return ExprError(Diag(Idx->getLocStart(),
8729 diag::err_typecheck_subscript_not_integer)
8730 << Idx->getSourceRange());
Richard Smitheda612882011-10-17 05:48:07 +00008731
Douglas Gregor882211c2010-04-28 22:16:22 +00008732 // Record this array index.
8733 Comps.push_back(OffsetOfNode(OC.LocStart, Exprs.size(), OC.LocEnd));
Richard Smith9fcc5c32011-10-17 23:29:39 +00008734 Exprs.push_back(Idx);
Douglas Gregor882211c2010-04-28 22:16:22 +00008735 continue;
8736 }
8737
8738 // Offset of a field.
8739 if (CurrentType->isDependentType()) {
8740 // We have the offset of a field, but we can't look into the dependent
8741 // type. Just record the identifier of the field.
8742 Comps.push_back(OffsetOfNode(OC.LocStart, OC.U.IdentInfo, OC.LocEnd));
8743 CurrentType = Context.DependentTy;
8744 continue;
8745 }
8746
8747 // We need to have a complete type to look into.
8748 if (RequireCompleteType(OC.LocStart, CurrentType,
8749 diag::err_offsetof_incomplete_type))
8750 return ExprError();
8751
8752 // Look for the designated field.
8753 const RecordType *RC = CurrentType->getAs<RecordType>();
8754 if (!RC)
8755 return ExprError(Diag(OC.LocEnd, diag::err_offsetof_record_type)
8756 << CurrentType);
8757 RecordDecl *RD = RC->getDecl();
8758
8759 // C++ [lib.support.types]p5:
8760 // The macro offsetof accepts a restricted set of type arguments in this
8761 // International Standard. type shall be a POD structure or a POD union
8762 // (clause 9).
Benjamin Kramer9e7876b2012-04-28 11:14:51 +00008763 // C++11 [support.types]p4:
8764 // If type is not a standard-layout class (Clause 9), the results are
8765 // undefined.
Douglas Gregor882211c2010-04-28 22:16:22 +00008766 if (CXXRecordDecl *CRD = dyn_cast<CXXRecordDecl>(RD)) {
Benjamin Kramer9e7876b2012-04-28 11:14:51 +00008767 bool IsSafe = LangOpts.CPlusPlus0x? CRD->isStandardLayout() : CRD->isPOD();
8768 unsigned DiagID =
8769 LangOpts.CPlusPlus0x? diag::warn_offsetof_non_standardlayout_type
8770 : diag::warn_offsetof_non_pod_type;
8771
8772 if (!IsSafe && !DidWarnAboutNonPOD &&
Ted Kremenek55ae3192011-02-23 01:51:43 +00008773 DiagRuntimeBehavior(BuiltinLoc, 0,
Benjamin Kramer9e7876b2012-04-28 11:14:51 +00008774 PDiag(DiagID)
Douglas Gregor882211c2010-04-28 22:16:22 +00008775 << SourceRange(CompPtr[0].LocStart, OC.LocEnd)
8776 << CurrentType))
8777 DidWarnAboutNonPOD = true;
8778 }
8779
8780 // Look for the field.
8781 LookupResult R(*this, OC.U.IdentInfo, OC.LocStart, LookupMemberName);
8782 LookupQualifiedName(R, RD);
8783 FieldDecl *MemberDecl = R.getAsSingle<FieldDecl>();
Francois Pichet783dd6e2010-11-21 06:08:52 +00008784 IndirectFieldDecl *IndirectMemberDecl = 0;
8785 if (!MemberDecl) {
Benjamin Kramer39593702010-11-21 14:11:41 +00008786 if ((IndirectMemberDecl = R.getAsSingle<IndirectFieldDecl>()))
Francois Pichet783dd6e2010-11-21 06:08:52 +00008787 MemberDecl = IndirectMemberDecl->getAnonField();
8788 }
8789
Douglas Gregor882211c2010-04-28 22:16:22 +00008790 if (!MemberDecl)
8791 return ExprError(Diag(BuiltinLoc, diag::err_no_member)
8792 << OC.U.IdentInfo << RD << SourceRange(OC.LocStart,
8793 OC.LocEnd));
8794
Douglas Gregor10982ea2010-04-28 22:36:06 +00008795 // C99 7.17p3:
8796 // (If the specified member is a bit-field, the behavior is undefined.)
8797 //
8798 // We diagnose this as an error.
Richard Smithcaf33902011-10-10 18:28:20 +00008799 if (MemberDecl->isBitField()) {
Douglas Gregor10982ea2010-04-28 22:36:06 +00008800 Diag(OC.LocEnd, diag::err_offsetof_bitfield)
8801 << MemberDecl->getDeclName()
8802 << SourceRange(BuiltinLoc, RParenLoc);
8803 Diag(MemberDecl->getLocation(), diag::note_bitfield_decl);
8804 return ExprError();
8805 }
Eli Friedman74ef7cf2010-08-05 10:11:36 +00008806
8807 RecordDecl *Parent = MemberDecl->getParent();
Francois Pichet783dd6e2010-11-21 06:08:52 +00008808 if (IndirectMemberDecl)
8809 Parent = cast<RecordDecl>(IndirectMemberDecl->getDeclContext());
Eli Friedman74ef7cf2010-08-05 10:11:36 +00008810
Douglas Gregord1702062010-04-29 00:18:15 +00008811 // If the member was found in a base class, introduce OffsetOfNodes for
8812 // the base class indirections.
8813 CXXBasePaths Paths(/*FindAmbiguities=*/true, /*RecordPaths=*/true,
8814 /*DetectVirtual=*/false);
Eli Friedman74ef7cf2010-08-05 10:11:36 +00008815 if (IsDerivedFrom(CurrentType, Context.getTypeDeclType(Parent), Paths)) {
Douglas Gregord1702062010-04-29 00:18:15 +00008816 CXXBasePath &Path = Paths.front();
8817 for (CXXBasePath::iterator B = Path.begin(), BEnd = Path.end();
8818 B != BEnd; ++B)
8819 Comps.push_back(OffsetOfNode(B->Base));
8820 }
Eli Friedman74ef7cf2010-08-05 10:11:36 +00008821
Francois Pichet783dd6e2010-11-21 06:08:52 +00008822 if (IndirectMemberDecl) {
8823 for (IndirectFieldDecl::chain_iterator FI =
8824 IndirectMemberDecl->chain_begin(),
8825 FEnd = IndirectMemberDecl->chain_end(); FI != FEnd; FI++) {
8826 assert(isa<FieldDecl>(*FI));
8827 Comps.push_back(OffsetOfNode(OC.LocStart,
8828 cast<FieldDecl>(*FI), OC.LocEnd));
8829 }
8830 } else
Douglas Gregor882211c2010-04-28 22:16:22 +00008831 Comps.push_back(OffsetOfNode(OC.LocStart, MemberDecl, OC.LocEnd));
Francois Pichet783dd6e2010-11-21 06:08:52 +00008832
Douglas Gregor882211c2010-04-28 22:16:22 +00008833 CurrentType = MemberDecl->getType().getNonReferenceType();
8834 }
8835
8836 return Owned(OffsetOfExpr::Create(Context, Context.getSizeType(), BuiltinLoc,
8837 TInfo, Comps.data(), Comps.size(),
8838 Exprs.data(), Exprs.size(), RParenLoc));
8839}
Mike Stump4e1f26a2009-02-19 03:04:26 +00008840
John McCalldadc5752010-08-24 06:29:42 +00008841ExprResult Sema::ActOnBuiltinOffsetOf(Scope *S,
John McCall36226622010-10-12 02:09:17 +00008842 SourceLocation BuiltinLoc,
8843 SourceLocation TypeLoc,
Richard Trieuba63ce62011-09-09 01:45:06 +00008844 ParsedType ParsedArgTy,
John McCall36226622010-10-12 02:09:17 +00008845 OffsetOfComponent *CompPtr,
8846 unsigned NumComponents,
Richard Trieuba63ce62011-09-09 01:45:06 +00008847 SourceLocation RParenLoc) {
John McCall36226622010-10-12 02:09:17 +00008848
Douglas Gregor882211c2010-04-28 22:16:22 +00008849 TypeSourceInfo *ArgTInfo;
Richard Trieuba63ce62011-09-09 01:45:06 +00008850 QualType ArgTy = GetTypeFromParser(ParsedArgTy, &ArgTInfo);
Douglas Gregor882211c2010-04-28 22:16:22 +00008851 if (ArgTy.isNull())
8852 return ExprError();
8853
Eli Friedman06dcfd92010-08-05 10:15:45 +00008854 if (!ArgTInfo)
8855 ArgTInfo = Context.getTrivialTypeSourceInfo(ArgTy, TypeLoc);
8856
8857 return BuildBuiltinOffsetOf(BuiltinLoc, ArgTInfo, CompPtr, NumComponents,
Richard Trieuba63ce62011-09-09 01:45:06 +00008858 RParenLoc);
Chris Lattnerf17bd422007-08-30 17:45:32 +00008859}
8860
8861
John McCalldadc5752010-08-24 06:29:42 +00008862ExprResult Sema::ActOnChooseExpr(SourceLocation BuiltinLoc,
John McCall36226622010-10-12 02:09:17 +00008863 Expr *CondExpr,
8864 Expr *LHSExpr, Expr *RHSExpr,
8865 SourceLocation RPLoc) {
Steve Naroff9efdabc2007-08-03 21:21:27 +00008866 assert((CondExpr && LHSExpr && RHSExpr) && "Missing type argument(s)");
8867
John McCall7decc9e2010-11-18 06:31:45 +00008868 ExprValueKind VK = VK_RValue;
8869 ExprObjectKind OK = OK_Ordinary;
Sebastian Redl8d2ccae2009-02-26 14:39:58 +00008870 QualType resType;
Douglas Gregor56751b52009-09-25 04:25:58 +00008871 bool ValueDependent = false;
Douglas Gregor0df91122009-05-19 22:43:30 +00008872 if (CondExpr->isTypeDependent() || CondExpr->isValueDependent()) {
Sebastian Redl8d2ccae2009-02-26 14:39:58 +00008873 resType = Context.DependentTy;
Douglas Gregor56751b52009-09-25 04:25:58 +00008874 ValueDependent = true;
Sebastian Redl8d2ccae2009-02-26 14:39:58 +00008875 } else {
8876 // The conditional expression is required to be a constant expression.
8877 llvm::APSInt condEval(32);
Douglas Gregore2b37442012-05-04 22:38:52 +00008878 ExprResult CondICE
8879 = VerifyIntegerConstantExpression(CondExpr, &condEval,
8880 diag::err_typecheck_choose_expr_requires_constant, false);
Richard Smithf4c51d92012-02-04 09:53:13 +00008881 if (CondICE.isInvalid())
8882 return ExprError();
8883 CondExpr = CondICE.take();
Steve Naroff9efdabc2007-08-03 21:21:27 +00008884
Sebastian Redl8d2ccae2009-02-26 14:39:58 +00008885 // If the condition is > zero, then the AST type is the same as the LSHExpr.
John McCall7decc9e2010-11-18 06:31:45 +00008886 Expr *ActiveExpr = condEval.getZExtValue() ? LHSExpr : RHSExpr;
8887
8888 resType = ActiveExpr->getType();
8889 ValueDependent = ActiveExpr->isValueDependent();
8890 VK = ActiveExpr->getValueKind();
8891 OK = ActiveExpr->getObjectKind();
Sebastian Redl8d2ccae2009-02-26 14:39:58 +00008892 }
8893
Sebastian Redl6d4256c2009-03-15 17:47:39 +00008894 return Owned(new (Context) ChooseExpr(BuiltinLoc, CondExpr, LHSExpr, RHSExpr,
John McCall7decc9e2010-11-18 06:31:45 +00008895 resType, VK, OK, RPLoc,
Douglas Gregor56751b52009-09-25 04:25:58 +00008896 resType->isDependentType(),
8897 ValueDependent));
Steve Naroff9efdabc2007-08-03 21:21:27 +00008898}
8899
Steve Naroffc540d662008-09-03 18:15:37 +00008900//===----------------------------------------------------------------------===//
8901// Clang Extensions.
8902//===----------------------------------------------------------------------===//
8903
8904/// ActOnBlockStart - This callback is invoked when a block literal is started.
Richard Trieuba63ce62011-09-09 01:45:06 +00008905void Sema::ActOnBlockStart(SourceLocation CaretLoc, Scope *CurScope) {
Douglas Gregor9a28e842010-03-01 23:15:13 +00008906 BlockDecl *Block = BlockDecl::Create(Context, CurContext, CaretLoc);
Richard Trieuba63ce62011-09-09 01:45:06 +00008907 PushBlockScope(CurScope, Block);
Douglas Gregor9a28e842010-03-01 23:15:13 +00008908 CurContext->addDecl(Block);
Richard Trieuba63ce62011-09-09 01:45:06 +00008909 if (CurScope)
8910 PushDeclContext(CurScope, Block);
Fariborz Jahanian1babe772010-07-09 18:44:02 +00008911 else
8912 CurContext = Block;
John McCallf1a3c2a2011-11-11 03:19:12 +00008913
Eli Friedman34b49062012-01-26 03:00:14 +00008914 getCurBlock()->HasImplicitReturnType = true;
8915
John McCallf1a3c2a2011-11-11 03:19:12 +00008916 // Enter a new evaluation context to insulate the block from any
8917 // cleanups from the enclosing full-expression.
8918 PushExpressionEvaluationContext(PotentiallyEvaluated);
Steve Naroff1d95e5a2008-10-10 01:28:17 +00008919}
8920
Mike Stump82f071f2009-02-04 22:31:32 +00008921void Sema::ActOnBlockArguments(Declarator &ParamInfo, Scope *CurScope) {
Mike Stumpf70bcf72009-05-07 18:43:07 +00008922 assert(ParamInfo.getIdentifier()==0 && "block-id should have no identifier!");
John McCall3882ace2011-01-05 12:14:39 +00008923 assert(ParamInfo.getContext() == Declarator::BlockLiteralContext);
Douglas Gregor9a28e842010-03-01 23:15:13 +00008924 BlockScopeInfo *CurBlock = getCurBlock();
Kovarththanan Rajaratnamba2c6522010-03-13 10:17:05 +00008925
John McCall8cb7bdf2010-06-04 23:28:52 +00008926 TypeSourceInfo *Sig = GetTypeForDeclarator(ParamInfo, CurScope);
John McCall8cb7bdf2010-06-04 23:28:52 +00008927 QualType T = Sig->getType();
Mike Stump82f071f2009-02-04 22:31:32 +00008928
John McCall3882ace2011-01-05 12:14:39 +00008929 // GetTypeForDeclarator always produces a function type for a block
8930 // literal signature. Furthermore, it is always a FunctionProtoType
8931 // unless the function was written with a typedef.
8932 assert(T->isFunctionType() &&
8933 "GetTypeForDeclarator made a non-function block signature");
8934
8935 // Look for an explicit signature in that function type.
8936 FunctionProtoTypeLoc ExplicitSignature;
8937
8938 TypeLoc tmp = Sig->getTypeLoc().IgnoreParens();
8939 if (isa<FunctionProtoTypeLoc>(tmp)) {
8940 ExplicitSignature = cast<FunctionProtoTypeLoc>(tmp);
8941
8942 // Check whether that explicit signature was synthesized by
8943 // GetTypeForDeclarator. If so, don't save that as part of the
8944 // written signature.
Abramo Bagnaraf2a79d92011-03-12 11:17:06 +00008945 if (ExplicitSignature.getLocalRangeBegin() ==
8946 ExplicitSignature.getLocalRangeEnd()) {
John McCall3882ace2011-01-05 12:14:39 +00008947 // This would be much cheaper if we stored TypeLocs instead of
8948 // TypeSourceInfos.
8949 TypeLoc Result = ExplicitSignature.getResultLoc();
8950 unsigned Size = Result.getFullDataSize();
8951 Sig = Context.CreateTypeSourceInfo(Result.getType(), Size);
8952 Sig->getTypeLoc().initializeFullCopy(Result, Size);
8953
8954 ExplicitSignature = FunctionProtoTypeLoc();
8955 }
John McCalla3ccba02010-06-04 11:21:44 +00008956 }
Mike Stump11289f42009-09-09 15:08:12 +00008957
John McCall3882ace2011-01-05 12:14:39 +00008958 CurBlock->TheDecl->setSignatureAsWritten(Sig);
8959 CurBlock->FunctionType = T;
8960
8961 const FunctionType *Fn = T->getAs<FunctionType>();
8962 QualType RetTy = Fn->getResultType();
8963 bool isVariadic =
8964 (isa<FunctionProtoType>(Fn) && cast<FunctionProtoType>(Fn)->isVariadic());
8965
John McCall8e346702010-06-04 19:02:56 +00008966 CurBlock->TheDecl->setIsVariadic(isVariadic);
Douglas Gregorb92a1562010-02-03 00:27:59 +00008967
John McCalla3ccba02010-06-04 11:21:44 +00008968 // Don't allow returning a objc interface by value.
8969 if (RetTy->isObjCObjectType()) {
Daniel Dunbar62ee6412012-03-09 18:35:03 +00008970 Diag(ParamInfo.getLocStart(),
John McCalla3ccba02010-06-04 11:21:44 +00008971 diag::err_object_cannot_be_passed_returned_by_value) << 0 << RetTy;
8972 return;
8973 }
Mike Stump4e1f26a2009-02-19 03:04:26 +00008974
John McCalla3ccba02010-06-04 11:21:44 +00008975 // Context.DependentTy is used as a placeholder for a missing block
John McCall8e346702010-06-04 19:02:56 +00008976 // return type. TODO: what should we do with declarators like:
8977 // ^ * { ... }
8978 // If the answer is "apply template argument deduction"....
Fariborz Jahaniandd5eb9d2011-12-03 17:47:53 +00008979 if (RetTy != Context.DependentTy) {
John McCalla3ccba02010-06-04 11:21:44 +00008980 CurBlock->ReturnType = RetTy;
Fariborz Jahaniandd5eb9d2011-12-03 17:47:53 +00008981 CurBlock->TheDecl->setBlockMissingReturnType(false);
Eli Friedman34b49062012-01-26 03:00:14 +00008982 CurBlock->HasImplicitReturnType = false;
Fariborz Jahaniandd5eb9d2011-12-03 17:47:53 +00008983 }
Mike Stump4e1f26a2009-02-19 03:04:26 +00008984
John McCalla3ccba02010-06-04 11:21:44 +00008985 // Push block parameters from the declarator if we had them.
Chris Lattner0e62c1c2011-07-23 10:55:15 +00008986 SmallVector<ParmVarDecl*, 8> Params;
John McCall3882ace2011-01-05 12:14:39 +00008987 if (ExplicitSignature) {
8988 for (unsigned I = 0, E = ExplicitSignature.getNumArgs(); I != E; ++I) {
8989 ParmVarDecl *Param = ExplicitSignature.getArg(I);
Fariborz Jahanian5ec502e2010-02-12 21:53:14 +00008990 if (Param->getIdentifier() == 0 &&
8991 !Param->isImplicit() &&
8992 !Param->isInvalidDecl() &&
David Blaikiebbafb8a2012-03-11 07:00:24 +00008993 !getLangOpts().CPlusPlus)
Fariborz Jahanian5ec502e2010-02-12 21:53:14 +00008994 Diag(Param->getLocation(), diag::err_parameter_name_omitted);
John McCall8e346702010-06-04 19:02:56 +00008995 Params.push_back(Param);
Fariborz Jahanian5ec502e2010-02-12 21:53:14 +00008996 }
John McCalla3ccba02010-06-04 11:21:44 +00008997
8998 // Fake up parameter variables if we have a typedef, like
8999 // ^ fntype { ... }
9000 } else if (const FunctionProtoType *Fn = T->getAs<FunctionProtoType>()) {
9001 for (FunctionProtoType::arg_type_iterator
9002 I = Fn->arg_type_begin(), E = Fn->arg_type_end(); I != E; ++I) {
9003 ParmVarDecl *Param =
9004 BuildParmVarDeclForTypedef(CurBlock->TheDecl,
Daniel Dunbar62ee6412012-03-09 18:35:03 +00009005 ParamInfo.getLocStart(),
John McCalla3ccba02010-06-04 11:21:44 +00009006 *I);
John McCall8e346702010-06-04 19:02:56 +00009007 Params.push_back(Param);
John McCalla3ccba02010-06-04 11:21:44 +00009008 }
Steve Naroffc540d662008-09-03 18:15:37 +00009009 }
John McCalla3ccba02010-06-04 11:21:44 +00009010
John McCall8e346702010-06-04 19:02:56 +00009011 // Set the parameters on the block decl.
Douglas Gregorb524d902010-11-01 18:37:59 +00009012 if (!Params.empty()) {
David Blaikie9c70e042011-09-21 18:16:56 +00009013 CurBlock->TheDecl->setParams(Params);
Douglas Gregorb524d902010-11-01 18:37:59 +00009014 CheckParmsForFunctionDef(CurBlock->TheDecl->param_begin(),
9015 CurBlock->TheDecl->param_end(),
9016 /*CheckParameterNames=*/false);
9017 }
9018
John McCalla3ccba02010-06-04 11:21:44 +00009019 // Finally we can process decl attributes.
Douglas Gregor758a8692009-06-17 21:51:59 +00009020 ProcessDeclAttributes(CurScope, CurBlock->TheDecl, ParamInfo);
John McCalldf8b37c2010-03-22 09:20:08 +00009021
John McCalla3ccba02010-06-04 11:21:44 +00009022 // Put the parameter variables in scope. We can bail out immediately
9023 // if we don't have any.
John McCall8e346702010-06-04 19:02:56 +00009024 if (Params.empty())
John McCalla3ccba02010-06-04 11:21:44 +00009025 return;
9026
Steve Naroff1d95e5a2008-10-10 01:28:17 +00009027 for (BlockDecl::param_iterator AI = CurBlock->TheDecl->param_begin(),
John McCallf7b2fb52010-01-22 00:28:27 +00009028 E = CurBlock->TheDecl->param_end(); AI != E; ++AI) {
9029 (*AI)->setOwningFunction(CurBlock->TheDecl);
9030
Steve Naroff1d95e5a2008-10-10 01:28:17 +00009031 // If this has an identifier, add it to the scope stack.
John McCalldf8b37c2010-03-22 09:20:08 +00009032 if ((*AI)->getIdentifier()) {
Argyrios Kyrtzidis1cb0de12010-12-15 18:44:22 +00009033 CheckShadow(CurBlock->TheScope, *AI);
John McCalldf8b37c2010-03-22 09:20:08 +00009034
Steve Naroff1d95e5a2008-10-10 01:28:17 +00009035 PushOnScopeChains(*AI, CurBlock->TheScope);
John McCalldf8b37c2010-03-22 09:20:08 +00009036 }
John McCallf7b2fb52010-01-22 00:28:27 +00009037 }
Steve Naroffc540d662008-09-03 18:15:37 +00009038}
9039
9040/// ActOnBlockError - If there is an error parsing a block, this callback
9041/// is invoked to pop the information about the block from the action impl.
9042void Sema::ActOnBlockError(SourceLocation CaretLoc, Scope *CurScope) {
John McCallf1a3c2a2011-11-11 03:19:12 +00009043 // Leave the expression-evaluation context.
9044 DiscardCleanupsInEvaluationContext();
9045 PopExpressionEvaluationContext();
9046
Steve Naroffc540d662008-09-03 18:15:37 +00009047 // Pop off CurBlock, handle nested blocks.
Chris Lattner41b86942009-04-21 22:38:46 +00009048 PopDeclContext();
Eli Friedman71c80552012-01-05 03:35:19 +00009049 PopFunctionScopeInfo();
Steve Naroffc540d662008-09-03 18:15:37 +00009050}
9051
9052/// ActOnBlockStmtExpr - This is called when the body of a block statement
9053/// literal was successfully completed. ^(int x){...}
John McCalldadc5752010-08-24 06:29:42 +00009054ExprResult Sema::ActOnBlockStmtExpr(SourceLocation CaretLoc,
Chris Lattner60f84492011-02-17 23:58:47 +00009055 Stmt *Body, Scope *CurScope) {
Chris Lattner9eac9312009-03-27 04:18:06 +00009056 // If blocks are disabled, emit an error.
9057 if (!LangOpts.Blocks)
9058 Diag(CaretLoc, diag::err_blocks_disable);
Mike Stump11289f42009-09-09 15:08:12 +00009059
John McCallf1a3c2a2011-11-11 03:19:12 +00009060 // Leave the expression-evaluation context.
John McCall85110b42012-03-08 22:00:17 +00009061 if (hasAnyUnrecoverableErrorsInThisFunction())
9062 DiscardCleanupsInEvaluationContext();
John McCallf1a3c2a2011-11-11 03:19:12 +00009063 assert(!ExprNeedsCleanups && "cleanups within block not correctly bound!");
9064 PopExpressionEvaluationContext();
9065
Douglas Gregor9a28e842010-03-01 23:15:13 +00009066 BlockScopeInfo *BSI = cast<BlockScopeInfo>(FunctionScopes.back());
Fariborz Jahanian1babe772010-07-09 18:44:02 +00009067
Steve Naroff1d95e5a2008-10-10 01:28:17 +00009068 PopDeclContext();
9069
Steve Naroffc540d662008-09-03 18:15:37 +00009070 QualType RetTy = Context.VoidTy;
Fariborz Jahanian3fd73102009-06-19 23:37:08 +00009071 if (!BSI->ReturnType.isNull())
9072 RetTy = BSI->ReturnType;
Mike Stump4e1f26a2009-02-19 03:04:26 +00009073
Mike Stump3bf1ab42009-07-28 22:04:01 +00009074 bool NoReturn = BSI->TheDecl->getAttr<NoReturnAttr>();
Steve Naroffc540d662008-09-03 18:15:37 +00009075 QualType BlockTy;
John McCall8e346702010-06-04 19:02:56 +00009076
John McCallc63de662011-02-02 13:00:07 +00009077 // Set the captured variables on the block.
Eli Friedman20139d32012-01-11 02:36:31 +00009078 // FIXME: Share capture structure between BlockDecl and CapturingScopeInfo!
9079 SmallVector<BlockDecl::Capture, 4> Captures;
9080 for (unsigned i = 0, e = BSI->Captures.size(); i != e; i++) {
9081 CapturingScopeInfo::Capture &Cap = BSI->Captures[i];
9082 if (Cap.isThisCapture())
9083 continue;
Eli Friedman24af8502012-02-03 22:47:37 +00009084 BlockDecl::Capture NewCap(Cap.getVariable(), Cap.isBlockCapture(),
Eli Friedman20139d32012-01-11 02:36:31 +00009085 Cap.isNested(), Cap.getCopyExpr());
9086 Captures.push_back(NewCap);
9087 }
9088 BSI->TheDecl->setCaptures(Context, Captures.begin(), Captures.end(),
9089 BSI->CXXThisCaptureIndex != 0);
John McCallc63de662011-02-02 13:00:07 +00009090
John McCall8e346702010-06-04 19:02:56 +00009091 // If the user wrote a function type in some form, try to use that.
9092 if (!BSI->FunctionType.isNull()) {
9093 const FunctionType *FTy = BSI->FunctionType->getAs<FunctionType>();
9094
9095 FunctionType::ExtInfo Ext = FTy->getExtInfo();
9096 if (NoReturn && !Ext.getNoReturn()) Ext = Ext.withNoReturn(true);
9097
9098 // Turn protoless block types into nullary block types.
9099 if (isa<FunctionNoProtoType>(FTy)) {
John McCalldb40c7f2010-12-14 08:05:40 +00009100 FunctionProtoType::ExtProtoInfo EPI;
9101 EPI.ExtInfo = Ext;
9102 BlockTy = Context.getFunctionType(RetTy, 0, 0, EPI);
John McCall8e346702010-06-04 19:02:56 +00009103
9104 // Otherwise, if we don't need to change anything about the function type,
9105 // preserve its sugar structure.
9106 } else if (FTy->getResultType() == RetTy &&
9107 (!NoReturn || FTy->getNoReturnAttr())) {
9108 BlockTy = BSI->FunctionType;
9109
9110 // Otherwise, make the minimal modifications to the function type.
9111 } else {
9112 const FunctionProtoType *FPT = cast<FunctionProtoType>(FTy);
John McCalldb40c7f2010-12-14 08:05:40 +00009113 FunctionProtoType::ExtProtoInfo EPI = FPT->getExtProtoInfo();
9114 EPI.TypeQuals = 0; // FIXME: silently?
9115 EPI.ExtInfo = Ext;
John McCall8e346702010-06-04 19:02:56 +00009116 BlockTy = Context.getFunctionType(RetTy,
9117 FPT->arg_type_begin(),
9118 FPT->getNumArgs(),
John McCalldb40c7f2010-12-14 08:05:40 +00009119 EPI);
John McCall8e346702010-06-04 19:02:56 +00009120 }
9121
9122 // If we don't have a function type, just build one from nothing.
9123 } else {
John McCalldb40c7f2010-12-14 08:05:40 +00009124 FunctionProtoType::ExtProtoInfo EPI;
John McCall31168b02011-06-15 23:02:42 +00009125 EPI.ExtInfo = FunctionType::ExtInfo().withNoReturn(NoReturn);
John McCalldb40c7f2010-12-14 08:05:40 +00009126 BlockTy = Context.getFunctionType(RetTy, 0, 0, EPI);
John McCall8e346702010-06-04 19:02:56 +00009127 }
Mike Stump4e1f26a2009-02-19 03:04:26 +00009128
John McCall8e346702010-06-04 19:02:56 +00009129 DiagnoseUnusedParameters(BSI->TheDecl->param_begin(),
9130 BSI->TheDecl->param_end());
Steve Naroffc540d662008-09-03 18:15:37 +00009131 BlockTy = Context.getBlockPointerType(BlockTy);
Mike Stump4e1f26a2009-02-19 03:04:26 +00009132
Chris Lattner45542ea2009-04-19 05:28:12 +00009133 // If needed, diagnose invalid gotos and switches in the block.
John McCall31168b02011-06-15 23:02:42 +00009134 if (getCurFunction()->NeedsScopeChecking() &&
9135 !hasAnyUnrecoverableErrorsInThisFunction())
John McCallb268a282010-08-23 23:25:46 +00009136 DiagnoseInvalidJumps(cast<CompoundStmt>(Body));
Mike Stump11289f42009-09-09 15:08:12 +00009137
Chris Lattner60f84492011-02-17 23:58:47 +00009138 BSI->TheDecl->setBody(cast<CompoundStmt>(Body));
Kovarththanan Rajaratnamba2c6522010-03-13 10:17:05 +00009139
Douglas Gregor49695f02011-09-06 20:46:03 +00009140 computeNRVO(Body, getCurBlock());
9141
Benjamin Kramera4fb8362011-07-12 14:11:05 +00009142 BlockExpr *Result = new (Context) BlockExpr(BSI->TheDecl, BlockTy);
9143 const AnalysisBasedWarnings::Policy &WP = AnalysisWarnings.getDefaultPolicy();
Eli Friedman71c80552012-01-05 03:35:19 +00009144 PopFunctionScopeInfo(&WP, Result->getBlockDecl(), Result);
Benjamin Kramera4fb8362011-07-12 14:11:05 +00009145
John McCall28fc7092011-11-10 05:35:25 +00009146 // If the block isn't obviously global, i.e. it captures anything at
John McCalld2393872012-04-13 01:08:17 +00009147 // all, then we need to do a few things in the surrounding context:
John McCall28fc7092011-11-10 05:35:25 +00009148 if (Result->getBlockDecl()->hasCaptures()) {
John McCalld2393872012-04-13 01:08:17 +00009149 // First, this expression has a new cleanup object.
John McCall28fc7092011-11-10 05:35:25 +00009150 ExprCleanupObjects.push_back(Result->getBlockDecl());
9151 ExprNeedsCleanups = true;
John McCalld2393872012-04-13 01:08:17 +00009152
9153 // It also gets a branch-protected scope if any of the captured
9154 // variables needs destruction.
9155 for (BlockDecl::capture_const_iterator
9156 ci = Result->getBlockDecl()->capture_begin(),
9157 ce = Result->getBlockDecl()->capture_end(); ci != ce; ++ci) {
9158 const VarDecl *var = ci->getVariable();
9159 if (var->getType().isDestructedType() != QualType::DK_none) {
9160 getCurFunction()->setHasBranchProtectedScope();
9161 break;
9162 }
9163 }
John McCall28fc7092011-11-10 05:35:25 +00009164 }
Fariborz Jahanian197c68c2012-03-06 18:41:35 +00009165
Douglas Gregor9a28e842010-03-01 23:15:13 +00009166 return Owned(Result);
Steve Naroffc540d662008-09-03 18:15:37 +00009167}
9168
John McCalldadc5752010-08-24 06:29:42 +00009169ExprResult Sema::ActOnVAArg(SourceLocation BuiltinLoc,
Richard Trieuba63ce62011-09-09 01:45:06 +00009170 Expr *E, ParsedType Ty,
Sebastian Redl6d4256c2009-03-15 17:47:39 +00009171 SourceLocation RPLoc) {
Abramo Bagnara27db2392010-08-10 10:06:15 +00009172 TypeSourceInfo *TInfo;
Richard Trieuba63ce62011-09-09 01:45:06 +00009173 GetTypeFromParser(Ty, &TInfo);
9174 return BuildVAArgExpr(BuiltinLoc, E, TInfo, RPLoc);
Abramo Bagnara27db2392010-08-10 10:06:15 +00009175}
9176
John McCalldadc5752010-08-24 06:29:42 +00009177ExprResult Sema::BuildVAArgExpr(SourceLocation BuiltinLoc,
John McCall7decc9e2010-11-18 06:31:45 +00009178 Expr *E, TypeSourceInfo *TInfo,
9179 SourceLocation RPLoc) {
Chris Lattner56382aa2009-04-05 15:49:53 +00009180 Expr *OrigExpr = E;
Mike Stump11289f42009-09-09 15:08:12 +00009181
Eli Friedman121ba0c2008-08-09 23:32:40 +00009182 // Get the va_list type
9183 QualType VaListType = Context.getBuiltinVaListType();
Eli Friedmane2cad652009-05-16 12:46:54 +00009184 if (VaListType->isArrayType()) {
9185 // Deal with implicit array decay; for example, on x86-64,
9186 // va_list is an array, but it's supposed to decay to
9187 // a pointer for va_arg.
Eli Friedman121ba0c2008-08-09 23:32:40 +00009188 VaListType = Context.getArrayDecayedType(VaListType);
Eli Friedmane2cad652009-05-16 12:46:54 +00009189 // Make sure the input expression also decays appropriately.
John Wiegley01296292011-04-08 18:41:53 +00009190 ExprResult Result = UsualUnaryConversions(E);
9191 if (Result.isInvalid())
9192 return ExprError();
9193 E = Result.take();
Eli Friedmane2cad652009-05-16 12:46:54 +00009194 } else {
9195 // Otherwise, the va_list argument must be an l-value because
9196 // it is modified by va_arg.
Mike Stump11289f42009-09-09 15:08:12 +00009197 if (!E->isTypeDependent() &&
Douglas Gregorad3150c2009-05-19 23:10:31 +00009198 CheckForModifiableLvalue(E, BuiltinLoc, *this))
Eli Friedmane2cad652009-05-16 12:46:54 +00009199 return ExprError();
9200 }
Eli Friedman121ba0c2008-08-09 23:32:40 +00009201
Douglas Gregorad3150c2009-05-19 23:10:31 +00009202 if (!E->isTypeDependent() &&
9203 !Context.hasSameType(VaListType, E->getType())) {
Sebastian Redl6d4256c2009-03-15 17:47:39 +00009204 return ExprError(Diag(E->getLocStart(),
9205 diag::err_first_argument_to_va_arg_not_of_type_va_list)
Chris Lattner56382aa2009-04-05 15:49:53 +00009206 << OrigExpr->getType() << E->getSourceRange());
Chris Lattner3f5cd772009-04-05 00:59:53 +00009207 }
Mike Stump4e1f26a2009-02-19 03:04:26 +00009208
David Majnemerc75d1a12011-06-14 05:17:32 +00009209 if (!TInfo->getType()->isDependentType()) {
9210 if (RequireCompleteType(TInfo->getTypeLoc().getBeginLoc(), TInfo->getType(),
Douglas Gregor7bfb2d02012-05-04 16:32:21 +00009211 diag::err_second_parameter_to_va_arg_incomplete,
9212 TInfo->getTypeLoc()))
David Majnemerc75d1a12011-06-14 05:17:32 +00009213 return ExprError();
David Majnemer254a5c02011-06-13 06:37:03 +00009214
David Majnemerc75d1a12011-06-14 05:17:32 +00009215 if (RequireNonAbstractType(TInfo->getTypeLoc().getBeginLoc(),
Douglas Gregorae298422012-05-04 17:09:59 +00009216 TInfo->getType(),
9217 diag::err_second_parameter_to_va_arg_abstract,
9218 TInfo->getTypeLoc()))
David Majnemerc75d1a12011-06-14 05:17:32 +00009219 return ExprError();
9220
Douglas Gregor7e1eb932011-07-30 06:45:27 +00009221 if (!TInfo->getType().isPODType(Context)) {
David Majnemerc75d1a12011-06-14 05:17:32 +00009222 Diag(TInfo->getTypeLoc().getBeginLoc(),
Douglas Gregor7e1eb932011-07-30 06:45:27 +00009223 TInfo->getType()->isObjCLifetimeType()
9224 ? diag::warn_second_parameter_to_va_arg_ownership_qualified
9225 : diag::warn_second_parameter_to_va_arg_not_pod)
David Majnemerc75d1a12011-06-14 05:17:32 +00009226 << TInfo->getType()
9227 << TInfo->getTypeLoc().getSourceRange();
Douglas Gregor7e1eb932011-07-30 06:45:27 +00009228 }
Eli Friedman6290ae42011-07-11 21:45:59 +00009229
9230 // Check for va_arg where arguments of the given type will be promoted
9231 // (i.e. this va_arg is guaranteed to have undefined behavior).
9232 QualType PromoteType;
9233 if (TInfo->getType()->isPromotableIntegerType()) {
9234 PromoteType = Context.getPromotedIntegerType(TInfo->getType());
9235 if (Context.typesAreCompatible(PromoteType, TInfo->getType()))
9236 PromoteType = QualType();
9237 }
9238 if (TInfo->getType()->isSpecificBuiltinType(BuiltinType::Float))
9239 PromoteType = Context.DoubleTy;
9240 if (!PromoteType.isNull())
9241 Diag(TInfo->getTypeLoc().getBeginLoc(),
9242 diag::warn_second_parameter_to_va_arg_never_compatible)
9243 << TInfo->getType()
9244 << PromoteType
9245 << TInfo->getTypeLoc().getSourceRange();
David Majnemerc75d1a12011-06-14 05:17:32 +00009246 }
Mike Stump4e1f26a2009-02-19 03:04:26 +00009247
Abramo Bagnara27db2392010-08-10 10:06:15 +00009248 QualType T = TInfo->getType().getNonLValueExprType(Context);
9249 return Owned(new (Context) VAArgExpr(BuiltinLoc, E, TInfo, RPLoc, T));
Anders Carlsson7e13ab82007-10-15 20:28:48 +00009250}
9251
John McCalldadc5752010-08-24 06:29:42 +00009252ExprResult Sema::ActOnGNUNullExpr(SourceLocation TokenLoc) {
Douglas Gregor3be4b122008-11-29 04:51:27 +00009253 // The type of __null will be int or long, depending on the size of
9254 // pointers on the target.
9255 QualType Ty;
Douglas Gregore8bbc122011-09-02 00:18:52 +00009256 unsigned pw = Context.getTargetInfo().getPointerWidth(0);
9257 if (pw == Context.getTargetInfo().getIntWidth())
Douglas Gregor3be4b122008-11-29 04:51:27 +00009258 Ty = Context.IntTy;
Douglas Gregore8bbc122011-09-02 00:18:52 +00009259 else if (pw == Context.getTargetInfo().getLongWidth())
Douglas Gregor3be4b122008-11-29 04:51:27 +00009260 Ty = Context.LongTy;
Douglas Gregore8bbc122011-09-02 00:18:52 +00009261 else if (pw == Context.getTargetInfo().getLongLongWidth())
NAKAMURA Takumi0d13fd32011-01-19 00:11:41 +00009262 Ty = Context.LongLongTy;
9263 else {
David Blaikie83d382b2011-09-23 05:06:16 +00009264 llvm_unreachable("I don't know size of pointer!");
NAKAMURA Takumi0d13fd32011-01-19 00:11:41 +00009265 }
Douglas Gregor3be4b122008-11-29 04:51:27 +00009266
Sebastian Redl6d4256c2009-03-15 17:47:39 +00009267 return Owned(new (Context) GNUNullExpr(Ty, TokenLoc));
Douglas Gregor3be4b122008-11-29 04:51:27 +00009268}
9269
Alexis Huntc46382e2010-04-28 23:02:27 +00009270static void MakeObjCStringLiteralFixItHint(Sema& SemaRef, QualType DstType,
Douglas Gregora771f462010-03-31 17:46:05 +00009271 Expr *SrcExpr, FixItHint &Hint) {
David Blaikiebbafb8a2012-03-11 07:00:24 +00009272 if (!SemaRef.getLangOpts().ObjC1)
Anders Carlssonace5d072009-11-10 04:46:30 +00009273 return;
Kovarththanan Rajaratnamba2c6522010-03-13 10:17:05 +00009274
Anders Carlssonace5d072009-11-10 04:46:30 +00009275 const ObjCObjectPointerType *PT = DstType->getAs<ObjCObjectPointerType>();
9276 if (!PT)
9277 return;
9278
9279 // Check if the destination is of type 'id'.
9280 if (!PT->isObjCIdType()) {
9281 // Check if the destination is the 'NSString' interface.
9282 const ObjCInterfaceDecl *ID = PT->getInterfaceDecl();
9283 if (!ID || !ID->getIdentifier()->isStr("NSString"))
9284 return;
9285 }
Kovarththanan Rajaratnamba2c6522010-03-13 10:17:05 +00009286
John McCallfe96e0b2011-11-06 09:01:30 +00009287 // Ignore any parens, implicit casts (should only be
9288 // array-to-pointer decays), and not-so-opaque values. The last is
9289 // important for making this trigger for property assignments.
9290 SrcExpr = SrcExpr->IgnoreParenImpCasts();
9291 if (OpaqueValueExpr *OV = dyn_cast<OpaqueValueExpr>(SrcExpr))
9292 if (OV->getSourceExpr())
9293 SrcExpr = OV->getSourceExpr()->IgnoreParenImpCasts();
9294
9295 StringLiteral *SL = dyn_cast<StringLiteral>(SrcExpr);
Douglas Gregorfb65e592011-07-27 05:40:30 +00009296 if (!SL || !SL->isAscii())
Anders Carlssonace5d072009-11-10 04:46:30 +00009297 return;
Kovarththanan Rajaratnamba2c6522010-03-13 10:17:05 +00009298
Douglas Gregora771f462010-03-31 17:46:05 +00009299 Hint = FixItHint::CreateInsertion(SL->getLocStart(), "@");
Anders Carlssonace5d072009-11-10 04:46:30 +00009300}
9301
Chris Lattner9bad62c2008-01-04 18:04:52 +00009302bool Sema::DiagnoseAssignmentResult(AssignConvertType ConvTy,
9303 SourceLocation Loc,
9304 QualType DstType, QualType SrcType,
Douglas Gregor4f4946a2010-04-22 00:20:18 +00009305 Expr *SrcExpr, AssignmentAction Action,
9306 bool *Complained) {
9307 if (Complained)
9308 *Complained = false;
9309
Chris Lattner9bad62c2008-01-04 18:04:52 +00009310 // Decode the result (notice that AST's are still created for extensions).
Douglas Gregor33823722011-06-11 01:09:30 +00009311 bool CheckInferredResultType = false;
Chris Lattner9bad62c2008-01-04 18:04:52 +00009312 bool isInvalid = false;
Eli Friedman381f4312012-02-29 20:59:56 +00009313 unsigned DiagKind = 0;
Douglas Gregora771f462010-03-31 17:46:05 +00009314 FixItHint Hint;
Anna Zaks3b402712011-07-28 19:51:27 +00009315 ConversionFixItGenerator ConvHints;
9316 bool MayHaveConvFixit = false;
Richard Trieucaff2472011-11-23 22:32:32 +00009317 bool MayHaveFunctionDiff = false;
Kovarththanan Rajaratnamba2c6522010-03-13 10:17:05 +00009318
Chris Lattner9bad62c2008-01-04 18:04:52 +00009319 switch (ConvTy) {
Chris Lattner9bad62c2008-01-04 18:04:52 +00009320 case Compatible: return false;
Chris Lattner940cfeb2008-01-04 18:22:42 +00009321 case PointerToInt:
Chris Lattner9bad62c2008-01-04 18:04:52 +00009322 DiagKind = diag::ext_typecheck_convert_pointer_int;
Anna Zaks3b402712011-07-28 19:51:27 +00009323 ConvHints.tryToFixConversion(SrcExpr, SrcType, DstType, *this);
9324 MayHaveConvFixit = true;
Chris Lattner9bad62c2008-01-04 18:04:52 +00009325 break;
Chris Lattner940cfeb2008-01-04 18:22:42 +00009326 case IntToPointer:
9327 DiagKind = diag::ext_typecheck_convert_int_pointer;
Anna Zaks3b402712011-07-28 19:51:27 +00009328 ConvHints.tryToFixConversion(SrcExpr, SrcType, DstType, *this);
9329 MayHaveConvFixit = true;
Chris Lattner940cfeb2008-01-04 18:22:42 +00009330 break;
Chris Lattner9bad62c2008-01-04 18:04:52 +00009331 case IncompatiblePointer:
Douglas Gregora771f462010-03-31 17:46:05 +00009332 MakeObjCStringLiteralFixItHint(*this, DstType, SrcExpr, Hint);
Chris Lattner9bad62c2008-01-04 18:04:52 +00009333 DiagKind = diag::ext_typecheck_convert_incompatible_pointer;
Douglas Gregor33823722011-06-11 01:09:30 +00009334 CheckInferredResultType = DstType->isObjCObjectPointerType() &&
9335 SrcType->isObjCObjectPointerType();
Anna Zaks3b402712011-07-28 19:51:27 +00009336 if (Hint.isNull() && !CheckInferredResultType) {
9337 ConvHints.tryToFixConversion(SrcExpr, SrcType, DstType, *this);
9338 }
9339 MayHaveConvFixit = true;
Chris Lattner9bad62c2008-01-04 18:04:52 +00009340 break;
Eli Friedman80160bd2009-03-22 23:59:44 +00009341 case IncompatiblePointerSign:
9342 DiagKind = diag::ext_typecheck_convert_incompatible_pointer_sign;
9343 break;
Chris Lattner9bad62c2008-01-04 18:04:52 +00009344 case FunctionVoidPointer:
9345 DiagKind = diag::ext_typecheck_convert_pointer_void_func;
9346 break;
John McCall4fff8f62011-02-01 00:10:29 +00009347 case IncompatiblePointerDiscardsQualifiers: {
John McCall71de91c2011-02-01 23:28:01 +00009348 // Perform array-to-pointer decay if necessary.
9349 if (SrcType->isArrayType()) SrcType = Context.getArrayDecayedType(SrcType);
9350
John McCall4fff8f62011-02-01 00:10:29 +00009351 Qualifiers lhq = SrcType->getPointeeType().getQualifiers();
9352 Qualifiers rhq = DstType->getPointeeType().getQualifiers();
9353 if (lhq.getAddressSpace() != rhq.getAddressSpace()) {
9354 DiagKind = diag::err_typecheck_incompatible_address_space;
9355 break;
John McCall31168b02011-06-15 23:02:42 +00009356
9357
9358 } else if (lhq.getObjCLifetime() != rhq.getObjCLifetime()) {
Argyrios Kyrtzidiscff00d92011-06-24 00:08:59 +00009359 DiagKind = diag::err_typecheck_incompatible_ownership;
John McCall31168b02011-06-15 23:02:42 +00009360 break;
John McCall4fff8f62011-02-01 00:10:29 +00009361 }
9362
9363 llvm_unreachable("unknown error case for discarding qualifiers!");
9364 // fallthrough
9365 }
Chris Lattner9bad62c2008-01-04 18:04:52 +00009366 case CompatiblePointerDiscardsQualifiers:
Douglas Gregoraa1e21d2008-09-12 00:47:35 +00009367 // If the qualifiers lost were because we were applying the
9368 // (deprecated) C++ conversion from a string literal to a char*
9369 // (or wchar_t*), then there was no error (C++ 4.2p2). FIXME:
9370 // Ideally, this check would be performed in
John McCallaba90822011-01-31 23:13:11 +00009371 // checkPointerTypesForAssignment. However, that would require a
Douglas Gregoraa1e21d2008-09-12 00:47:35 +00009372 // bit of refactoring (so that the second argument is an
9373 // expression, rather than a type), which should be done as part
John McCallaba90822011-01-31 23:13:11 +00009374 // of a larger effort to fix checkPointerTypesForAssignment for
Douglas Gregoraa1e21d2008-09-12 00:47:35 +00009375 // C++ semantics.
David Blaikiebbafb8a2012-03-11 07:00:24 +00009376 if (getLangOpts().CPlusPlus &&
Douglas Gregoraa1e21d2008-09-12 00:47:35 +00009377 IsStringLiteralToNonConstPointerConversion(SrcExpr, DstType))
9378 return false;
Chris Lattner9bad62c2008-01-04 18:04:52 +00009379 DiagKind = diag::ext_typecheck_convert_discards_qualifiers;
9380 break;
Alexis Hunt6f3de502009-11-08 07:46:34 +00009381 case IncompatibleNestedPointerQualifiers:
Fariborz Jahanianb98dade2009-11-09 22:16:37 +00009382 DiagKind = diag::ext_nested_pointer_qualifier_mismatch;
Fariborz Jahaniand7aa9d82009-11-07 20:20:40 +00009383 break;
Steve Naroff081c7422008-09-04 15:10:53 +00009384 case IntToBlockPointer:
9385 DiagKind = diag::err_int_to_block_pointer;
9386 break;
9387 case IncompatibleBlockPointer:
Mike Stumpd79b5a82009-04-21 22:51:42 +00009388 DiagKind = diag::err_typecheck_convert_incompatible_block_pointer;
Steve Naroff081c7422008-09-04 15:10:53 +00009389 break;
Steve Naroff8afa9892008-10-14 22:18:38 +00009390 case IncompatibleObjCQualifiedId:
Mike Stump4e1f26a2009-02-19 03:04:26 +00009391 // FIXME: Diagnose the problem in ObjCQualifiedIdTypesAreCompatible, since
Steve Naroff8afa9892008-10-14 22:18:38 +00009392 // it can give a more specific diagnostic.
9393 DiagKind = diag::warn_incompatible_qualified_id;
9394 break;
Anders Carlssondb5a9b62009-01-30 23:17:46 +00009395 case IncompatibleVectors:
9396 DiagKind = diag::warn_incompatible_vectors;
9397 break;
Fariborz Jahanian6f472e82011-07-07 18:55:47 +00009398 case IncompatibleObjCWeakRef:
9399 DiagKind = diag::err_arc_weak_unavailable_assign;
9400 break;
Chris Lattner9bad62c2008-01-04 18:04:52 +00009401 case Incompatible:
9402 DiagKind = diag::err_typecheck_convert_incompatible;
Anna Zaks3b402712011-07-28 19:51:27 +00009403 ConvHints.tryToFixConversion(SrcExpr, SrcType, DstType, *this);
9404 MayHaveConvFixit = true;
Chris Lattner9bad62c2008-01-04 18:04:52 +00009405 isInvalid = true;
Richard Trieucaff2472011-11-23 22:32:32 +00009406 MayHaveFunctionDiff = true;
Chris Lattner9bad62c2008-01-04 18:04:52 +00009407 break;
9408 }
Mike Stump4e1f26a2009-02-19 03:04:26 +00009409
Douglas Gregorc68e1402010-04-09 00:35:39 +00009410 QualType FirstType, SecondType;
9411 switch (Action) {
9412 case AA_Assigning:
9413 case AA_Initializing:
9414 // The destination type comes first.
9415 FirstType = DstType;
9416 SecondType = SrcType;
9417 break;
Alexis Huntc46382e2010-04-28 23:02:27 +00009418
Douglas Gregorc68e1402010-04-09 00:35:39 +00009419 case AA_Returning:
9420 case AA_Passing:
9421 case AA_Converting:
9422 case AA_Sending:
9423 case AA_Casting:
9424 // The source type comes first.
9425 FirstType = SrcType;
9426 SecondType = DstType;
9427 break;
9428 }
Alexis Huntc46382e2010-04-28 23:02:27 +00009429
Anna Zaks3b402712011-07-28 19:51:27 +00009430 PartialDiagnostic FDiag = PDiag(DiagKind);
9431 FDiag << FirstType << SecondType << Action << SrcExpr->getSourceRange();
9432
9433 // If we can fix the conversion, suggest the FixIts.
9434 assert(ConvHints.isNull() || Hint.isNull());
9435 if (!ConvHints.isNull()) {
Benjamin Kramer490afa62012-01-14 21:05:10 +00009436 for (std::vector<FixItHint>::iterator HI = ConvHints.Hints.begin(),
9437 HE = ConvHints.Hints.end(); HI != HE; ++HI)
Anna Zaks3b402712011-07-28 19:51:27 +00009438 FDiag << *HI;
9439 } else {
9440 FDiag << Hint;
9441 }
9442 if (MayHaveConvFixit) { FDiag << (unsigned) (ConvHints.Kind); }
9443
Richard Trieucaff2472011-11-23 22:32:32 +00009444 if (MayHaveFunctionDiff)
9445 HandleFunctionTypeMismatch(FDiag, SecondType, FirstType);
9446
Anna Zaks3b402712011-07-28 19:51:27 +00009447 Diag(Loc, FDiag);
9448
Richard Trieucaff2472011-11-23 22:32:32 +00009449 if (SecondType == Context.OverloadTy)
9450 NoteAllOverloadCandidates(OverloadExpr::find(SrcExpr).Expression,
9451 FirstType);
9452
Douglas Gregor33823722011-06-11 01:09:30 +00009453 if (CheckInferredResultType)
9454 EmitRelatedResultTypeNote(SrcExpr);
9455
Douglas Gregor4f4946a2010-04-22 00:20:18 +00009456 if (Complained)
9457 *Complained = true;
Chris Lattner9bad62c2008-01-04 18:04:52 +00009458 return isInvalid;
9459}
Anders Carlssone54e8a12008-11-30 19:50:32 +00009460
Richard Smithf4c51d92012-02-04 09:53:13 +00009461ExprResult Sema::VerifyIntegerConstantExpression(Expr *E,
9462 llvm::APSInt *Result) {
Douglas Gregore2b37442012-05-04 22:38:52 +00009463 class SimpleICEDiagnoser : public VerifyICEDiagnoser {
9464 public:
9465 virtual void diagnoseNotICE(Sema &S, SourceLocation Loc, SourceRange SR) {
9466 S.Diag(Loc, diag::err_expr_not_ice) << S.LangOpts.CPlusPlus << SR;
9467 }
9468 } Diagnoser;
9469
9470 return VerifyIntegerConstantExpression(E, Result, Diagnoser);
9471}
9472
9473ExprResult Sema::VerifyIntegerConstantExpression(Expr *E,
9474 llvm::APSInt *Result,
9475 unsigned DiagID,
9476 bool AllowFold) {
9477 class IDDiagnoser : public VerifyICEDiagnoser {
9478 unsigned DiagID;
9479
9480 public:
9481 IDDiagnoser(unsigned DiagID)
9482 : VerifyICEDiagnoser(DiagID == 0), DiagID(DiagID) { }
9483
9484 virtual void diagnoseNotICE(Sema &S, SourceLocation Loc, SourceRange SR) {
9485 S.Diag(Loc, DiagID) << SR;
9486 }
9487 } Diagnoser(DiagID);
9488
9489 return VerifyIntegerConstantExpression(E, Result, Diagnoser, AllowFold);
9490}
9491
9492void Sema::VerifyICEDiagnoser::diagnoseFold(Sema &S, SourceLocation Loc,
9493 SourceRange SR) {
9494 S.Diag(Loc, diag::ext_expr_not_ice) << SR << S.LangOpts.CPlusPlus;
Richard Smithf4c51d92012-02-04 09:53:13 +00009495}
9496
Benjamin Kramer33adaae2012-04-18 14:22:41 +00009497ExprResult
9498Sema::VerifyIntegerConstantExpression(Expr *E, llvm::APSInt *Result,
Douglas Gregore2b37442012-05-04 22:38:52 +00009499 VerifyICEDiagnoser &Diagnoser,
9500 bool AllowFold) {
Daniel Dunbar62ee6412012-03-09 18:35:03 +00009501 SourceLocation DiagLoc = E->getLocStart();
Richard Smithf4c51d92012-02-04 09:53:13 +00009502
David Blaikiebbafb8a2012-03-11 07:00:24 +00009503 if (getLangOpts().CPlusPlus0x) {
Richard Smithf4c51d92012-02-04 09:53:13 +00009504 // C++11 [expr.const]p5:
9505 // If an expression of literal class type is used in a context where an
9506 // integral constant expression is required, then that class type shall
9507 // have a single non-explicit conversion function to an integral or
9508 // unscoped enumeration type
9509 ExprResult Converted;
Douglas Gregore2b37442012-05-04 22:38:52 +00009510 if (!Diagnoser.Suppress) {
9511 class CXX11ConvertDiagnoser : public ICEConvertDiagnoser {
9512 public:
9513 CXX11ConvertDiagnoser() : ICEConvertDiagnoser(false, true) { }
9514
9515 virtual DiagnosticBuilder diagnoseNotInt(Sema &S, SourceLocation Loc,
9516 QualType T) {
9517 return S.Diag(Loc, diag::err_ice_not_integral) << T;
9518 }
9519
9520 virtual DiagnosticBuilder diagnoseIncomplete(Sema &S,
9521 SourceLocation Loc,
9522 QualType T) {
9523 return S.Diag(Loc, diag::err_ice_incomplete_type) << T;
9524 }
9525
9526 virtual DiagnosticBuilder diagnoseExplicitConv(Sema &S,
9527 SourceLocation Loc,
9528 QualType T,
9529 QualType ConvTy) {
9530 return S.Diag(Loc, diag::err_ice_explicit_conversion) << T << ConvTy;
9531 }
9532
9533 virtual DiagnosticBuilder noteExplicitConv(Sema &S,
9534 CXXConversionDecl *Conv,
9535 QualType ConvTy) {
9536 return S.Diag(Conv->getLocation(), diag::note_ice_conversion_here)
9537 << ConvTy->isEnumeralType() << ConvTy;
9538 }
9539
9540 virtual DiagnosticBuilder diagnoseAmbiguous(Sema &S, SourceLocation Loc,
9541 QualType T) {
9542 return S.Diag(Loc, diag::err_ice_ambiguous_conversion) << T;
9543 }
9544
9545 virtual DiagnosticBuilder noteAmbiguous(Sema &S,
9546 CXXConversionDecl *Conv,
9547 QualType ConvTy) {
9548 return S.Diag(Conv->getLocation(), diag::note_ice_conversion_here)
9549 << ConvTy->isEnumeralType() << ConvTy;
9550 }
9551
9552 virtual DiagnosticBuilder diagnoseConversion(Sema &S,
9553 SourceLocation Loc,
9554 QualType T,
9555 QualType ConvTy) {
9556 return DiagnosticBuilder::getEmpty();
9557 }
9558 } ConvertDiagnoser;
9559
9560 Converted = ConvertToIntegralOrEnumerationType(DiagLoc, E,
9561 ConvertDiagnoser,
9562 /*AllowScopedEnumerations*/ false);
Richard Smithf4c51d92012-02-04 09:53:13 +00009563 } else {
9564 // The caller wants to silently enquire whether this is an ICE. Don't
9565 // produce any diagnostics if it isn't.
Douglas Gregore2b37442012-05-04 22:38:52 +00009566 class SilentICEConvertDiagnoser : public ICEConvertDiagnoser {
9567 public:
9568 SilentICEConvertDiagnoser() : ICEConvertDiagnoser(true, true) { }
9569
9570 virtual DiagnosticBuilder diagnoseNotInt(Sema &S, SourceLocation Loc,
9571 QualType T) {
9572 return DiagnosticBuilder::getEmpty();
9573 }
9574
9575 virtual DiagnosticBuilder diagnoseIncomplete(Sema &S,
9576 SourceLocation Loc,
9577 QualType T) {
9578 return DiagnosticBuilder::getEmpty();
9579 }
9580
9581 virtual DiagnosticBuilder diagnoseExplicitConv(Sema &S,
9582 SourceLocation Loc,
9583 QualType T,
9584 QualType ConvTy) {
9585 return DiagnosticBuilder::getEmpty();
9586 }
9587
9588 virtual DiagnosticBuilder noteExplicitConv(Sema &S,
9589 CXXConversionDecl *Conv,
9590 QualType ConvTy) {
9591 return DiagnosticBuilder::getEmpty();
9592 }
9593
9594 virtual DiagnosticBuilder diagnoseAmbiguous(Sema &S, SourceLocation Loc,
9595 QualType T) {
9596 return DiagnosticBuilder::getEmpty();
9597 }
9598
9599 virtual DiagnosticBuilder noteAmbiguous(Sema &S,
9600 CXXConversionDecl *Conv,
9601 QualType ConvTy) {
9602 return DiagnosticBuilder::getEmpty();
9603 }
9604
9605 virtual DiagnosticBuilder diagnoseConversion(Sema &S,
9606 SourceLocation Loc,
9607 QualType T,
9608 QualType ConvTy) {
9609 return DiagnosticBuilder::getEmpty();
9610 }
9611 } ConvertDiagnoser;
9612
9613 Converted = ConvertToIntegralOrEnumerationType(DiagLoc, E,
9614 ConvertDiagnoser, false);
Richard Smithf4c51d92012-02-04 09:53:13 +00009615 }
9616 if (Converted.isInvalid())
9617 return Converted;
9618 E = Converted.take();
9619 if (!E->getType()->isIntegralOrUnscopedEnumerationType())
9620 return ExprError();
9621 } else if (!E->getType()->isIntegralOrUnscopedEnumerationType()) {
9622 // An ICE must be of integral or unscoped enumeration type.
Douglas Gregore2b37442012-05-04 22:38:52 +00009623 if (!Diagnoser.Suppress)
9624 Diagnoser.diagnoseNotICE(*this, DiagLoc, E->getSourceRange());
Richard Smithf4c51d92012-02-04 09:53:13 +00009625 return ExprError();
9626 }
9627
Richard Smith902ca212011-12-14 23:32:26 +00009628 // Circumvent ICE checking in C++11 to avoid evaluating the expression twice
9629 // in the non-ICE case.
David Blaikiebbafb8a2012-03-11 07:00:24 +00009630 if (!getLangOpts().CPlusPlus0x && E->isIntegerConstantExpr(Context)) {
Richard Smithf4c51d92012-02-04 09:53:13 +00009631 if (Result)
9632 *Result = E->EvaluateKnownConstInt(Context);
9633 return Owned(E);
Eli Friedmanbb967cc2009-04-25 22:26:58 +00009634 }
9635
Anders Carlssone54e8a12008-11-30 19:50:32 +00009636 Expr::EvalResult EvalResult;
Richard Smith92b1ce02011-12-12 09:28:41 +00009637 llvm::SmallVector<PartialDiagnosticAt, 8> Notes;
9638 EvalResult.Diag = &Notes;
Anders Carlssone54e8a12008-11-30 19:50:32 +00009639
Richard Smith902ca212011-12-14 23:32:26 +00009640 // Try to evaluate the expression, and produce diagnostics explaining why it's
9641 // not a constant expression as a side-effect.
9642 bool Folded = E->EvaluateAsRValue(EvalResult, Context) &&
9643 EvalResult.Val.isInt() && !EvalResult.HasSideEffects;
9644
9645 // In C++11, we can rely on diagnostics being produced for any expression
9646 // which is not a constant expression. If no diagnostics were produced, then
9647 // this is a constant expression.
David Blaikiebbafb8a2012-03-11 07:00:24 +00009648 if (Folded && getLangOpts().CPlusPlus0x && Notes.empty()) {
Richard Smith902ca212011-12-14 23:32:26 +00009649 if (Result)
9650 *Result = EvalResult.Val.getInt();
Richard Smithf4c51d92012-02-04 09:53:13 +00009651 return Owned(E);
9652 }
9653
9654 // If our only note is the usual "invalid subexpression" note, just point
9655 // the caret at its location rather than producing an essentially
9656 // redundant note.
9657 if (Notes.size() == 1 && Notes[0].second.getDiagID() ==
9658 diag::note_invalid_subexpr_in_const_expr) {
9659 DiagLoc = Notes[0].first;
9660 Notes.clear();
Richard Smith902ca212011-12-14 23:32:26 +00009661 }
9662
9663 if (!Folded || !AllowFold) {
Douglas Gregore2b37442012-05-04 22:38:52 +00009664 if (!Diagnoser.Suppress) {
9665 Diagnoser.diagnoseNotICE(*this, DiagLoc, E->getSourceRange());
Richard Smith92b1ce02011-12-12 09:28:41 +00009666 for (unsigned I = 0, N = Notes.size(); I != N; ++I)
9667 Diag(Notes[I].first, Notes[I].second);
Anders Carlssone54e8a12008-11-30 19:50:32 +00009668 }
Mike Stump4e1f26a2009-02-19 03:04:26 +00009669
Richard Smithf4c51d92012-02-04 09:53:13 +00009670 return ExprError();
Anders Carlssone54e8a12008-11-30 19:50:32 +00009671 }
9672
Douglas Gregore2b37442012-05-04 22:38:52 +00009673 Diagnoser.diagnoseFold(*this, DiagLoc, E->getSourceRange());
Richard Smith2ec40612012-01-15 03:51:30 +00009674 for (unsigned I = 0, N = Notes.size(); I != N; ++I)
9675 Diag(Notes[I].first, Notes[I].second);
Mike Stump4e1f26a2009-02-19 03:04:26 +00009676
Anders Carlssone54e8a12008-11-30 19:50:32 +00009677 if (Result)
9678 *Result = EvalResult.Val.getInt();
Richard Smithf4c51d92012-02-04 09:53:13 +00009679 return Owned(E);
Anders Carlssone54e8a12008-11-30 19:50:32 +00009680}
Douglas Gregorc9c02ed2009-06-19 23:52:42 +00009681
Eli Friedman456f0182012-01-20 01:26:23 +00009682namespace {
9683 // Handle the case where we conclude a expression which we speculatively
9684 // considered to be unevaluated is actually evaluated.
9685 class TransformToPE : public TreeTransform<TransformToPE> {
9686 typedef TreeTransform<TransformToPE> BaseTransform;
9687
9688 public:
9689 TransformToPE(Sema &SemaRef) : BaseTransform(SemaRef) { }
9690
9691 // Make sure we redo semantic analysis
9692 bool AlwaysRebuild() { return true; }
9693
Eli Friedman5f0ca242012-02-06 23:29:57 +00009694 // Make sure we handle LabelStmts correctly.
9695 // FIXME: This does the right thing, but maybe we need a more general
9696 // fix to TreeTransform?
9697 StmtResult TransformLabelStmt(LabelStmt *S) {
9698 S->getDecl()->setStmt(0);
9699 return BaseTransform::TransformLabelStmt(S);
9700 }
9701
Eli Friedman456f0182012-01-20 01:26:23 +00009702 // We need to special-case DeclRefExprs referring to FieldDecls which
9703 // are not part of a member pointer formation; normal TreeTransforming
9704 // doesn't catch this case because of the way we represent them in the AST.
9705 // FIXME: This is a bit ugly; is it really the best way to handle this
9706 // case?
9707 //
9708 // Error on DeclRefExprs referring to FieldDecls.
9709 ExprResult TransformDeclRefExpr(DeclRefExpr *E) {
9710 if (isa<FieldDecl>(E->getDecl()) &&
9711 SemaRef.ExprEvalContexts.back().Context != Sema::Unevaluated)
9712 return SemaRef.Diag(E->getLocation(),
9713 diag::err_invalid_non_static_member_use)
9714 << E->getDecl() << E->getSourceRange();
9715
9716 return BaseTransform::TransformDeclRefExpr(E);
9717 }
9718
9719 // Exception: filter out member pointer formation
9720 ExprResult TransformUnaryOperator(UnaryOperator *E) {
9721 if (E->getOpcode() == UO_AddrOf && E->getType()->isMemberPointerType())
9722 return E;
9723
9724 return BaseTransform::TransformUnaryOperator(E);
9725 }
9726
Douglas Gregor89625492012-02-09 08:14:43 +00009727 ExprResult TransformLambdaExpr(LambdaExpr *E) {
9728 // Lambdas never need to be transformed.
9729 return E;
9730 }
Eli Friedman456f0182012-01-20 01:26:23 +00009731 };
Eli Friedmanfbc0dff2012-01-18 01:05:54 +00009732}
9733
Eli Friedman456f0182012-01-20 01:26:23 +00009734ExprResult Sema::TranformToPotentiallyEvaluated(Expr *E) {
Eli Friedmane4f22df2012-02-29 04:03:55 +00009735 assert(ExprEvalContexts.back().Context == Unevaluated &&
9736 "Should only transform unevaluated expressions");
Eli Friedman456f0182012-01-20 01:26:23 +00009737 ExprEvalContexts.back().Context =
9738 ExprEvalContexts[ExprEvalContexts.size()-2].Context;
9739 if (ExprEvalContexts.back().Context == Unevaluated)
9740 return E;
9741 return TransformToPE(*this).TransformExpr(E);
Eli Friedmanfbc0dff2012-01-18 01:05:54 +00009742}
9743
Douglas Gregorff790f12009-11-26 00:44:06 +00009744void
Douglas Gregor7fcbd902012-02-21 00:37:24 +00009745Sema::PushExpressionEvaluationContext(ExpressionEvaluationContext NewContext,
Richard Smithfd555f62012-02-22 02:04:18 +00009746 Decl *LambdaContextDecl,
9747 bool IsDecltype) {
Douglas Gregorff790f12009-11-26 00:44:06 +00009748 ExprEvalContexts.push_back(
John McCall31168b02011-06-15 23:02:42 +00009749 ExpressionEvaluationContextRecord(NewContext,
John McCall28fc7092011-11-10 05:35:25 +00009750 ExprCleanupObjects.size(),
Douglas Gregor7fcbd902012-02-21 00:37:24 +00009751 ExprNeedsCleanups,
Richard Smithfd555f62012-02-22 02:04:18 +00009752 LambdaContextDecl,
9753 IsDecltype));
John McCall31168b02011-06-15 23:02:42 +00009754 ExprNeedsCleanups = false;
Eli Friedman3bda6b12012-02-02 23:15:15 +00009755 if (!MaybeODRUseExprs.empty())
9756 std::swap(MaybeODRUseExprs, ExprEvalContexts.back().SavedMaybeODRUseExprs);
Douglas Gregor0b6a6242009-06-22 20:57:11 +00009757}
9758
Richard Trieucfc491d2011-08-02 04:35:43 +00009759void Sema::PopExpressionEvaluationContext() {
Eli Friedmanfa0df832012-02-02 03:46:19 +00009760 ExpressionEvaluationContextRecord& Rec = ExprEvalContexts.back();
Douglas Gregor0b6a6242009-06-22 20:57:11 +00009761
Douglas Gregor89625492012-02-09 08:14:43 +00009762 if (!Rec.Lambdas.empty()) {
9763 if (Rec.Context == Unevaluated) {
9764 // C++11 [expr.prim.lambda]p2:
9765 // A lambda-expression shall not appear in an unevaluated operand
9766 // (Clause 5).
9767 for (unsigned I = 0, N = Rec.Lambdas.size(); I != N; ++I)
9768 Diag(Rec.Lambdas[I]->getLocStart(),
9769 diag::err_lambda_unevaluated_operand);
9770 } else {
9771 // Mark the capture expressions odr-used. This was deferred
9772 // during lambda expression creation.
9773 for (unsigned I = 0, N = Rec.Lambdas.size(); I != N; ++I) {
9774 LambdaExpr *Lambda = Rec.Lambdas[I];
9775 for (LambdaExpr::capture_init_iterator
9776 C = Lambda->capture_init_begin(),
9777 CEnd = Lambda->capture_init_end();
9778 C != CEnd; ++C) {
9779 MarkDeclarationsReferencedInExpr(*C);
9780 }
9781 }
9782 }
9783 }
9784
Douglas Gregorff790f12009-11-26 00:44:06 +00009785 // When are coming out of an unevaluated context, clear out any
9786 // temporaries that we may have created as part of the evaluation of
9787 // the expression in that context: they aren't relevant because they
9788 // will never be constructed.
Richard Smith764d2fe2011-12-20 02:08:33 +00009789 if (Rec.Context == Unevaluated || Rec.Context == ConstantEvaluated) {
John McCall28fc7092011-11-10 05:35:25 +00009790 ExprCleanupObjects.erase(ExprCleanupObjects.begin() + Rec.NumCleanupObjects,
9791 ExprCleanupObjects.end());
John McCall31168b02011-06-15 23:02:42 +00009792 ExprNeedsCleanups = Rec.ParentNeedsCleanups;
Eli Friedman3bda6b12012-02-02 23:15:15 +00009793 CleanupVarDeclMarking();
9794 std::swap(MaybeODRUseExprs, Rec.SavedMaybeODRUseExprs);
John McCall31168b02011-06-15 23:02:42 +00009795 // Otherwise, merge the contexts together.
9796 } else {
9797 ExprNeedsCleanups |= Rec.ParentNeedsCleanups;
Eli Friedman3bda6b12012-02-02 23:15:15 +00009798 MaybeODRUseExprs.insert(Rec.SavedMaybeODRUseExprs.begin(),
9799 Rec.SavedMaybeODRUseExprs.end());
John McCall31168b02011-06-15 23:02:42 +00009800 }
Eli Friedmanfa0df832012-02-02 03:46:19 +00009801
9802 // Pop the current expression evaluation context off the stack.
9803 ExprEvalContexts.pop_back();
Douglas Gregor0b6a6242009-06-22 20:57:11 +00009804}
Douglas Gregorc9c02ed2009-06-19 23:52:42 +00009805
John McCall31168b02011-06-15 23:02:42 +00009806void Sema::DiscardCleanupsInEvaluationContext() {
John McCall28fc7092011-11-10 05:35:25 +00009807 ExprCleanupObjects.erase(
9808 ExprCleanupObjects.begin() + ExprEvalContexts.back().NumCleanupObjects,
9809 ExprCleanupObjects.end());
John McCall31168b02011-06-15 23:02:42 +00009810 ExprNeedsCleanups = false;
Eli Friedman3bda6b12012-02-02 23:15:15 +00009811 MaybeODRUseExprs.clear();
John McCall31168b02011-06-15 23:02:42 +00009812}
9813
Eli Friedmane0afc982012-01-21 01:01:51 +00009814ExprResult Sema::HandleExprEvaluationContextForTypeof(Expr *E) {
9815 if (!E->getType()->isVariablyModifiedType())
9816 return E;
9817 return TranformToPotentiallyEvaluated(E);
9818}
9819
Benjamin Kramerbf8da9d2012-02-06 11:13:08 +00009820static bool IsPotentiallyEvaluatedContext(Sema &SemaRef) {
Douglas Gregorc9c02ed2009-06-19 23:52:42 +00009821 // Do not mark anything as "used" within a dependent context; wait for
9822 // an instantiation.
Eli Friedmanfa0df832012-02-02 03:46:19 +00009823 if (SemaRef.CurContext->isDependentContext())
9824 return false;
Mike Stump11289f42009-09-09 15:08:12 +00009825
Eli Friedmanfa0df832012-02-02 03:46:19 +00009826 switch (SemaRef.ExprEvalContexts.back().Context) {
9827 case Sema::Unevaluated:
Douglas Gregor0b6a6242009-06-22 20:57:11 +00009828 // We are in an expression that is not potentially evaluated; do nothing.
Eli Friedman02b58512012-01-21 04:44:06 +00009829 // (Depending on how you read the standard, we actually do need to do
9830 // something here for null pointer constants, but the standard's
9831 // definition of a null pointer constant is completely crazy.)
Eli Friedmanfa0df832012-02-02 03:46:19 +00009832 return false;
Mike Stump11289f42009-09-09 15:08:12 +00009833
Eli Friedmanfa0df832012-02-02 03:46:19 +00009834 case Sema::ConstantEvaluated:
9835 case Sema::PotentiallyEvaluated:
Eli Friedman02b58512012-01-21 04:44:06 +00009836 // We are in a potentially evaluated expression (or a constant-expression
9837 // in C++03); we need to do implicit template instantiation, implicitly
9838 // define class members, and mark most declarations as used.
Eli Friedmanfa0df832012-02-02 03:46:19 +00009839 return true;
Mike Stump11289f42009-09-09 15:08:12 +00009840
Eli Friedmanfa0df832012-02-02 03:46:19 +00009841 case Sema::PotentiallyEvaluatedIfUsed:
Douglas Gregor8a01b2a2010-09-11 20:24:53 +00009842 // Referenced declarations will only be used if the construct in the
9843 // containing expression is used.
Eli Friedmanfa0df832012-02-02 03:46:19 +00009844 return false;
Douglas Gregor0b6a6242009-06-22 20:57:11 +00009845 }
Matt Beaumont-Gay248bc722012-02-02 18:35:35 +00009846 llvm_unreachable("Invalid context");
Eli Friedmanfa0df832012-02-02 03:46:19 +00009847}
9848
9849/// \brief Mark a function referenced, and check whether it is odr-used
9850/// (C++ [basic.def.odr]p2, C99 6.9p3)
9851void Sema::MarkFunctionReferenced(SourceLocation Loc, FunctionDecl *Func) {
9852 assert(Func && "No function?");
9853
9854 Func->setReferenced();
9855
Richard Smith4a941e22012-02-14 22:25:15 +00009856 // Don't mark this function as used multiple times, unless it's a constexpr
9857 // function which we need to instantiate.
9858 if (Func->isUsed(false) &&
9859 !(Func->isConstexpr() && !Func->getBody() &&
9860 Func->isImplicitlyInstantiable()))
Eli Friedmanfa0df832012-02-02 03:46:19 +00009861 return;
9862
9863 if (!IsPotentiallyEvaluatedContext(*this))
9864 return;
Mike Stump11289f42009-09-09 15:08:12 +00009865
Douglas Gregorc9c02ed2009-06-19 23:52:42 +00009866 // Note that this declaration has been used.
Eli Friedmanfa0df832012-02-02 03:46:19 +00009867 if (CXXConstructorDecl *Constructor = dyn_cast<CXXConstructorDecl>(Func)) {
Richard Smith273c4e92012-02-26 07:51:39 +00009868 if (Constructor->isDefaulted() && !Constructor->isDeleted()) {
Sebastian Redl22653ba2011-08-30 19:58:05 +00009869 if (Constructor->isDefaultConstructor()) {
9870 if (Constructor->isTrivial())
9871 return;
9872 if (!Constructor->isUsed(false))
9873 DefineImplicitDefaultConstructor(Loc, Constructor);
9874 } else if (Constructor->isCopyConstructor()) {
9875 if (!Constructor->isUsed(false))
9876 DefineImplicitCopyConstructor(Loc, Constructor);
9877 } else if (Constructor->isMoveConstructor()) {
9878 if (!Constructor->isUsed(false))
9879 DefineImplicitMoveConstructor(Loc, Constructor);
9880 }
Fariborz Jahanian477d2422009-06-22 23:34:40 +00009881 }
Kovarththanan Rajaratnamba2c6522010-03-13 10:17:05 +00009882
Douglas Gregor88d292c2010-05-13 16:44:06 +00009883 MarkVTableUsed(Loc, Constructor->getParent());
Eli Friedmanfa0df832012-02-02 03:46:19 +00009884 } else if (CXXDestructorDecl *Destructor =
9885 dyn_cast<CXXDestructorDecl>(Func)) {
Richard Smith273c4e92012-02-26 07:51:39 +00009886 if (Destructor->isDefaulted() && !Destructor->isDeleted() &&
9887 !Destructor->isUsed(false))
Fariborz Jahanian24a175b2009-06-26 23:49:16 +00009888 DefineImplicitDestructor(Loc, Destructor);
Douglas Gregor88d292c2010-05-13 16:44:06 +00009889 if (Destructor->isVirtual())
9890 MarkVTableUsed(Loc, Destructor->getParent());
Eli Friedmanfa0df832012-02-02 03:46:19 +00009891 } else if (CXXMethodDecl *MethodDecl = dyn_cast<CXXMethodDecl>(Func)) {
Richard Smith273c4e92012-02-26 07:51:39 +00009892 if (MethodDecl->isDefaulted() && !MethodDecl->isDeleted() &&
9893 MethodDecl->isOverloadedOperator() &&
Fariborz Jahanian41f79272009-06-25 21:45:19 +00009894 MethodDecl->getOverloadedOperator() == OO_Equal) {
Sebastian Redl22653ba2011-08-30 19:58:05 +00009895 if (!MethodDecl->isUsed(false)) {
9896 if (MethodDecl->isCopyAssignmentOperator())
9897 DefineImplicitCopyAssignment(Loc, MethodDecl);
9898 else
9899 DefineImplicitMoveAssignment(Loc, MethodDecl);
9900 }
Douglas Gregord3b672c2012-02-16 01:06:16 +00009901 } else if (isa<CXXConversionDecl>(MethodDecl) &&
9902 MethodDecl->getParent()->isLambda()) {
9903 CXXConversionDecl *Conversion = cast<CXXConversionDecl>(MethodDecl);
9904 if (Conversion->isLambdaToBlockPointerConversion())
9905 DefineImplicitLambdaToBlockPointerConversion(Loc, Conversion);
9906 else
9907 DefineImplicitLambdaToFunctionPointerConversion(Loc, Conversion);
Douglas Gregor88d292c2010-05-13 16:44:06 +00009908 } else if (MethodDecl->isVirtual())
9909 MarkVTableUsed(Loc, MethodDecl->getParent());
Fariborz Jahanian41f79272009-06-25 21:45:19 +00009910 }
John McCall83779672011-02-19 02:53:41 +00009911
Eli Friedmanfa0df832012-02-02 03:46:19 +00009912 // Recursive functions should be marked when used from another function.
9913 // FIXME: Is this really right?
9914 if (CurContext == Func) return;
Kovarththanan Rajaratnamba2c6522010-03-13 10:17:05 +00009915
Richard Smithf623c962012-04-17 00:58:00 +00009916 // Instantiate the exception specification for any function which is
9917 // used: CodeGen will need it.
Richard Smithd3729422012-04-19 00:08:28 +00009918 const FunctionProtoType *FPT = Func->getType()->getAs<FunctionProtoType>();
9919 if (FPT && FPT->getExceptionSpecType() == EST_Uninstantiated)
Richard Smithf623c962012-04-17 00:58:00 +00009920 InstantiateExceptionSpec(Loc, Func);
9921
Eli Friedmanfa0df832012-02-02 03:46:19 +00009922 // Implicit instantiation of function templates and member functions of
9923 // class templates.
9924 if (Func->isImplicitlyInstantiable()) {
9925 bool AlreadyInstantiated = false;
Richard Smith4a941e22012-02-14 22:25:15 +00009926 SourceLocation PointOfInstantiation = Loc;
Eli Friedmanfa0df832012-02-02 03:46:19 +00009927 if (FunctionTemplateSpecializationInfo *SpecInfo
9928 = Func->getTemplateSpecializationInfo()) {
9929 if (SpecInfo->getPointOfInstantiation().isInvalid())
9930 SpecInfo->setPointOfInstantiation(Loc);
9931 else if (SpecInfo->getTemplateSpecializationKind()
Richard Smith4a941e22012-02-14 22:25:15 +00009932 == TSK_ImplicitInstantiation) {
Eli Friedmanfa0df832012-02-02 03:46:19 +00009933 AlreadyInstantiated = true;
Richard Smith4a941e22012-02-14 22:25:15 +00009934 PointOfInstantiation = SpecInfo->getPointOfInstantiation();
9935 }
Eli Friedmanfa0df832012-02-02 03:46:19 +00009936 } else if (MemberSpecializationInfo *MSInfo
9937 = Func->getMemberSpecializationInfo()) {
9938 if (MSInfo->getPointOfInstantiation().isInvalid())
Douglas Gregor06db9f52009-10-12 20:18:28 +00009939 MSInfo->setPointOfInstantiation(Loc);
Eli Friedmanfa0df832012-02-02 03:46:19 +00009940 else if (MSInfo->getTemplateSpecializationKind()
Richard Smith4a941e22012-02-14 22:25:15 +00009941 == TSK_ImplicitInstantiation) {
Eli Friedmanfa0df832012-02-02 03:46:19 +00009942 AlreadyInstantiated = true;
Richard Smith4a941e22012-02-14 22:25:15 +00009943 PointOfInstantiation = MSInfo->getPointOfInstantiation();
9944 }
Douglas Gregor06db9f52009-10-12 20:18:28 +00009945 }
Mike Stump11289f42009-09-09 15:08:12 +00009946
Richard Smith4a941e22012-02-14 22:25:15 +00009947 if (!AlreadyInstantiated || Func->isConstexpr()) {
Eli Friedmanfa0df832012-02-02 03:46:19 +00009948 if (isa<CXXRecordDecl>(Func->getDeclContext()) &&
9949 cast<CXXRecordDecl>(Func->getDeclContext())->isLocalClass())
Richard Smith4a941e22012-02-14 22:25:15 +00009950 PendingLocalImplicitInstantiations.push_back(
9951 std::make_pair(Func, PointOfInstantiation));
9952 else if (Func->isConstexpr())
Eli Friedmanfa0df832012-02-02 03:46:19 +00009953 // Do not defer instantiations of constexpr functions, to avoid the
9954 // expression evaluator needing to call back into Sema if it sees a
9955 // call to such a function.
Richard Smith4a941e22012-02-14 22:25:15 +00009956 InstantiateFunctionDefinition(PointOfInstantiation, Func);
Argyrios Kyrtzidise5dc5b32012-02-10 20:10:44 +00009957 else {
Richard Smith4a941e22012-02-14 22:25:15 +00009958 PendingInstantiations.push_back(std::make_pair(Func,
9959 PointOfInstantiation));
Argyrios Kyrtzidise5dc5b32012-02-10 20:10:44 +00009960 // Notify the consumer that a function was implicitly instantiated.
9961 Consumer.HandleCXXImplicitFunctionInstantiation(Func);
9962 }
John McCall83779672011-02-19 02:53:41 +00009963 }
Eli Friedmanfa0df832012-02-02 03:46:19 +00009964 } else {
9965 // Walk redefinitions, as some of them may be instantiable.
9966 for (FunctionDecl::redecl_iterator i(Func->redecls_begin()),
9967 e(Func->redecls_end()); i != e; ++i) {
9968 if (!i->isUsed(false) && i->isImplicitlyInstantiable())
9969 MarkFunctionReferenced(Loc, *i);
9970 }
Sam Weinigbae69142009-09-11 03:29:30 +00009971 }
Eli Friedmanfa0df832012-02-02 03:46:19 +00009972
9973 // Keep track of used but undefined functions.
9974 if (!Func->isPure() && !Func->hasBody() &&
9975 Func->getLinkage() != ExternalLinkage) {
9976 SourceLocation &old = UndefinedInternals[Func->getCanonicalDecl()];
9977 if (old.isInvalid()) old = Loc;
9978 }
9979
9980 Func->setUsed(true);
9981}
9982
Eli Friedman9bb33f52012-02-03 02:04:35 +00009983static void
9984diagnoseUncapturableValueReference(Sema &S, SourceLocation loc,
9985 VarDecl *var, DeclContext *DC) {
Eli Friedmandd053f62012-02-07 00:15:00 +00009986 DeclContext *VarDC = var->getDeclContext();
9987
Eli Friedman9bb33f52012-02-03 02:04:35 +00009988 // If the parameter still belongs to the translation unit, then
9989 // we're actually just using one parameter in the declaration of
9990 // the next.
9991 if (isa<ParmVarDecl>(var) &&
Eli Friedmandd053f62012-02-07 00:15:00 +00009992 isa<TranslationUnitDecl>(VarDC))
Eli Friedman9bb33f52012-02-03 02:04:35 +00009993 return;
9994
Eli Friedmandd053f62012-02-07 00:15:00 +00009995 // For C code, don't diagnose about capture if we're not actually in code
9996 // right now; it's impossible to write a non-constant expression outside of
9997 // function context, so we'll get other (more useful) diagnostics later.
9998 //
9999 // For C++, things get a bit more nasty... it would be nice to suppress this
10000 // diagnostic for certain cases like using a local variable in an array bound
10001 // for a member of a local class, but the correct predicate is not obvious.
David Blaikiebbafb8a2012-03-11 07:00:24 +000010002 if (!S.getLangOpts().CPlusPlus && !S.CurContext->isFunctionOrMethod())
Eli Friedman9bb33f52012-02-03 02:04:35 +000010003 return;
10004
Eli Friedmandd053f62012-02-07 00:15:00 +000010005 if (isa<CXXMethodDecl>(VarDC) &&
10006 cast<CXXRecordDecl>(VarDC->getParent())->isLambda()) {
10007 S.Diag(loc, diag::err_reference_to_local_var_in_enclosing_lambda)
10008 << var->getIdentifier();
10009 } else if (FunctionDecl *fn = dyn_cast<FunctionDecl>(VarDC)) {
10010 S.Diag(loc, diag::err_reference_to_local_var_in_enclosing_function)
10011 << var->getIdentifier() << fn->getDeclName();
10012 } else if (isa<BlockDecl>(VarDC)) {
10013 S.Diag(loc, diag::err_reference_to_local_var_in_enclosing_block)
10014 << var->getIdentifier();
10015 } else {
10016 // FIXME: Is there any other context where a local variable can be
10017 // declared?
10018 S.Diag(loc, diag::err_reference_to_local_var_in_enclosing_context)
10019 << var->getIdentifier();
10020 }
Eli Friedman9bb33f52012-02-03 02:04:35 +000010021
Eli Friedman9bb33f52012-02-03 02:04:35 +000010022 S.Diag(var->getLocation(), diag::note_local_variable_declared_here)
10023 << var->getIdentifier();
Eli Friedmandd053f62012-02-07 00:15:00 +000010024
10025 // FIXME: Add additional diagnostic info about class etc. which prevents
10026 // capture.
Eli Friedman9bb33f52012-02-03 02:04:35 +000010027}
10028
Douglas Gregor81495f32012-02-12 18:42:33 +000010029/// \brief Capture the given variable in the given lambda expression.
10030static ExprResult captureInLambda(Sema &S, LambdaScopeInfo *LSI,
Douglas Gregorfdf598e2012-02-18 09:37:24 +000010031 VarDecl *Var, QualType FieldType,
10032 QualType DeclRefType,
10033 SourceLocation Loc) {
Douglas Gregor81495f32012-02-12 18:42:33 +000010034 CXXRecordDecl *Lambda = LSI->Lambda;
Douglas Gregor81495f32012-02-12 18:42:33 +000010035
Douglas Gregorabecb9c2012-02-09 01:56:40 +000010036 // Build the non-static data member.
10037 FieldDecl *Field
10038 = FieldDecl::Create(S.Context, Lambda, Loc, Loc, 0, FieldType,
10039 S.Context.getTrivialTypeSourceInfo(FieldType, Loc),
10040 0, false, false);
10041 Field->setImplicit(true);
10042 Field->setAccess(AS_private);
Douglas Gregor3d23f7882012-02-09 02:12:34 +000010043 Lambda->addDecl(Field);
Douglas Gregorabecb9c2012-02-09 01:56:40 +000010044
10045 // C++11 [expr.prim.lambda]p21:
10046 // When the lambda-expression is evaluated, the entities that
10047 // are captured by copy are used to direct-initialize each
10048 // corresponding non-static data member of the resulting closure
10049 // object. (For array members, the array elements are
10050 // direct-initialized in increasing subscript order.) These
10051 // initializations are performed in the (unspecified) order in
10052 // which the non-static data members are declared.
Douglas Gregorabecb9c2012-02-09 01:56:40 +000010053
Douglas Gregor89625492012-02-09 08:14:43 +000010054 // Introduce a new evaluation context for the initialization, so
10055 // that temporaries introduced as part of the capture are retained
10056 // to be re-"exported" from the lambda expression itself.
Douglas Gregorabecb9c2012-02-09 01:56:40 +000010057 S.PushExpressionEvaluationContext(Sema::PotentiallyEvaluated);
10058
Douglas Gregorf02455e2012-02-10 09:26:04 +000010059 // C++ [expr.prim.labda]p12:
10060 // An entity captured by a lambda-expression is odr-used (3.2) in
10061 // the scope containing the lambda-expression.
John McCall113bee02012-03-10 09:33:50 +000010062 Expr *Ref = new (S.Context) DeclRefExpr(Var, false, DeclRefType,
10063 VK_LValue, Loc);
Eli Friedman23b1be92012-03-01 21:32:56 +000010064 Var->setReferenced(true);
Douglas Gregorf02455e2012-02-10 09:26:04 +000010065 Var->setUsed(true);
Douglas Gregor199cec72012-02-09 02:45:47 +000010066
10067 // When the field has array type, create index variables for each
10068 // dimension of the array. We use these index variables to subscript
10069 // the source array, and other clients (e.g., CodeGen) will perform
10070 // the necessary iteration with these index variables.
10071 SmallVector<VarDecl *, 4> IndexVariables;
Douglas Gregor199cec72012-02-09 02:45:47 +000010072 QualType BaseType = FieldType;
10073 QualType SizeType = S.Context.getSizeType();
Douglas Gregor54fcea62012-02-13 16:35:30 +000010074 LSI->ArrayIndexStarts.push_back(LSI->ArrayIndexVars.size());
Douglas Gregor199cec72012-02-09 02:45:47 +000010075 while (const ConstantArrayType *Array
10076 = S.Context.getAsConstantArrayType(BaseType)) {
Douglas Gregor199cec72012-02-09 02:45:47 +000010077 // Create the iteration variable for this array index.
10078 IdentifierInfo *IterationVarName = 0;
10079 {
10080 SmallString<8> Str;
10081 llvm::raw_svector_ostream OS(Str);
10082 OS << "__i" << IndexVariables.size();
10083 IterationVarName = &S.Context.Idents.get(OS.str());
10084 }
10085 VarDecl *IterationVar
10086 = VarDecl::Create(S.Context, S.CurContext, Loc, Loc,
10087 IterationVarName, SizeType,
10088 S.Context.getTrivialTypeSourceInfo(SizeType, Loc),
10089 SC_None, SC_None);
10090 IndexVariables.push_back(IterationVar);
Douglas Gregor54fcea62012-02-13 16:35:30 +000010091 LSI->ArrayIndexVars.push_back(IterationVar);
10092
Douglas Gregor199cec72012-02-09 02:45:47 +000010093 // Create a reference to the iteration variable.
10094 ExprResult IterationVarRef
10095 = S.BuildDeclRefExpr(IterationVar, SizeType, VK_LValue, Loc);
10096 assert(!IterationVarRef.isInvalid() &&
10097 "Reference to invented variable cannot fail!");
10098 IterationVarRef = S.DefaultLvalueConversion(IterationVarRef.take());
10099 assert(!IterationVarRef.isInvalid() &&
10100 "Conversion of invented variable cannot fail!");
10101
10102 // Subscript the array with this iteration variable.
10103 ExprResult Subscript = S.CreateBuiltinArraySubscriptExpr(
10104 Ref, Loc, IterationVarRef.take(), Loc);
10105 if (Subscript.isInvalid()) {
10106 S.CleanupVarDeclMarking();
10107 S.DiscardCleanupsInEvaluationContext();
10108 S.PopExpressionEvaluationContext();
10109 return ExprError();
10110 }
10111
10112 Ref = Subscript.take();
10113 BaseType = Array->getElementType();
10114 }
10115
10116 // Construct the entity that we will be initializing. For an array, this
10117 // will be first element in the array, which may require several levels
10118 // of array-subscript entities.
10119 SmallVector<InitializedEntity, 4> Entities;
10120 Entities.reserve(1 + IndexVariables.size());
Douglas Gregor19666fb2012-02-15 16:57:26 +000010121 Entities.push_back(
10122 InitializedEntity::InitializeLambdaCapture(Var, Field, Loc));
Douglas Gregor199cec72012-02-09 02:45:47 +000010123 for (unsigned I = 0, N = IndexVariables.size(); I != N; ++I)
10124 Entities.push_back(InitializedEntity::InitializeElement(S.Context,
10125 0,
10126 Entities.back()));
10127
Douglas Gregorabecb9c2012-02-09 01:56:40 +000010128 InitializationKind InitKind
10129 = InitializationKind::CreateDirect(Loc, Loc, Loc);
Douglas Gregor199cec72012-02-09 02:45:47 +000010130 InitializationSequence Init(S, Entities.back(), InitKind, &Ref, 1);
Douglas Gregorabecb9c2012-02-09 01:56:40 +000010131 ExprResult Result(true);
Douglas Gregor199cec72012-02-09 02:45:47 +000010132 if (!Init.Diagnose(S, Entities.back(), InitKind, &Ref, 1))
10133 Result = Init.Perform(S, Entities.back(), InitKind,
Douglas Gregorabecb9c2012-02-09 01:56:40 +000010134 MultiExprArg(S, &Ref, 1));
10135
10136 // If this initialization requires any cleanups (e.g., due to a
10137 // default argument to a copy constructor), note that for the
10138 // lambda.
10139 if (S.ExprNeedsCleanups)
10140 LSI->ExprNeedsCleanups = true;
10141
10142 // Exit the expression evaluation context used for the capture.
10143 S.CleanupVarDeclMarking();
10144 S.DiscardCleanupsInEvaluationContext();
10145 S.PopExpressionEvaluationContext();
10146 return Result;
Douglas Gregor199cec72012-02-09 02:45:47 +000010147}
Douglas Gregorabecb9c2012-02-09 01:56:40 +000010148
Douglas Gregorfdf598e2012-02-18 09:37:24 +000010149bool Sema::tryCaptureVariable(VarDecl *Var, SourceLocation Loc,
10150 TryCaptureKind Kind, SourceLocation EllipsisLoc,
10151 bool BuildAndDiagnose,
10152 QualType &CaptureType,
10153 QualType &DeclRefType) {
10154 bool Nested = false;
Douglas Gregor81495f32012-02-12 18:42:33 +000010155
Eli Friedman24af8502012-02-03 22:47:37 +000010156 DeclContext *DC = CurContext;
Douglas Gregorfdf598e2012-02-18 09:37:24 +000010157 if (Var->getDeclContext() == DC) return true;
10158 if (!Var->hasLocalStorage()) return true;
Eli Friedman9bb33f52012-02-03 02:04:35 +000010159
Douglas Gregor81495f32012-02-12 18:42:33 +000010160 bool HasBlocksAttr = Var->hasAttr<BlocksAttr>();
Eli Friedman9bb33f52012-02-03 02:04:35 +000010161
Douglas Gregorfdf598e2012-02-18 09:37:24 +000010162 // Walk up the stack to determine whether we can capture the variable,
10163 // performing the "simple" checks that don't depend on type. We stop when
10164 // we've either hit the declared scope of the variable or find an existing
10165 // capture of that variable.
10166 CaptureType = Var->getType();
10167 DeclRefType = CaptureType.getNonReferenceType();
10168 bool Explicit = (Kind != TryCapture_Implicit);
10169 unsigned FunctionScopesIndex = FunctionScopes.size() - 1;
Eli Friedman9bb33f52012-02-03 02:04:35 +000010170 do {
Eli Friedman24af8502012-02-03 22:47:37 +000010171 // Only block literals and lambda expressions can capture; other
Eli Friedman9bb33f52012-02-03 02:04:35 +000010172 // scopes don't work.
Eli Friedman24af8502012-02-03 22:47:37 +000010173 DeclContext *ParentDC;
10174 if (isa<BlockDecl>(DC))
10175 ParentDC = DC->getParent();
10176 else if (isa<CXXMethodDecl>(DC) &&
Douglas Gregor81495f32012-02-12 18:42:33 +000010177 cast<CXXMethodDecl>(DC)->getOverloadedOperator() == OO_Call &&
Eli Friedman24af8502012-02-03 22:47:37 +000010178 cast<CXXRecordDecl>(DC->getParent())->isLambda())
10179 ParentDC = DC->getParent()->getParent();
Douglas Gregor81495f32012-02-12 18:42:33 +000010180 else {
Douglas Gregorfdf598e2012-02-18 09:37:24 +000010181 if (BuildAndDiagnose)
Douglas Gregor81495f32012-02-12 18:42:33 +000010182 diagnoseUncapturableValueReference(*this, Loc, Var, DC);
Douglas Gregorfdf598e2012-02-18 09:37:24 +000010183 return true;
Douglas Gregor81495f32012-02-12 18:42:33 +000010184 }
Eli Friedman9bb33f52012-02-03 02:04:35 +000010185
Eli Friedman24af8502012-02-03 22:47:37 +000010186 CapturingScopeInfo *CSI =
Douglas Gregor81495f32012-02-12 18:42:33 +000010187 cast<CapturingScopeInfo>(FunctionScopes[FunctionScopesIndex]);
Eli Friedman9bb33f52012-02-03 02:04:35 +000010188
Eli Friedman24af8502012-02-03 22:47:37 +000010189 // Check whether we've already captured it.
Douglas Gregor81495f32012-02-12 18:42:33 +000010190 if (CSI->CaptureMap.count(Var)) {
Douglas Gregorfdf598e2012-02-18 09:37:24 +000010191 // If we found a capture, any subcaptures are nested.
Eli Friedman9bb33f52012-02-03 02:04:35 +000010192 Nested = true;
Douglas Gregorfdf598e2012-02-18 09:37:24 +000010193
10194 // Retrieve the capture type for this variable.
10195 CaptureType = CSI->getCapture(Var).getCaptureType();
10196
10197 // Compute the type of an expression that refers to this variable.
10198 DeclRefType = CaptureType.getNonReferenceType();
10199
10200 const CapturingScopeInfo::Capture &Cap = CSI->getCapture(Var);
10201 if (Cap.isCopyCapture() &&
10202 !(isa<LambdaScopeInfo>(CSI) && cast<LambdaScopeInfo>(CSI)->Mutable))
10203 DeclRefType.addConst();
Eli Friedman9bb33f52012-02-03 02:04:35 +000010204 break;
10205 }
10206
Douglas Gregor81495f32012-02-12 18:42:33 +000010207 bool IsBlock = isa<BlockScopeInfo>(CSI);
Douglas Gregorfdf598e2012-02-18 09:37:24 +000010208 bool IsLambda = !IsBlock;
Eli Friedman24af8502012-02-03 22:47:37 +000010209
10210 // Lambdas are not allowed to capture unnamed variables
10211 // (e.g. anonymous unions).
10212 // FIXME: The C++11 rule don't actually state this explicitly, but I'm
10213 // assuming that's the intent.
Douglas Gregor81495f32012-02-12 18:42:33 +000010214 if (IsLambda && !Var->getDeclName()) {
Douglas Gregorfdf598e2012-02-18 09:37:24 +000010215 if (BuildAndDiagnose) {
Douglas Gregor81495f32012-02-12 18:42:33 +000010216 Diag(Loc, diag::err_lambda_capture_anonymous_var);
10217 Diag(Var->getLocation(), diag::note_declared_at);
10218 }
Douglas Gregorfdf598e2012-02-18 09:37:24 +000010219 return true;
Eli Friedman24af8502012-02-03 22:47:37 +000010220 }
10221
10222 // Prohibit variably-modified types; they're difficult to deal with.
Douglas Gregorfdf598e2012-02-18 09:37:24 +000010223 if (Var->getType()->isVariablyModifiedType()) {
10224 if (BuildAndDiagnose) {
Douglas Gregor81495f32012-02-12 18:42:33 +000010225 if (IsBlock)
10226 Diag(Loc, diag::err_ref_vm_type);
10227 else
10228 Diag(Loc, diag::err_lambda_capture_vm_type) << Var->getDeclName();
10229 Diag(Var->getLocation(), diag::note_previous_decl)
10230 << Var->getDeclName();
10231 }
Douglas Gregorfdf598e2012-02-18 09:37:24 +000010232 return true;
Eli Friedman9bb33f52012-02-03 02:04:35 +000010233 }
10234
Eli Friedman24af8502012-02-03 22:47:37 +000010235 // Lambdas are not allowed to capture __block variables; they don't
10236 // support the expected semantics.
Douglas Gregor81495f32012-02-12 18:42:33 +000010237 if (IsLambda && HasBlocksAttr) {
Douglas Gregorfdf598e2012-02-18 09:37:24 +000010238 if (BuildAndDiagnose) {
Douglas Gregor81495f32012-02-12 18:42:33 +000010239 Diag(Loc, diag::err_lambda_capture_block)
10240 << Var->getDeclName();
10241 Diag(Var->getLocation(), diag::note_previous_decl)
10242 << Var->getDeclName();
10243 }
Douglas Gregorfdf598e2012-02-18 09:37:24 +000010244 return true;
Eli Friedman24af8502012-02-03 22:47:37 +000010245 }
10246
Douglas Gregor81495f32012-02-12 18:42:33 +000010247 if (CSI->ImpCaptureStyle == CapturingScopeInfo::ImpCap_None && !Explicit) {
10248 // No capture-default
Douglas Gregorfdf598e2012-02-18 09:37:24 +000010249 if (BuildAndDiagnose) {
Douglas Gregor81495f32012-02-12 18:42:33 +000010250 Diag(Loc, diag::err_lambda_impcap) << Var->getDeclName();
10251 Diag(Var->getLocation(), diag::note_previous_decl)
10252 << Var->getDeclName();
10253 Diag(cast<LambdaScopeInfo>(CSI)->Lambda->getLocStart(),
10254 diag::note_lambda_decl);
10255 }
Douglas Gregorfdf598e2012-02-18 09:37:24 +000010256 return true;
Douglas Gregor81495f32012-02-12 18:42:33 +000010257 }
10258
10259 FunctionScopesIndex--;
10260 DC = ParentDC;
10261 Explicit = false;
10262 } while (!Var->getDeclContext()->Equals(DC));
10263
Douglas Gregorfdf598e2012-02-18 09:37:24 +000010264 // Walk back down the scope stack, computing the type of the capture at
10265 // each step, checking type-specific requirements, and adding captures if
10266 // requested.
10267 for (unsigned I = ++FunctionScopesIndex, N = FunctionScopes.size(); I != N;
10268 ++I) {
10269 CapturingScopeInfo *CSI = cast<CapturingScopeInfo>(FunctionScopes[I]);
Douglas Gregor812d8f62012-02-18 05:51:20 +000010270
Douglas Gregorfdf598e2012-02-18 09:37:24 +000010271 // Compute the type of the capture and of a reference to the capture within
10272 // this scope.
10273 if (isa<BlockScopeInfo>(CSI)) {
10274 Expr *CopyExpr = 0;
10275 bool ByRef = false;
10276
10277 // Blocks are not allowed to capture arrays.
10278 if (CaptureType->isArrayType()) {
10279 if (BuildAndDiagnose) {
10280 Diag(Loc, diag::err_ref_array_type);
10281 Diag(Var->getLocation(), diag::note_previous_decl)
10282 << Var->getDeclName();
10283 }
10284 return true;
10285 }
10286
John McCall67cd5e02012-03-30 05:23:48 +000010287 // Forbid the block-capture of autoreleasing variables.
10288 if (CaptureType.getObjCLifetime() == Qualifiers::OCL_Autoreleasing) {
10289 if (BuildAndDiagnose) {
10290 Diag(Loc, diag::err_arc_autoreleasing_capture)
10291 << /*block*/ 0;
10292 Diag(Var->getLocation(), diag::note_previous_decl)
10293 << Var->getDeclName();
10294 }
10295 return true;
10296 }
10297
Douglas Gregorfdf598e2012-02-18 09:37:24 +000010298 if (HasBlocksAttr || CaptureType->isReferenceType()) {
10299 // Block capture by reference does not change the capture or
10300 // declaration reference types.
10301 ByRef = true;
10302 } else {
10303 // Block capture by copy introduces 'const'.
10304 CaptureType = CaptureType.getNonReferenceType().withConst();
10305 DeclRefType = CaptureType;
10306
David Blaikiebbafb8a2012-03-11 07:00:24 +000010307 if (getLangOpts().CPlusPlus && BuildAndDiagnose) {
Douglas Gregorfdf598e2012-02-18 09:37:24 +000010308 if (const RecordType *Record = DeclRefType->getAs<RecordType>()) {
10309 // The capture logic needs the destructor, so make sure we mark it.
10310 // Usually this is unnecessary because most local variables have
10311 // their destructors marked at declaration time, but parameters are
10312 // an exception because it's technically only the call site that
10313 // actually requires the destructor.
10314 if (isa<ParmVarDecl>(Var))
10315 FinalizeVarWithDestructor(Var, Record);
10316
10317 // According to the blocks spec, the capture of a variable from
10318 // the stack requires a const copy constructor. This is not true
10319 // of the copy/move done to move a __block variable to the heap.
John McCall113bee02012-03-10 09:33:50 +000010320 Expr *DeclRef = new (Context) DeclRefExpr(Var, false,
Douglas Gregorfdf598e2012-02-18 09:37:24 +000010321 DeclRefType.withConst(),
10322 VK_LValue, Loc);
10323 ExprResult Result
10324 = PerformCopyInitialization(
10325 InitializedEntity::InitializeBlock(Var->getLocation(),
10326 CaptureType, false),
10327 Loc, Owned(DeclRef));
10328
10329 // Build a full-expression copy expression if initialization
10330 // succeeded and used a non-trivial constructor. Recover from
10331 // errors by pretending that the copy isn't necessary.
10332 if (!Result.isInvalid() &&
10333 !cast<CXXConstructExpr>(Result.get())->getConstructor()
10334 ->isTrivial()) {
10335 Result = MaybeCreateExprWithCleanups(Result);
10336 CopyExpr = Result.take();
10337 }
10338 }
10339 }
10340 }
10341
10342 // Actually capture the variable.
10343 if (BuildAndDiagnose)
10344 CSI->addCapture(Var, HasBlocksAttr, ByRef, Nested, Loc,
10345 SourceLocation(), CaptureType, CopyExpr);
10346 Nested = true;
10347 continue;
10348 }
Douglas Gregor812d8f62012-02-18 05:51:20 +000010349
Douglas Gregorfdf598e2012-02-18 09:37:24 +000010350 LambdaScopeInfo *LSI = cast<LambdaScopeInfo>(CSI);
10351
10352 // Determine whether we are capturing by reference or by value.
10353 bool ByRef = false;
10354 if (I == N - 1 && Kind != TryCapture_Implicit) {
10355 ByRef = (Kind == TryCapture_ExplicitByRef);
Eli Friedman24af8502012-02-03 22:47:37 +000010356 } else {
Douglas Gregorfdf598e2012-02-18 09:37:24 +000010357 ByRef = (LSI->ImpCaptureStyle == LambdaScopeInfo::ImpCap_LambdaByref);
Eli Friedman24af8502012-02-03 22:47:37 +000010358 }
Douglas Gregorfdf598e2012-02-18 09:37:24 +000010359
10360 // Compute the type of the field that will capture this variable.
10361 if (ByRef) {
10362 // C++11 [expr.prim.lambda]p15:
10363 // An entity is captured by reference if it is implicitly or
10364 // explicitly captured but not captured by copy. It is
10365 // unspecified whether additional unnamed non-static data
10366 // members are declared in the closure type for entities
10367 // captured by reference.
10368 //
10369 // FIXME: It is not clear whether we want to build an lvalue reference
10370 // to the DeclRefType or to CaptureType.getNonReferenceType(). GCC appears
10371 // to do the former, while EDG does the latter. Core issue 1249 will
10372 // clarify, but for now we follow GCC because it's a more permissive and
10373 // easily defensible position.
10374 CaptureType = Context.getLValueReferenceType(DeclRefType);
10375 } else {
10376 // C++11 [expr.prim.lambda]p14:
10377 // For each entity captured by copy, an unnamed non-static
10378 // data member is declared in the closure type. The
10379 // declaration order of these members is unspecified. The type
10380 // of such a data member is the type of the corresponding
10381 // captured entity if the entity is not a reference to an
10382 // object, or the referenced type otherwise. [Note: If the
10383 // captured entity is a reference to a function, the
10384 // corresponding data member is also a reference to a
10385 // function. - end note ]
10386 if (const ReferenceType *RefType = CaptureType->getAs<ReferenceType>()){
10387 if (!RefType->getPointeeType()->isFunctionType())
10388 CaptureType = RefType->getPointeeType();
Eli Friedman9bb33f52012-02-03 02:04:35 +000010389 }
John McCall67cd5e02012-03-30 05:23:48 +000010390
10391 // Forbid the lambda copy-capture of autoreleasing variables.
10392 if (CaptureType.getObjCLifetime() == Qualifiers::OCL_Autoreleasing) {
10393 if (BuildAndDiagnose) {
10394 Diag(Loc, diag::err_arc_autoreleasing_capture) << /*lambda*/ 1;
10395 Diag(Var->getLocation(), diag::note_previous_decl)
10396 << Var->getDeclName();
10397 }
10398 return true;
10399 }
Eli Friedman9bb33f52012-02-03 02:04:35 +000010400 }
10401
Douglas Gregorfdf598e2012-02-18 09:37:24 +000010402 // Capture this variable in the lambda.
10403 Expr *CopyExpr = 0;
10404 if (BuildAndDiagnose) {
10405 ExprResult Result = captureInLambda(*this, LSI, Var, CaptureType,
10406 DeclRefType, Loc);
10407 if (!Result.isInvalid())
10408 CopyExpr = Result.take();
10409 }
10410
10411 // Compute the type of a reference to this captured variable.
10412 if (ByRef)
10413 DeclRefType = CaptureType.getNonReferenceType();
10414 else {
10415 // C++ [expr.prim.lambda]p5:
10416 // The closure type for a lambda-expression has a public inline
10417 // function call operator [...]. This function call operator is
10418 // declared const (9.3.1) if and only if the lambda-expression’s
10419 // parameter-declaration-clause is not followed by mutable.
10420 DeclRefType = CaptureType.getNonReferenceType();
10421 if (!LSI->Mutable && !CaptureType->isReferenceType())
10422 DeclRefType.addConst();
10423 }
10424
10425 // Add the capture.
10426 if (BuildAndDiagnose)
10427 CSI->addCapture(Var, /*IsBlock=*/false, ByRef, Nested, Loc,
10428 EllipsisLoc, CaptureType, CopyExpr);
Eli Friedman9bb33f52012-02-03 02:04:35 +000010429 Nested = true;
10430 }
Douglas Gregorfdf598e2012-02-18 09:37:24 +000010431
10432 return false;
10433}
10434
10435bool Sema::tryCaptureVariable(VarDecl *Var, SourceLocation Loc,
10436 TryCaptureKind Kind, SourceLocation EllipsisLoc) {
10437 QualType CaptureType;
10438 QualType DeclRefType;
10439 return tryCaptureVariable(Var, Loc, Kind, EllipsisLoc,
10440 /*BuildAndDiagnose=*/true, CaptureType,
10441 DeclRefType);
10442}
10443
10444QualType Sema::getCapturedDeclRefType(VarDecl *Var, SourceLocation Loc) {
10445 QualType CaptureType;
10446 QualType DeclRefType;
10447
10448 // Determine whether we can capture this variable.
10449 if (tryCaptureVariable(Var, Loc, TryCapture_Implicit, SourceLocation(),
10450 /*BuildAndDiagnose=*/false, CaptureType, DeclRefType))
10451 return QualType();
10452
10453 return DeclRefType;
Eli Friedman9bb33f52012-02-03 02:04:35 +000010454}
10455
Eli Friedman3bda6b12012-02-02 23:15:15 +000010456static void MarkVarDeclODRUsed(Sema &SemaRef, VarDecl *Var,
10457 SourceLocation Loc) {
10458 // Keep track of used but undefined variables.
Eli Friedman130bbd02012-02-04 00:54:05 +000010459 // FIXME: We shouldn't suppress this warning for static data members.
Daniel Dunbar9d355812012-03-09 01:51:51 +000010460 if (Var->hasDefinition(SemaRef.Context) == VarDecl::DeclarationOnly &&
Eli Friedman130bbd02012-02-04 00:54:05 +000010461 Var->getLinkage() != ExternalLinkage &&
10462 !(Var->isStaticDataMember() && Var->hasInit())) {
Eli Friedman3bda6b12012-02-02 23:15:15 +000010463 SourceLocation &old = SemaRef.UndefinedInternals[Var->getCanonicalDecl()];
10464 if (old.isInvalid()) old = Loc;
10465 }
10466
Douglas Gregorfdf598e2012-02-18 09:37:24 +000010467 SemaRef.tryCaptureVariable(Var, Loc);
Eli Friedman9bb33f52012-02-03 02:04:35 +000010468
Eli Friedman3bda6b12012-02-02 23:15:15 +000010469 Var->setUsed(true);
10470}
10471
10472void Sema::UpdateMarkingForLValueToRValue(Expr *E) {
10473 // Per C++11 [basic.def.odr], a variable is odr-used "unless it is
10474 // an object that satisfies the requirements for appearing in a
10475 // constant expression (5.19) and the lvalue-to-rvalue conversion (4.1)
10476 // is immediately applied." This function handles the lvalue-to-rvalue
10477 // conversion part.
10478 MaybeODRUseExprs.erase(E->IgnoreParens());
10479}
10480
Eli Friedmanc6237c62012-02-29 03:16:56 +000010481ExprResult Sema::ActOnConstantExpression(ExprResult Res) {
10482 if (!Res.isUsable())
10483 return Res;
10484
10485 // If a constant-expression is a reference to a variable where we delay
10486 // deciding whether it is an odr-use, just assume we will apply the
10487 // lvalue-to-rvalue conversion. In the one case where this doesn't happen
10488 // (a non-type template argument), we have special handling anyway.
10489 UpdateMarkingForLValueToRValue(Res.get());
10490 return Res;
10491}
10492
Eli Friedman3bda6b12012-02-02 23:15:15 +000010493void Sema::CleanupVarDeclMarking() {
10494 for (llvm::SmallPtrSetIterator<Expr*> i = MaybeODRUseExprs.begin(),
10495 e = MaybeODRUseExprs.end();
10496 i != e; ++i) {
10497 VarDecl *Var;
10498 SourceLocation Loc;
John McCall113bee02012-03-10 09:33:50 +000010499 if (DeclRefExpr *DRE = dyn_cast<DeclRefExpr>(*i)) {
Eli Friedman3bda6b12012-02-02 23:15:15 +000010500 Var = cast<VarDecl>(DRE->getDecl());
10501 Loc = DRE->getLocation();
10502 } else if (MemberExpr *ME = dyn_cast<MemberExpr>(*i)) {
10503 Var = cast<VarDecl>(ME->getMemberDecl());
10504 Loc = ME->getMemberLoc();
10505 } else {
10506 llvm_unreachable("Unexpcted expression");
10507 }
10508
10509 MarkVarDeclODRUsed(*this, Var, Loc);
10510 }
10511
10512 MaybeODRUseExprs.clear();
10513}
10514
10515// Mark a VarDecl referenced, and perform the necessary handling to compute
10516// odr-uses.
10517static void DoMarkVarDeclReferenced(Sema &SemaRef, SourceLocation Loc,
10518 VarDecl *Var, Expr *E) {
Eli Friedmanfa0df832012-02-02 03:46:19 +000010519 Var->setReferenced();
10520
Eli Friedman3bda6b12012-02-02 23:15:15 +000010521 if (!IsPotentiallyEvaluatedContext(SemaRef))
Eli Friedmanfa0df832012-02-02 03:46:19 +000010522 return;
10523
10524 // Implicit instantiation of static data members of class templates.
Richard Smithd3cf2382012-02-15 02:42:50 +000010525 if (Var->isStaticDataMember() && Var->getInstantiatedFromStaticDataMember()) {
Eli Friedmanfa0df832012-02-02 03:46:19 +000010526 MemberSpecializationInfo *MSInfo = Var->getMemberSpecializationInfo();
10527 assert(MSInfo && "Missing member specialization information?");
Richard Smithd3cf2382012-02-15 02:42:50 +000010528 bool AlreadyInstantiated = !MSInfo->getPointOfInstantiation().isInvalid();
10529 if (MSInfo->getTemplateSpecializationKind() == TSK_ImplicitInstantiation &&
Daniel Dunbar9d355812012-03-09 01:51:51 +000010530 (!AlreadyInstantiated ||
10531 Var->isUsableInConstantExpressions(SemaRef.Context))) {
Richard Smithd3cf2382012-02-15 02:42:50 +000010532 if (!AlreadyInstantiated) {
10533 // This is a modification of an existing AST node. Notify listeners.
10534 if (ASTMutationListener *L = SemaRef.getASTMutationListener())
10535 L->StaticDataMemberInstantiated(Var);
10536 MSInfo->setPointOfInstantiation(Loc);
10537 }
10538 SourceLocation PointOfInstantiation = MSInfo->getPointOfInstantiation();
Daniel Dunbar9d355812012-03-09 01:51:51 +000010539 if (Var->isUsableInConstantExpressions(SemaRef.Context))
Eli Friedmanfa0df832012-02-02 03:46:19 +000010540 // Do not defer instantiations of variables which could be used in a
10541 // constant expression.
Richard Smithd3cf2382012-02-15 02:42:50 +000010542 SemaRef.InstantiateStaticDataMemberDefinition(PointOfInstantiation,Var);
Eli Friedmanfa0df832012-02-02 03:46:19 +000010543 else
Richard Smithd3cf2382012-02-15 02:42:50 +000010544 SemaRef.PendingInstantiations.push_back(
10545 std::make_pair(Var, PointOfInstantiation));
Eli Friedmanfa0df832012-02-02 03:46:19 +000010546 }
10547 }
10548
Eli Friedman3bda6b12012-02-02 23:15:15 +000010549 // Per C++11 [basic.def.odr], a variable is odr-used "unless it is
10550 // an object that satisfies the requirements for appearing in a
10551 // constant expression (5.19) and the lvalue-to-rvalue conversion (4.1)
10552 // is immediately applied." We check the first part here, and
10553 // Sema::UpdateMarkingForLValueToRValue deals with the second part.
10554 // Note that we use the C++11 definition everywhere because nothing in
Richard Smith35ecb362012-03-02 04:14:40 +000010555 // C++03 depends on whether we get the C++03 version correct. This does not
10556 // apply to references, since they are not objects.
Eli Friedman3bda6b12012-02-02 23:15:15 +000010557 const VarDecl *DefVD;
Richard Smith35ecb362012-03-02 04:14:40 +000010558 if (E && !isa<ParmVarDecl>(Var) && !Var->getType()->isReferenceType() &&
Daniel Dunbar9d355812012-03-09 01:51:51 +000010559 Var->isUsableInConstantExpressions(SemaRef.Context) &&
Eli Friedman3bda6b12012-02-02 23:15:15 +000010560 Var->getAnyInitializer(DefVD) && DefVD->checkInitIsICE())
10561 SemaRef.MaybeODRUseExprs.insert(E);
10562 else
10563 MarkVarDeclODRUsed(SemaRef, Var, Loc);
10564}
Eli Friedmanfa0df832012-02-02 03:46:19 +000010565
Eli Friedman3bda6b12012-02-02 23:15:15 +000010566/// \brief Mark a variable referenced, and check whether it is odr-used
10567/// (C++ [basic.def.odr]p2, C99 6.9p3). Note that this should not be
10568/// used directly for normal expressions referring to VarDecl.
10569void Sema::MarkVariableReferenced(SourceLocation Loc, VarDecl *Var) {
10570 DoMarkVarDeclReferenced(*this, Loc, Var, 0);
Eli Friedmanfa0df832012-02-02 03:46:19 +000010571}
10572
10573static void MarkExprReferenced(Sema &SemaRef, SourceLocation Loc,
10574 Decl *D, Expr *E) {
Eli Friedman3bda6b12012-02-02 23:15:15 +000010575 if (VarDecl *Var = dyn_cast<VarDecl>(D)) {
10576 DoMarkVarDeclReferenced(SemaRef, Loc, Var, E);
10577 return;
10578 }
10579
Eli Friedmanfa0df832012-02-02 03:46:19 +000010580 SemaRef.MarkAnyDeclReferenced(Loc, D);
Douglas Gregord3b672c2012-02-16 01:06:16 +000010581}
Eli Friedmanfa0df832012-02-02 03:46:19 +000010582
Eli Friedmanfa0df832012-02-02 03:46:19 +000010583/// \brief Perform reference-marking and odr-use handling for a DeclRefExpr.
10584void Sema::MarkDeclRefReferenced(DeclRefExpr *E) {
10585 MarkExprReferenced(*this, E->getLocation(), E->getDecl(), E);
10586}
10587
10588/// \brief Perform reference-marking and odr-use handling for a MemberExpr.
10589void Sema::MarkMemberReferenced(MemberExpr *E) {
10590 MarkExprReferenced(*this, E->getMemberLoc(), E->getMemberDecl(), E);
10591}
10592
Douglas Gregorf02455e2012-02-10 09:26:04 +000010593/// \brief Perform marking for a reference to an arbitrary declaration. It
Eli Friedmanfa0df832012-02-02 03:46:19 +000010594/// marks the declaration referenced, and performs odr-use checking for functions
10595/// and variables. This method should not be used when building an normal
10596/// expression which refers to a variable.
10597void Sema::MarkAnyDeclReferenced(SourceLocation Loc, Decl *D) {
10598 if (VarDecl *VD = dyn_cast<VarDecl>(D))
10599 MarkVariableReferenced(Loc, VD);
10600 else if (FunctionDecl *FD = dyn_cast<FunctionDecl>(D))
10601 MarkFunctionReferenced(Loc, FD);
10602 else
10603 D->setReferenced();
Douglas Gregorc9c02ed2009-06-19 23:52:42 +000010604}
Anders Carlsson7f84ed92009-10-09 23:51:55 +000010605
Douglas Gregor5597ab42010-05-07 23:12:07 +000010606namespace {
Chandler Carruthaf80f662010-06-09 08:17:30 +000010607 // Mark all of the declarations referenced
Douglas Gregor5597ab42010-05-07 23:12:07 +000010608 // FIXME: Not fully implemented yet! We need to have a better understanding
Chandler Carruthaf80f662010-06-09 08:17:30 +000010609 // of when we're entering
Douglas Gregor5597ab42010-05-07 23:12:07 +000010610 class MarkReferencedDecls : public RecursiveASTVisitor<MarkReferencedDecls> {
10611 Sema &S;
10612 SourceLocation Loc;
Chandler Carruthaf80f662010-06-09 08:17:30 +000010613
Douglas Gregor5597ab42010-05-07 23:12:07 +000010614 public:
10615 typedef RecursiveASTVisitor<MarkReferencedDecls> Inherited;
Chandler Carruthaf80f662010-06-09 08:17:30 +000010616
Douglas Gregor5597ab42010-05-07 23:12:07 +000010617 MarkReferencedDecls(Sema &S, SourceLocation Loc) : S(S), Loc(Loc) { }
Chandler Carruthaf80f662010-06-09 08:17:30 +000010618
10619 bool TraverseTemplateArgument(const TemplateArgument &Arg);
10620 bool TraverseRecordType(RecordType *T);
Douglas Gregor5597ab42010-05-07 23:12:07 +000010621 };
10622}
10623
Chandler Carruthaf80f662010-06-09 08:17:30 +000010624bool MarkReferencedDecls::TraverseTemplateArgument(
10625 const TemplateArgument &Arg) {
Douglas Gregor5597ab42010-05-07 23:12:07 +000010626 if (Arg.getKind() == TemplateArgument::Declaration) {
Douglas Gregor31f55dc2012-04-06 22:40:38 +000010627 if (Decl *D = Arg.getAsDecl())
10628 S.MarkAnyDeclReferenced(Loc, D);
Douglas Gregor5597ab42010-05-07 23:12:07 +000010629 }
Chandler Carruthaf80f662010-06-09 08:17:30 +000010630
10631 return Inherited::TraverseTemplateArgument(Arg);
Douglas Gregor5597ab42010-05-07 23:12:07 +000010632}
10633
Chandler Carruthaf80f662010-06-09 08:17:30 +000010634bool MarkReferencedDecls::TraverseRecordType(RecordType *T) {
Douglas Gregor5597ab42010-05-07 23:12:07 +000010635 if (ClassTemplateSpecializationDecl *Spec
10636 = dyn_cast<ClassTemplateSpecializationDecl>(T->getDecl())) {
10637 const TemplateArgumentList &Args = Spec->getTemplateArgs();
Douglas Gregor1ccc8412010-11-07 23:05:16 +000010638 return TraverseTemplateArguments(Args.data(), Args.size());
Douglas Gregor5597ab42010-05-07 23:12:07 +000010639 }
10640
Chandler Carruthc65667c2010-06-10 10:31:57 +000010641 return true;
Douglas Gregor5597ab42010-05-07 23:12:07 +000010642}
10643
10644void Sema::MarkDeclarationsReferencedInType(SourceLocation Loc, QualType T) {
10645 MarkReferencedDecls Marker(*this, Loc);
Chandler Carruthaf80f662010-06-09 08:17:30 +000010646 Marker.TraverseType(Context.getCanonicalType(T));
Douglas Gregor5597ab42010-05-07 23:12:07 +000010647}
10648
Douglas Gregor8a01b2a2010-09-11 20:24:53 +000010649namespace {
10650 /// \brief Helper class that marks all of the declarations referenced by
10651 /// potentially-evaluated subexpressions as "referenced".
10652 class EvaluatedExprMarker : public EvaluatedExprVisitor<EvaluatedExprMarker> {
10653 Sema &S;
Douglas Gregor680e9e02012-02-21 19:11:17 +000010654 bool SkipLocalVariables;
Douglas Gregor8a01b2a2010-09-11 20:24:53 +000010655
10656 public:
10657 typedef EvaluatedExprVisitor<EvaluatedExprMarker> Inherited;
10658
Douglas Gregor680e9e02012-02-21 19:11:17 +000010659 EvaluatedExprMarker(Sema &S, bool SkipLocalVariables)
10660 : Inherited(S.Context), S(S), SkipLocalVariables(SkipLocalVariables) { }
Douglas Gregor8a01b2a2010-09-11 20:24:53 +000010661
10662 void VisitDeclRefExpr(DeclRefExpr *E) {
Douglas Gregor680e9e02012-02-21 19:11:17 +000010663 // If we were asked not to visit local variables, don't.
10664 if (SkipLocalVariables) {
10665 if (VarDecl *VD = dyn_cast<VarDecl>(E->getDecl()))
10666 if (VD->hasLocalStorage())
10667 return;
10668 }
10669
Eli Friedmanfa0df832012-02-02 03:46:19 +000010670 S.MarkDeclRefReferenced(E);
Douglas Gregor8a01b2a2010-09-11 20:24:53 +000010671 }
10672
10673 void VisitMemberExpr(MemberExpr *E) {
Eli Friedmanfa0df832012-02-02 03:46:19 +000010674 S.MarkMemberReferenced(E);
Douglas Gregor32b3de52010-09-11 23:32:50 +000010675 Inherited::VisitMemberExpr(E);
Douglas Gregor8a01b2a2010-09-11 20:24:53 +000010676 }
10677
John McCall28fc7092011-11-10 05:35:25 +000010678 void VisitCXXBindTemporaryExpr(CXXBindTemporaryExpr *E) {
Eli Friedmanfa0df832012-02-02 03:46:19 +000010679 S.MarkFunctionReferenced(E->getLocStart(),
John McCall28fc7092011-11-10 05:35:25 +000010680 const_cast<CXXDestructorDecl*>(E->getTemporary()->getDestructor()));
10681 Visit(E->getSubExpr());
10682 }
10683
Douglas Gregor8a01b2a2010-09-11 20:24:53 +000010684 void VisitCXXNewExpr(CXXNewExpr *E) {
Douglas Gregor8a01b2a2010-09-11 20:24:53 +000010685 if (E->getOperatorNew())
Eli Friedmanfa0df832012-02-02 03:46:19 +000010686 S.MarkFunctionReferenced(E->getLocStart(), E->getOperatorNew());
Douglas Gregor8a01b2a2010-09-11 20:24:53 +000010687 if (E->getOperatorDelete())
Eli Friedmanfa0df832012-02-02 03:46:19 +000010688 S.MarkFunctionReferenced(E->getLocStart(), E->getOperatorDelete());
Douglas Gregor32b3de52010-09-11 23:32:50 +000010689 Inherited::VisitCXXNewExpr(E);
Douglas Gregor8a01b2a2010-09-11 20:24:53 +000010690 }
Sebastian Redl6047f072012-02-16 12:22:20 +000010691
Douglas Gregor8a01b2a2010-09-11 20:24:53 +000010692 void VisitCXXDeleteExpr(CXXDeleteExpr *E) {
10693 if (E->getOperatorDelete())
Eli Friedmanfa0df832012-02-02 03:46:19 +000010694 S.MarkFunctionReferenced(E->getLocStart(), E->getOperatorDelete());
Douglas Gregor6ed2fee2010-09-14 22:55:20 +000010695 QualType Destroyed = S.Context.getBaseElementType(E->getDestroyedType());
10696 if (const RecordType *DestroyedRec = Destroyed->getAs<RecordType>()) {
10697 CXXRecordDecl *Record = cast<CXXRecordDecl>(DestroyedRec->getDecl());
Eli Friedmanfa0df832012-02-02 03:46:19 +000010698 S.MarkFunctionReferenced(E->getLocStart(),
Douglas Gregor6ed2fee2010-09-14 22:55:20 +000010699 S.LookupDestructor(Record));
10700 }
10701
Douglas Gregor32b3de52010-09-11 23:32:50 +000010702 Inherited::VisitCXXDeleteExpr(E);
Douglas Gregor8a01b2a2010-09-11 20:24:53 +000010703 }
10704
10705 void VisitCXXConstructExpr(CXXConstructExpr *E) {
Eli Friedmanfa0df832012-02-02 03:46:19 +000010706 S.MarkFunctionReferenced(E->getLocStart(), E->getConstructor());
Douglas Gregor32b3de52010-09-11 23:32:50 +000010707 Inherited::VisitCXXConstructExpr(E);
Douglas Gregor8a01b2a2010-09-11 20:24:53 +000010708 }
10709
Douglas Gregorf0873f42010-10-19 17:17:35 +000010710 void VisitCXXDefaultArgExpr(CXXDefaultArgExpr *E) {
10711 Visit(E->getExpr());
10712 }
Eli Friedman3bda6b12012-02-02 23:15:15 +000010713
10714 void VisitImplicitCastExpr(ImplicitCastExpr *E) {
10715 Inherited::VisitImplicitCastExpr(E);
10716
10717 if (E->getCastKind() == CK_LValueToRValue)
10718 S.UpdateMarkingForLValueToRValue(E->getSubExpr());
10719 }
Douglas Gregor8a01b2a2010-09-11 20:24:53 +000010720 };
10721}
10722
10723/// \brief Mark any declarations that appear within this expression or any
10724/// potentially-evaluated subexpressions as "referenced".
Douglas Gregor680e9e02012-02-21 19:11:17 +000010725///
10726/// \param SkipLocalVariables If true, don't mark local variables as
10727/// 'referenced'.
10728void Sema::MarkDeclarationsReferencedInExpr(Expr *E,
10729 bool SkipLocalVariables) {
10730 EvaluatedExprMarker(*this, SkipLocalVariables).Visit(E);
Douglas Gregor8a01b2a2010-09-11 20:24:53 +000010731}
10732
Douglas Gregorda8cdbc2009-12-22 01:01:55 +000010733/// \brief Emit a diagnostic that describes an effect on the run-time behavior
10734/// of the program being compiled.
10735///
10736/// This routine emits the given diagnostic when the code currently being
Kovarththanan Rajaratnamba2c6522010-03-13 10:17:05 +000010737/// type-checked is "potentially evaluated", meaning that there is a
Douglas Gregorda8cdbc2009-12-22 01:01:55 +000010738/// possibility that the code will actually be executable. Code in sizeof()
10739/// expressions, code used only during overload resolution, etc., are not
10740/// potentially evaluated. This routine will suppress such diagnostics or,
10741/// in the absolutely nutty case of potentially potentially evaluated
Kovarththanan Rajaratnamba2c6522010-03-13 10:17:05 +000010742/// expressions (C++ typeid), queue the diagnostic to potentially emit it
Douglas Gregorda8cdbc2009-12-22 01:01:55 +000010743/// later.
Kovarththanan Rajaratnamba2c6522010-03-13 10:17:05 +000010744///
Douglas Gregorda8cdbc2009-12-22 01:01:55 +000010745/// This routine should be used for all diagnostics that describe the run-time
10746/// behavior of a program, such as passing a non-POD value through an ellipsis.
10747/// Failure to do so will likely result in spurious diagnostics or failures
10748/// during overload resolution or within sizeof/alignof/typeof/typeid.
Richard Trieuba63ce62011-09-09 01:45:06 +000010749bool Sema::DiagRuntimeBehavior(SourceLocation Loc, const Stmt *Statement,
Douglas Gregorda8cdbc2009-12-22 01:01:55 +000010750 const PartialDiagnostic &PD) {
John McCall31168b02011-06-15 23:02:42 +000010751 switch (ExprEvalContexts.back().Context) {
Douglas Gregorda8cdbc2009-12-22 01:01:55 +000010752 case Unevaluated:
10753 // The argument will never be evaluated, so don't complain.
10754 break;
Kovarththanan Rajaratnamba2c6522010-03-13 10:17:05 +000010755
Richard Smith764d2fe2011-12-20 02:08:33 +000010756 case ConstantEvaluated:
10757 // Relevant diagnostics should be produced by constant evaluation.
10758 break;
10759
Douglas Gregorda8cdbc2009-12-22 01:01:55 +000010760 case PotentiallyEvaluated:
Douglas Gregor8a01b2a2010-09-11 20:24:53 +000010761 case PotentiallyEvaluatedIfUsed:
Richard Trieuba63ce62011-09-09 01:45:06 +000010762 if (Statement && getCurFunctionOrMethodDecl()) {
Ted Kremenek3427fac2011-02-23 01:52:04 +000010763 FunctionScopes.back()->PossiblyUnreachableDiags.
Richard Trieuba63ce62011-09-09 01:45:06 +000010764 push_back(sema::PossiblyUnreachableDiag(PD, Loc, Statement));
Ted Kremenek3427fac2011-02-23 01:52:04 +000010765 }
10766 else
10767 Diag(Loc, PD);
10768
Douglas Gregorda8cdbc2009-12-22 01:01:55 +000010769 return true;
Douglas Gregorda8cdbc2009-12-22 01:01:55 +000010770 }
10771
10772 return false;
10773}
10774
Anders Carlsson7f84ed92009-10-09 23:51:55 +000010775bool Sema::CheckCallReturnType(QualType ReturnType, SourceLocation Loc,
10776 CallExpr *CE, FunctionDecl *FD) {
10777 if (ReturnType->isVoidType() || !ReturnType->isIncompleteType())
10778 return false;
10779
Richard Smithfd555f62012-02-22 02:04:18 +000010780 // If we're inside a decltype's expression, don't check for a valid return
10781 // type or construct temporaries until we know whether this is the last call.
10782 if (ExprEvalContexts.back().IsDecltype) {
10783 ExprEvalContexts.back().DelayedDecltypeCalls.push_back(CE);
10784 return false;
10785 }
10786
Douglas Gregora6c5abb2012-05-04 16:48:41 +000010787 class CallReturnIncompleteDiagnoser : public TypeDiagnoser {
Douglas Gregor7bfb2d02012-05-04 16:32:21 +000010788 FunctionDecl *FD;
10789 CallExpr *CE;
10790
10791 public:
10792 CallReturnIncompleteDiagnoser(FunctionDecl *FD, CallExpr *CE)
10793 : FD(FD), CE(CE) { }
10794
10795 virtual void diagnose(Sema &S, SourceLocation Loc, QualType T) {
10796 if (!FD) {
10797 S.Diag(Loc, diag::err_call_incomplete_return)
10798 << T << CE->getSourceRange();
10799 return;
10800 }
10801
10802 S.Diag(Loc, diag::err_call_function_incomplete_return)
10803 << CE->getSourceRange() << FD->getDeclName() << T;
10804 S.Diag(FD->getLocation(),
10805 diag::note_function_with_incomplete_return_type_declared_here)
10806 << FD->getDeclName();
10807 }
10808 } Diagnoser(FD, CE);
10809
10810 if (RequireCompleteType(Loc, ReturnType, Diagnoser))
Anders Carlsson7f84ed92009-10-09 23:51:55 +000010811 return true;
10812
10813 return false;
10814}
10815
Douglas Gregor2d4f64f2011-01-19 16:50:08 +000010816// Diagnose the s/=/==/ and s/\|=/!=/ typos. Note that adding parentheses
John McCalld5707ab2009-10-12 21:59:07 +000010817// will prevent this condition from triggering, which is what we want.
10818void Sema::DiagnoseAssignmentAsCondition(Expr *E) {
10819 SourceLocation Loc;
10820
John McCall0506e4a2009-11-11 02:41:58 +000010821 unsigned diagnostic = diag::warn_condition_is_assignment;
Douglas Gregor2d4f64f2011-01-19 16:50:08 +000010822 bool IsOrAssign = false;
John McCall0506e4a2009-11-11 02:41:58 +000010823
Chandler Carruthf87d6c02011-08-16 22:30:10 +000010824 if (BinaryOperator *Op = dyn_cast<BinaryOperator>(E)) {
Douglas Gregor2d4f64f2011-01-19 16:50:08 +000010825 if (Op->getOpcode() != BO_Assign && Op->getOpcode() != BO_OrAssign)
John McCalld5707ab2009-10-12 21:59:07 +000010826 return;
10827
Douglas Gregor2d4f64f2011-01-19 16:50:08 +000010828 IsOrAssign = Op->getOpcode() == BO_OrAssign;
10829
John McCallb0e419e2009-11-12 00:06:05 +000010830 // Greylist some idioms by putting them into a warning subcategory.
10831 if (ObjCMessageExpr *ME
10832 = dyn_cast<ObjCMessageExpr>(Op->getRHS()->IgnoreParenCasts())) {
10833 Selector Sel = ME->getSelector();
10834
John McCallb0e419e2009-11-12 00:06:05 +000010835 // self = [<foo> init...]
Douglas Gregor486b74e2011-09-27 16:10:05 +000010836 if (isSelfExpr(Op->getLHS()) && Sel.getNameForSlot(0).startswith("init"))
John McCallb0e419e2009-11-12 00:06:05 +000010837 diagnostic = diag::warn_condition_is_idiomatic_assignment;
10838
10839 // <foo> = [<bar> nextObject]
Douglas Gregoraf2a6ae2011-02-18 22:29:55 +000010840 else if (Sel.isUnarySelector() && Sel.getNameForSlot(0) == "nextObject")
John McCallb0e419e2009-11-12 00:06:05 +000010841 diagnostic = diag::warn_condition_is_idiomatic_assignment;
10842 }
John McCall0506e4a2009-11-11 02:41:58 +000010843
John McCalld5707ab2009-10-12 21:59:07 +000010844 Loc = Op->getOperatorLoc();
Chandler Carruthf87d6c02011-08-16 22:30:10 +000010845 } else if (CXXOperatorCallExpr *Op = dyn_cast<CXXOperatorCallExpr>(E)) {
Douglas Gregor2d4f64f2011-01-19 16:50:08 +000010846 if (Op->getOperator() != OO_Equal && Op->getOperator() != OO_PipeEqual)
John McCalld5707ab2009-10-12 21:59:07 +000010847 return;
10848
Douglas Gregor2d4f64f2011-01-19 16:50:08 +000010849 IsOrAssign = Op->getOperator() == OO_PipeEqual;
John McCalld5707ab2009-10-12 21:59:07 +000010850 Loc = Op->getOperatorLoc();
10851 } else {
10852 // Not an assignment.
10853 return;
10854 }
10855
Douglas Gregor2bf2d3d2010-04-14 16:09:52 +000010856 Diag(Loc, diagnostic) << E->getSourceRange();
Douglas Gregor2d4f64f2011-01-19 16:50:08 +000010857
Daniel Dunbar62ee6412012-03-09 18:35:03 +000010858 SourceLocation Open = E->getLocStart();
Argyrios Kyrtzidise1b97c42011-04-25 23:01:29 +000010859 SourceLocation Close = PP.getLocForEndOfToken(E->getSourceRange().getEnd());
10860 Diag(Loc, diag::note_condition_assign_silence)
10861 << FixItHint::CreateInsertion(Open, "(")
10862 << FixItHint::CreateInsertion(Close, ")");
10863
Douglas Gregor2d4f64f2011-01-19 16:50:08 +000010864 if (IsOrAssign)
10865 Diag(Loc, diag::note_condition_or_assign_to_comparison)
10866 << FixItHint::CreateReplacement(Loc, "!=");
10867 else
10868 Diag(Loc, diag::note_condition_assign_to_comparison)
10869 << FixItHint::CreateReplacement(Loc, "==");
John McCalld5707ab2009-10-12 21:59:07 +000010870}
10871
Argyrios Kyrtzidis8b6ec682011-02-01 18:24:22 +000010872/// \brief Redundant parentheses over an equality comparison can indicate
10873/// that the user intended an assignment used as condition.
Richard Trieuba63ce62011-09-09 01:45:06 +000010874void Sema::DiagnoseEqualityWithExtraParens(ParenExpr *ParenE) {
Argyrios Kyrtzidisf4f82782011-02-01 22:23:56 +000010875 // Don't warn if the parens came from a macro.
Richard Trieuba63ce62011-09-09 01:45:06 +000010876 SourceLocation parenLoc = ParenE->getLocStart();
Argyrios Kyrtzidisf4f82782011-02-01 22:23:56 +000010877 if (parenLoc.isInvalid() || parenLoc.isMacroID())
10878 return;
Argyrios Kyrtzidisba699d62011-03-28 23:52:04 +000010879 // Don't warn for dependent expressions.
Richard Trieuba63ce62011-09-09 01:45:06 +000010880 if (ParenE->isTypeDependent())
Argyrios Kyrtzidisba699d62011-03-28 23:52:04 +000010881 return;
Argyrios Kyrtzidisf4f82782011-02-01 22:23:56 +000010882
Richard Trieuba63ce62011-09-09 01:45:06 +000010883 Expr *E = ParenE->IgnoreParens();
Argyrios Kyrtzidis8b6ec682011-02-01 18:24:22 +000010884
10885 if (BinaryOperator *opE = dyn_cast<BinaryOperator>(E))
Argyrios Kyrtzidis582dd682011-02-01 19:32:59 +000010886 if (opE->getOpcode() == BO_EQ &&
10887 opE->getLHS()->IgnoreParenImpCasts()->isModifiableLvalue(Context)
10888 == Expr::MLV_Valid) {
Argyrios Kyrtzidis8b6ec682011-02-01 18:24:22 +000010889 SourceLocation Loc = opE->getOperatorLoc();
Ted Kremenekc358d9f2011-02-01 22:36:09 +000010890
Ted Kremenekae022092011-02-02 02:20:30 +000010891 Diag(Loc, diag::warn_equality_with_extra_parens) << E->getSourceRange();
Daniel Dunbar62ee6412012-03-09 18:35:03 +000010892 SourceRange ParenERange = ParenE->getSourceRange();
Ted Kremenekae022092011-02-02 02:20:30 +000010893 Diag(Loc, diag::note_equality_comparison_silence)
Daniel Dunbar62ee6412012-03-09 18:35:03 +000010894 << FixItHint::CreateRemoval(ParenERange.getBegin())
10895 << FixItHint::CreateRemoval(ParenERange.getEnd());
Argyrios Kyrtzidise1b97c42011-04-25 23:01:29 +000010896 Diag(Loc, diag::note_equality_comparison_to_assign)
10897 << FixItHint::CreateReplacement(Loc, "=");
Argyrios Kyrtzidis8b6ec682011-02-01 18:24:22 +000010898 }
10899}
10900
John Wiegley01296292011-04-08 18:41:53 +000010901ExprResult Sema::CheckBooleanCondition(Expr *E, SourceLocation Loc) {
John McCalld5707ab2009-10-12 21:59:07 +000010902 DiagnoseAssignmentAsCondition(E);
Argyrios Kyrtzidis8b6ec682011-02-01 18:24:22 +000010903 if (ParenExpr *parenE = dyn_cast<ParenExpr>(E))
10904 DiagnoseEqualityWithExtraParens(parenE);
John McCalld5707ab2009-10-12 21:59:07 +000010905
John McCall0009fcc2011-04-26 20:42:42 +000010906 ExprResult result = CheckPlaceholderExpr(E);
10907 if (result.isInvalid()) return ExprError();
10908 E = result.take();
Argyrios Kyrtzidisca766292010-11-01 18:49:26 +000010909
John McCall0009fcc2011-04-26 20:42:42 +000010910 if (!E->isTypeDependent()) {
David Blaikiebbafb8a2012-03-11 07:00:24 +000010911 if (getLangOpts().CPlusPlus)
John McCall34376a62010-12-04 03:47:34 +000010912 return CheckCXXBooleanCondition(E); // C++ 6.4p4
10913
John Wiegley01296292011-04-08 18:41:53 +000010914 ExprResult ERes = DefaultFunctionArrayLvalueConversion(E);
10915 if (ERes.isInvalid())
10916 return ExprError();
10917 E = ERes.take();
John McCall29cb2fd2010-12-04 06:09:13 +000010918
10919 QualType T = E->getType();
John Wiegley01296292011-04-08 18:41:53 +000010920 if (!T->isScalarType()) { // C99 6.8.4.1p1
10921 Diag(Loc, diag::err_typecheck_statement_requires_scalar)
10922 << T << E->getSourceRange();
10923 return ExprError();
10924 }
John McCalld5707ab2009-10-12 21:59:07 +000010925 }
10926
John Wiegley01296292011-04-08 18:41:53 +000010927 return Owned(E);
John McCalld5707ab2009-10-12 21:59:07 +000010928}
Douglas Gregore60e41a2010-05-06 17:25:47 +000010929
John McCalldadc5752010-08-24 06:29:42 +000010930ExprResult Sema::ActOnBooleanCondition(Scope *S, SourceLocation Loc,
Richard Trieuba63ce62011-09-09 01:45:06 +000010931 Expr *SubExpr) {
10932 if (!SubExpr)
Douglas Gregore60e41a2010-05-06 17:25:47 +000010933 return ExprError();
John Wiegley01296292011-04-08 18:41:53 +000010934
Richard Trieuba63ce62011-09-09 01:45:06 +000010935 return CheckBooleanCondition(SubExpr, Loc);
Douglas Gregore60e41a2010-05-06 17:25:47 +000010936}
John McCall36e7fe32010-10-12 00:20:44 +000010937
John McCall31996342011-04-07 08:22:57 +000010938namespace {
John McCall2979fe02011-04-12 00:42:48 +000010939 /// A visitor for rebuilding a call to an __unknown_any expression
10940 /// to have an appropriate type.
10941 struct RebuildUnknownAnyFunction
10942 : StmtVisitor<RebuildUnknownAnyFunction, ExprResult> {
10943
10944 Sema &S;
10945
10946 RebuildUnknownAnyFunction(Sema &S) : S(S) {}
10947
10948 ExprResult VisitStmt(Stmt *S) {
10949 llvm_unreachable("unexpected statement!");
John McCall2979fe02011-04-12 00:42:48 +000010950 }
10951
Richard Trieu10162ab2011-09-09 03:59:41 +000010952 ExprResult VisitExpr(Expr *E) {
10953 S.Diag(E->getExprLoc(), diag::err_unsupported_unknown_any_call)
10954 << E->getSourceRange();
John McCall2979fe02011-04-12 00:42:48 +000010955 return ExprError();
10956 }
10957
10958 /// Rebuild an expression which simply semantically wraps another
10959 /// expression which it shares the type and value kind of.
Richard Trieu10162ab2011-09-09 03:59:41 +000010960 template <class T> ExprResult rebuildSugarExpr(T *E) {
10961 ExprResult SubResult = Visit(E->getSubExpr());
10962 if (SubResult.isInvalid()) return ExprError();
John McCall2979fe02011-04-12 00:42:48 +000010963
Richard Trieu10162ab2011-09-09 03:59:41 +000010964 Expr *SubExpr = SubResult.take();
10965 E->setSubExpr(SubExpr);
10966 E->setType(SubExpr->getType());
10967 E->setValueKind(SubExpr->getValueKind());
10968 assert(E->getObjectKind() == OK_Ordinary);
10969 return E;
John McCall2979fe02011-04-12 00:42:48 +000010970 }
10971
Richard Trieu10162ab2011-09-09 03:59:41 +000010972 ExprResult VisitParenExpr(ParenExpr *E) {
10973 return rebuildSugarExpr(E);
John McCall2979fe02011-04-12 00:42:48 +000010974 }
10975
Richard Trieu10162ab2011-09-09 03:59:41 +000010976 ExprResult VisitUnaryExtension(UnaryOperator *E) {
10977 return rebuildSugarExpr(E);
John McCall2979fe02011-04-12 00:42:48 +000010978 }
10979
Richard Trieu10162ab2011-09-09 03:59:41 +000010980 ExprResult VisitUnaryAddrOf(UnaryOperator *E) {
10981 ExprResult SubResult = Visit(E->getSubExpr());
10982 if (SubResult.isInvalid()) return ExprError();
John McCall2979fe02011-04-12 00:42:48 +000010983
Richard Trieu10162ab2011-09-09 03:59:41 +000010984 Expr *SubExpr = SubResult.take();
10985 E->setSubExpr(SubExpr);
10986 E->setType(S.Context.getPointerType(SubExpr->getType()));
10987 assert(E->getValueKind() == VK_RValue);
10988 assert(E->getObjectKind() == OK_Ordinary);
10989 return E;
John McCall2979fe02011-04-12 00:42:48 +000010990 }
10991
Richard Trieu10162ab2011-09-09 03:59:41 +000010992 ExprResult resolveDecl(Expr *E, ValueDecl *VD) {
10993 if (!isa<FunctionDecl>(VD)) return VisitExpr(E);
John McCall2979fe02011-04-12 00:42:48 +000010994
Richard Trieu10162ab2011-09-09 03:59:41 +000010995 E->setType(VD->getType());
John McCall2979fe02011-04-12 00:42:48 +000010996
Richard Trieu10162ab2011-09-09 03:59:41 +000010997 assert(E->getValueKind() == VK_RValue);
David Blaikiebbafb8a2012-03-11 07:00:24 +000010998 if (S.getLangOpts().CPlusPlus &&
Richard Trieu10162ab2011-09-09 03:59:41 +000010999 !(isa<CXXMethodDecl>(VD) &&
11000 cast<CXXMethodDecl>(VD)->isInstance()))
11001 E->setValueKind(VK_LValue);
John McCall2979fe02011-04-12 00:42:48 +000011002
Richard Trieu10162ab2011-09-09 03:59:41 +000011003 return E;
John McCall2979fe02011-04-12 00:42:48 +000011004 }
11005
Richard Trieu10162ab2011-09-09 03:59:41 +000011006 ExprResult VisitMemberExpr(MemberExpr *E) {
11007 return resolveDecl(E, E->getMemberDecl());
John McCall2979fe02011-04-12 00:42:48 +000011008 }
11009
Richard Trieu10162ab2011-09-09 03:59:41 +000011010 ExprResult VisitDeclRefExpr(DeclRefExpr *E) {
11011 return resolveDecl(E, E->getDecl());
John McCall2979fe02011-04-12 00:42:48 +000011012 }
11013 };
11014}
11015
11016/// Given a function expression of unknown-any type, try to rebuild it
11017/// to have a function type.
Richard Trieu10162ab2011-09-09 03:59:41 +000011018static ExprResult rebuildUnknownAnyFunction(Sema &S, Expr *FunctionExpr) {
11019 ExprResult Result = RebuildUnknownAnyFunction(S).Visit(FunctionExpr);
11020 if (Result.isInvalid()) return ExprError();
11021 return S.DefaultFunctionArrayConversion(Result.take());
John McCall2979fe02011-04-12 00:42:48 +000011022}
11023
11024namespace {
John McCall2d2e8702011-04-11 07:02:50 +000011025 /// A visitor for rebuilding an expression of type __unknown_anytype
11026 /// into one which resolves the type directly on the referring
11027 /// expression. Strict preservation of the original source
11028 /// structure is not a goal.
John McCall31996342011-04-07 08:22:57 +000011029 struct RebuildUnknownAnyExpr
John McCall39439732011-04-09 22:50:59 +000011030 : StmtVisitor<RebuildUnknownAnyExpr, ExprResult> {
John McCall31996342011-04-07 08:22:57 +000011031
11032 Sema &S;
11033
11034 /// The current destination type.
11035 QualType DestType;
11036
Richard Trieu10162ab2011-09-09 03:59:41 +000011037 RebuildUnknownAnyExpr(Sema &S, QualType CastType)
11038 : S(S), DestType(CastType) {}
John McCall31996342011-04-07 08:22:57 +000011039
John McCall39439732011-04-09 22:50:59 +000011040 ExprResult VisitStmt(Stmt *S) {
John McCall2d2e8702011-04-11 07:02:50 +000011041 llvm_unreachable("unexpected statement!");
John McCall31996342011-04-07 08:22:57 +000011042 }
11043
Richard Trieu10162ab2011-09-09 03:59:41 +000011044 ExprResult VisitExpr(Expr *E) {
11045 S.Diag(E->getExprLoc(), diag::err_unsupported_unknown_any_expr)
11046 << E->getSourceRange();
John McCall2d2e8702011-04-11 07:02:50 +000011047 return ExprError();
John McCall31996342011-04-07 08:22:57 +000011048 }
11049
Richard Trieu10162ab2011-09-09 03:59:41 +000011050 ExprResult VisitCallExpr(CallExpr *E);
11051 ExprResult VisitObjCMessageExpr(ObjCMessageExpr *E);
John McCall2d2e8702011-04-11 07:02:50 +000011052
John McCall39439732011-04-09 22:50:59 +000011053 /// Rebuild an expression which simply semantically wraps another
11054 /// expression which it shares the type and value kind of.
Richard Trieu10162ab2011-09-09 03:59:41 +000011055 template <class T> ExprResult rebuildSugarExpr(T *E) {
11056 ExprResult SubResult = Visit(E->getSubExpr());
11057 if (SubResult.isInvalid()) return ExprError();
11058 Expr *SubExpr = SubResult.take();
11059 E->setSubExpr(SubExpr);
11060 E->setType(SubExpr->getType());
11061 E->setValueKind(SubExpr->getValueKind());
11062 assert(E->getObjectKind() == OK_Ordinary);
11063 return E;
John McCall39439732011-04-09 22:50:59 +000011064 }
John McCall31996342011-04-07 08:22:57 +000011065
Richard Trieu10162ab2011-09-09 03:59:41 +000011066 ExprResult VisitParenExpr(ParenExpr *E) {
11067 return rebuildSugarExpr(E);
John McCall39439732011-04-09 22:50:59 +000011068 }
11069
Richard Trieu10162ab2011-09-09 03:59:41 +000011070 ExprResult VisitUnaryExtension(UnaryOperator *E) {
11071 return rebuildSugarExpr(E);
John McCall39439732011-04-09 22:50:59 +000011072 }
11073
Richard Trieu10162ab2011-09-09 03:59:41 +000011074 ExprResult VisitUnaryAddrOf(UnaryOperator *E) {
11075 const PointerType *Ptr = DestType->getAs<PointerType>();
11076 if (!Ptr) {
11077 S.Diag(E->getOperatorLoc(), diag::err_unknown_any_addrof)
11078 << E->getSourceRange();
John McCall2979fe02011-04-12 00:42:48 +000011079 return ExprError();
11080 }
Richard Trieu10162ab2011-09-09 03:59:41 +000011081 assert(E->getValueKind() == VK_RValue);
11082 assert(E->getObjectKind() == OK_Ordinary);
11083 E->setType(DestType);
John McCall2979fe02011-04-12 00:42:48 +000011084
11085 // Build the sub-expression as if it were an object of the pointee type.
Richard Trieu10162ab2011-09-09 03:59:41 +000011086 DestType = Ptr->getPointeeType();
11087 ExprResult SubResult = Visit(E->getSubExpr());
11088 if (SubResult.isInvalid()) return ExprError();
11089 E->setSubExpr(SubResult.take());
11090 return E;
John McCall2979fe02011-04-12 00:42:48 +000011091 }
11092
Richard Trieu10162ab2011-09-09 03:59:41 +000011093 ExprResult VisitImplicitCastExpr(ImplicitCastExpr *E);
John McCall39439732011-04-09 22:50:59 +000011094
Richard Trieu10162ab2011-09-09 03:59:41 +000011095 ExprResult resolveDecl(Expr *E, ValueDecl *VD);
John McCall39439732011-04-09 22:50:59 +000011096
Richard Trieu10162ab2011-09-09 03:59:41 +000011097 ExprResult VisitMemberExpr(MemberExpr *E) {
11098 return resolveDecl(E, E->getMemberDecl());
John McCall2979fe02011-04-12 00:42:48 +000011099 }
John McCall39439732011-04-09 22:50:59 +000011100
Richard Trieu10162ab2011-09-09 03:59:41 +000011101 ExprResult VisitDeclRefExpr(DeclRefExpr *E) {
11102 return resolveDecl(E, E->getDecl());
John McCall31996342011-04-07 08:22:57 +000011103 }
11104 };
11105}
11106
John McCall2d2e8702011-04-11 07:02:50 +000011107/// Rebuilds a call expression which yielded __unknown_anytype.
Richard Trieu10162ab2011-09-09 03:59:41 +000011108ExprResult RebuildUnknownAnyExpr::VisitCallExpr(CallExpr *E) {
11109 Expr *CalleeExpr = E->getCallee();
John McCall2d2e8702011-04-11 07:02:50 +000011110
11111 enum FnKind {
John McCall4adb38c2011-04-27 00:36:17 +000011112 FK_MemberFunction,
John McCall2d2e8702011-04-11 07:02:50 +000011113 FK_FunctionPointer,
11114 FK_BlockPointer
11115 };
11116
Richard Trieu10162ab2011-09-09 03:59:41 +000011117 FnKind Kind;
11118 QualType CalleeType = CalleeExpr->getType();
11119 if (CalleeType == S.Context.BoundMemberTy) {
11120 assert(isa<CXXMemberCallExpr>(E) || isa<CXXOperatorCallExpr>(E));
11121 Kind = FK_MemberFunction;
11122 CalleeType = Expr::findBoundMemberType(CalleeExpr);
11123 } else if (const PointerType *Ptr = CalleeType->getAs<PointerType>()) {
11124 CalleeType = Ptr->getPointeeType();
11125 Kind = FK_FunctionPointer;
John McCall2d2e8702011-04-11 07:02:50 +000011126 } else {
Richard Trieu10162ab2011-09-09 03:59:41 +000011127 CalleeType = CalleeType->castAs<BlockPointerType>()->getPointeeType();
11128 Kind = FK_BlockPointer;
John McCall2d2e8702011-04-11 07:02:50 +000011129 }
Richard Trieu10162ab2011-09-09 03:59:41 +000011130 const FunctionType *FnType = CalleeType->castAs<FunctionType>();
John McCall2d2e8702011-04-11 07:02:50 +000011131
11132 // Verify that this is a legal result type of a function.
11133 if (DestType->isArrayType() || DestType->isFunctionType()) {
11134 unsigned diagID = diag::err_func_returning_array_function;
Richard Trieu10162ab2011-09-09 03:59:41 +000011135 if (Kind == FK_BlockPointer)
John McCall2d2e8702011-04-11 07:02:50 +000011136 diagID = diag::err_block_returning_array_function;
11137
Richard Trieu10162ab2011-09-09 03:59:41 +000011138 S.Diag(E->getExprLoc(), diagID)
John McCall2d2e8702011-04-11 07:02:50 +000011139 << DestType->isFunctionType() << DestType;
11140 return ExprError();
11141 }
11142
11143 // Otherwise, go ahead and set DestType as the call's result.
Richard Trieu10162ab2011-09-09 03:59:41 +000011144 E->setType(DestType.getNonLValueExprType(S.Context));
11145 E->setValueKind(Expr::getValueKindForType(DestType));
11146 assert(E->getObjectKind() == OK_Ordinary);
John McCall2d2e8702011-04-11 07:02:50 +000011147
11148 // Rebuild the function type, replacing the result type with DestType.
Richard Trieu10162ab2011-09-09 03:59:41 +000011149 if (const FunctionProtoType *Proto = dyn_cast<FunctionProtoType>(FnType))
John McCall2d2e8702011-04-11 07:02:50 +000011150 DestType = S.Context.getFunctionType(DestType,
Richard Trieu10162ab2011-09-09 03:59:41 +000011151 Proto->arg_type_begin(),
11152 Proto->getNumArgs(),
11153 Proto->getExtProtoInfo());
John McCall2d2e8702011-04-11 07:02:50 +000011154 else
11155 DestType = S.Context.getFunctionNoProtoType(DestType,
Richard Trieu10162ab2011-09-09 03:59:41 +000011156 FnType->getExtInfo());
John McCall2d2e8702011-04-11 07:02:50 +000011157
11158 // Rebuild the appropriate pointer-to-function type.
Richard Trieu10162ab2011-09-09 03:59:41 +000011159 switch (Kind) {
John McCall4adb38c2011-04-27 00:36:17 +000011160 case FK_MemberFunction:
John McCall2d2e8702011-04-11 07:02:50 +000011161 // Nothing to do.
11162 break;
11163
11164 case FK_FunctionPointer:
11165 DestType = S.Context.getPointerType(DestType);
11166 break;
11167
11168 case FK_BlockPointer:
11169 DestType = S.Context.getBlockPointerType(DestType);
11170 break;
11171 }
11172
11173 // Finally, we can recurse.
Richard Trieu10162ab2011-09-09 03:59:41 +000011174 ExprResult CalleeResult = Visit(CalleeExpr);
11175 if (!CalleeResult.isUsable()) return ExprError();
11176 E->setCallee(CalleeResult.take());
John McCall2d2e8702011-04-11 07:02:50 +000011177
11178 // Bind a temporary if necessary.
Richard Trieu10162ab2011-09-09 03:59:41 +000011179 return S.MaybeBindToTemporary(E);
John McCall2d2e8702011-04-11 07:02:50 +000011180}
11181
Richard Trieu10162ab2011-09-09 03:59:41 +000011182ExprResult RebuildUnknownAnyExpr::VisitObjCMessageExpr(ObjCMessageExpr *E) {
John McCall2979fe02011-04-12 00:42:48 +000011183 // Verify that this is a legal result type of a call.
11184 if (DestType->isArrayType() || DestType->isFunctionType()) {
Richard Trieu10162ab2011-09-09 03:59:41 +000011185 S.Diag(E->getExprLoc(), diag::err_func_returning_array_function)
John McCall2979fe02011-04-12 00:42:48 +000011186 << DestType->isFunctionType() << DestType;
11187 return ExprError();
John McCall2d2e8702011-04-11 07:02:50 +000011188 }
11189
John McCall3f4138c2011-07-13 17:56:40 +000011190 // Rewrite the method result type if available.
Richard Trieu10162ab2011-09-09 03:59:41 +000011191 if (ObjCMethodDecl *Method = E->getMethodDecl()) {
11192 assert(Method->getResultType() == S.Context.UnknownAnyTy);
11193 Method->setResultType(DestType);
John McCall3f4138c2011-07-13 17:56:40 +000011194 }
John McCall2979fe02011-04-12 00:42:48 +000011195
John McCall2d2e8702011-04-11 07:02:50 +000011196 // Change the type of the message.
Richard Trieu10162ab2011-09-09 03:59:41 +000011197 E->setType(DestType.getNonReferenceType());
11198 E->setValueKind(Expr::getValueKindForType(DestType));
John McCall2d2e8702011-04-11 07:02:50 +000011199
Richard Trieu10162ab2011-09-09 03:59:41 +000011200 return S.MaybeBindToTemporary(E);
John McCall2d2e8702011-04-11 07:02:50 +000011201}
11202
Richard Trieu10162ab2011-09-09 03:59:41 +000011203ExprResult RebuildUnknownAnyExpr::VisitImplicitCastExpr(ImplicitCastExpr *E) {
John McCall2979fe02011-04-12 00:42:48 +000011204 // The only case we should ever see here is a function-to-pointer decay.
Sean Callanan2db103c2012-03-06 23:12:57 +000011205 if (E->getCastKind() == CK_FunctionToPointerDecay) {
Sean Callanan12495112012-03-06 21:34:12 +000011206 assert(E->getValueKind() == VK_RValue);
11207 assert(E->getObjectKind() == OK_Ordinary);
11208
11209 E->setType(DestType);
11210
11211 // Rebuild the sub-expression as the pointee (function) type.
11212 DestType = DestType->castAs<PointerType>()->getPointeeType();
11213
11214 ExprResult Result = Visit(E->getSubExpr());
11215 if (!Result.isUsable()) return ExprError();
11216
11217 E->setSubExpr(Result.take());
11218 return S.Owned(E);
Sean Callanan2db103c2012-03-06 23:12:57 +000011219 } else if (E->getCastKind() == CK_LValueToRValue) {
Sean Callanan12495112012-03-06 21:34:12 +000011220 assert(E->getValueKind() == VK_RValue);
11221 assert(E->getObjectKind() == OK_Ordinary);
John McCall2d2e8702011-04-11 07:02:50 +000011222
Sean Callanan12495112012-03-06 21:34:12 +000011223 assert(isa<BlockPointerType>(E->getType()));
John McCall2979fe02011-04-12 00:42:48 +000011224
Sean Callanan12495112012-03-06 21:34:12 +000011225 E->setType(DestType);
John McCall2d2e8702011-04-11 07:02:50 +000011226
Sean Callanan12495112012-03-06 21:34:12 +000011227 // The sub-expression has to be a lvalue reference, so rebuild it as such.
11228 DestType = S.Context.getLValueReferenceType(DestType);
John McCall2d2e8702011-04-11 07:02:50 +000011229
Sean Callanan12495112012-03-06 21:34:12 +000011230 ExprResult Result = Visit(E->getSubExpr());
11231 if (!Result.isUsable()) return ExprError();
11232
11233 E->setSubExpr(Result.take());
11234 return S.Owned(E);
Sean Callanan2db103c2012-03-06 23:12:57 +000011235 } else {
Sean Callanan12495112012-03-06 21:34:12 +000011236 llvm_unreachable("Unhandled cast type!");
11237 }
John McCall2d2e8702011-04-11 07:02:50 +000011238}
11239
Richard Trieu10162ab2011-09-09 03:59:41 +000011240ExprResult RebuildUnknownAnyExpr::resolveDecl(Expr *E, ValueDecl *VD) {
11241 ExprValueKind ValueKind = VK_LValue;
11242 QualType Type = DestType;
John McCall2d2e8702011-04-11 07:02:50 +000011243
11244 // We know how to make this work for certain kinds of decls:
11245
11246 // - functions
Richard Trieu10162ab2011-09-09 03:59:41 +000011247 if (FunctionDecl *FD = dyn_cast<FunctionDecl>(VD)) {
11248 if (const PointerType *Ptr = Type->getAs<PointerType>()) {
11249 DestType = Ptr->getPointeeType();
11250 ExprResult Result = resolveDecl(E, VD);
11251 if (Result.isInvalid()) return ExprError();
11252 return S.ImpCastExprToType(Result.take(), Type,
John McCall9a877fe2011-08-10 04:12:23 +000011253 CK_FunctionToPointerDecay, VK_RValue);
11254 }
11255
Richard Trieu10162ab2011-09-09 03:59:41 +000011256 if (!Type->isFunctionType()) {
11257 S.Diag(E->getExprLoc(), diag::err_unknown_any_function)
11258 << VD << E->getSourceRange();
John McCall9a877fe2011-08-10 04:12:23 +000011259 return ExprError();
11260 }
John McCall2d2e8702011-04-11 07:02:50 +000011261
Richard Trieu10162ab2011-09-09 03:59:41 +000011262 if (CXXMethodDecl *MD = dyn_cast<CXXMethodDecl>(FD))
11263 if (MD->isInstance()) {
11264 ValueKind = VK_RValue;
11265 Type = S.Context.BoundMemberTy;
John McCall4adb38c2011-04-27 00:36:17 +000011266 }
11267
John McCall2d2e8702011-04-11 07:02:50 +000011268 // Function references aren't l-values in C.
David Blaikiebbafb8a2012-03-11 07:00:24 +000011269 if (!S.getLangOpts().CPlusPlus)
Richard Trieu10162ab2011-09-09 03:59:41 +000011270 ValueKind = VK_RValue;
John McCall2d2e8702011-04-11 07:02:50 +000011271
11272 // - variables
Richard Trieu10162ab2011-09-09 03:59:41 +000011273 } else if (isa<VarDecl>(VD)) {
11274 if (const ReferenceType *RefTy = Type->getAs<ReferenceType>()) {
11275 Type = RefTy->getPointeeType();
11276 } else if (Type->isFunctionType()) {
11277 S.Diag(E->getExprLoc(), diag::err_unknown_any_var_function_type)
11278 << VD << E->getSourceRange();
John McCall2979fe02011-04-12 00:42:48 +000011279 return ExprError();
John McCall2d2e8702011-04-11 07:02:50 +000011280 }
11281
11282 // - nothing else
11283 } else {
Richard Trieu10162ab2011-09-09 03:59:41 +000011284 S.Diag(E->getExprLoc(), diag::err_unsupported_unknown_any_decl)
11285 << VD << E->getSourceRange();
John McCall2d2e8702011-04-11 07:02:50 +000011286 return ExprError();
11287 }
11288
Richard Trieu10162ab2011-09-09 03:59:41 +000011289 VD->setType(DestType);
11290 E->setType(Type);
11291 E->setValueKind(ValueKind);
11292 return S.Owned(E);
John McCall2d2e8702011-04-11 07:02:50 +000011293}
11294
John McCall31996342011-04-07 08:22:57 +000011295/// Check a cast of an unknown-any type. We intentionally only
11296/// trigger this for C-style casts.
Richard Trieuba63ce62011-09-09 01:45:06 +000011297ExprResult Sema::checkUnknownAnyCast(SourceRange TypeRange, QualType CastType,
11298 Expr *CastExpr, CastKind &CastKind,
11299 ExprValueKind &VK, CXXCastPath &Path) {
John McCall31996342011-04-07 08:22:57 +000011300 // Rewrite the casted expression from scratch.
Richard Trieuba63ce62011-09-09 01:45:06 +000011301 ExprResult result = RebuildUnknownAnyExpr(*this, CastType).Visit(CastExpr);
John McCall39439732011-04-09 22:50:59 +000011302 if (!result.isUsable()) return ExprError();
John McCall31996342011-04-07 08:22:57 +000011303
Richard Trieuba63ce62011-09-09 01:45:06 +000011304 CastExpr = result.take();
11305 VK = CastExpr->getValueKind();
11306 CastKind = CK_NoOp;
John McCall39439732011-04-09 22:50:59 +000011307
Richard Trieuba63ce62011-09-09 01:45:06 +000011308 return CastExpr;
John McCall31996342011-04-07 08:22:57 +000011309}
11310
Douglas Gregord8fb1e32011-12-01 01:37:36 +000011311ExprResult Sema::forceUnknownAnyToType(Expr *E, QualType ToType) {
11312 return RebuildUnknownAnyExpr(*this, ToType).Visit(E);
11313}
11314
Richard Trieuba63ce62011-09-09 01:45:06 +000011315static ExprResult diagnoseUnknownAnyExpr(Sema &S, Expr *E) {
11316 Expr *orig = E;
John McCall2d2e8702011-04-11 07:02:50 +000011317 unsigned diagID = diag::err_uncasted_use_of_unknown_any;
John McCall31996342011-04-07 08:22:57 +000011318 while (true) {
Richard Trieuba63ce62011-09-09 01:45:06 +000011319 E = E->IgnoreParenImpCasts();
11320 if (CallExpr *call = dyn_cast<CallExpr>(E)) {
11321 E = call->getCallee();
John McCall2d2e8702011-04-11 07:02:50 +000011322 diagID = diag::err_uncasted_call_of_unknown_any;
11323 } else {
John McCall31996342011-04-07 08:22:57 +000011324 break;
John McCall2d2e8702011-04-11 07:02:50 +000011325 }
John McCall31996342011-04-07 08:22:57 +000011326 }
11327
John McCall2d2e8702011-04-11 07:02:50 +000011328 SourceLocation loc;
11329 NamedDecl *d;
Richard Trieuba63ce62011-09-09 01:45:06 +000011330 if (DeclRefExpr *ref = dyn_cast<DeclRefExpr>(E)) {
John McCall2d2e8702011-04-11 07:02:50 +000011331 loc = ref->getLocation();
11332 d = ref->getDecl();
Richard Trieuba63ce62011-09-09 01:45:06 +000011333 } else if (MemberExpr *mem = dyn_cast<MemberExpr>(E)) {
John McCall2d2e8702011-04-11 07:02:50 +000011334 loc = mem->getMemberLoc();
11335 d = mem->getMemberDecl();
Richard Trieuba63ce62011-09-09 01:45:06 +000011336 } else if (ObjCMessageExpr *msg = dyn_cast<ObjCMessageExpr>(E)) {
John McCall2d2e8702011-04-11 07:02:50 +000011337 diagID = diag::err_uncasted_call_of_unknown_any;
Argyrios Kyrtzidisa6011e22011-10-03 06:36:51 +000011338 loc = msg->getSelectorStartLoc();
John McCall2d2e8702011-04-11 07:02:50 +000011339 d = msg->getMethodDecl();
John McCallfa6f5d62011-08-31 20:57:36 +000011340 if (!d) {
11341 S.Diag(loc, diag::err_uncasted_send_to_unknown_any_method)
11342 << static_cast<unsigned>(msg->isClassMessage()) << msg->getSelector()
11343 << orig->getSourceRange();
11344 return ExprError();
11345 }
John McCall2d2e8702011-04-11 07:02:50 +000011346 } else {
Richard Trieuba63ce62011-09-09 01:45:06 +000011347 S.Diag(E->getExprLoc(), diag::err_unsupported_unknown_any_expr)
11348 << E->getSourceRange();
John McCall2d2e8702011-04-11 07:02:50 +000011349 return ExprError();
11350 }
11351
11352 S.Diag(loc, diagID) << d << orig->getSourceRange();
John McCall31996342011-04-07 08:22:57 +000011353
11354 // Never recoverable.
11355 return ExprError();
11356}
11357
John McCall36e7fe32010-10-12 00:20:44 +000011358/// Check for operands with placeholder types and complain if found.
11359/// Returns true if there was an error and no recovery was possible.
John McCall3aef3d82011-04-10 19:13:55 +000011360ExprResult Sema::CheckPlaceholderExpr(Expr *E) {
John McCall4124c492011-10-17 18:40:02 +000011361 const BuiltinType *placeholderType = E->getType()->getAsPlaceholderType();
11362 if (!placeholderType) return Owned(E);
11363
11364 switch (placeholderType->getKind()) {
John McCall36e7fe32010-10-12 00:20:44 +000011365
John McCall31996342011-04-07 08:22:57 +000011366 // Overloaded expressions.
John McCall4124c492011-10-17 18:40:02 +000011367 case BuiltinType::Overload: {
John McCall50a2c2c2011-10-11 23:14:30 +000011368 // Try to resolve a single function template specialization.
11369 // This is obligatory.
11370 ExprResult result = Owned(E);
11371 if (ResolveAndFixSingleFunctionTemplateSpecialization(result, false)) {
11372 return result;
11373
11374 // If that failed, try to recover with a call.
11375 } else {
11376 tryToRecoverWithCall(result, PDiag(diag::err_ovl_unresolvable),
11377 /*complain*/ true);
11378 return result;
11379 }
11380 }
John McCall31996342011-04-07 08:22:57 +000011381
John McCall0009fcc2011-04-26 20:42:42 +000011382 // Bound member functions.
John McCall4124c492011-10-17 18:40:02 +000011383 case BuiltinType::BoundMember: {
John McCall50a2c2c2011-10-11 23:14:30 +000011384 ExprResult result = Owned(E);
11385 tryToRecoverWithCall(result, PDiag(diag::err_bound_member_function),
11386 /*complain*/ true);
11387 return result;
John McCall4124c492011-10-17 18:40:02 +000011388 }
11389
11390 // ARC unbridged casts.
11391 case BuiltinType::ARCUnbridgedCast: {
11392 Expr *realCast = stripARCUnbridgedCast(E);
11393 diagnoseARCUnbridgedCast(realCast);
11394 return Owned(realCast);
11395 }
John McCall0009fcc2011-04-26 20:42:42 +000011396
John McCall31996342011-04-07 08:22:57 +000011397 // Expressions of unknown type.
John McCall4124c492011-10-17 18:40:02 +000011398 case BuiltinType::UnknownAny:
John McCall31996342011-04-07 08:22:57 +000011399 return diagnoseUnknownAnyExpr(*this, E);
11400
John McCall526ab472011-10-25 17:37:35 +000011401 // Pseudo-objects.
11402 case BuiltinType::PseudoObject:
11403 return checkPseudoObjectRValue(E);
11404
John McCalle314e272011-10-18 21:02:43 +000011405 // Everything else should be impossible.
11406#define BUILTIN_TYPE(Id, SingletonId) \
11407 case BuiltinType::Id:
11408#define PLACEHOLDER_TYPE(Id, SingletonId)
11409#include "clang/AST/BuiltinTypes.def"
John McCall4124c492011-10-17 18:40:02 +000011410 break;
11411 }
11412
11413 llvm_unreachable("invalid placeholder type!");
John McCall36e7fe32010-10-12 00:20:44 +000011414}
Richard Trieu2c850c02011-04-21 21:44:26 +000011415
Richard Trieuba63ce62011-09-09 01:45:06 +000011416bool Sema::CheckCaseExpression(Expr *E) {
11417 if (E->isTypeDependent())
Richard Trieu2c850c02011-04-21 21:44:26 +000011418 return true;
Richard Trieuba63ce62011-09-09 01:45:06 +000011419 if (E->isValueDependent() || E->isIntegerConstantExpr(Context))
11420 return E->getType()->isIntegralOrEnumerationType();
Richard Trieu2c850c02011-04-21 21:44:26 +000011421 return false;
11422}
Ted Kremeneke65b0862012-03-06 20:05:56 +000011423
11424/// ActOnObjCBoolLiteral - Parse {__objc_yes,__objc_no} literals.
11425ExprResult
11426Sema::ActOnObjCBoolLiteral(SourceLocation OpLoc, tok::TokenKind Kind) {
11427 assert((Kind == tok::kw___objc_yes || Kind == tok::kw___objc_no) &&
11428 "Unknown Objective-C Boolean value!");
11429 return Owned(new (Context) ObjCBoolLiteralExpr(Kind == tok::kw___objc_yes,
Fariborz Jahanian29898f42012-04-16 21:03:30 +000011430 Context.ObjCBuiltinBoolTy, OpLoc));
Ted Kremeneke65b0862012-03-06 20:05:56 +000011431}