blob: ae3a6369e19df5f59fe4b9f0816d82525990044c [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();
Jordan Rose2684c682012-06-15 18:19:48 +0000185
186 // Warn if we're in an extern inline function referring to a decl
187 // with internal linkage. (C99 6.7.4p3)
188 // FIXME: This is not explicitly forbidden in C++, but it's not clear
189 // what the correct behavior is. We should probably still have a warning.
190 // (However, in C++ const variables have internal linkage by default, while
191 // functions still have external linkage by default, so this warning becomes
192 // very noisy.)
193 if (!getLangOpts().CPlusPlus) {
194 if (FunctionDecl *Current = getCurFunctionDecl()) {
195 if (Current->isInlined() && Current->getLinkage() > InternalLinkage) {
196 if (D->getLinkage() == InternalLinkage) {
197 Diag(Loc, diag::warn_internal_in_extern_inline)
198 << !isa<FunctionDecl>(D) << D << isa<CXXMethodDecl>(Current);
199
200 // If the user didn't explicitly specify a storage class,
201 // suggest adding "static" to fix the problem.
202 const FunctionDecl *FirstDecl = Current->getCanonicalDecl();
203 if (FirstDecl->getStorageClassAsWritten() == SC_None) {
204 SourceLocation DeclBegin = FirstDecl->getSourceRange().getBegin();
205 Diag(DeclBegin, diag::note_convert_inline_to_static)
206 << Current << FixItHint::CreateInsertion(DeclBegin, "static ");
207 }
208
209 Diag(D->getCanonicalDecl()->getLocation(),
210 diag::note_internal_decl_declared_here)
211 << D;
212 }
213 }
214 }
215 }
216
Douglas Gregor171c45a2009-02-18 21:56:37 +0000217 return false;
Chris Lattner4bf74fd2009-02-15 22:43:40 +0000218}
219
Douglas Gregor20b2ebd2011-03-23 00:50:03 +0000220/// \brief Retrieve the message suffix that should be added to a
221/// diagnostic complaining about the given function being deleted or
222/// unavailable.
223std::string Sema::getDeletedOrUnavailableSuffix(const FunctionDecl *FD) {
224 // FIXME: C++0x implicitly-deleted special member functions could be
225 // detected here so that we could improve diagnostics to say, e.g.,
226 // "base class 'A' had a deleted copy constructor".
227 if (FD->isDeleted())
228 return std::string();
229
230 std::string Message;
231 if (FD->getAvailability(&Message))
232 return ": " + Message;
233
234 return std::string();
235}
236
John McCallb46f2872011-09-09 07:56:05 +0000237/// DiagnoseSentinelCalls - This routine checks whether a call or
238/// message-send is to a declaration with the sentinel attribute, and
239/// if so, it checks that the requirements of the sentinel are
240/// satisfied.
Fariborz Jahanian027b8862009-05-13 18:09:35 +0000241void Sema::DiagnoseSentinelCalls(NamedDecl *D, SourceLocation Loc,
John McCallb46f2872011-09-09 07:56:05 +0000242 Expr **args, unsigned numArgs) {
Argyrios Kyrtzidisb4b64ca2009-06-30 02:34:44 +0000243 const SentinelAttr *attr = D->getAttr<SentinelAttr>();
Mike Stump11289f42009-09-09 15:08:12 +0000244 if (!attr)
Fariborz Jahanian9e877212009-05-13 23:20:50 +0000245 return;
Douglas Gregorc298ffc2010-04-22 16:44:27 +0000246
John McCallb46f2872011-09-09 07:56:05 +0000247 // The number of formal parameters of the declaration.
248 unsigned numFormalParams;
Mike Stump11289f42009-09-09 15:08:12 +0000249
John McCallb46f2872011-09-09 07:56:05 +0000250 // The kind of declaration. This is also an index into a %select in
251 // the diagnostic.
252 enum CalleeType { CT_Function, CT_Method, CT_Block } calleeType;
253
Fariborz Jahanian4a528032009-05-14 18:00:00 +0000254 if (ObjCMethodDecl *MD = dyn_cast<ObjCMethodDecl>(D)) {
John McCallb46f2872011-09-09 07:56:05 +0000255 numFormalParams = MD->param_size();
256 calleeType = CT_Method;
Mike Stump12b8ce12009-08-04 21:02:39 +0000257 } else if (FunctionDecl *FD = dyn_cast<FunctionDecl>(D)) {
John McCallb46f2872011-09-09 07:56:05 +0000258 numFormalParams = FD->param_size();
259 calleeType = CT_Function;
260 } else if (isa<VarDecl>(D)) {
261 QualType type = cast<ValueDecl>(D)->getType();
262 const FunctionType *fn = 0;
263 if (const PointerType *ptr = type->getAs<PointerType>()) {
264 fn = ptr->getPointeeType()->getAs<FunctionType>();
265 if (!fn) return;
266 calleeType = CT_Function;
267 } else if (const BlockPointerType *ptr = type->getAs<BlockPointerType>()) {
268 fn = ptr->getPointeeType()->castAs<FunctionType>();
269 calleeType = CT_Block;
270 } else {
Fariborz Jahanian0aa5c452009-05-15 20:33:25 +0000271 return;
John McCallb46f2872011-09-09 07:56:05 +0000272 }
Fariborz Jahanian4a528032009-05-14 18:00:00 +0000273
John McCallb46f2872011-09-09 07:56:05 +0000274 if (const FunctionProtoType *proto = dyn_cast<FunctionProtoType>(fn)) {
275 numFormalParams = proto->getNumArgs();
276 } else {
277 numFormalParams = 0;
278 }
279 } else {
Fariborz Jahanian9e877212009-05-13 23:20:50 +0000280 return;
281 }
John McCallb46f2872011-09-09 07:56:05 +0000282
283 // "nullPos" is the number of formal parameters at the end which
284 // effectively count as part of the variadic arguments. This is
285 // useful if you would prefer to not have *any* formal parameters,
286 // but the language forces you to have at least one.
287 unsigned nullPos = attr->getNullPos();
288 assert((nullPos == 0 || nullPos == 1) && "invalid null position on sentinel");
289 numFormalParams = (nullPos > numFormalParams ? 0 : numFormalParams - nullPos);
290
291 // The number of arguments which should follow the sentinel.
292 unsigned numArgsAfterSentinel = attr->getSentinel();
293
294 // If there aren't enough arguments for all the formal parameters,
295 // the sentinel, and the args after the sentinel, complain.
296 if (numArgs < numFormalParams + numArgsAfterSentinel + 1) {
Fariborz Jahanian9e877212009-05-13 23:20:50 +0000297 Diag(Loc, diag::warn_not_enough_argument) << D->getDeclName();
John McCallb46f2872011-09-09 07:56:05 +0000298 Diag(D->getLocation(), diag::note_sentinel_here) << calleeType;
Fariborz Jahanian9e877212009-05-13 23:20:50 +0000299 return;
300 }
John McCallb46f2872011-09-09 07:56:05 +0000301
302 // Otherwise, find the sentinel expression.
303 Expr *sentinelExpr = args[numArgs - numArgsAfterSentinel - 1];
John McCall7ddbcf42010-05-06 23:53:00 +0000304 if (!sentinelExpr) return;
John McCall7ddbcf42010-05-06 23:53:00 +0000305 if (sentinelExpr->isValueDependent()) return;
Argyrios Kyrtzidis2e809ce2012-02-03 05:58:16 +0000306 if (Context.isSentinelNullExpr(sentinelExpr)) return;
John McCall7ddbcf42010-05-06 23:53:00 +0000307
John McCallb46f2872011-09-09 07:56:05 +0000308 // Pick a reasonable string to insert. Optimistically use 'nil' or
309 // 'NULL' if those are actually defined in the context. Only use
310 // 'nil' for ObjC methods, where it's much more likely that the
311 // variadic arguments form a list of object pointers.
312 SourceLocation MissingNilLoc
Douglas Gregor5ff4e982011-07-30 08:57:03 +0000313 = PP.getLocForEndOfToken(sentinelExpr->getLocEnd());
314 std::string NullValue;
John McCallb46f2872011-09-09 07:56:05 +0000315 if (calleeType == CT_Method &&
316 PP.getIdentifierInfo("nil")->hasMacroDefinition())
Douglas Gregor5ff4e982011-07-30 08:57:03 +0000317 NullValue = "nil";
318 else if (PP.getIdentifierInfo("NULL")->hasMacroDefinition())
319 NullValue = "NULL";
Douglas Gregor5ff4e982011-07-30 08:57:03 +0000320 else
John McCallb46f2872011-09-09 07:56:05 +0000321 NullValue = "(void*) 0";
Eli Friedman9ab36372011-09-27 23:46:37 +0000322
323 if (MissingNilLoc.isInvalid())
324 Diag(Loc, diag::warn_missing_sentinel) << calleeType;
325 else
326 Diag(MissingNilLoc, diag::warn_missing_sentinel)
327 << calleeType
328 << FixItHint::CreateInsertion(MissingNilLoc, ", " + NullValue);
John McCallb46f2872011-09-09 07:56:05 +0000329 Diag(D->getLocation(), diag::note_sentinel_here) << calleeType;
Fariborz Jahanian027b8862009-05-13 18:09:35 +0000330}
331
Richard Trieuba63ce62011-09-09 01:45:06 +0000332SourceRange Sema::getExprRange(Expr *E) const {
333 return E ? E->getSourceRange() : SourceRange();
Douglas Gregor87f95b02009-02-26 21:00:50 +0000334}
335
Chris Lattner513165e2008-07-25 21:10:04 +0000336//===----------------------------------------------------------------------===//
337// Standard Promotions and Conversions
338//===----------------------------------------------------------------------===//
339
Chris Lattner513165e2008-07-25 21:10:04 +0000340/// DefaultFunctionArrayConversion (C99 6.3.2.1p3, C99 6.3.2.1p4).
John Wiegley01296292011-04-08 18:41:53 +0000341ExprResult Sema::DefaultFunctionArrayConversion(Expr *E) {
John McCall50a2c2c2011-10-11 23:14:30 +0000342 // Handle any placeholder expressions which made it here.
343 if (E->getType()->isPlaceholderType()) {
344 ExprResult result = CheckPlaceholderExpr(E);
345 if (result.isInvalid()) return ExprError();
346 E = result.take();
347 }
348
Chris Lattner513165e2008-07-25 21:10:04 +0000349 QualType Ty = E->getType();
350 assert(!Ty.isNull() && "DefaultFunctionArrayConversion - missing type");
351
Chris Lattner513165e2008-07-25 21:10:04 +0000352 if (Ty->isFunctionType())
John Wiegley01296292011-04-08 18:41:53 +0000353 E = ImpCastExprToType(E, Context.getPointerType(Ty),
354 CK_FunctionToPointerDecay).take();
Chris Lattner61f60a02008-07-25 21:33:13 +0000355 else if (Ty->isArrayType()) {
356 // In C90 mode, arrays only promote to pointers if the array expression is
357 // an lvalue. The relevant legalese is C90 6.2.2.1p3: "an lvalue that has
358 // type 'array of type' is converted to an expression that has type 'pointer
359 // to type'...". In C99 this was changed to: C99 6.3.2.1p3: "an expression
360 // that has type 'array of type' ...". The relevant change is "an lvalue"
361 // (C90) to "an expression" (C99).
Argyrios Kyrtzidis9321c742008-09-11 04:25:59 +0000362 //
363 // C++ 4.2p1:
364 // An lvalue or rvalue of type "array of N T" or "array of unknown bound of
365 // T" can be converted to an rvalue of type "pointer to T".
366 //
David Blaikiebbafb8a2012-03-11 07:00:24 +0000367 if (getLangOpts().C99 || getLangOpts().CPlusPlus || E->isLValue())
John Wiegley01296292011-04-08 18:41:53 +0000368 E = ImpCastExprToType(E, Context.getArrayDecayedType(Ty),
369 CK_ArrayToPointerDecay).take();
Chris Lattner61f60a02008-07-25 21:33:13 +0000370 }
John Wiegley01296292011-04-08 18:41:53 +0000371 return Owned(E);
Chris Lattner513165e2008-07-25 21:10:04 +0000372}
373
Argyrios Kyrtzidisa9b630e2011-04-26 17:41:22 +0000374static void CheckForNullPointerDereference(Sema &S, Expr *E) {
375 // Check to see if we are dereferencing a null pointer. If so,
376 // and if not volatile-qualified, this is undefined behavior that the
377 // optimizer will delete, so warn about it. People sometimes try to use this
378 // to get a deterministic trap and are surprised by clang's behavior. This
379 // only handles the pattern "*null", which is a very syntactic check.
380 if (UnaryOperator *UO = dyn_cast<UnaryOperator>(E->IgnoreParenCasts()))
381 if (UO->getOpcode() == UO_Deref &&
382 UO->getSubExpr()->IgnoreParenCasts()->
383 isNullPointerConstant(S.Context, Expr::NPC_ValueDependentIsNotNull) &&
384 !UO->getType().isVolatileQualified()) {
385 S.DiagRuntimeBehavior(UO->getOperatorLoc(), UO,
386 S.PDiag(diag::warn_indirection_through_null)
387 << UO->getSubExpr()->getSourceRange());
388 S.DiagRuntimeBehavior(UO->getOperatorLoc(), UO,
389 S.PDiag(diag::note_indirection_through_null));
390 }
391}
392
John Wiegley01296292011-04-08 18:41:53 +0000393ExprResult Sema::DefaultLvalueConversion(Expr *E) {
John McCall50a2c2c2011-10-11 23:14:30 +0000394 // Handle any placeholder expressions which made it here.
395 if (E->getType()->isPlaceholderType()) {
396 ExprResult result = CheckPlaceholderExpr(E);
397 if (result.isInvalid()) return ExprError();
398 E = result.take();
399 }
400
John McCallf3735e02010-12-01 04:43:34 +0000401 // C++ [conv.lval]p1:
402 // A glvalue of a non-function, non-array type T can be
403 // converted to a prvalue.
John Wiegley01296292011-04-08 18:41:53 +0000404 if (!E->isGLValue()) return Owned(E);
Kaelyn Uhrain2e7aa5a2011-08-05 23:18:04 +0000405
John McCall27584242010-12-06 20:48:59 +0000406 QualType T = E->getType();
407 assert(!T.isNull() && "r-value conversion on typeless expression?");
John McCall34376a62010-12-04 03:47:34 +0000408
John McCall27584242010-12-06 20:48:59 +0000409 // We don't want to throw lvalue-to-rvalue casts on top of
410 // expressions of certain types in C++.
David Blaikiebbafb8a2012-03-11 07:00:24 +0000411 if (getLangOpts().CPlusPlus &&
John McCall27584242010-12-06 20:48:59 +0000412 (E->getType() == Context.OverloadTy ||
413 T->isDependentType() ||
414 T->isRecordType()))
John Wiegley01296292011-04-08 18:41:53 +0000415 return Owned(E);
John McCall27584242010-12-06 20:48:59 +0000416
417 // The C standard is actually really unclear on this point, and
418 // DR106 tells us what the result should be but not why. It's
419 // generally best to say that void types just doesn't undergo
420 // lvalue-to-rvalue at all. Note that expressions of unqualified
421 // 'void' type are never l-values, but qualified void can be.
422 if (T->isVoidType())
John Wiegley01296292011-04-08 18:41:53 +0000423 return Owned(E);
John McCall27584242010-12-06 20:48:59 +0000424
Argyrios Kyrtzidisa9b630e2011-04-26 17:41:22 +0000425 CheckForNullPointerDereference(*this, E);
426
John McCall27584242010-12-06 20:48:59 +0000427 // C++ [conv.lval]p1:
428 // [...] If T is a non-class type, the type of the prvalue is the
429 // cv-unqualified version of T. Otherwise, the type of the
430 // rvalue is T.
431 //
432 // C99 6.3.2.1p2:
433 // If the lvalue has qualified type, the value has the unqualified
434 // version of the type of the lvalue; otherwise, the value has the
Anton Korobeynikovf0c267e2011-10-14 23:23:15 +0000435 // type of the lvalue.
John McCall27584242010-12-06 20:48:59 +0000436 if (T.hasQualifiers())
437 T = T.getUnqualifiedType();
Anton Korobeynikovf0c267e2011-10-14 23:23:15 +0000438
Eli Friedman3bda6b12012-02-02 23:15:15 +0000439 UpdateMarkingForLValueToRValue(E);
440
Anton Korobeynikovf0c267e2011-10-14 23:23:15 +0000441 ExprResult Res = Owned(ImplicitCastExpr::Create(Context, T, CK_LValueToRValue,
442 E, 0, VK_RValue));
443
Douglas Gregorc79862f2012-04-12 17:51:55 +0000444 // C11 6.3.2.1p2:
445 // ... if the lvalue has atomic type, the value has the non-atomic version
446 // of the type of the lvalue ...
447 if (const AtomicType *Atomic = T->getAs<AtomicType>()) {
448 T = Atomic->getValueType().getUnqualifiedType();
449 Res = Owned(ImplicitCastExpr::Create(Context, T, CK_AtomicToNonAtomic,
450 Res.get(), 0, VK_RValue));
451 }
452
Anton Korobeynikovf0c267e2011-10-14 23:23:15 +0000453 return Res;
John McCall27584242010-12-06 20:48:59 +0000454}
455
John Wiegley01296292011-04-08 18:41:53 +0000456ExprResult Sema::DefaultFunctionArrayLvalueConversion(Expr *E) {
457 ExprResult Res = DefaultFunctionArrayConversion(E);
458 if (Res.isInvalid())
459 return ExprError();
460 Res = DefaultLvalueConversion(Res.take());
461 if (Res.isInvalid())
462 return ExprError();
463 return move(Res);
Douglas Gregorb92a1562010-02-03 00:27:59 +0000464}
465
466
Chris Lattner513165e2008-07-25 21:10:04 +0000467/// UsualUnaryConversions - Performs various conversions that are common to most
Mike Stump11289f42009-09-09 15:08:12 +0000468/// operators (C99 6.3). The conversions of array and function types are
Chris Lattner57540c52011-04-15 05:22:18 +0000469/// sometimes suppressed. For example, the array->pointer conversion doesn't
Chris Lattner513165e2008-07-25 21:10:04 +0000470/// apply if the array is an argument to the sizeof or address (&) operators.
471/// In these instances, this routine should *not* be called.
John Wiegley01296292011-04-08 18:41:53 +0000472ExprResult Sema::UsualUnaryConversions(Expr *E) {
John McCallf3735e02010-12-01 04:43:34 +0000473 // First, convert to an r-value.
John Wiegley01296292011-04-08 18:41:53 +0000474 ExprResult Res = DefaultFunctionArrayLvalueConversion(E);
475 if (Res.isInvalid())
476 return Owned(E);
477 E = Res.take();
Anton Korobeynikovf0c267e2011-10-14 23:23:15 +0000478
John McCallf3735e02010-12-01 04:43:34 +0000479 QualType Ty = E->getType();
Chris Lattner513165e2008-07-25 21:10:04 +0000480 assert(!Ty.isNull() && "UsualUnaryConversions - missing type");
Anton Korobeynikovf0c267e2011-10-14 23:23:15 +0000481
482 // Half FP is a bit different: it's a storage-only type, meaning that any
483 // "use" of it should be promoted to float.
484 if (Ty->isHalfType())
485 return ImpCastExprToType(Res.take(), Context.FloatTy, CK_FloatingCast);
486
John McCallf3735e02010-12-01 04:43:34 +0000487 // Try to perform integral promotions if the object has a theoretically
488 // promotable type.
489 if (Ty->isIntegralOrUnscopedEnumerationType()) {
490 // C99 6.3.1.1p2:
491 //
492 // The following may be used in an expression wherever an int or
493 // unsigned int may be used:
494 // - an object or expression with an integer type whose integer
495 // conversion rank is less than or equal to the rank of int
496 // and unsigned int.
497 // - A bit-field of type _Bool, int, signed int, or unsigned int.
498 //
499 // If an int can represent all values of the original type, the
500 // value is converted to an int; otherwise, it is converted to an
501 // unsigned int. These are called the integer promotions. All
502 // other types are unchanged by the integer promotions.
Anton Korobeynikovf0c267e2011-10-14 23:23:15 +0000503
John McCallf3735e02010-12-01 04:43:34 +0000504 QualType PTy = Context.isPromotableBitField(E);
505 if (!PTy.isNull()) {
John Wiegley01296292011-04-08 18:41:53 +0000506 E = ImpCastExprToType(E, PTy, CK_IntegralCast).take();
507 return Owned(E);
John McCallf3735e02010-12-01 04:43:34 +0000508 }
509 if (Ty->isPromotableIntegerType()) {
510 QualType PT = Context.getPromotedIntegerType(Ty);
John Wiegley01296292011-04-08 18:41:53 +0000511 E = ImpCastExprToType(E, PT, CK_IntegralCast).take();
512 return Owned(E);
John McCallf3735e02010-12-01 04:43:34 +0000513 }
Eli Friedman629ffb92009-08-20 04:21:42 +0000514 }
John Wiegley01296292011-04-08 18:41:53 +0000515 return Owned(E);
Chris Lattner513165e2008-07-25 21:10:04 +0000516}
517
Chris Lattner2ce500f2008-07-25 22:25:12 +0000518/// DefaultArgumentPromotion (C99 6.5.2.2p6). Used for function calls that
Mike Stump11289f42009-09-09 15:08:12 +0000519/// do not have a prototype. Arguments that have type float are promoted to
Chris Lattner2ce500f2008-07-25 22:25:12 +0000520/// double. All other argument types are converted by UsualUnaryConversions().
John Wiegley01296292011-04-08 18:41:53 +0000521ExprResult Sema::DefaultArgumentPromotion(Expr *E) {
522 QualType Ty = E->getType();
Chris Lattner2ce500f2008-07-25 22:25:12 +0000523 assert(!Ty.isNull() && "DefaultArgumentPromotion - missing type");
Mike Stump11289f42009-09-09 15:08:12 +0000524
John Wiegley01296292011-04-08 18:41:53 +0000525 ExprResult Res = UsualUnaryConversions(E);
526 if (Res.isInvalid())
527 return Owned(E);
528 E = Res.take();
John McCall9bc26772010-12-06 18:36:11 +0000529
Chris Lattner2ce500f2008-07-25 22:25:12 +0000530 // If this is a 'float' (CVR qualified or typedef) promote to double.
Chris Lattnerbb53efb2010-05-16 04:01:30 +0000531 if (Ty->isSpecificBuiltinType(BuiltinType::Float))
John Wiegley01296292011-04-08 18:41:53 +0000532 E = ImpCastExprToType(E, Context.DoubleTy, CK_FloatingCast).take();
533
John McCall4bb057d2011-08-27 22:06:17 +0000534 // C++ performs lvalue-to-rvalue conversion as a default argument
John McCall0562caa2011-08-29 23:55:37 +0000535 // promotion, even on class types, but note:
536 // C++11 [conv.lval]p2:
537 // When an lvalue-to-rvalue conversion occurs in an unevaluated
538 // operand or a subexpression thereof the value contained in the
539 // referenced object is not accessed. Otherwise, if the glvalue
540 // has a class type, the conversion copy-initializes a temporary
541 // of type T from the glvalue and the result of the conversion
542 // is a prvalue for the temporary.
Eli Friedman05e28012012-01-17 02:13:45 +0000543 // FIXME: add some way to gate this entire thing for correctness in
544 // potentially potentially evaluated contexts.
David Blaikiebbafb8a2012-03-11 07:00:24 +0000545 if (getLangOpts().CPlusPlus && E->isGLValue() &&
Eli Friedman05e28012012-01-17 02:13:45 +0000546 ExprEvalContexts.back().Context != Unevaluated) {
547 ExprResult Temp = PerformCopyInitialization(
548 InitializedEntity::InitializeTemporary(E->getType()),
549 E->getExprLoc(),
550 Owned(E));
551 if (Temp.isInvalid())
552 return ExprError();
553 E = Temp.get();
John McCall29ad95b2011-08-27 01:09:30 +0000554 }
555
John Wiegley01296292011-04-08 18:41:53 +0000556 return Owned(E);
Chris Lattner2ce500f2008-07-25 22:25:12 +0000557}
558
Chris Lattnera8a7d0f2009-04-12 08:11:20 +0000559/// DefaultVariadicArgumentPromotion - Like DefaultArgumentPromotion, but
560/// will warn if the resulting type is not a POD type, and rejects ObjC
John Wiegley01296292011-04-08 18:41:53 +0000561/// interfaces passed by value.
562ExprResult Sema::DefaultVariadicArgumentPromotion(Expr *E, VariadicCallType CT,
John McCall31168b02011-06-15 23:02:42 +0000563 FunctionDecl *FDecl) {
John McCall4124c492011-10-17 18:40:02 +0000564 if (const BuiltinType *PlaceholderTy = E->getType()->getAsPlaceholderType()) {
565 // Strip the unbridged-cast placeholder expression off, if applicable.
566 if (PlaceholderTy->getKind() == BuiltinType::ARCUnbridgedCast &&
567 (CT == VariadicMethod ||
568 (FDecl && FDecl->hasAttr<CFAuditedTransferAttr>()))) {
569 E = stripARCUnbridgedCast(E);
570
571 // Otherwise, do normal placeholder checking.
572 } else {
573 ExprResult ExprRes = CheckPlaceholderExpr(E);
574 if (ExprRes.isInvalid())
575 return ExprError();
576 E = ExprRes.take();
577 }
578 }
Douglas Gregorcbd446d2011-06-17 00:15:10 +0000579
John McCall4124c492011-10-17 18:40:02 +0000580 ExprResult ExprRes = DefaultArgumentPromotion(E);
John Wiegley01296292011-04-08 18:41:53 +0000581 if (ExprRes.isInvalid())
582 return ExprError();
583 E = ExprRes.take();
Mike Stump11289f42009-09-09 15:08:12 +0000584
Douglas Gregor347e0f22011-05-21 19:26:31 +0000585 // Don't allow one to pass an Objective-C interface to a vararg.
John Wiegley01296292011-04-08 18:41:53 +0000586 if (E->getType()->isObjCObjectType() &&
Douglas Gregor347e0f22011-05-21 19:26:31 +0000587 DiagRuntimeBehavior(E->getLocStart(), 0,
588 PDiag(diag::err_cannot_pass_objc_interface_to_vararg)
589 << E->getType() << CT))
John Wiegley01296292011-04-08 18:41:53 +0000590 return ExprError();
John McCall29ad95b2011-08-27 01:09:30 +0000591
Douglas Gregor7e1aa5b2011-10-14 20:34:19 +0000592 // Complain about passing non-POD types through varargs. However, don't
593 // perform this check for incomplete types, which we can get here when we're
594 // in an unevaluated context.
Benjamin Kramer6a0a2112012-04-28 10:00:42 +0000595 if (!E->getType()->isIncompleteType() &&
596 !E->getType().isCXX98PODType(Context)) {
Douglas Gregor253cadf2011-05-21 16:27:21 +0000597 // C++0x [expr.call]p7:
598 // Passing a potentially-evaluated argument of class type (Clause 9)
599 // having a non-trivial copy constructor, a non-trivial move constructor,
600 // or a non-trivial destructor, with no corresponding parameter,
601 // is conditionally-supported with implementation-defined semantics.
602 bool TrivialEnough = false;
David Blaikiebbafb8a2012-03-11 07:00:24 +0000603 if (getLangOpts().CPlusPlus0x && !E->getType()->isDependentType()) {
Douglas Gregor253cadf2011-05-21 16:27:21 +0000604 if (CXXRecordDecl *Record = E->getType()->getAsCXXRecordDecl()) {
605 if (Record->hasTrivialCopyConstructor() &&
606 Record->hasTrivialMoveConstructor() &&
Richard Smith0bf8a4922011-10-18 20:49:44 +0000607 Record->hasTrivialDestructor()) {
608 DiagRuntimeBehavior(E->getLocStart(), 0,
609 PDiag(diag::warn_cxx98_compat_pass_non_pod_arg_to_vararg)
610 << E->getType() << CT);
Douglas Gregor253cadf2011-05-21 16:27:21 +0000611 TrivialEnough = true;
Richard Smith0bf8a4922011-10-18 20:49:44 +0000612 }
Douglas Gregor253cadf2011-05-21 16:27:21 +0000613 }
614 }
John McCall31168b02011-06-15 23:02:42 +0000615
616 if (!TrivialEnough &&
David Blaikiebbafb8a2012-03-11 07:00:24 +0000617 getLangOpts().ObjCAutoRefCount &&
John McCall31168b02011-06-15 23:02:42 +0000618 E->getType()->isObjCLifetimeType())
619 TrivialEnough = true;
Douglas Gregor253cadf2011-05-21 16:27:21 +0000620
621 if (TrivialEnough) {
622 // Nothing to diagnose. This is okay.
623 } else if (DiagRuntimeBehavior(E->getLocStart(), 0,
Douglas Gregorda8cdbc2009-12-22 01:01:55 +0000624 PDiag(diag::warn_cannot_pass_non_pod_arg_to_vararg)
David Blaikiebbafb8a2012-03-11 07:00:24 +0000625 << getLangOpts().CPlusPlus0x << E->getType()
Douglas Gregor347e0f22011-05-21 19:26:31 +0000626 << CT)) {
627 // Turn this into a trap.
628 CXXScopeSpec SS;
Abramo Bagnara7945c982012-01-27 09:46:47 +0000629 SourceLocation TemplateKWLoc;
Douglas Gregor347e0f22011-05-21 19:26:31 +0000630 UnqualifiedId Name;
631 Name.setIdentifier(PP.getIdentifierInfo("__builtin_trap"),
632 E->getLocStart());
Abramo Bagnara7945c982012-01-27 09:46:47 +0000633 ExprResult TrapFn = ActOnIdExpression(TUScope, SS, TemplateKWLoc, Name,
634 true, false);
Douglas Gregor347e0f22011-05-21 19:26:31 +0000635 if (TrapFn.isInvalid())
636 return ExprError();
637
638 ExprResult Call = ActOnCallExpr(TUScope, TrapFn.get(), E->getLocStart(),
639 MultiExprArg(), E->getLocEnd());
640 if (Call.isInvalid())
641 return ExprError();
642
643 ExprResult Comma = ActOnBinOp(TUScope, E->getLocStart(), tok::comma,
644 Call.get(), E);
645 if (Comma.isInvalid())
John McCall1cd60a22011-08-26 18:41:18 +0000646 return ExprError();
Douglas Gregor347e0f22011-05-21 19:26:31 +0000647 E = Comma.get();
648 }
Douglas Gregor253cadf2011-05-21 16:27:21 +0000649 }
Fariborz Jahanianbf482812012-03-02 17:05:03 +0000650 // c++ rules are enforced elsewhere.
David Blaikiebbafb8a2012-03-11 07:00:24 +0000651 if (!getLangOpts().CPlusPlus &&
Fariborz Jahanian3854a552012-03-01 23:42:00 +0000652 RequireCompleteType(E->getExprLoc(), E->getType(),
Fariborz Jahanianbf482812012-03-02 17:05:03 +0000653 diag::err_call_incomplete_argument))
Fariborz Jahanian3854a552012-03-01 23:42:00 +0000654 return ExprError();
Douglas Gregor253cadf2011-05-21 16:27:21 +0000655
John Wiegley01296292011-04-08 18:41:53 +0000656 return Owned(E);
Anders Carlssona7d069d2009-01-16 16:48:51 +0000657}
658
Richard Trieu7aa58f12011-09-02 20:58:51 +0000659/// \brief Converts an integer to complex float type. Helper function of
660/// UsualArithmeticConversions()
661///
662/// \return false if the integer expression is an integer type and is
663/// successfully converted to the complex type.
Richard Trieuba63ce62011-09-09 01:45:06 +0000664static bool handleIntegerToComplexFloatConversion(Sema &S, ExprResult &IntExpr,
665 ExprResult &ComplexExpr,
666 QualType IntTy,
667 QualType ComplexTy,
668 bool SkipCast) {
669 if (IntTy->isComplexType() || IntTy->isRealFloatingType()) return true;
670 if (SkipCast) return false;
671 if (IntTy->isIntegerType()) {
672 QualType fpTy = cast<ComplexType>(ComplexTy)->getElementType();
673 IntExpr = S.ImpCastExprToType(IntExpr.take(), fpTy, CK_IntegralToFloating);
674 IntExpr = S.ImpCastExprToType(IntExpr.take(), ComplexTy,
Richard Trieu7aa58f12011-09-02 20:58:51 +0000675 CK_FloatingRealToComplex);
676 } else {
Richard Trieuba63ce62011-09-09 01:45:06 +0000677 assert(IntTy->isComplexIntegerType());
678 IntExpr = S.ImpCastExprToType(IntExpr.take(), ComplexTy,
Richard Trieu7aa58f12011-09-02 20:58:51 +0000679 CK_IntegralComplexToFloatingComplex);
680 }
681 return false;
682}
683
684/// \brief Takes two complex float types and converts them to the same type.
685/// Helper function of UsualArithmeticConversions()
686static QualType
Richard Trieu5065cdd2011-09-06 18:25:09 +0000687handleComplexFloatToComplexFloatConverstion(Sema &S, ExprResult &LHS,
688 ExprResult &RHS, QualType LHSType,
689 QualType RHSType,
Richard Trieuba63ce62011-09-09 01:45:06 +0000690 bool IsCompAssign) {
Richard Trieu5065cdd2011-09-06 18:25:09 +0000691 int order = S.Context.getFloatingTypeOrder(LHSType, RHSType);
Richard Trieu7aa58f12011-09-02 20:58:51 +0000692
693 if (order < 0) {
694 // _Complex float -> _Complex double
Richard Trieuba63ce62011-09-09 01:45:06 +0000695 if (!IsCompAssign)
Richard Trieu5065cdd2011-09-06 18:25:09 +0000696 LHS = S.ImpCastExprToType(LHS.take(), RHSType, CK_FloatingComplexCast);
697 return RHSType;
Richard Trieu7aa58f12011-09-02 20:58:51 +0000698 }
699 if (order > 0)
700 // _Complex float -> _Complex double
Richard Trieu5065cdd2011-09-06 18:25:09 +0000701 RHS = S.ImpCastExprToType(RHS.take(), LHSType, CK_FloatingComplexCast);
702 return LHSType;
Richard Trieu7aa58f12011-09-02 20:58:51 +0000703}
704
705/// \brief Converts otherExpr to complex float and promotes complexExpr if
706/// necessary. Helper function of UsualArithmeticConversions()
707static QualType handleOtherComplexFloatConversion(Sema &S,
Richard Trieuba63ce62011-09-09 01:45:06 +0000708 ExprResult &ComplexExpr,
709 ExprResult &OtherExpr,
710 QualType ComplexTy,
711 QualType OtherTy,
712 bool ConvertComplexExpr,
713 bool ConvertOtherExpr) {
714 int order = S.Context.getFloatingTypeOrder(ComplexTy, OtherTy);
Richard Trieu7aa58f12011-09-02 20:58:51 +0000715
716 // If just the complexExpr is complex, the otherExpr needs to be converted,
717 // and the complexExpr might need to be promoted.
718 if (order > 0) { // complexExpr is wider
719 // float -> _Complex double
Richard Trieuba63ce62011-09-09 01:45:06 +0000720 if (ConvertOtherExpr) {
721 QualType fp = cast<ComplexType>(ComplexTy)->getElementType();
722 OtherExpr = S.ImpCastExprToType(OtherExpr.take(), fp, CK_FloatingCast);
723 OtherExpr = S.ImpCastExprToType(OtherExpr.take(), ComplexTy,
Richard Trieu7aa58f12011-09-02 20:58:51 +0000724 CK_FloatingRealToComplex);
725 }
Richard Trieuba63ce62011-09-09 01:45:06 +0000726 return ComplexTy;
Richard Trieu7aa58f12011-09-02 20:58:51 +0000727 }
728
729 // otherTy is at least as wide. Find its corresponding complex type.
Richard Trieuba63ce62011-09-09 01:45:06 +0000730 QualType result = (order == 0 ? ComplexTy :
731 S.Context.getComplexType(OtherTy));
Richard Trieu7aa58f12011-09-02 20:58:51 +0000732
733 // double -> _Complex double
Richard Trieuba63ce62011-09-09 01:45:06 +0000734 if (ConvertOtherExpr)
735 OtherExpr = S.ImpCastExprToType(OtherExpr.take(), result,
Richard Trieu7aa58f12011-09-02 20:58:51 +0000736 CK_FloatingRealToComplex);
737
738 // _Complex float -> _Complex double
Richard Trieuba63ce62011-09-09 01:45:06 +0000739 if (ConvertComplexExpr && order < 0)
740 ComplexExpr = S.ImpCastExprToType(ComplexExpr.take(), result,
Richard Trieu7aa58f12011-09-02 20:58:51 +0000741 CK_FloatingComplexCast);
742
743 return result;
744}
745
746/// \brief Handle arithmetic conversion with complex types. Helper function of
747/// UsualArithmeticConversions()
Richard Trieu5065cdd2011-09-06 18:25:09 +0000748static QualType handleComplexFloatConversion(Sema &S, ExprResult &LHS,
749 ExprResult &RHS, QualType LHSType,
750 QualType RHSType,
Richard Trieuba63ce62011-09-09 01:45:06 +0000751 bool IsCompAssign) {
Richard Trieu7aa58f12011-09-02 20:58:51 +0000752 // if we have an integer operand, the result is the complex type.
Richard Trieu5065cdd2011-09-06 18:25:09 +0000753 if (!handleIntegerToComplexFloatConversion(S, RHS, LHS, RHSType, LHSType,
Richard Trieu7aa58f12011-09-02 20:58:51 +0000754 /*skipCast*/false))
Richard Trieu5065cdd2011-09-06 18:25:09 +0000755 return LHSType;
756 if (!handleIntegerToComplexFloatConversion(S, LHS, RHS, LHSType, RHSType,
Richard Trieuba63ce62011-09-09 01:45:06 +0000757 /*skipCast*/IsCompAssign))
Richard Trieu5065cdd2011-09-06 18:25:09 +0000758 return RHSType;
Richard Trieu7aa58f12011-09-02 20:58:51 +0000759
760 // This handles complex/complex, complex/float, or float/complex.
761 // When both operands are complex, the shorter operand is converted to the
762 // type of the longer, and that is the type of the result. This corresponds
763 // to what is done when combining two real floating-point operands.
764 // The fun begins when size promotion occur across type domains.
765 // From H&S 6.3.4: When one operand is complex and the other is a real
766 // floating-point type, the less precise type is converted, within it's
767 // real or complex domain, to the precision of the other type. For example,
768 // when combining a "long double" with a "double _Complex", the
769 // "double _Complex" is promoted to "long double _Complex".
770
Richard Trieu5065cdd2011-09-06 18:25:09 +0000771 bool LHSComplexFloat = LHSType->isComplexType();
772 bool RHSComplexFloat = RHSType->isComplexType();
Richard Trieu7aa58f12011-09-02 20:58:51 +0000773
774 // If both are complex, just cast to the more precise type.
775 if (LHSComplexFloat && RHSComplexFloat)
Richard Trieu5065cdd2011-09-06 18:25:09 +0000776 return handleComplexFloatToComplexFloatConverstion(S, LHS, RHS,
777 LHSType, RHSType,
Richard Trieuba63ce62011-09-09 01:45:06 +0000778 IsCompAssign);
Richard Trieu7aa58f12011-09-02 20:58:51 +0000779
780 // If only one operand is complex, promote it if necessary and convert the
781 // other operand to complex.
782 if (LHSComplexFloat)
783 return handleOtherComplexFloatConversion(
Richard Trieuba63ce62011-09-09 01:45:06 +0000784 S, LHS, RHS, LHSType, RHSType, /*convertComplexExpr*/!IsCompAssign,
Richard Trieu7aa58f12011-09-02 20:58:51 +0000785 /*convertOtherExpr*/ true);
786
787 assert(RHSComplexFloat);
788 return handleOtherComplexFloatConversion(
Richard Trieu5065cdd2011-09-06 18:25:09 +0000789 S, RHS, LHS, RHSType, LHSType, /*convertComplexExpr*/true,
Richard Trieuba63ce62011-09-09 01:45:06 +0000790 /*convertOtherExpr*/ !IsCompAssign);
Richard Trieu7aa58f12011-09-02 20:58:51 +0000791}
792
793/// \brief Hande arithmetic conversion from integer to float. Helper function
794/// of UsualArithmeticConversions()
Richard Trieuba63ce62011-09-09 01:45:06 +0000795static QualType handleIntToFloatConversion(Sema &S, ExprResult &FloatExpr,
796 ExprResult &IntExpr,
797 QualType FloatTy, QualType IntTy,
798 bool ConvertFloat, bool ConvertInt) {
799 if (IntTy->isIntegerType()) {
800 if (ConvertInt)
Richard Trieu7aa58f12011-09-02 20:58:51 +0000801 // Convert intExpr to the lhs floating point type.
Richard Trieuba63ce62011-09-09 01:45:06 +0000802 IntExpr = S.ImpCastExprToType(IntExpr.take(), FloatTy,
Richard Trieu7aa58f12011-09-02 20:58:51 +0000803 CK_IntegralToFloating);
Richard Trieuba63ce62011-09-09 01:45:06 +0000804 return FloatTy;
Richard Trieu7aa58f12011-09-02 20:58:51 +0000805 }
806
807 // Convert both sides to the appropriate complex float.
Richard Trieuba63ce62011-09-09 01:45:06 +0000808 assert(IntTy->isComplexIntegerType());
809 QualType result = S.Context.getComplexType(FloatTy);
Richard Trieu7aa58f12011-09-02 20:58:51 +0000810
811 // _Complex int -> _Complex float
Richard Trieuba63ce62011-09-09 01:45:06 +0000812 if (ConvertInt)
813 IntExpr = S.ImpCastExprToType(IntExpr.take(), result,
Richard Trieu7aa58f12011-09-02 20:58:51 +0000814 CK_IntegralComplexToFloatingComplex);
815
816 // float -> _Complex float
Richard Trieuba63ce62011-09-09 01:45:06 +0000817 if (ConvertFloat)
818 FloatExpr = S.ImpCastExprToType(FloatExpr.take(), result,
Richard Trieu7aa58f12011-09-02 20:58:51 +0000819 CK_FloatingRealToComplex);
820
821 return result;
822}
823
824/// \brief Handle arithmethic conversion with floating point types. Helper
825/// function of UsualArithmeticConversions()
Richard Trieucfe3f212011-09-06 18:38:41 +0000826static QualType handleFloatConversion(Sema &S, ExprResult &LHS,
827 ExprResult &RHS, QualType LHSType,
Richard Trieuba63ce62011-09-09 01:45:06 +0000828 QualType RHSType, bool IsCompAssign) {
Richard Trieucfe3f212011-09-06 18:38:41 +0000829 bool LHSFloat = LHSType->isRealFloatingType();
830 bool RHSFloat = RHSType->isRealFloatingType();
Richard Trieu7aa58f12011-09-02 20:58:51 +0000831
832 // If we have two real floating types, convert the smaller operand
833 // to the bigger result.
834 if (LHSFloat && RHSFloat) {
Richard Trieucfe3f212011-09-06 18:38:41 +0000835 int order = S.Context.getFloatingTypeOrder(LHSType, RHSType);
Richard Trieu7aa58f12011-09-02 20:58:51 +0000836 if (order > 0) {
Richard Trieucfe3f212011-09-06 18:38:41 +0000837 RHS = S.ImpCastExprToType(RHS.take(), LHSType, CK_FloatingCast);
838 return LHSType;
Richard Trieu7aa58f12011-09-02 20:58:51 +0000839 }
840
841 assert(order < 0 && "illegal float comparison");
Richard Trieuba63ce62011-09-09 01:45:06 +0000842 if (!IsCompAssign)
Richard Trieucfe3f212011-09-06 18:38:41 +0000843 LHS = S.ImpCastExprToType(LHS.take(), RHSType, CK_FloatingCast);
844 return RHSType;
Richard Trieu7aa58f12011-09-02 20:58:51 +0000845 }
846
847 if (LHSFloat)
Richard Trieucfe3f212011-09-06 18:38:41 +0000848 return handleIntToFloatConversion(S, LHS, RHS, LHSType, RHSType,
Richard Trieuba63ce62011-09-09 01:45:06 +0000849 /*convertFloat=*/!IsCompAssign,
Richard Trieu7aa58f12011-09-02 20:58:51 +0000850 /*convertInt=*/ true);
851 assert(RHSFloat);
Richard Trieucfe3f212011-09-06 18:38:41 +0000852 return handleIntToFloatConversion(S, RHS, LHS, RHSType, LHSType,
Richard Trieu7aa58f12011-09-02 20:58:51 +0000853 /*convertInt=*/ true,
Richard Trieuba63ce62011-09-09 01:45:06 +0000854 /*convertFloat=*/!IsCompAssign);
Richard Trieu7aa58f12011-09-02 20:58:51 +0000855}
856
857/// \brief Handle conversions with GCC complex int extension. Helper function
Benjamin Kramer499c68b2011-09-06 19:57:14 +0000858/// of UsualArithmeticConversions()
Richard Trieu7aa58f12011-09-02 20:58:51 +0000859// FIXME: if the operands are (int, _Complex long), we currently
860// don't promote the complex. Also, signedness?
Benjamin Kramer499c68b2011-09-06 19:57:14 +0000861static QualType handleComplexIntConversion(Sema &S, ExprResult &LHS,
862 ExprResult &RHS, QualType LHSType,
863 QualType RHSType,
Richard Trieuba63ce62011-09-09 01:45:06 +0000864 bool IsCompAssign) {
Richard Trieucfe3f212011-09-06 18:38:41 +0000865 const ComplexType *LHSComplexInt = LHSType->getAsComplexIntegerType();
866 const ComplexType *RHSComplexInt = RHSType->getAsComplexIntegerType();
Richard Trieu7aa58f12011-09-02 20:58:51 +0000867
Richard Trieucfe3f212011-09-06 18:38:41 +0000868 if (LHSComplexInt && RHSComplexInt) {
869 int order = S.Context.getIntegerTypeOrder(LHSComplexInt->getElementType(),
870 RHSComplexInt->getElementType());
Richard Trieu7aa58f12011-09-02 20:58:51 +0000871 assert(order && "inequal types with equal element ordering");
872 if (order > 0) {
873 // _Complex int -> _Complex long
Richard Trieucfe3f212011-09-06 18:38:41 +0000874 RHS = S.ImpCastExprToType(RHS.take(), LHSType, CK_IntegralComplexCast);
875 return LHSType;
Richard Trieu7aa58f12011-09-02 20:58:51 +0000876 }
877
Richard Trieuba63ce62011-09-09 01:45:06 +0000878 if (!IsCompAssign)
Richard Trieucfe3f212011-09-06 18:38:41 +0000879 LHS = S.ImpCastExprToType(LHS.take(), RHSType, CK_IntegralComplexCast);
880 return RHSType;
Richard Trieu7aa58f12011-09-02 20:58:51 +0000881 }
882
Richard Trieucfe3f212011-09-06 18:38:41 +0000883 if (LHSComplexInt) {
Richard Trieu7aa58f12011-09-02 20:58:51 +0000884 // int -> _Complex int
Eli Friedman47133be2011-11-12 03:56:23 +0000885 // FIXME: This needs to take integer ranks into account
886 RHS = S.ImpCastExprToType(RHS.take(), LHSComplexInt->getElementType(),
887 CK_IntegralCast);
Richard Trieucfe3f212011-09-06 18:38:41 +0000888 RHS = S.ImpCastExprToType(RHS.take(), LHSType, CK_IntegralRealToComplex);
889 return LHSType;
Richard Trieu7aa58f12011-09-02 20:58:51 +0000890 }
891
Richard Trieucfe3f212011-09-06 18:38:41 +0000892 assert(RHSComplexInt);
Richard Trieu7aa58f12011-09-02 20:58:51 +0000893 // int -> _Complex int
Eli Friedman47133be2011-11-12 03:56:23 +0000894 // FIXME: This needs to take integer ranks into account
895 if (!IsCompAssign) {
896 LHS = S.ImpCastExprToType(LHS.take(), RHSComplexInt->getElementType(),
897 CK_IntegralCast);
Richard Trieucfe3f212011-09-06 18:38:41 +0000898 LHS = S.ImpCastExprToType(LHS.take(), RHSType, CK_IntegralRealToComplex);
Eli Friedman47133be2011-11-12 03:56:23 +0000899 }
Richard Trieucfe3f212011-09-06 18:38:41 +0000900 return RHSType;
Richard Trieu7aa58f12011-09-02 20:58:51 +0000901}
902
903/// \brief Handle integer arithmetic conversions. Helper function of
904/// UsualArithmeticConversions()
Richard Trieu9a52fbb2011-09-06 19:52:52 +0000905static QualType handleIntegerConversion(Sema &S, ExprResult &LHS,
906 ExprResult &RHS, QualType LHSType,
Richard Trieuba63ce62011-09-09 01:45:06 +0000907 QualType RHSType, bool IsCompAssign) {
Richard Trieu7aa58f12011-09-02 20:58:51 +0000908 // The rules for this case are in C99 6.3.1.8
Richard Trieu9a52fbb2011-09-06 19:52:52 +0000909 int order = S.Context.getIntegerTypeOrder(LHSType, RHSType);
910 bool LHSSigned = LHSType->hasSignedIntegerRepresentation();
911 bool RHSSigned = RHSType->hasSignedIntegerRepresentation();
912 if (LHSSigned == RHSSigned) {
Richard Trieu7aa58f12011-09-02 20:58:51 +0000913 // Same signedness; use the higher-ranked type
914 if (order >= 0) {
Richard Trieu9a52fbb2011-09-06 19:52:52 +0000915 RHS = S.ImpCastExprToType(RHS.take(), LHSType, CK_IntegralCast);
916 return LHSType;
Richard Trieuba63ce62011-09-09 01:45:06 +0000917 } else if (!IsCompAssign)
Richard Trieu9a52fbb2011-09-06 19:52:52 +0000918 LHS = S.ImpCastExprToType(LHS.take(), RHSType, CK_IntegralCast);
919 return RHSType;
920 } else if (order != (LHSSigned ? 1 : -1)) {
Richard Trieu7aa58f12011-09-02 20:58:51 +0000921 // The unsigned type has greater than or equal rank to the
922 // signed type, so use the unsigned type
Richard Trieu9a52fbb2011-09-06 19:52:52 +0000923 if (RHSSigned) {
924 RHS = S.ImpCastExprToType(RHS.take(), LHSType, CK_IntegralCast);
925 return LHSType;
Richard Trieuba63ce62011-09-09 01:45:06 +0000926 } else if (!IsCompAssign)
Richard Trieu9a52fbb2011-09-06 19:52:52 +0000927 LHS = S.ImpCastExprToType(LHS.take(), RHSType, CK_IntegralCast);
928 return RHSType;
929 } else if (S.Context.getIntWidth(LHSType) != S.Context.getIntWidth(RHSType)) {
Richard Trieu7aa58f12011-09-02 20:58:51 +0000930 // The two types are different widths; if we are here, that
931 // means the signed type is larger than the unsigned type, so
932 // use the signed type.
Richard Trieu9a52fbb2011-09-06 19:52:52 +0000933 if (LHSSigned) {
934 RHS = S.ImpCastExprToType(RHS.take(), LHSType, CK_IntegralCast);
935 return LHSType;
Richard Trieuba63ce62011-09-09 01:45:06 +0000936 } else if (!IsCompAssign)
Richard Trieu9a52fbb2011-09-06 19:52:52 +0000937 LHS = S.ImpCastExprToType(LHS.take(), RHSType, CK_IntegralCast);
938 return RHSType;
Richard Trieu7aa58f12011-09-02 20:58:51 +0000939 } else {
940 // The signed type is higher-ranked than the unsigned type,
941 // but isn't actually any bigger (like unsigned int and long
942 // on most 32-bit systems). Use the unsigned type corresponding
943 // to the signed type.
944 QualType result =
Richard Trieu9a52fbb2011-09-06 19:52:52 +0000945 S.Context.getCorrespondingUnsignedType(LHSSigned ? LHSType : RHSType);
946 RHS = S.ImpCastExprToType(RHS.take(), result, CK_IntegralCast);
Richard Trieuba63ce62011-09-09 01:45:06 +0000947 if (!IsCompAssign)
Richard Trieu9a52fbb2011-09-06 19:52:52 +0000948 LHS = S.ImpCastExprToType(LHS.take(), result, CK_IntegralCast);
Richard Trieu7aa58f12011-09-02 20:58:51 +0000949 return result;
950 }
951}
952
Chris Lattner513165e2008-07-25 21:10:04 +0000953/// UsualArithmeticConversions - Performs various conversions that are common to
954/// binary operators (C99 6.3.1.8). If both operands aren't arithmetic, this
Mike Stump11289f42009-09-09 15:08:12 +0000955/// routine returns the first non-arithmetic type found. The client is
Chris Lattner513165e2008-07-25 21:10:04 +0000956/// responsible for emitting appropriate error diagnostics.
957/// FIXME: verify the conversion rules for "complex int" are consistent with
958/// GCC.
Richard Trieu9a52fbb2011-09-06 19:52:52 +0000959QualType Sema::UsualArithmeticConversions(ExprResult &LHS, ExprResult &RHS,
Richard Trieuba63ce62011-09-09 01:45:06 +0000960 bool IsCompAssign) {
961 if (!IsCompAssign) {
Richard Trieu9a52fbb2011-09-06 19:52:52 +0000962 LHS = UsualUnaryConversions(LHS.take());
963 if (LHS.isInvalid())
John Wiegley01296292011-04-08 18:41:53 +0000964 return QualType();
965 }
Eli Friedman8b7b1b12009-03-28 01:22:36 +0000966
Richard Trieu9a52fbb2011-09-06 19:52:52 +0000967 RHS = UsualUnaryConversions(RHS.take());
968 if (RHS.isInvalid())
John Wiegley01296292011-04-08 18:41:53 +0000969 return QualType();
Douglas Gregora11693b2008-11-12 17:17:38 +0000970
Mike Stump11289f42009-09-09 15:08:12 +0000971 // For conversion purposes, we ignore any qualifiers.
Chris Lattner513165e2008-07-25 21:10:04 +0000972 // For example, "const float" and "float" are equivalent.
Richard Trieu9a52fbb2011-09-06 19:52:52 +0000973 QualType LHSType =
974 Context.getCanonicalType(LHS.get()->getType()).getUnqualifiedType();
975 QualType RHSType =
976 Context.getCanonicalType(RHS.get()->getType()).getUnqualifiedType();
Douglas Gregora11693b2008-11-12 17:17:38 +0000977
Eli Friedman93ee5ca2012-06-16 02:19:17 +0000978 // For conversion purposes, we ignore any atomic qualifier on the LHS.
979 if (const AtomicType *AtomicLHS = LHSType->getAs<AtomicType>())
980 LHSType = AtomicLHS->getValueType();
981
Douglas Gregora11693b2008-11-12 17:17:38 +0000982 // If both types are identical, no conversion is needed.
Richard Trieu9a52fbb2011-09-06 19:52:52 +0000983 if (LHSType == RHSType)
984 return LHSType;
Douglas Gregora11693b2008-11-12 17:17:38 +0000985
986 // If either side is a non-arithmetic type (e.g. a pointer), we are done.
987 // The caller can deal with this (e.g. pointer + int).
Richard Trieu9a52fbb2011-09-06 19:52:52 +0000988 if (!LHSType->isArithmeticType() || !RHSType->isArithmeticType())
Eli Friedman93ee5ca2012-06-16 02:19:17 +0000989 return QualType();
Douglas Gregora11693b2008-11-12 17:17:38 +0000990
John McCalld005ac92010-11-13 08:17:45 +0000991 // Apply unary and bitfield promotions to the LHS's type.
Richard Trieu9a52fbb2011-09-06 19:52:52 +0000992 QualType LHSUnpromotedType = LHSType;
993 if (LHSType->isPromotableIntegerType())
994 LHSType = Context.getPromotedIntegerType(LHSType);
995 QualType LHSBitfieldPromoteTy = Context.isPromotableBitField(LHS.get());
Douglas Gregord2c2d172009-05-02 00:36:19 +0000996 if (!LHSBitfieldPromoteTy.isNull())
Richard Trieu9a52fbb2011-09-06 19:52:52 +0000997 LHSType = LHSBitfieldPromoteTy;
Richard Trieuba63ce62011-09-09 01:45:06 +0000998 if (LHSType != LHSUnpromotedType && !IsCompAssign)
Richard Trieu9a52fbb2011-09-06 19:52:52 +0000999 LHS = ImpCastExprToType(LHS.take(), LHSType, CK_IntegralCast);
Douglas Gregord2c2d172009-05-02 00:36:19 +00001000
John McCalld005ac92010-11-13 08:17:45 +00001001 // If both types are identical, no conversion is needed.
Richard Trieu9a52fbb2011-09-06 19:52:52 +00001002 if (LHSType == RHSType)
1003 return LHSType;
John McCalld005ac92010-11-13 08:17:45 +00001004
1005 // At this point, we have two different arithmetic types.
1006
1007 // Handle complex types first (C99 6.3.1.8p1).
Richard Trieu9a52fbb2011-09-06 19:52:52 +00001008 if (LHSType->isComplexType() || RHSType->isComplexType())
1009 return handleComplexFloatConversion(*this, LHS, RHS, LHSType, RHSType,
Richard Trieuba63ce62011-09-09 01:45:06 +00001010 IsCompAssign);
John McCalld005ac92010-11-13 08:17:45 +00001011
1012 // Now handle "real" floating types (i.e. float, double, long double).
Richard Trieu9a52fbb2011-09-06 19:52:52 +00001013 if (LHSType->isRealFloatingType() || RHSType->isRealFloatingType())
1014 return handleFloatConversion(*this, LHS, RHS, LHSType, RHSType,
Richard Trieuba63ce62011-09-09 01:45:06 +00001015 IsCompAssign);
John McCalld005ac92010-11-13 08:17:45 +00001016
1017 // Handle GCC complex int extension.
Richard Trieu9a52fbb2011-09-06 19:52:52 +00001018 if (LHSType->isComplexIntegerType() || RHSType->isComplexIntegerType())
Benjamin Kramer499c68b2011-09-06 19:57:14 +00001019 return handleComplexIntConversion(*this, LHS, RHS, LHSType, RHSType,
Richard Trieuba63ce62011-09-09 01:45:06 +00001020 IsCompAssign);
John McCalld005ac92010-11-13 08:17:45 +00001021
1022 // Finally, we have two differing integer types.
Richard Trieu9a52fbb2011-09-06 19:52:52 +00001023 return handleIntegerConversion(*this, LHS, RHS, LHSType, RHSType,
Richard Trieuba63ce62011-09-09 01:45:06 +00001024 IsCompAssign);
Douglas Gregora11693b2008-11-12 17:17:38 +00001025}
1026
Chris Lattner513165e2008-07-25 21:10:04 +00001027//===----------------------------------------------------------------------===//
1028// Semantic Analysis for various Expression Types
1029//===----------------------------------------------------------------------===//
1030
1031
Peter Collingbourne91147592011-04-15 00:35:48 +00001032ExprResult
1033Sema::ActOnGenericSelectionExpr(SourceLocation KeyLoc,
1034 SourceLocation DefaultLoc,
1035 SourceLocation RParenLoc,
1036 Expr *ControllingExpr,
Richard Trieuba63ce62011-09-09 01:45:06 +00001037 MultiTypeArg ArgTypes,
1038 MultiExprArg ArgExprs) {
1039 unsigned NumAssocs = ArgTypes.size();
1040 assert(NumAssocs == ArgExprs.size());
Peter Collingbourne91147592011-04-15 00:35:48 +00001041
Richard Trieuba63ce62011-09-09 01:45:06 +00001042 ParsedType *ParsedTypes = ArgTypes.release();
1043 Expr **Exprs = ArgExprs.release();
Peter Collingbourne91147592011-04-15 00:35:48 +00001044
1045 TypeSourceInfo **Types = new TypeSourceInfo*[NumAssocs];
1046 for (unsigned i = 0; i < NumAssocs; ++i) {
1047 if (ParsedTypes[i])
1048 (void) GetTypeFromParser(ParsedTypes[i], &Types[i]);
1049 else
1050 Types[i] = 0;
1051 }
1052
1053 ExprResult ER = CreateGenericSelectionExpr(KeyLoc, DefaultLoc, RParenLoc,
1054 ControllingExpr, Types, Exprs,
1055 NumAssocs);
Benjamin Kramer34623762011-04-15 11:21:57 +00001056 delete [] Types;
Peter Collingbourne91147592011-04-15 00:35:48 +00001057 return ER;
1058}
1059
1060ExprResult
1061Sema::CreateGenericSelectionExpr(SourceLocation KeyLoc,
1062 SourceLocation DefaultLoc,
1063 SourceLocation RParenLoc,
1064 Expr *ControllingExpr,
1065 TypeSourceInfo **Types,
1066 Expr **Exprs,
1067 unsigned NumAssocs) {
1068 bool TypeErrorFound = false,
1069 IsResultDependent = ControllingExpr->isTypeDependent(),
1070 ContainsUnexpandedParameterPack
1071 = ControllingExpr->containsUnexpandedParameterPack();
1072
1073 for (unsigned i = 0; i < NumAssocs; ++i) {
1074 if (Exprs[i]->containsUnexpandedParameterPack())
1075 ContainsUnexpandedParameterPack = true;
1076
1077 if (Types[i]) {
1078 if (Types[i]->getType()->containsUnexpandedParameterPack())
1079 ContainsUnexpandedParameterPack = true;
1080
1081 if (Types[i]->getType()->isDependentType()) {
1082 IsResultDependent = true;
1083 } else {
Benjamin Kramere56f3932011-12-23 17:00:35 +00001084 // C11 6.5.1.1p2 "The type name in a generic association shall specify a
Peter Collingbourne91147592011-04-15 00:35:48 +00001085 // complete object type other than a variably modified type."
1086 unsigned D = 0;
1087 if (Types[i]->getType()->isIncompleteType())
1088 D = diag::err_assoc_type_incomplete;
1089 else if (!Types[i]->getType()->isObjectType())
1090 D = diag::err_assoc_type_nonobject;
1091 else if (Types[i]->getType()->isVariablyModifiedType())
1092 D = diag::err_assoc_type_variably_modified;
1093
1094 if (D != 0) {
1095 Diag(Types[i]->getTypeLoc().getBeginLoc(), D)
1096 << Types[i]->getTypeLoc().getSourceRange()
1097 << Types[i]->getType();
1098 TypeErrorFound = true;
1099 }
1100
Benjamin Kramere56f3932011-12-23 17:00:35 +00001101 // C11 6.5.1.1p2 "No two generic associations in the same generic
Peter Collingbourne91147592011-04-15 00:35:48 +00001102 // selection shall specify compatible types."
1103 for (unsigned j = i+1; j < NumAssocs; ++j)
1104 if (Types[j] && !Types[j]->getType()->isDependentType() &&
1105 Context.typesAreCompatible(Types[i]->getType(),
1106 Types[j]->getType())) {
1107 Diag(Types[j]->getTypeLoc().getBeginLoc(),
1108 diag::err_assoc_compatible_types)
1109 << Types[j]->getTypeLoc().getSourceRange()
1110 << Types[j]->getType()
1111 << Types[i]->getType();
1112 Diag(Types[i]->getTypeLoc().getBeginLoc(),
1113 diag::note_compat_assoc)
1114 << Types[i]->getTypeLoc().getSourceRange()
1115 << Types[i]->getType();
1116 TypeErrorFound = true;
1117 }
1118 }
1119 }
1120 }
1121 if (TypeErrorFound)
1122 return ExprError();
1123
1124 // If we determined that the generic selection is result-dependent, don't
1125 // try to compute the result expression.
1126 if (IsResultDependent)
1127 return Owned(new (Context) GenericSelectionExpr(
1128 Context, KeyLoc, ControllingExpr,
1129 Types, Exprs, NumAssocs, DefaultLoc,
1130 RParenLoc, ContainsUnexpandedParameterPack));
1131
Chris Lattner0e62c1c2011-07-23 10:55:15 +00001132 SmallVector<unsigned, 1> CompatIndices;
Peter Collingbourne91147592011-04-15 00:35:48 +00001133 unsigned DefaultIndex = -1U;
1134 for (unsigned i = 0; i < NumAssocs; ++i) {
1135 if (!Types[i])
1136 DefaultIndex = i;
1137 else if (Context.typesAreCompatible(ControllingExpr->getType(),
1138 Types[i]->getType()))
1139 CompatIndices.push_back(i);
1140 }
1141
Benjamin Kramere56f3932011-12-23 17:00:35 +00001142 // C11 6.5.1.1p2 "The controlling expression of a generic selection shall have
Peter Collingbourne91147592011-04-15 00:35:48 +00001143 // type compatible with at most one of the types named in its generic
1144 // association list."
1145 if (CompatIndices.size() > 1) {
1146 // We strip parens here because the controlling expression is typically
1147 // parenthesized in macro definitions.
1148 ControllingExpr = ControllingExpr->IgnoreParens();
1149 Diag(ControllingExpr->getLocStart(), diag::err_generic_sel_multi_match)
1150 << ControllingExpr->getSourceRange() << ControllingExpr->getType()
1151 << (unsigned) CompatIndices.size();
Chris Lattner0e62c1c2011-07-23 10:55:15 +00001152 for (SmallVector<unsigned, 1>::iterator I = CompatIndices.begin(),
Peter Collingbourne91147592011-04-15 00:35:48 +00001153 E = CompatIndices.end(); I != E; ++I) {
1154 Diag(Types[*I]->getTypeLoc().getBeginLoc(),
1155 diag::note_compat_assoc)
1156 << Types[*I]->getTypeLoc().getSourceRange()
1157 << Types[*I]->getType();
1158 }
1159 return ExprError();
1160 }
1161
Benjamin Kramere56f3932011-12-23 17:00:35 +00001162 // C11 6.5.1.1p2 "If a generic selection has no default generic association,
Peter Collingbourne91147592011-04-15 00:35:48 +00001163 // its controlling expression shall have type compatible with exactly one of
1164 // the types named in its generic association list."
1165 if (DefaultIndex == -1U && CompatIndices.size() == 0) {
1166 // We strip parens here because the controlling expression is typically
1167 // parenthesized in macro definitions.
1168 ControllingExpr = ControllingExpr->IgnoreParens();
1169 Diag(ControllingExpr->getLocStart(), diag::err_generic_sel_no_match)
1170 << ControllingExpr->getSourceRange() << ControllingExpr->getType();
1171 return ExprError();
1172 }
1173
Benjamin Kramere56f3932011-12-23 17:00:35 +00001174 // C11 6.5.1.1p3 "If a generic selection has a generic association with a
Peter Collingbourne91147592011-04-15 00:35:48 +00001175 // type name that is compatible with the type of the controlling expression,
1176 // then the result expression of the generic selection is the expression
1177 // in that generic association. Otherwise, the result expression of the
1178 // generic selection is the expression in the default generic association."
1179 unsigned ResultIndex =
1180 CompatIndices.size() ? CompatIndices[0] : DefaultIndex;
1181
1182 return Owned(new (Context) GenericSelectionExpr(
1183 Context, KeyLoc, ControllingExpr,
1184 Types, Exprs, NumAssocs, DefaultLoc,
1185 RParenLoc, ContainsUnexpandedParameterPack,
1186 ResultIndex));
1187}
1188
Richard Smith75b67d62012-03-08 01:34:56 +00001189/// getUDSuffixLoc - Create a SourceLocation for a ud-suffix, given the
1190/// location of the token and the offset of the ud-suffix within it.
1191static SourceLocation getUDSuffixLoc(Sema &S, SourceLocation TokLoc,
1192 unsigned Offset) {
1193 return Lexer::AdvanceToTokenCharacter(TokLoc, Offset, S.getSourceManager(),
David Blaikiebbafb8a2012-03-11 07:00:24 +00001194 S.getLangOpts());
Richard Smith75b67d62012-03-08 01:34:56 +00001195}
1196
Richard Smithbcc22fc2012-03-09 08:00:36 +00001197/// BuildCookedLiteralOperatorCall - A user-defined literal was found. Look up
1198/// the corresponding cooked (non-raw) literal operator, and build a call to it.
1199static ExprResult BuildCookedLiteralOperatorCall(Sema &S, Scope *Scope,
1200 IdentifierInfo *UDSuffix,
1201 SourceLocation UDSuffixLoc,
1202 ArrayRef<Expr*> Args,
1203 SourceLocation LitEndLoc) {
1204 assert(Args.size() <= 2 && "too many arguments for literal operator");
1205
1206 QualType ArgTy[2];
1207 for (unsigned ArgIdx = 0; ArgIdx != Args.size(); ++ArgIdx) {
1208 ArgTy[ArgIdx] = Args[ArgIdx]->getType();
1209 if (ArgTy[ArgIdx]->isArrayType())
1210 ArgTy[ArgIdx] = S.Context.getArrayDecayedType(ArgTy[ArgIdx]);
1211 }
1212
1213 DeclarationName OpName =
1214 S.Context.DeclarationNames.getCXXLiteralOperatorName(UDSuffix);
1215 DeclarationNameInfo OpNameInfo(OpName, UDSuffixLoc);
1216 OpNameInfo.setCXXLiteralOperatorNameLoc(UDSuffixLoc);
1217
1218 LookupResult R(S, OpName, UDSuffixLoc, Sema::LookupOrdinaryName);
1219 if (S.LookupLiteralOperator(Scope, R, llvm::makeArrayRef(ArgTy, Args.size()),
1220 /*AllowRawAndTemplate*/false) == Sema::LOLR_Error)
1221 return ExprError();
1222
1223 return S.BuildLiteralOperatorCall(R, OpNameInfo, Args, LitEndLoc);
1224}
1225
Steve Naroff83895f72007-09-16 03:34:24 +00001226/// ActOnStringLiteral - The specified tokens were lexed as pasted string
Chris Lattner5b183d82006-11-10 05:03:26 +00001227/// fragments (e.g. "foo" "bar" L"baz"). The result string has to handle string
1228/// concatenation ([C99 5.1.1.2, translation phase #6]), so it may come from
1229/// multiple tokens. However, the common case is that StringToks points to one
1230/// string.
Sebastian Redlffbcf962009-01-18 18:53:16 +00001231///
John McCalldadc5752010-08-24 06:29:42 +00001232ExprResult
Richard Smithbcc22fc2012-03-09 08:00:36 +00001233Sema::ActOnStringLiteral(const Token *StringToks, unsigned NumStringToks,
1234 Scope *UDLScope) {
Chris Lattner5b183d82006-11-10 05:03:26 +00001235 assert(NumStringToks && "Must have at least one string!");
1236
Chris Lattner8a24e582009-01-16 18:51:42 +00001237 StringLiteralParser Literal(StringToks, NumStringToks, PP);
Steve Naroff4f88b312007-03-13 22:37:02 +00001238 if (Literal.hadError)
Sebastian Redlffbcf962009-01-18 18:53:16 +00001239 return ExprError();
Chris Lattner5b183d82006-11-10 05:03:26 +00001240
Chris Lattner0e62c1c2011-07-23 10:55:15 +00001241 SmallVector<SourceLocation, 4> StringTokLocs;
Chris Lattner5b183d82006-11-10 05:03:26 +00001242 for (unsigned i = 0; i != NumStringToks; ++i)
1243 StringTokLocs.push_back(StringToks[i].getLocation());
Chris Lattner36fc8792008-02-11 00:02:17 +00001244
Chris Lattner36fc8792008-02-11 00:02:17 +00001245 QualType StrTy = Context.CharTy;
Douglas Gregorfb65e592011-07-27 05:40:30 +00001246 if (Literal.isWide())
Anders Carlsson6b06e182011-04-06 18:42:48 +00001247 StrTy = Context.getWCharType();
Douglas Gregorfb65e592011-07-27 05:40:30 +00001248 else if (Literal.isUTF16())
1249 StrTy = Context.Char16Ty;
1250 else if (Literal.isUTF32())
1251 StrTy = Context.Char32Ty;
Eli Friedmanfcec6302011-11-01 02:23:42 +00001252 else if (Literal.isPascal())
Anders Carlsson6b06e182011-04-06 18:42:48 +00001253 StrTy = Context.UnsignedCharTy;
Douglas Gregoraa1e21d2008-09-12 00:47:35 +00001254
Douglas Gregorfb65e592011-07-27 05:40:30 +00001255 StringLiteral::StringKind Kind = StringLiteral::Ascii;
1256 if (Literal.isWide())
1257 Kind = StringLiteral::Wide;
1258 else if (Literal.isUTF8())
1259 Kind = StringLiteral::UTF8;
1260 else if (Literal.isUTF16())
1261 Kind = StringLiteral::UTF16;
1262 else if (Literal.isUTF32())
1263 Kind = StringLiteral::UTF32;
1264
Douglas Gregoraa1e21d2008-09-12 00:47:35 +00001265 // A C++ string literal has a const-qualified element type (C++ 2.13.4p1).
David Blaikiebbafb8a2012-03-11 07:00:24 +00001266 if (getLangOpts().CPlusPlus || getLangOpts().ConstStrings)
Douglas Gregoraa1e21d2008-09-12 00:47:35 +00001267 StrTy.addConst();
Sebastian Redlffbcf962009-01-18 18:53:16 +00001268
Chris Lattner36fc8792008-02-11 00:02:17 +00001269 // Get an array type for the string, according to C99 6.4.5. This includes
1270 // the nul terminator character as well as the string length for pascal
1271 // strings.
1272 StrTy = Context.getConstantArrayType(StrTy,
Chris Lattnerd42c29f2009-02-26 23:01:51 +00001273 llvm::APInt(32, Literal.GetNumStringChars()+1),
Chris Lattner36fc8792008-02-11 00:02:17 +00001274 ArrayType::Normal, 0);
Mike Stump11289f42009-09-09 15:08:12 +00001275
Chris Lattner5b183d82006-11-10 05:03:26 +00001276 // Pass &StringTokLocs[0], StringTokLocs.size() to factory!
Richard Smithc67fdd42012-03-07 08:35:16 +00001277 StringLiteral *Lit = StringLiteral::Create(Context, Literal.GetString(),
1278 Kind, Literal.Pascal, StrTy,
1279 &StringTokLocs[0],
1280 StringTokLocs.size());
1281 if (Literal.getUDSuffix().empty())
1282 return Owned(Lit);
1283
1284 // We're building a user-defined literal.
1285 IdentifierInfo *UDSuffix = &Context.Idents.get(Literal.getUDSuffix());
Richard Smith75b67d62012-03-08 01:34:56 +00001286 SourceLocation UDSuffixLoc =
1287 getUDSuffixLoc(*this, StringTokLocs[Literal.getUDSuffixToken()],
1288 Literal.getUDSuffixOffset());
Richard Smithc67fdd42012-03-07 08:35:16 +00001289
Richard Smithbcc22fc2012-03-09 08:00:36 +00001290 // Make sure we're allowed user-defined literals here.
1291 if (!UDLScope)
1292 return ExprError(Diag(UDSuffixLoc, diag::err_invalid_string_udl));
1293
Richard Smithc67fdd42012-03-07 08:35:16 +00001294 // C++11 [lex.ext]p5: The literal L is treated as a call of the form
1295 // operator "" X (str, len)
1296 QualType SizeType = Context.getSizeType();
1297 llvm::APInt Len(Context.getIntWidth(SizeType), Literal.GetNumStringChars());
1298 IntegerLiteral *LenArg = IntegerLiteral::Create(Context, Len, SizeType,
1299 StringTokLocs[0]);
1300 Expr *Args[] = { Lit, LenArg };
Richard Smithbcc22fc2012-03-09 08:00:36 +00001301 return BuildCookedLiteralOperatorCall(*this, UDLScope, UDSuffix, UDSuffixLoc,
1302 Args, StringTokLocs.back());
Chris Lattner5b183d82006-11-10 05:03:26 +00001303}
1304
John McCalldadc5752010-08-24 06:29:42 +00001305ExprResult
John McCall7decc9e2010-11-18 06:31:45 +00001306Sema::BuildDeclRefExpr(ValueDecl *D, QualType Ty, ExprValueKind VK,
John McCallf4cd4f92011-02-09 01:13:10 +00001307 SourceLocation Loc,
1308 const CXXScopeSpec *SS) {
Abramo Bagnarad6d2f182010-08-11 22:01:17 +00001309 DeclarationNameInfo NameInfo(D->getDeclName(), Loc);
John McCall7decc9e2010-11-18 06:31:45 +00001310 return BuildDeclRefExpr(D, Ty, VK, NameInfo, SS);
Abramo Bagnarad6d2f182010-08-11 22:01:17 +00001311}
1312
John McCallf4cd4f92011-02-09 01:13:10 +00001313/// BuildDeclRefExpr - Build an expression that references a
1314/// declaration that does not require a closure capture.
John McCalldadc5752010-08-24 06:29:42 +00001315ExprResult
John McCallf4cd4f92011-02-09 01:13:10 +00001316Sema::BuildDeclRefExpr(ValueDecl *D, QualType Ty, ExprValueKind VK,
Abramo Bagnarad6d2f182010-08-11 22:01:17 +00001317 const DeclarationNameInfo &NameInfo,
1318 const CXXScopeSpec *SS) {
David Blaikiebbafb8a2012-03-11 07:00:24 +00001319 if (getLangOpts().CUDA)
Peter Collingbourne7277fe82011-10-02 23:49:40 +00001320 if (const FunctionDecl *Caller = dyn_cast<FunctionDecl>(CurContext))
1321 if (const FunctionDecl *Callee = dyn_cast<FunctionDecl>(D)) {
1322 CUDAFunctionTarget CallerTarget = IdentifyCUDATarget(Caller),
1323 CalleeTarget = IdentifyCUDATarget(Callee);
1324 if (CheckCUDATarget(CallerTarget, CalleeTarget)) {
1325 Diag(NameInfo.getLoc(), diag::err_ref_bad_target)
1326 << CalleeTarget << D->getIdentifier() << CallerTarget;
1327 Diag(D->getLocation(), diag::note_previous_decl)
1328 << D->getIdentifier();
1329 return ExprError();
1330 }
1331 }
1332
John McCall113bee02012-03-10 09:33:50 +00001333 bool refersToEnclosingScope =
1334 (CurContext != D->getDeclContext() &&
1335 D->getDeclContext()->isFunctionOrMethod());
1336
Eli Friedmanfa0df832012-02-02 03:46:19 +00001337 DeclRefExpr *E = DeclRefExpr::Create(Context,
1338 SS ? SS->getWithLocInContext(Context)
1339 : NestedNameSpecifierLoc(),
John McCall113bee02012-03-10 09:33:50 +00001340 SourceLocation(),
1341 D, refersToEnclosingScope,
1342 NameInfo, Ty, VK);
Mike Stump11289f42009-09-09 15:08:12 +00001343
Eli Friedmanfa0df832012-02-02 03:46:19 +00001344 MarkDeclRefReferenced(E);
John McCall086a4642010-11-24 05:12:34 +00001345
1346 // Just in case we're building an illegal pointer-to-member.
Richard Smithcaf33902011-10-10 18:28:20 +00001347 FieldDecl *FD = dyn_cast<FieldDecl>(D);
1348 if (FD && FD->isBitField())
John McCall086a4642010-11-24 05:12:34 +00001349 E->setObjectKind(OK_BitField);
1350
1351 return Owned(E);
Douglas Gregorc7acfdf2009-01-06 05:10:23 +00001352}
1353
Abramo Bagnarad6d2f182010-08-11 22:01:17 +00001354/// Decomposes the given name into a DeclarationNameInfo, its location, and
John McCall10eae182009-11-30 22:42:35 +00001355/// possibly a list of template arguments.
1356///
1357/// If this produces template arguments, it is permitted to call
1358/// DecomposeTemplateName.
1359///
1360/// This actually loses a lot of source location information for
1361/// non-standard name kinds; we should consider preserving that in
1362/// some way.
Richard Trieucfc491d2011-08-02 04:35:43 +00001363void
1364Sema::DecomposeUnqualifiedId(const UnqualifiedId &Id,
1365 TemplateArgumentListInfo &Buffer,
1366 DeclarationNameInfo &NameInfo,
1367 const TemplateArgumentListInfo *&TemplateArgs) {
John McCall10eae182009-11-30 22:42:35 +00001368 if (Id.getKind() == UnqualifiedId::IK_TemplateId) {
1369 Buffer.setLAngleLoc(Id.TemplateId->LAngleLoc);
1370 Buffer.setRAngleLoc(Id.TemplateId->RAngleLoc);
1371
Douglas Gregor5476205b2011-06-23 00:49:38 +00001372 ASTTemplateArgsPtr TemplateArgsPtr(*this,
John McCall10eae182009-11-30 22:42:35 +00001373 Id.TemplateId->getTemplateArgs(),
1374 Id.TemplateId->NumArgs);
Douglas Gregor5476205b2011-06-23 00:49:38 +00001375 translateTemplateArguments(TemplateArgsPtr, Buffer);
John McCall10eae182009-11-30 22:42:35 +00001376 TemplateArgsPtr.release();
1377
John McCall3e56fd42010-08-23 07:28:44 +00001378 TemplateName TName = Id.TemplateId->Template.get();
Abramo Bagnarad6d2f182010-08-11 22:01:17 +00001379 SourceLocation TNameLoc = Id.TemplateId->TemplateNameLoc;
Douglas Gregor5476205b2011-06-23 00:49:38 +00001380 NameInfo = Context.getNameForTemplate(TName, TNameLoc);
John McCall10eae182009-11-30 22:42:35 +00001381 TemplateArgs = &Buffer;
1382 } else {
Douglas Gregor5476205b2011-06-23 00:49:38 +00001383 NameInfo = GetNameFromUnqualifiedId(Id);
John McCall10eae182009-11-30 22:42:35 +00001384 TemplateArgs = 0;
1385 }
1386}
1387
John McCalld681c392009-12-16 08:11:27 +00001388/// Diagnose an empty lookup.
1389///
1390/// \return false if new lookup candidates were found
Nick Lewyckyc96c37f2010-07-06 19:51:49 +00001391bool Sema::DiagnoseEmptyLookup(Scope *S, CXXScopeSpec &SS, LookupResult &R,
Kaelyn Uhrain79d01c12012-01-18 05:58:54 +00001392 CorrectionCandidateCallback &CCC,
Kaelyn Uhrain42830922011-08-05 00:09:52 +00001393 TemplateArgumentListInfo *ExplicitTemplateArgs,
Ahmed Charlesb24b9aa2012-02-25 11:00:22 +00001394 llvm::ArrayRef<Expr *> Args) {
John McCalld681c392009-12-16 08:11:27 +00001395 DeclarationName Name = R.getLookupName();
1396
John McCalld681c392009-12-16 08:11:27 +00001397 unsigned diagnostic = diag::err_undeclared_var_use;
Douglas Gregor598b08f2009-12-31 05:20:13 +00001398 unsigned diagnostic_suggest = diag::err_undeclared_var_use_suggest;
John McCalld681c392009-12-16 08:11:27 +00001399 if (Name.getNameKind() == DeclarationName::CXXOperatorName ||
1400 Name.getNameKind() == DeclarationName::CXXLiteralOperatorName ||
Douglas Gregor598b08f2009-12-31 05:20:13 +00001401 Name.getNameKind() == DeclarationName::CXXConversionFunctionName) {
John McCalld681c392009-12-16 08:11:27 +00001402 diagnostic = diag::err_undeclared_use;
Douglas Gregor598b08f2009-12-31 05:20:13 +00001403 diagnostic_suggest = diag::err_undeclared_use_suggest;
1404 }
John McCalld681c392009-12-16 08:11:27 +00001405
Douglas Gregor598b08f2009-12-31 05:20:13 +00001406 // If the original lookup was an unqualified lookup, fake an
1407 // unqualified lookup. This is useful when (for example) the
1408 // original lookup would not have found something because it was a
1409 // dependent name.
David Blaikiec4c0e8a2012-05-28 01:26:45 +00001410 DeclContext *DC = (SS.isEmpty() && !CallsUndergoingInstantiation.empty())
1411 ? CurContext : 0;
Francois Pichetde232cb2011-11-25 01:10:54 +00001412 while (DC) {
John McCalld681c392009-12-16 08:11:27 +00001413 if (isa<CXXRecordDecl>(DC)) {
1414 LookupQualifiedName(R, DC);
1415
1416 if (!R.empty()) {
1417 // Don't give errors about ambiguities in this lookup.
1418 R.suppressDiagnostics();
1419
Francois Pichet857f9d62011-11-17 03:44:24 +00001420 // During a default argument instantiation the CurContext points
1421 // to a CXXMethodDecl; but we can't apply a this-> fixit inside a
1422 // function parameter list, hence add an explicit check.
1423 bool isDefaultArgument = !ActiveTemplateInstantiations.empty() &&
1424 ActiveTemplateInstantiations.back().Kind ==
1425 ActiveTemplateInstantiation::DefaultFunctionArgumentInstantiation;
John McCalld681c392009-12-16 08:11:27 +00001426 CXXMethodDecl *CurMethod = dyn_cast<CXXMethodDecl>(CurContext);
1427 bool isInstance = CurMethod &&
1428 CurMethod->isInstance() &&
Francois Pichet857f9d62011-11-17 03:44:24 +00001429 DC == CurMethod->getParent() && !isDefaultArgument;
1430
John McCalld681c392009-12-16 08:11:27 +00001431
1432 // Give a code modification hint to insert 'this->'.
1433 // TODO: fixit for inserting 'Base<T>::' in the other cases.
1434 // Actually quite difficult!
Nick Lewyckyc96c37f2010-07-06 19:51:49 +00001435 if (isInstance) {
Nick Lewyckyc96c37f2010-07-06 19:51:49 +00001436 UnresolvedLookupExpr *ULE = cast<UnresolvedLookupExpr>(
1437 CallsUndergoingInstantiation.back()->getCallee());
Nick Lewyckyfe712382010-08-20 20:54:15 +00001438 CXXMethodDecl *DepMethod = cast_or_null<CXXMethodDecl>(
Nick Lewyckyc96c37f2010-07-06 19:51:49 +00001439 CurMethod->getInstantiatedFromMemberFunction());
Eli Friedman04831922010-08-22 01:00:03 +00001440 if (DepMethod) {
David Blaikiebbafb8a2012-03-11 07:00:24 +00001441 if (getLangOpts().MicrosoftMode)
Francois Pichetbcf64712011-09-07 00:14:57 +00001442 diagnostic = diag::warn_found_via_dependent_bases_lookup;
Nick Lewyckyfe712382010-08-20 20:54:15 +00001443 Diag(R.getNameLoc(), diagnostic) << Name
1444 << FixItHint::CreateInsertion(R.getNameLoc(), "this->");
1445 QualType DepThisType = DepMethod->getThisType(Context);
Eli Friedman73a04092012-01-07 04:59:52 +00001446 CheckCXXThisCapture(R.getNameLoc());
Nick Lewyckyfe712382010-08-20 20:54:15 +00001447 CXXThisExpr *DepThis = new (Context) CXXThisExpr(
1448 R.getNameLoc(), DepThisType, false);
1449 TemplateArgumentListInfo TList;
1450 if (ULE->hasExplicitTemplateArgs())
1451 ULE->copyTemplateArgumentsInto(TList);
Douglas Gregore16af532011-02-28 18:50:33 +00001452
Douglas Gregore16af532011-02-28 18:50:33 +00001453 CXXScopeSpec SS;
Douglas Gregor0da1d432011-02-28 20:01:57 +00001454 SS.Adopt(ULE->getQualifierLoc());
Nick Lewyckyfe712382010-08-20 20:54:15 +00001455 CXXDependentScopeMemberExpr *DepExpr =
1456 CXXDependentScopeMemberExpr::Create(
1457 Context, DepThis, DepThisType, true, SourceLocation(),
Abramo Bagnara7945c982012-01-27 09:46:47 +00001458 SS.getWithLocInContext(Context),
1459 ULE->getTemplateKeywordLoc(), 0,
Francois Pichet4391c752011-09-04 23:00:48 +00001460 R.getLookupNameInfo(),
1461 ULE->hasExplicitTemplateArgs() ? &TList : 0);
Nick Lewyckyfe712382010-08-20 20:54:15 +00001462 CallsUndergoingInstantiation.back()->setCallee(DepExpr);
Eli Friedman04831922010-08-22 01:00:03 +00001463 } else {
Nick Lewyckyfe712382010-08-20 20:54:15 +00001464 // FIXME: we should be able to handle this case too. It is correct
1465 // to add this-> here. This is a workaround for PR7947.
1466 Diag(R.getNameLoc(), diagnostic) << Name;
Eli Friedman04831922010-08-22 01:00:03 +00001467 }
Nick Lewyckyc96c37f2010-07-06 19:51:49 +00001468 } else {
David Blaikiebbafb8a2012-03-11 07:00:24 +00001469 if (getLangOpts().MicrosoftMode)
Francois Pichet78286b22011-11-15 23:33:34 +00001470 diagnostic = diag::warn_found_via_dependent_bases_lookup;
John McCalld681c392009-12-16 08:11:27 +00001471 Diag(R.getNameLoc(), diagnostic) << Name;
Nick Lewyckyc96c37f2010-07-06 19:51:49 +00001472 }
John McCalld681c392009-12-16 08:11:27 +00001473
1474 // Do we really want to note all of these?
1475 for (LookupResult::iterator I = R.begin(), E = R.end(); I != E; ++I)
1476 Diag((*I)->getLocation(), diag::note_dependent_var_use);
1477
Francois Pichet857f9d62011-11-17 03:44:24 +00001478 // Return true if we are inside a default argument instantiation
1479 // and the found name refers to an instance member function, otherwise
1480 // the function calling DiagnoseEmptyLookup will try to create an
1481 // implicit member call and this is wrong for default argument.
1482 if (isDefaultArgument && ((*R.begin())->isCXXInstanceMember())) {
1483 Diag(R.getNameLoc(), diag::err_member_call_without_object);
1484 return true;
1485 }
1486
John McCalld681c392009-12-16 08:11:27 +00001487 // Tell the callee to try to recover.
1488 return false;
1489 }
Douglas Gregor86b8d9f2010-08-09 22:38:14 +00001490
1491 R.clear();
John McCalld681c392009-12-16 08:11:27 +00001492 }
Francois Pichetde232cb2011-11-25 01:10:54 +00001493
1494 // In Microsoft mode, if we are performing lookup from within a friend
1495 // function definition declared at class scope then we must set
1496 // DC to the lexical parent to be able to search into the parent
1497 // class.
David Blaikiebbafb8a2012-03-11 07:00:24 +00001498 if (getLangOpts().MicrosoftMode && isa<FunctionDecl>(DC) &&
Francois Pichetde232cb2011-11-25 01:10:54 +00001499 cast<FunctionDecl>(DC)->getFriendObjectKind() &&
1500 DC->getLexicalParent()->isRecord())
1501 DC = DC->getLexicalParent();
1502 else
1503 DC = DC->getParent();
John McCalld681c392009-12-16 08:11:27 +00001504 }
1505
Douglas Gregor598b08f2009-12-31 05:20:13 +00001506 // We didn't find anything, so try to correct for a typo.
Douglas Gregorc2fa1692011-06-28 16:20:02 +00001507 TypoCorrection Corrected;
1508 if (S && (Corrected = CorrectTypo(R.getLookupNameInfo(), R.getLookupKind(),
Kaelyn Uhrain4e8942c2012-01-31 23:49:25 +00001509 S, &SS, CCC))) {
David Blaikiebbafb8a2012-03-11 07:00:24 +00001510 std::string CorrectedStr(Corrected.getAsString(getLangOpts()));
1511 std::string CorrectedQuotedStr(Corrected.getQuoted(getLangOpts()));
Douglas Gregorc2fa1692011-06-28 16:20:02 +00001512 R.setLookupName(Corrected.getCorrection());
1513
Hans Wennborg38198de2011-07-12 08:45:31 +00001514 if (NamedDecl *ND = Corrected.getCorrectionDecl()) {
Kaelyn Uhrainacbdc572011-08-03 20:36:05 +00001515 if (Corrected.isOverloaded()) {
1516 OverloadCandidateSet OCS(R.getNameLoc());
1517 OverloadCandidateSet::iterator Best;
1518 for (TypoCorrection::decl_iterator CD = Corrected.begin(),
1519 CDEnd = Corrected.end();
1520 CD != CDEnd; ++CD) {
Kaelyn Uhrain62422202011-08-08 17:35:31 +00001521 if (FunctionTemplateDecl *FTD =
Kaelyn Uhrain42830922011-08-05 00:09:52 +00001522 dyn_cast<FunctionTemplateDecl>(*CD))
1523 AddTemplateOverloadCandidate(
1524 FTD, DeclAccessPair::make(FTD, AS_none), ExplicitTemplateArgs,
Ahmed Charlesb24b9aa2012-02-25 11:00:22 +00001525 Args, OCS);
Kaelyn Uhrain62422202011-08-08 17:35:31 +00001526 else if (FunctionDecl *FD = dyn_cast<FunctionDecl>(*CD))
1527 if (!ExplicitTemplateArgs || ExplicitTemplateArgs->size() == 0)
1528 AddOverloadCandidate(FD, DeclAccessPair::make(FD, AS_none),
Ahmed Charlesb24b9aa2012-02-25 11:00:22 +00001529 Args, OCS);
Kaelyn Uhrainacbdc572011-08-03 20:36:05 +00001530 }
1531 switch (OCS.BestViableFunction(*this, R.getNameLoc(), Best)) {
1532 case OR_Success:
1533 ND = Best->Function;
1534 break;
1535 default:
Kaelyn Uhrainea350182011-08-04 23:30:54 +00001536 break;
Kaelyn Uhrainacbdc572011-08-03 20:36:05 +00001537 }
1538 }
Douglas Gregorc2fa1692011-06-28 16:20:02 +00001539 R.addDecl(ND);
1540 if (isa<ValueDecl>(ND) || isa<FunctionTemplateDecl>(ND)) {
Douglas Gregor280e1ee2010-04-14 20:04:41 +00001541 if (SS.isEmpty())
Douglas Gregorc2fa1692011-06-28 16:20:02 +00001542 Diag(R.getNameLoc(), diagnostic_suggest) << Name << CorrectedQuotedStr
1543 << FixItHint::CreateReplacement(R.getNameLoc(), CorrectedStr);
Douglas Gregor280e1ee2010-04-14 20:04:41 +00001544 else
1545 Diag(R.getNameLoc(), diag::err_no_member_suggest)
Douglas Gregorc2fa1692011-06-28 16:20:02 +00001546 << Name << computeDeclContext(SS, false) << CorrectedQuotedStr
Douglas Gregor280e1ee2010-04-14 20:04:41 +00001547 << SS.getRange()
Douglas Gregorc2fa1692011-06-28 16:20:02 +00001548 << FixItHint::CreateReplacement(R.getNameLoc(), CorrectedStr);
1549 if (ND)
Douglas Gregor280e1ee2010-04-14 20:04:41 +00001550 Diag(ND->getLocation(), diag::note_previous_decl)
Douglas Gregorc2fa1692011-06-28 16:20:02 +00001551 << CorrectedQuotedStr;
Douglas Gregor280e1ee2010-04-14 20:04:41 +00001552
1553 // Tell the callee to try to recover.
1554 return false;
1555 }
Alexis Huntc46382e2010-04-28 23:02:27 +00001556
Douglas Gregorc2fa1692011-06-28 16:20:02 +00001557 if (isa<TypeDecl>(ND) || isa<ObjCInterfaceDecl>(ND)) {
Douglas Gregor280e1ee2010-04-14 20:04:41 +00001558 // FIXME: If we ended up with a typo for a type name or
1559 // Objective-C class name, we're in trouble because the parser
1560 // is in the wrong place to recover. Suggest the typo
1561 // correction, but don't make it a fix-it since we're not going
1562 // to recover well anyway.
1563 if (SS.isEmpty())
Richard Trieucfc491d2011-08-02 04:35:43 +00001564 Diag(R.getNameLoc(), diagnostic_suggest)
1565 << Name << CorrectedQuotedStr;
Douglas Gregor280e1ee2010-04-14 20:04:41 +00001566 else
1567 Diag(R.getNameLoc(), diag::err_no_member_suggest)
Douglas Gregorc2fa1692011-06-28 16:20:02 +00001568 << Name << computeDeclContext(SS, false) << CorrectedQuotedStr
Douglas Gregor280e1ee2010-04-14 20:04:41 +00001569 << SS.getRange();
1570
1571 // Don't try to recover; it won't work.
1572 return true;
1573 }
1574 } else {
Alexis Huntc46382e2010-04-28 23:02:27 +00001575 // FIXME: We found a keyword. Suggest it, but don't provide a fix-it
Douglas Gregor280e1ee2010-04-14 20:04:41 +00001576 // because we aren't able to recover.
Douglas Gregor25363982010-01-01 00:15:04 +00001577 if (SS.isEmpty())
Douglas Gregorc2fa1692011-06-28 16:20:02 +00001578 Diag(R.getNameLoc(), diagnostic_suggest) << Name << CorrectedQuotedStr;
Kovarththanan Rajaratnamba2c6522010-03-13 10:17:05 +00001579 else
Douglas Gregor25363982010-01-01 00:15:04 +00001580 Diag(R.getNameLoc(), diag::err_no_member_suggest)
Douglas Gregorc2fa1692011-06-28 16:20:02 +00001581 << Name << computeDeclContext(SS, false) << CorrectedQuotedStr
Douglas Gregor280e1ee2010-04-14 20:04:41 +00001582 << SS.getRange();
Douglas Gregor25363982010-01-01 00:15:04 +00001583 return true;
1584 }
Douglas Gregor598b08f2009-12-31 05:20:13 +00001585 }
Douglas Gregorc2fa1692011-06-28 16:20:02 +00001586 R.clear();
Douglas Gregor598b08f2009-12-31 05:20:13 +00001587
1588 // Emit a special diagnostic for failed member lookups.
1589 // FIXME: computing the declaration context might fail here (?)
1590 if (!SS.isEmpty()) {
1591 Diag(R.getNameLoc(), diag::err_no_member)
1592 << Name << computeDeclContext(SS, false)
1593 << SS.getRange();
1594 return true;
1595 }
1596
John McCalld681c392009-12-16 08:11:27 +00001597 // Give up, we can't recover.
1598 Diag(R.getNameLoc(), diagnostic) << Name;
1599 return true;
1600}
1601
John McCalldadc5752010-08-24 06:29:42 +00001602ExprResult Sema::ActOnIdExpression(Scope *S,
John McCall24d18942010-08-24 22:52:39 +00001603 CXXScopeSpec &SS,
Abramo Bagnara7945c982012-01-27 09:46:47 +00001604 SourceLocation TemplateKWLoc,
John McCall24d18942010-08-24 22:52:39 +00001605 UnqualifiedId &Id,
1606 bool HasTrailingLParen,
Kaelyn Uhrain77e21fc2012-01-25 20:49:08 +00001607 bool IsAddressOfOperand,
1608 CorrectionCandidateCallback *CCC) {
Richard Trieuba63ce62011-09-09 01:45:06 +00001609 assert(!(IsAddressOfOperand && HasTrailingLParen) &&
John McCalle66edc12009-11-24 19:00:30 +00001610 "cannot be direct & operand and have a trailing lparen");
1611
1612 if (SS.isInvalid())
Douglas Gregored8f2882009-01-30 01:04:22 +00001613 return ExprError();
Douglas Gregor90a1a652009-03-19 17:26:29 +00001614
John McCall10eae182009-11-30 22:42:35 +00001615 TemplateArgumentListInfo TemplateArgsBuffer;
John McCalle66edc12009-11-24 19:00:30 +00001616
1617 // Decompose the UnqualifiedId into the following data.
Abramo Bagnarad6d2f182010-08-11 22:01:17 +00001618 DeclarationNameInfo NameInfo;
John McCalle66edc12009-11-24 19:00:30 +00001619 const TemplateArgumentListInfo *TemplateArgs;
Douglas Gregor5476205b2011-06-23 00:49:38 +00001620 DecomposeUnqualifiedId(Id, TemplateArgsBuffer, NameInfo, TemplateArgs);
Douglas Gregor90a1a652009-03-19 17:26:29 +00001621
Abramo Bagnarad6d2f182010-08-11 22:01:17 +00001622 DeclarationName Name = NameInfo.getName();
Douglas Gregor4ea80432008-11-18 15:03:34 +00001623 IdentifierInfo *II = Name.getAsIdentifierInfo();
Abramo Bagnarad6d2f182010-08-11 22:01:17 +00001624 SourceLocation NameLoc = NameInfo.getLoc();
John McCalld14a8642009-11-21 08:51:07 +00001625
John McCalle66edc12009-11-24 19:00:30 +00001626 // C++ [temp.dep.expr]p3:
1627 // An id-expression is type-dependent if it contains:
Douglas Gregorea0a0a92010-01-11 18:40:55 +00001628 // -- an identifier that was declared with a dependent type,
1629 // (note: handled after lookup)
1630 // -- a template-id that is dependent,
1631 // (note: handled in BuildTemplateIdExpr)
1632 // -- a conversion-function-id that specifies a dependent type,
John McCalle66edc12009-11-24 19:00:30 +00001633 // -- a nested-name-specifier that contains a class-name that
1634 // names a dependent type.
1635 // Determine whether this is a member of an unknown specialization;
1636 // we need to handle these differently.
Eli Friedman964dbda2010-08-06 23:41:47 +00001637 bool DependentID = false;
1638 if (Name.getNameKind() == DeclarationName::CXXConversionFunctionName &&
1639 Name.getCXXNameType()->isDependentType()) {
1640 DependentID = true;
1641 } else if (SS.isSet()) {
Chris Lattnerebb5c6c2011-02-18 01:27:55 +00001642 if (DeclContext *DC = computeDeclContext(SS, false)) {
Eli Friedman964dbda2010-08-06 23:41:47 +00001643 if (RequireCompleteDeclContext(SS, DC))
1644 return ExprError();
Eli Friedman964dbda2010-08-06 23:41:47 +00001645 } else {
1646 DependentID = true;
1647 }
1648 }
1649
Chris Lattnerebb5c6c2011-02-18 01:27:55 +00001650 if (DependentID)
Abramo Bagnara7945c982012-01-27 09:46:47 +00001651 return ActOnDependentIdExpression(SS, TemplateKWLoc, NameInfo,
1652 IsAddressOfOperand, TemplateArgs);
Chris Lattnerebb5c6c2011-02-18 01:27:55 +00001653
John McCalle66edc12009-11-24 19:00:30 +00001654 // Perform the required lookup.
Fariborz Jahanian7f4427f2011-07-12 17:16:56 +00001655 LookupResult R(*this, NameInfo,
1656 (Id.getKind() == UnqualifiedId::IK_ImplicitSelfParam)
1657 ? LookupObjCImplicitSelfParam : LookupOrdinaryName);
John McCalle66edc12009-11-24 19:00:30 +00001658 if (TemplateArgs) {
Douglas Gregor3e51e172010-05-20 20:58:56 +00001659 // Lookup the template name again to correctly establish the context in
1660 // which it was found. This is really unfortunate as we already did the
1661 // lookup to determine that it was a template name in the first place. If
1662 // this becomes a performance hit, we can work harder to preserve those
1663 // results until we get here but it's likely not worth it.
Douglas Gregor786123d2010-05-21 23:18:07 +00001664 bool MemberOfUnknownSpecialization;
1665 LookupTemplateName(R, S, SS, QualType(), /*EnteringContext=*/false,
1666 MemberOfUnknownSpecialization);
Douglas Gregora5226932011-02-04 13:35:07 +00001667
1668 if (MemberOfUnknownSpecialization ||
1669 (R.getResultKind() == LookupResult::NotFoundInCurrentInstantiation))
Abramo Bagnara7945c982012-01-27 09:46:47 +00001670 return ActOnDependentIdExpression(SS, TemplateKWLoc, NameInfo,
1671 IsAddressOfOperand, TemplateArgs);
John McCalle66edc12009-11-24 19:00:30 +00001672 } else {
Benjamin Kramer46921442012-01-20 14:57:34 +00001673 bool IvarLookupFollowUp = II && !SS.isSet() && getCurMethodDecl();
Fariborz Jahanian6fada5b2010-01-12 23:58:59 +00001674 LookupParsedName(R, S, &SS, !IvarLookupFollowUp);
Mike Stump11289f42009-09-09 15:08:12 +00001675
Douglas Gregora5226932011-02-04 13:35:07 +00001676 // If the result might be in a dependent base class, this is a dependent
1677 // id-expression.
1678 if (R.getResultKind() == LookupResult::NotFoundInCurrentInstantiation)
Abramo Bagnara7945c982012-01-27 09:46:47 +00001679 return ActOnDependentIdExpression(SS, TemplateKWLoc, NameInfo,
1680 IsAddressOfOperand, TemplateArgs);
1681
John McCalle66edc12009-11-24 19:00:30 +00001682 // If this reference is in an Objective-C method, then we need to do
1683 // some special Objective-C lookup, too.
Fariborz Jahanian6fada5b2010-01-12 23:58:59 +00001684 if (IvarLookupFollowUp) {
John McCalldadc5752010-08-24 06:29:42 +00001685 ExprResult E(LookupInObjCMethod(R, S, II, true));
John McCalle66edc12009-11-24 19:00:30 +00001686 if (E.isInvalid())
1687 return ExprError();
Mike Stump11289f42009-09-09 15:08:12 +00001688
Chris Lattnerebb5c6c2011-02-18 01:27:55 +00001689 if (Expr *Ex = E.takeAs<Expr>())
1690 return Owned(Ex);
Steve Naroffebf4cb42008-06-02 23:03:37 +00001691 }
Chris Lattner59a25942008-03-31 00:36:02 +00001692 }
Douglas Gregorf15f5d32009-02-16 19:28:42 +00001693
John McCalle66edc12009-11-24 19:00:30 +00001694 if (R.isAmbiguous())
1695 return ExprError();
1696
Douglas Gregor171c45a2009-02-18 21:56:37 +00001697 // Determine whether this name might be a candidate for
1698 // argument-dependent lookup.
John McCalle66edc12009-11-24 19:00:30 +00001699 bool ADL = UseArgumentDependentLookup(SS, R, HasTrailingLParen);
Douglas Gregor171c45a2009-02-18 21:56:37 +00001700
John McCalle66edc12009-11-24 19:00:30 +00001701 if (R.empty() && !ADL) {
Bill Wendling4073ed52007-02-13 01:51:42 +00001702 // Otherwise, this could be an implicitly declared function reference (legal
John McCalle66edc12009-11-24 19:00:30 +00001703 // in C90, extension in C99, forbidden in C++).
David Blaikiebbafb8a2012-03-11 07:00:24 +00001704 if (HasTrailingLParen && II && !getLangOpts().CPlusPlus) {
John McCalle66edc12009-11-24 19:00:30 +00001705 NamedDecl *D = ImplicitlyDefineFunction(NameLoc, *II, S);
1706 if (D) R.addDecl(D);
1707 }
1708
1709 // If this name wasn't predeclared and if this is not a function
1710 // call, diagnose the problem.
1711 if (R.empty()) {
Francois Pichetd8e4e412011-09-24 10:38:05 +00001712
1713 // In Microsoft mode, if we are inside a template class member function
1714 // and we can't resolve an identifier then assume the identifier is type
1715 // dependent. The goal is to postpone name lookup to instantiation time
1716 // to be able to search into type dependent base classes.
David Blaikiebbafb8a2012-03-11 07:00:24 +00001717 if (getLangOpts().MicrosoftMode && CurContext->isDependentContext() &&
Francois Pichetd8e4e412011-09-24 10:38:05 +00001718 isa<CXXMethodDecl>(CurContext))
Abramo Bagnara7945c982012-01-27 09:46:47 +00001719 return ActOnDependentIdExpression(SS, TemplateKWLoc, NameInfo,
1720 IsAddressOfOperand, TemplateArgs);
Francois Pichetd8e4e412011-09-24 10:38:05 +00001721
Kaelyn Uhrain79d01c12012-01-18 05:58:54 +00001722 CorrectionCandidateCallback DefaultValidator;
Kaelyn Uhrain77e21fc2012-01-25 20:49:08 +00001723 if (DiagnoseEmptyLookup(S, SS, R, CCC ? *CCC : DefaultValidator))
John McCalld681c392009-12-16 08:11:27 +00001724 return ExprError();
1725
1726 assert(!R.empty() &&
1727 "DiagnoseEmptyLookup returned false but added no results");
Douglas Gregor35b0bac2010-01-03 18:01:57 +00001728
1729 // If we found an Objective-C instance variable, let
1730 // LookupInObjCMethod build the appropriate expression to
Kovarththanan Rajaratnamba2c6522010-03-13 10:17:05 +00001731 // reference the ivar.
Douglas Gregor35b0bac2010-01-03 18:01:57 +00001732 if (ObjCIvarDecl *Ivar = R.getAsSingle<ObjCIvarDecl>()) {
1733 R.clear();
John McCalldadc5752010-08-24 06:29:42 +00001734 ExprResult E(LookupInObjCMethod(R, S, Ivar->getIdentifier()));
Fariborz Jahanian44653702011-09-23 23:11:38 +00001735 // In a hopelessly buggy code, Objective-C instance variable
1736 // lookup fails and no expression will be built to reference it.
1737 if (!E.isInvalid() && !E.get())
1738 return ExprError();
Douglas Gregor35b0bac2010-01-03 18:01:57 +00001739 return move(E);
1740 }
Steve Naroff92e30f82007-04-02 22:35:25 +00001741 }
Chris Lattner17ed4872006-11-20 04:58:19 +00001742 }
Mike Stump11289f42009-09-09 15:08:12 +00001743
John McCalle66edc12009-11-24 19:00:30 +00001744 // This is guaranteed from this point on.
1745 assert(!R.empty() || ADL);
1746
John McCall2d74de92009-12-01 22:10:20 +00001747 // Check whether this might be a C++ implicit instance member access.
John McCall24d18942010-08-24 22:52:39 +00001748 // C++ [class.mfct.non-static]p3:
1749 // When an id-expression that is not part of a class member access
1750 // syntax and not used to form a pointer to member is used in the
1751 // body of a non-static member function of class X, if name lookup
1752 // resolves the name in the id-expression to a non-static non-type
1753 // member of some class C, the id-expression is transformed into a
1754 // class member access expression using (*this) as the
1755 // postfix-expression to the left of the . operator.
John McCall8d08b9b2010-08-27 09:08:28 +00001756 //
1757 // But we don't actually need to do this for '&' operands if R
1758 // resolved to a function or overloaded function set, because the
1759 // expression is ill-formed if it actually works out to be a
1760 // non-static member function:
1761 //
1762 // C++ [expr.ref]p4:
1763 // Otherwise, if E1.E2 refers to a non-static member function. . .
1764 // [t]he expression can be used only as the left-hand operand of a
1765 // member function call.
1766 //
1767 // There are other safeguards against such uses, but it's important
1768 // to get this right here so that we don't end up making a
1769 // spuriously dependent expression if we're inside a dependent
1770 // instance method.
John McCall57500772009-12-16 12:17:52 +00001771 if (!R.empty() && (*R.begin())->isCXXClassMember()) {
John McCall8d08b9b2010-08-27 09:08:28 +00001772 bool MightBeImplicitMember;
Richard Trieuba63ce62011-09-09 01:45:06 +00001773 if (!IsAddressOfOperand)
John McCall8d08b9b2010-08-27 09:08:28 +00001774 MightBeImplicitMember = true;
1775 else if (!SS.isEmpty())
1776 MightBeImplicitMember = false;
1777 else if (R.isOverloadedResult())
1778 MightBeImplicitMember = false;
Douglas Gregor1262b062010-08-30 16:00:47 +00001779 else if (R.isUnresolvableResult())
1780 MightBeImplicitMember = true;
John McCall8d08b9b2010-08-27 09:08:28 +00001781 else
Francois Pichet783dd6e2010-11-21 06:08:52 +00001782 MightBeImplicitMember = isa<FieldDecl>(R.getFoundDecl()) ||
1783 isa<IndirectFieldDecl>(R.getFoundDecl());
John McCall8d08b9b2010-08-27 09:08:28 +00001784
1785 if (MightBeImplicitMember)
Abramo Bagnara7945c982012-01-27 09:46:47 +00001786 return BuildPossibleImplicitMemberExpr(SS, TemplateKWLoc,
1787 R, TemplateArgs);
John McCallb53bbd42009-11-22 01:44:31 +00001788 }
1789
Abramo Bagnara65f7c3d2012-02-06 14:31:00 +00001790 if (TemplateArgs || TemplateKWLoc.isValid())
1791 return BuildTemplateIdExpr(SS, TemplateKWLoc, R, ADL, TemplateArgs);
John McCallb53bbd42009-11-22 01:44:31 +00001792
John McCalle66edc12009-11-24 19:00:30 +00001793 return BuildDeclarationNameExpr(SS, R, ADL);
1794}
1795
John McCall10eae182009-11-30 22:42:35 +00001796/// BuildQualifiedDeclarationNameExpr - Build a C++ qualified
1797/// declaration name, generally during template instantiation.
1798/// There's a large number of things which don't need to be done along
1799/// this path.
John McCalldadc5752010-08-24 06:29:42 +00001800ExprResult
Jeffrey Yasskinc76498d2010-04-08 16:38:48 +00001801Sema::BuildQualifiedDeclarationNameExpr(CXXScopeSpec &SS,
Abramo Bagnarad6d2f182010-08-11 22:01:17 +00001802 const DeclarationNameInfo &NameInfo) {
John McCalle66edc12009-11-24 19:00:30 +00001803 DeclContext *DC;
Douglas Gregora02bb342010-04-28 07:04:26 +00001804 if (!(DC = computeDeclContext(SS, false)) || DC->isDependentContext())
Abramo Bagnara65f7c3d2012-02-06 14:31:00 +00001805 return BuildDependentDeclRefExpr(SS, /*TemplateKWLoc=*/SourceLocation(),
1806 NameInfo, /*TemplateArgs=*/0);
John McCalle66edc12009-11-24 19:00:30 +00001807
John McCall0b66eb32010-05-01 00:40:08 +00001808 if (RequireCompleteDeclContext(SS, DC))
Douglas Gregora02bb342010-04-28 07:04:26 +00001809 return ExprError();
1810
Abramo Bagnarad6d2f182010-08-11 22:01:17 +00001811 LookupResult R(*this, NameInfo, LookupOrdinaryName);
John McCalle66edc12009-11-24 19:00:30 +00001812 LookupQualifiedName(R, DC);
1813
1814 if (R.isAmbiguous())
1815 return ExprError();
1816
1817 if (R.empty()) {
Abramo Bagnarad6d2f182010-08-11 22:01:17 +00001818 Diag(NameInfo.getLoc(), diag::err_no_member)
1819 << NameInfo.getName() << DC << SS.getRange();
John McCalle66edc12009-11-24 19:00:30 +00001820 return ExprError();
1821 }
1822
1823 return BuildDeclarationNameExpr(SS, R, /*ADL*/ false);
1824}
1825
1826/// LookupInObjCMethod - The parser has read a name in, and Sema has
1827/// detected that we're currently inside an ObjC method. Perform some
1828/// additional lookup.
1829///
1830/// Ideally, most of this would be done by lookup, but there's
1831/// actually quite a lot of extra work involved.
1832///
1833/// Returns a null sentinel to indicate trivial success.
John McCalldadc5752010-08-24 06:29:42 +00001834ExprResult
John McCalle66edc12009-11-24 19:00:30 +00001835Sema::LookupInObjCMethod(LookupResult &Lookup, Scope *S,
Chris Lattnera36ec422010-04-11 08:28:14 +00001836 IdentifierInfo *II, bool AllowBuiltinCreation) {
John McCalle66edc12009-11-24 19:00:30 +00001837 SourceLocation Loc = Lookup.getNameLoc();
Chris Lattner87313662010-04-12 05:10:17 +00001838 ObjCMethodDecl *CurMethod = getCurMethodDecl();
Alexis Huntc46382e2010-04-28 23:02:27 +00001839
John McCalle66edc12009-11-24 19:00:30 +00001840 // There are two cases to handle here. 1) scoped lookup could have failed,
1841 // in which case we should look for an ivar. 2) scoped lookup could have
1842 // found a decl, but that decl is outside the current instance method (i.e.
1843 // a global variable). In these two cases, we do a lookup for an ivar with
1844 // this name, if the lookup sucedes, we replace it our current decl.
1845
1846 // If we're in a class method, we don't normally want to look for
1847 // ivars. But if we don't find anything else, and there's an
1848 // ivar, that's an error.
Chris Lattner87313662010-04-12 05:10:17 +00001849 bool IsClassMethod = CurMethod->isClassMethod();
John McCalle66edc12009-11-24 19:00:30 +00001850
1851 bool LookForIvars;
1852 if (Lookup.empty())
1853 LookForIvars = true;
1854 else if (IsClassMethod)
1855 LookForIvars = false;
1856 else
1857 LookForIvars = (Lookup.isSingleResult() &&
1858 Lookup.getFoundDecl()->isDefinedOutsideFunctionOrMethod());
Fariborz Jahanian45878032010-02-09 19:31:38 +00001859 ObjCInterfaceDecl *IFace = 0;
John McCalle66edc12009-11-24 19:00:30 +00001860 if (LookForIvars) {
Chris Lattner87313662010-04-12 05:10:17 +00001861 IFace = CurMethod->getClassInterface();
John McCalle66edc12009-11-24 19:00:30 +00001862 ObjCInterfaceDecl *ClassDeclared;
Argyrios Kyrtzidis4e8b1362011-10-19 02:25:16 +00001863 ObjCIvarDecl *IV = 0;
1864 if (IFace && (IV = IFace->lookupInstanceVariable(II, ClassDeclared))) {
John McCalle66edc12009-11-24 19:00:30 +00001865 // Diagnose using an ivar in a class method.
1866 if (IsClassMethod)
1867 return ExprError(Diag(Loc, diag::error_ivar_use_in_class_method)
1868 << IV->getDeclName());
1869
1870 // If we're referencing an invalid decl, just return this as a silent
1871 // error node. The error diagnostic was already emitted on the decl.
1872 if (IV->isInvalidDecl())
1873 return ExprError();
1874
1875 // Check if referencing a field with __attribute__((deprecated)).
1876 if (DiagnoseUseOfDecl(IV, Loc))
1877 return ExprError();
1878
1879 // Diagnose the use of an ivar outside of the declaring class.
1880 if (IV->getAccessControl() == ObjCIvarDecl::Private &&
Fariborz Jahaniand6cb4a82012-03-07 00:58:41 +00001881 !declaresSameEntity(ClassDeclared, IFace) &&
David Blaikiebbafb8a2012-03-11 07:00:24 +00001882 !getLangOpts().DebuggerSupport)
John McCalle66edc12009-11-24 19:00:30 +00001883 Diag(Loc, diag::error_private_ivar_access) << IV->getDeclName();
1884
1885 // FIXME: This should use a new expr for a direct reference, don't
1886 // turn this into Self->ivar, just return a BareIVarExpr or something.
1887 IdentifierInfo &II = Context.Idents.get("self");
1888 UnqualifiedId SelfName;
Kovarththanan Rajaratnamba2c6522010-03-13 10:17:05 +00001889 SelfName.setIdentifier(&II, SourceLocation());
Fariborz Jahanian7f4427f2011-07-12 17:16:56 +00001890 SelfName.setKind(UnqualifiedId::IK_ImplicitSelfParam);
John McCalle66edc12009-11-24 19:00:30 +00001891 CXXScopeSpec SelfScopeSpec;
Abramo Bagnara7945c982012-01-27 09:46:47 +00001892 SourceLocation TemplateKWLoc;
1893 ExprResult SelfExpr = ActOnIdExpression(S, SelfScopeSpec, TemplateKWLoc,
Douglas Gregora1ed39b2010-09-22 16:33:13 +00001894 SelfName, false, false);
1895 if (SelfExpr.isInvalid())
1896 return ExprError();
1897
John Wiegley01296292011-04-08 18:41:53 +00001898 SelfExpr = DefaultLvalueConversion(SelfExpr.take());
1899 if (SelfExpr.isInvalid())
1900 return ExprError();
John McCall27584242010-12-06 20:48:59 +00001901
Eli Friedmanfa0df832012-02-02 03:46:19 +00001902 MarkAnyDeclReferenced(Loc, IV);
John McCalle66edc12009-11-24 19:00:30 +00001903 return Owned(new (Context)
1904 ObjCIvarRefExpr(IV, IV->getType(), Loc,
John Wiegley01296292011-04-08 18:41:53 +00001905 SelfExpr.take(), true, true));
John McCalle66edc12009-11-24 19:00:30 +00001906 }
Chris Lattner87313662010-04-12 05:10:17 +00001907 } else if (CurMethod->isInstanceMethod()) {
John McCalle66edc12009-11-24 19:00:30 +00001908 // We should warn if a local variable hides an ivar.
Fariborz Jahanian557fc9a2011-11-08 22:51:27 +00001909 if (ObjCInterfaceDecl *IFace = CurMethod->getClassInterface()) {
1910 ObjCInterfaceDecl *ClassDeclared;
1911 if (ObjCIvarDecl *IV = IFace->lookupInstanceVariable(II, ClassDeclared)) {
1912 if (IV->getAccessControl() != ObjCIvarDecl::Private ||
Douglas Gregor0b144e12011-12-15 00:29:59 +00001913 declaresSameEntity(IFace, ClassDeclared))
Fariborz Jahanian557fc9a2011-11-08 22:51:27 +00001914 Diag(Loc, diag::warn_ivar_use_hidden) << IV->getDeclName();
1915 }
John McCalle66edc12009-11-24 19:00:30 +00001916 }
Fariborz Jahanian028b9e12011-12-20 22:21:08 +00001917 } else if (Lookup.isSingleResult() &&
1918 Lookup.getFoundDecl()->isDefinedOutsideFunctionOrMethod()) {
1919 // If accessing a stand-alone ivar in a class method, this is an error.
1920 if (const ObjCIvarDecl *IV = dyn_cast<ObjCIvarDecl>(Lookup.getFoundDecl()))
1921 return ExprError(Diag(Loc, diag::error_ivar_use_in_class_method)
1922 << IV->getDeclName());
John McCalle66edc12009-11-24 19:00:30 +00001923 }
1924
Fariborz Jahanian6fada5b2010-01-12 23:58:59 +00001925 if (Lookup.empty() && II && AllowBuiltinCreation) {
1926 // FIXME. Consolidate this with similar code in LookupName.
1927 if (unsigned BuiltinID = II->getBuiltinID()) {
David Blaikiebbafb8a2012-03-11 07:00:24 +00001928 if (!(getLangOpts().CPlusPlus &&
Fariborz Jahanian6fada5b2010-01-12 23:58:59 +00001929 Context.BuiltinInfo.isPredefinedLibFunction(BuiltinID))) {
1930 NamedDecl *D = LazilyCreateBuiltin((IdentifierInfo *)II, BuiltinID,
1931 S, Lookup.isForRedeclaration(),
1932 Lookup.getNameLoc());
1933 if (D) Lookup.addDecl(D);
1934 }
1935 }
1936 }
John McCalle66edc12009-11-24 19:00:30 +00001937 // Sentinel value saying that we didn't do anything special.
1938 return Owned((Expr*) 0);
Douglas Gregor3256d042009-06-30 15:47:41 +00001939}
John McCalld14a8642009-11-21 08:51:07 +00001940
John McCall16df1e52010-03-30 21:47:33 +00001941/// \brief Cast a base object to a member's actual type.
1942///
1943/// Logically this happens in three phases:
1944///
1945/// * First we cast from the base type to the naming class.
1946/// The naming class is the class into which we were looking
1947/// when we found the member; it's the qualifier type if a
1948/// qualifier was provided, and otherwise it's the base type.
1949///
1950/// * Next we cast from the naming class to the declaring class.
1951/// If the member we found was brought into a class's scope by
1952/// a using declaration, this is that class; otherwise it's
1953/// the class declaring the member.
1954///
1955/// * Finally we cast from the declaring class to the "true"
1956/// declaring class of the member. This conversion does not
1957/// obey access control.
John Wiegley01296292011-04-08 18:41:53 +00001958ExprResult
1959Sema::PerformObjectMemberConversion(Expr *From,
Douglas Gregorcc3f3252010-03-03 23:55:11 +00001960 NestedNameSpecifier *Qualifier,
John McCall16df1e52010-03-30 21:47:33 +00001961 NamedDecl *FoundDecl,
Douglas Gregorcc3f3252010-03-03 23:55:11 +00001962 NamedDecl *Member) {
1963 CXXRecordDecl *RD = dyn_cast<CXXRecordDecl>(Member->getDeclContext());
1964 if (!RD)
John Wiegley01296292011-04-08 18:41:53 +00001965 return Owned(From);
Kovarththanan Rajaratnamba2c6522010-03-13 10:17:05 +00001966
Douglas Gregorcc3f3252010-03-03 23:55:11 +00001967 QualType DestRecordType;
1968 QualType DestType;
1969 QualType FromRecordType;
1970 QualType FromType = From->getType();
1971 bool PointerConversions = false;
1972 if (isa<FieldDecl>(Member)) {
1973 DestRecordType = Context.getCanonicalType(Context.getTypeDeclType(RD));
Kovarththanan Rajaratnamba2c6522010-03-13 10:17:05 +00001974
Douglas Gregorcc3f3252010-03-03 23:55:11 +00001975 if (FromType->getAs<PointerType>()) {
1976 DestType = Context.getPointerType(DestRecordType);
1977 FromRecordType = FromType->getPointeeType();
1978 PointerConversions = true;
1979 } else {
1980 DestType = DestRecordType;
1981 FromRecordType = FromType;
Fariborz Jahanianbb67b822009-07-29 18:40:24 +00001982 }
Douglas Gregorcc3f3252010-03-03 23:55:11 +00001983 } else if (CXXMethodDecl *Method = dyn_cast<CXXMethodDecl>(Member)) {
1984 if (Method->isStatic())
John Wiegley01296292011-04-08 18:41:53 +00001985 return Owned(From);
Kovarththanan Rajaratnamba2c6522010-03-13 10:17:05 +00001986
Douglas Gregorcc3f3252010-03-03 23:55:11 +00001987 DestType = Method->getThisType(Context);
1988 DestRecordType = DestType->getPointeeType();
Kovarththanan Rajaratnamba2c6522010-03-13 10:17:05 +00001989
Douglas Gregorcc3f3252010-03-03 23:55:11 +00001990 if (FromType->getAs<PointerType>()) {
1991 FromRecordType = FromType->getPointeeType();
1992 PointerConversions = true;
1993 } else {
1994 FromRecordType = FromType;
1995 DestType = DestRecordType;
1996 }
1997 } else {
1998 // No conversion necessary.
John Wiegley01296292011-04-08 18:41:53 +00001999 return Owned(From);
Douglas Gregorcc3f3252010-03-03 23:55:11 +00002000 }
Kovarththanan Rajaratnamba2c6522010-03-13 10:17:05 +00002001
Douglas Gregorcc3f3252010-03-03 23:55:11 +00002002 if (DestType->isDependentType() || FromType->isDependentType())
John Wiegley01296292011-04-08 18:41:53 +00002003 return Owned(From);
Kovarththanan Rajaratnamba2c6522010-03-13 10:17:05 +00002004
Douglas Gregorcc3f3252010-03-03 23:55:11 +00002005 // If the unqualified types are the same, no conversion is necessary.
2006 if (Context.hasSameUnqualifiedType(FromRecordType, DestRecordType))
John Wiegley01296292011-04-08 18:41:53 +00002007 return Owned(From);
Kovarththanan Rajaratnamba2c6522010-03-13 10:17:05 +00002008
John McCall16df1e52010-03-30 21:47:33 +00002009 SourceRange FromRange = From->getSourceRange();
2010 SourceLocation FromLoc = FromRange.getBegin();
2011
Eli Friedmanbe4b3632011-09-27 21:58:52 +00002012 ExprValueKind VK = From->getValueKind();
Sebastian Redlc57d34b2010-07-20 04:20:21 +00002013
Douglas Gregorcc3f3252010-03-03 23:55:11 +00002014 // C++ [class.member.lookup]p8:
Kovarththanan Rajaratnamba2c6522010-03-13 10:17:05 +00002015 // [...] Ambiguities can often be resolved by qualifying a name with its
Douglas Gregorcc3f3252010-03-03 23:55:11 +00002016 // class name.
2017 //
2018 // If the member was a qualified name and the qualified referred to a
2019 // specific base subobject type, we'll cast to that intermediate type
2020 // first and then to the object in which the member is declared. That allows
2021 // one to resolve ambiguities in, e.g., a diamond-shaped hierarchy such as:
2022 //
2023 // class Base { public: int x; };
2024 // class Derived1 : public Base { };
2025 // class Derived2 : public Base { };
2026 // class VeryDerived : public Derived1, public Derived2 { void f(); };
2027 //
2028 // void VeryDerived::f() {
2029 // x = 17; // error: ambiguous base subobjects
2030 // Derived1::x = 17; // okay, pick the Base subobject of Derived1
2031 // }
Douglas Gregorcc3f3252010-03-03 23:55:11 +00002032 if (Qualifier) {
John McCall16df1e52010-03-30 21:47:33 +00002033 QualType QType = QualType(Qualifier->getAsType(), 0);
2034 assert(!QType.isNull() && "lookup done with dependent qualifier?");
2035 assert(QType->isRecordType() && "lookup done with non-record type");
2036
2037 QualType QRecordType = QualType(QType->getAs<RecordType>(), 0);
2038
2039 // In C++98, the qualifier type doesn't actually have to be a base
2040 // type of the object type, in which case we just ignore it.
2041 // Otherwise build the appropriate casts.
2042 if (IsDerivedFrom(FromRecordType, QRecordType)) {
John McCallcf142162010-08-07 06:22:56 +00002043 CXXCastPath BasePath;
John McCall16df1e52010-03-30 21:47:33 +00002044 if (CheckDerivedToBaseConversion(FromRecordType, QRecordType,
Anders Carlssonb78feca2010-04-24 19:22:20 +00002045 FromLoc, FromRange, &BasePath))
John Wiegley01296292011-04-08 18:41:53 +00002046 return ExprError();
John McCall16df1e52010-03-30 21:47:33 +00002047
Douglas Gregorcc3f3252010-03-03 23:55:11 +00002048 if (PointerConversions)
John McCall16df1e52010-03-30 21:47:33 +00002049 QType = Context.getPointerType(QType);
John Wiegley01296292011-04-08 18:41:53 +00002050 From = ImpCastExprToType(From, QType, CK_UncheckedDerivedToBase,
2051 VK, &BasePath).take();
John McCall16df1e52010-03-30 21:47:33 +00002052
2053 FromType = QType;
2054 FromRecordType = QRecordType;
2055
2056 // If the qualifier type was the same as the destination type,
2057 // we're done.
2058 if (Context.hasSameUnqualifiedType(FromRecordType, DestRecordType))
John Wiegley01296292011-04-08 18:41:53 +00002059 return Owned(From);
Douglas Gregorcc3f3252010-03-03 23:55:11 +00002060 }
2061 }
Kovarththanan Rajaratnamba2c6522010-03-13 10:17:05 +00002062
John McCall16df1e52010-03-30 21:47:33 +00002063 bool IgnoreAccess = false;
Douglas Gregorcc3f3252010-03-03 23:55:11 +00002064
John McCall16df1e52010-03-30 21:47:33 +00002065 // If we actually found the member through a using declaration, cast
2066 // down to the using declaration's type.
2067 //
2068 // Pointer equality is fine here because only one declaration of a
2069 // class ever has member declarations.
2070 if (FoundDecl->getDeclContext() != Member->getDeclContext()) {
2071 assert(isa<UsingShadowDecl>(FoundDecl));
2072 QualType URecordType = Context.getTypeDeclType(
2073 cast<CXXRecordDecl>(FoundDecl->getDeclContext()));
2074
2075 // We only need to do this if the naming-class to declaring-class
2076 // conversion is non-trivial.
2077 if (!Context.hasSameUnqualifiedType(FromRecordType, URecordType)) {
2078 assert(IsDerivedFrom(FromRecordType, URecordType));
John McCallcf142162010-08-07 06:22:56 +00002079 CXXCastPath BasePath;
John McCall16df1e52010-03-30 21:47:33 +00002080 if (CheckDerivedToBaseConversion(FromRecordType, URecordType,
Anders Carlssonb78feca2010-04-24 19:22:20 +00002081 FromLoc, FromRange, &BasePath))
John Wiegley01296292011-04-08 18:41:53 +00002082 return ExprError();
Alexis Huntc46382e2010-04-28 23:02:27 +00002083
John McCall16df1e52010-03-30 21:47:33 +00002084 QualType UType = URecordType;
2085 if (PointerConversions)
2086 UType = Context.getPointerType(UType);
John Wiegley01296292011-04-08 18:41:53 +00002087 From = ImpCastExprToType(From, UType, CK_UncheckedDerivedToBase,
2088 VK, &BasePath).take();
John McCall16df1e52010-03-30 21:47:33 +00002089 FromType = UType;
2090 FromRecordType = URecordType;
2091 }
2092
2093 // We don't do access control for the conversion from the
2094 // declaring class to the true declaring class.
2095 IgnoreAccess = true;
Douglas Gregorcc3f3252010-03-03 23:55:11 +00002096 }
Kovarththanan Rajaratnamba2c6522010-03-13 10:17:05 +00002097
John McCallcf142162010-08-07 06:22:56 +00002098 CXXCastPath BasePath;
Anders Carlssonb78feca2010-04-24 19:22:20 +00002099 if (CheckDerivedToBaseConversion(FromRecordType, DestRecordType,
2100 FromLoc, FromRange, &BasePath,
John McCall16df1e52010-03-30 21:47:33 +00002101 IgnoreAccess))
John Wiegley01296292011-04-08 18:41:53 +00002102 return ExprError();
Kovarththanan Rajaratnamba2c6522010-03-13 10:17:05 +00002103
John Wiegley01296292011-04-08 18:41:53 +00002104 return ImpCastExprToType(From, DestType, CK_UncheckedDerivedToBase,
2105 VK, &BasePath);
Fariborz Jahanianbb67b822009-07-29 18:40:24 +00002106}
Douglas Gregor3256d042009-06-30 15:47:41 +00002107
John McCalle66edc12009-11-24 19:00:30 +00002108bool Sema::UseArgumentDependentLookup(const CXXScopeSpec &SS,
John McCallb53bbd42009-11-22 01:44:31 +00002109 const LookupResult &R,
2110 bool HasTrailingLParen) {
John McCalld14a8642009-11-21 08:51:07 +00002111 // Only when used directly as the postfix-expression of a call.
2112 if (!HasTrailingLParen)
2113 return false;
2114
2115 // Never if a scope specifier was provided.
John McCalle66edc12009-11-24 19:00:30 +00002116 if (SS.isSet())
John McCalld14a8642009-11-21 08:51:07 +00002117 return false;
2118
2119 // Only in C++ or ObjC++.
David Blaikiebbafb8a2012-03-11 07:00:24 +00002120 if (!getLangOpts().CPlusPlus)
John McCalld14a8642009-11-21 08:51:07 +00002121 return false;
2122
2123 // Turn off ADL when we find certain kinds of declarations during
2124 // normal lookup:
2125 for (LookupResult::iterator I = R.begin(), E = R.end(); I != E; ++I) {
2126 NamedDecl *D = *I;
2127
2128 // C++0x [basic.lookup.argdep]p3:
2129 // -- a declaration of a class member
2130 // Since using decls preserve this property, we check this on the
2131 // original decl.
John McCall57500772009-12-16 12:17:52 +00002132 if (D->isCXXClassMember())
John McCalld14a8642009-11-21 08:51:07 +00002133 return false;
2134
2135 // C++0x [basic.lookup.argdep]p3:
2136 // -- a block-scope function declaration that is not a
2137 // using-declaration
2138 // NOTE: we also trigger this for function templates (in fact, we
2139 // don't check the decl type at all, since all other decl types
2140 // turn off ADL anyway).
2141 if (isa<UsingShadowDecl>(D))
2142 D = cast<UsingShadowDecl>(D)->getTargetDecl();
2143 else if (D->getDeclContext()->isFunctionOrMethod())
2144 return false;
2145
2146 // C++0x [basic.lookup.argdep]p3:
2147 // -- a declaration that is neither a function or a function
2148 // template
2149 // And also for builtin functions.
2150 if (isa<FunctionDecl>(D)) {
2151 FunctionDecl *FDecl = cast<FunctionDecl>(D);
2152
2153 // But also builtin functions.
2154 if (FDecl->getBuiltinID() && FDecl->isImplicit())
2155 return false;
2156 } else if (!isa<FunctionTemplateDecl>(D))
2157 return false;
2158 }
2159
2160 return true;
2161}
2162
2163
John McCalld14a8642009-11-21 08:51:07 +00002164/// Diagnoses obvious problems with the use of the given declaration
2165/// as an expression. This is only actually called for lookups that
2166/// were not overloaded, and it doesn't promise that the declaration
2167/// will in fact be used.
2168static bool CheckDeclInExpr(Sema &S, SourceLocation Loc, NamedDecl *D) {
Richard Smithdda56e42011-04-15 14:24:37 +00002169 if (isa<TypedefNameDecl>(D)) {
John McCalld14a8642009-11-21 08:51:07 +00002170 S.Diag(Loc, diag::err_unexpected_typedef) << D->getDeclName();
2171 return true;
2172 }
2173
2174 if (isa<ObjCInterfaceDecl>(D)) {
2175 S.Diag(Loc, diag::err_unexpected_interface) << D->getDeclName();
2176 return true;
2177 }
2178
2179 if (isa<NamespaceDecl>(D)) {
2180 S.Diag(Loc, diag::err_unexpected_namespace) << D->getDeclName();
2181 return true;
2182 }
2183
2184 return false;
2185}
2186
John McCalldadc5752010-08-24 06:29:42 +00002187ExprResult
John McCalle66edc12009-11-24 19:00:30 +00002188Sema::BuildDeclarationNameExpr(const CXXScopeSpec &SS,
John McCallb53bbd42009-11-22 01:44:31 +00002189 LookupResult &R,
2190 bool NeedsADL) {
John McCall3a60c872009-12-08 22:45:53 +00002191 // If this is a single, fully-resolved result and we don't need ADL,
2192 // just build an ordinary singleton decl ref.
Douglas Gregor4b4844f2010-01-29 17:15:43 +00002193 if (!NeedsADL && R.isSingleResult() && !R.getAsSingle<FunctionTemplateDecl>())
Abramo Bagnarad6d2f182010-08-11 22:01:17 +00002194 return BuildDeclarationNameExpr(SS, R.getLookupNameInfo(),
2195 R.getFoundDecl());
John McCalld14a8642009-11-21 08:51:07 +00002196
2197 // We only need to check the declaration if there's exactly one
2198 // result, because in the overloaded case the results can only be
2199 // functions and function templates.
John McCallb53bbd42009-11-22 01:44:31 +00002200 if (R.isSingleResult() &&
2201 CheckDeclInExpr(*this, R.getNameLoc(), R.getFoundDecl()))
John McCalld14a8642009-11-21 08:51:07 +00002202 return ExprError();
2203
John McCall58cc69d2010-01-27 01:50:18 +00002204 // Otherwise, just build an unresolved lookup expression. Suppress
2205 // any lookup-related diagnostics; we'll hash these out later, when
2206 // we've picked a target.
2207 R.suppressDiagnostics();
2208
John McCalld14a8642009-11-21 08:51:07 +00002209 UnresolvedLookupExpr *ULE
Douglas Gregora6e053e2010-12-15 01:34:56 +00002210 = UnresolvedLookupExpr::Create(Context, R.getNamingClass(),
Douglas Gregor0da1d432011-02-28 20:01:57 +00002211 SS.getWithLocInContext(Context),
2212 R.getLookupNameInfo(),
Douglas Gregor30a4f4c2010-05-23 18:57:34 +00002213 NeedsADL, R.isOverloadedResult(),
2214 R.begin(), R.end());
John McCalld14a8642009-11-21 08:51:07 +00002215
2216 return Owned(ULE);
2217}
Kovarththanan Rajaratnamba2c6522010-03-13 10:17:05 +00002218
John McCalld14a8642009-11-21 08:51:07 +00002219/// \brief Complete semantic analysis for a reference to the given declaration.
John McCalldadc5752010-08-24 06:29:42 +00002220ExprResult
John McCalle66edc12009-11-24 19:00:30 +00002221Sema::BuildDeclarationNameExpr(const CXXScopeSpec &SS,
Abramo Bagnarad6d2f182010-08-11 22:01:17 +00002222 const DeclarationNameInfo &NameInfo,
2223 NamedDecl *D) {
John McCalld14a8642009-11-21 08:51:07 +00002224 assert(D && "Cannot refer to a NULL declaration");
John McCall283b9012009-11-22 00:44:51 +00002225 assert(!isa<FunctionTemplateDecl>(D) &&
2226 "Cannot refer unambiguously to a function template");
John McCalld14a8642009-11-21 08:51:07 +00002227
Abramo Bagnarad6d2f182010-08-11 22:01:17 +00002228 SourceLocation Loc = NameInfo.getLoc();
John McCalld14a8642009-11-21 08:51:07 +00002229 if (CheckDeclInExpr(*this, Loc, D))
2230 return ExprError();
Steve Narofff1e53692007-03-23 22:27:02 +00002231
Douglas Gregore7488b92009-12-01 16:58:18 +00002232 if (TemplateDecl *Template = dyn_cast<TemplateDecl>(D)) {
2233 // Specifically diagnose references to class templates that are missing
2234 // a template argument list.
2235 Diag(Loc, diag::err_template_decl_ref)
2236 << Template << SS.getRange();
2237 Diag(Template->getLocation(), diag::note_template_decl_here);
2238 return ExprError();
2239 }
2240
2241 // Make sure that we're referring to a value.
2242 ValueDecl *VD = dyn_cast<ValueDecl>(D);
2243 if (!VD) {
Kovarththanan Rajaratnamba2c6522010-03-13 10:17:05 +00002244 Diag(Loc, diag::err_ref_non_value)
Douglas Gregore7488b92009-12-01 16:58:18 +00002245 << D << SS.getRange();
John McCallb48971d2009-12-18 18:35:10 +00002246 Diag(D->getLocation(), diag::note_declared_at);
Douglas Gregore7488b92009-12-01 16:58:18 +00002247 return ExprError();
2248 }
Sebastian Redlffbcf962009-01-18 18:53:16 +00002249
Douglas Gregor171c45a2009-02-18 21:56:37 +00002250 // Check whether this declaration can be used. Note that we suppress
2251 // this check when we're going to perform argument-dependent lookup
2252 // on this function name, because this might not be the function
2253 // that overload resolution actually selects.
John McCalld14a8642009-11-21 08:51:07 +00002254 if (DiagnoseUseOfDecl(VD, Loc))
Douglas Gregor171c45a2009-02-18 21:56:37 +00002255 return ExprError();
2256
Steve Naroff8de9c3a2008-09-05 22:11:13 +00002257 // Only create DeclRefExpr's for valid Decl's.
2258 if (VD->isInvalidDecl())
Sebastian Redlffbcf962009-01-18 18:53:16 +00002259 return ExprError();
2260
John McCallf3a88602011-02-03 08:15:49 +00002261 // Handle members of anonymous structs and unions. If we got here,
2262 // and the reference is to a class member indirect field, then this
2263 // must be the subject of a pointer-to-member expression.
2264 if (IndirectFieldDecl *indirectField = dyn_cast<IndirectFieldDecl>(VD))
2265 if (!indirectField->isCXXClassMember())
2266 return BuildAnonymousStructUnionMemberReference(SS, NameInfo.getLoc(),
2267 indirectField);
Francois Pichet783dd6e2010-11-21 06:08:52 +00002268
Eli Friedman9bb33f52012-02-03 02:04:35 +00002269 {
John McCallf4cd4f92011-02-09 01:13:10 +00002270 QualType type = VD->getType();
Daniel Dunbar7c2dc362011-02-10 18:29:28 +00002271 ExprValueKind valueKind = VK_RValue;
John McCallf4cd4f92011-02-09 01:13:10 +00002272
2273 switch (D->getKind()) {
2274 // Ignore all the non-ValueDecl kinds.
2275#define ABSTRACT_DECL(kind)
2276#define VALUE(type, base)
2277#define DECL(type, base) \
2278 case Decl::type:
2279#include "clang/AST/DeclNodes.inc"
2280 llvm_unreachable("invalid value decl kind");
John McCallf4cd4f92011-02-09 01:13:10 +00002281
2282 // These shouldn't make it here.
2283 case Decl::ObjCAtDefsField:
2284 case Decl::ObjCIvar:
2285 llvm_unreachable("forming non-member reference to ivar?");
John McCallf4cd4f92011-02-09 01:13:10 +00002286
2287 // Enum constants are always r-values and never references.
2288 // Unresolved using declarations are dependent.
2289 case Decl::EnumConstant:
2290 case Decl::UnresolvedUsingValue:
2291 valueKind = VK_RValue;
2292 break;
2293
2294 // Fields and indirect fields that got here must be for
2295 // pointer-to-member expressions; we just call them l-values for
2296 // internal consistency, because this subexpression doesn't really
2297 // exist in the high-level semantics.
2298 case Decl::Field:
2299 case Decl::IndirectField:
David Blaikiebbafb8a2012-03-11 07:00:24 +00002300 assert(getLangOpts().CPlusPlus &&
John McCallf4cd4f92011-02-09 01:13:10 +00002301 "building reference to field in C?");
2302
2303 // These can't have reference type in well-formed programs, but
2304 // for internal consistency we do this anyway.
2305 type = type.getNonReferenceType();
2306 valueKind = VK_LValue;
2307 break;
2308
2309 // Non-type template parameters are either l-values or r-values
2310 // depending on the type.
2311 case Decl::NonTypeTemplateParm: {
2312 if (const ReferenceType *reftype = type->getAs<ReferenceType>()) {
2313 type = reftype->getPointeeType();
2314 valueKind = VK_LValue; // even if the parameter is an r-value reference
2315 break;
2316 }
2317
2318 // For non-references, we need to strip qualifiers just in case
2319 // the template parameter was declared as 'const int' or whatever.
2320 valueKind = VK_RValue;
2321 type = type.getUnqualifiedType();
2322 break;
2323 }
2324
2325 case Decl::Var:
2326 // In C, "extern void blah;" is valid and is an r-value.
David Blaikiebbafb8a2012-03-11 07:00:24 +00002327 if (!getLangOpts().CPlusPlus &&
John McCallf4cd4f92011-02-09 01:13:10 +00002328 !type.hasQualifiers() &&
2329 type->isVoidType()) {
2330 valueKind = VK_RValue;
2331 break;
2332 }
2333 // fallthrough
2334
2335 case Decl::ImplicitParam:
Douglas Gregor812d8f62012-02-18 05:51:20 +00002336 case Decl::ParmVar: {
John McCallf4cd4f92011-02-09 01:13:10 +00002337 // These are always l-values.
2338 valueKind = VK_LValue;
2339 type = type.getNonReferenceType();
Eli Friedman9bb33f52012-02-03 02:04:35 +00002340
Douglas Gregor812d8f62012-02-18 05:51:20 +00002341 // FIXME: Does the addition of const really only apply in
2342 // potentially-evaluated contexts? Since the variable isn't actually
2343 // captured in an unevaluated context, it seems that the answer is no.
2344 if (ExprEvalContexts.back().Context != Sema::Unevaluated) {
2345 QualType CapturedType = getCapturedDeclRefType(cast<VarDecl>(VD), Loc);
2346 if (!CapturedType.isNull())
2347 type = CapturedType;
2348 }
2349
John McCallf4cd4f92011-02-09 01:13:10 +00002350 break;
Douglas Gregor812d8f62012-02-18 05:51:20 +00002351 }
2352
John McCallf4cd4f92011-02-09 01:13:10 +00002353 case Decl::Function: {
John McCall2979fe02011-04-12 00:42:48 +00002354 const FunctionType *fty = type->castAs<FunctionType>();
2355
2356 // If we're referring to a function with an __unknown_anytype
2357 // result type, make the entire expression __unknown_anytype.
2358 if (fty->getResultType() == Context.UnknownAnyTy) {
2359 type = Context.UnknownAnyTy;
2360 valueKind = VK_RValue;
2361 break;
2362 }
2363
John McCallf4cd4f92011-02-09 01:13:10 +00002364 // Functions are l-values in C++.
David Blaikiebbafb8a2012-03-11 07:00:24 +00002365 if (getLangOpts().CPlusPlus) {
John McCallf4cd4f92011-02-09 01:13:10 +00002366 valueKind = VK_LValue;
2367 break;
2368 }
2369
2370 // C99 DR 316 says that, if a function type comes from a
2371 // function definition (without a prototype), that type is only
2372 // used for checking compatibility. Therefore, when referencing
2373 // the function, we pretend that we don't have the full function
2374 // type.
John McCall2979fe02011-04-12 00:42:48 +00002375 if (!cast<FunctionDecl>(VD)->hasPrototype() &&
2376 isa<FunctionProtoType>(fty))
2377 type = Context.getFunctionNoProtoType(fty->getResultType(),
2378 fty->getExtInfo());
John McCallf4cd4f92011-02-09 01:13:10 +00002379
2380 // Functions are r-values in C.
2381 valueKind = VK_RValue;
2382 break;
2383 }
2384
2385 case Decl::CXXMethod:
John McCall2979fe02011-04-12 00:42:48 +00002386 // If we're referring to a method with an __unknown_anytype
2387 // result type, make the entire expression __unknown_anytype.
2388 // This should only be possible with a type written directly.
Richard Trieucfc491d2011-08-02 04:35:43 +00002389 if (const FunctionProtoType *proto
2390 = dyn_cast<FunctionProtoType>(VD->getType()))
John McCall2979fe02011-04-12 00:42:48 +00002391 if (proto->getResultType() == Context.UnknownAnyTy) {
2392 type = Context.UnknownAnyTy;
2393 valueKind = VK_RValue;
2394 break;
2395 }
2396
John McCallf4cd4f92011-02-09 01:13:10 +00002397 // C++ methods are l-values if static, r-values if non-static.
2398 if (cast<CXXMethodDecl>(VD)->isStatic()) {
2399 valueKind = VK_LValue;
2400 break;
2401 }
2402 // fallthrough
2403
2404 case Decl::CXXConversion:
2405 case Decl::CXXDestructor:
2406 case Decl::CXXConstructor:
2407 valueKind = VK_RValue;
2408 break;
2409 }
2410
2411 return BuildDeclRefExpr(VD, type, valueKind, NameInfo, &SS);
2412 }
Chris Lattner17ed4872006-11-20 04:58:19 +00002413}
Chris Lattnere168f762006-11-10 05:29:30 +00002414
John McCall2979fe02011-04-12 00:42:48 +00002415ExprResult Sema::ActOnPredefinedExpr(SourceLocation Loc, tok::TokenKind Kind) {
Chris Lattner6307f192008-08-10 01:53:14 +00002416 PredefinedExpr::IdentType IT;
Sebastian Redlffbcf962009-01-18 18:53:16 +00002417
Chris Lattnere168f762006-11-10 05:29:30 +00002418 switch (Kind) {
David Blaikie83d382b2011-09-23 05:06:16 +00002419 default: llvm_unreachable("Unknown simple primary expr!");
Chris Lattner6307f192008-08-10 01:53:14 +00002420 case tok::kw___func__: IT = PredefinedExpr::Func; break; // [C99 6.4.2.2]
2421 case tok::kw___FUNCTION__: IT = PredefinedExpr::Function; break;
2422 case tok::kw___PRETTY_FUNCTION__: IT = PredefinedExpr::PrettyFunction; break;
Chris Lattnere168f762006-11-10 05:29:30 +00002423 }
Chris Lattner317e6ba2008-01-12 18:39:25 +00002424
Chris Lattnera81a0272008-01-12 08:14:25 +00002425 // Pre-defined identifiers are of type char[x], where x is the length of the
2426 // string.
Mike Stump11289f42009-09-09 15:08:12 +00002427
Anders Carlsson2fb08242009-09-08 18:24:21 +00002428 Decl *currentDecl = getCurFunctionOrMethodDecl();
Fariborz Jahanian94627442010-07-23 21:53:24 +00002429 if (!currentDecl && getCurBlock())
2430 currentDecl = getCurBlock()->TheDecl;
Anders Carlsson2fb08242009-09-08 18:24:21 +00002431 if (!currentDecl) {
Chris Lattnerf45c5ec2008-12-12 05:05:20 +00002432 Diag(Loc, diag::ext_predef_outside_function);
Anders Carlsson2fb08242009-09-08 18:24:21 +00002433 currentDecl = Context.getTranslationUnitDecl();
Chris Lattnerf45c5ec2008-12-12 05:05:20 +00002434 }
Sebastian Redlffbcf962009-01-18 18:53:16 +00002435
Anders Carlsson0b209a82009-09-11 01:22:35 +00002436 QualType ResTy;
2437 if (cast<DeclContext>(currentDecl)->isDependentContext()) {
2438 ResTy = Context.DependentTy;
2439 } else {
Anders Carlsson5bd8d192010-02-11 18:20:28 +00002440 unsigned Length = PredefinedExpr::ComputeName(IT, currentDecl).length();
Sebastian Redlffbcf962009-01-18 18:53:16 +00002441
Anders Carlsson0b209a82009-09-11 01:22:35 +00002442 llvm::APInt LengthI(32, Length + 1);
John McCall8ccfcb52009-09-24 19:53:00 +00002443 ResTy = Context.CharTy.withConst();
Anders Carlsson0b209a82009-09-11 01:22:35 +00002444 ResTy = Context.getConstantArrayType(ResTy, LengthI, ArrayType::Normal, 0);
2445 }
Steve Narofff6009ed2009-01-21 00:14:39 +00002446 return Owned(new (Context) PredefinedExpr(Loc, ResTy, IT));
Chris Lattnere168f762006-11-10 05:29:30 +00002447}
2448
Richard Smithbcc22fc2012-03-09 08:00:36 +00002449ExprResult Sema::ActOnCharacterConstant(const Token &Tok, Scope *UDLScope) {
Dylan Noblesmith2c1dd272012-02-05 02:13:05 +00002450 SmallString<16> CharBuffer;
Douglas Gregordc970f02010-03-16 22:30:13 +00002451 bool Invalid = false;
Chris Lattner0e62c1c2011-07-23 10:55:15 +00002452 StringRef ThisTok = PP.getSpelling(Tok, CharBuffer, &Invalid);
Douglas Gregordc970f02010-03-16 22:30:13 +00002453 if (Invalid)
2454 return ExprError();
Sebastian Redlffbcf962009-01-18 18:53:16 +00002455
Benjamin Kramer0a1abd42010-02-27 13:44:12 +00002456 CharLiteralParser Literal(ThisTok.begin(), ThisTok.end(), Tok.getLocation(),
Douglas Gregorfb65e592011-07-27 05:40:30 +00002457 PP, Tok.getKind());
Steve Naroffae4143e2007-04-26 20:39:23 +00002458 if (Literal.hadError())
Sebastian Redlffbcf962009-01-18 18:53:16 +00002459 return ExprError();
Chris Lattneref24b382008-03-01 08:32:21 +00002460
Chris Lattnerc3847ba2009-12-30 21:19:39 +00002461 QualType Ty;
Seth Cantrell02f86052012-01-18 12:27:06 +00002462 if (Literal.isWide())
2463 Ty = Context.WCharTy; // L'x' -> wchar_t in C and C++.
Douglas Gregorfb65e592011-07-27 05:40:30 +00002464 else if (Literal.isUTF16())
Seth Cantrell02f86052012-01-18 12:27:06 +00002465 Ty = Context.Char16Ty; // u'x' -> char16_t in C11 and C++11.
Douglas Gregorfb65e592011-07-27 05:40:30 +00002466 else if (Literal.isUTF32())
Seth Cantrell02f86052012-01-18 12:27:06 +00002467 Ty = Context.Char32Ty; // U'x' -> char32_t in C11 and C++11.
David Blaikiebbafb8a2012-03-11 07:00:24 +00002468 else if (!getLangOpts().CPlusPlus || Literal.isMultiChar())
Seth Cantrell02f86052012-01-18 12:27:06 +00002469 Ty = Context.IntTy; // 'x' -> int in C, 'wxyz' -> int in C++.
Chris Lattnerc3847ba2009-12-30 21:19:39 +00002470 else
2471 Ty = Context.CharTy; // 'x' -> char in C++
Chris Lattneref24b382008-03-01 08:32:21 +00002472
Douglas Gregorfb65e592011-07-27 05:40:30 +00002473 CharacterLiteral::CharacterKind Kind = CharacterLiteral::Ascii;
2474 if (Literal.isWide())
2475 Kind = CharacterLiteral::Wide;
2476 else if (Literal.isUTF16())
2477 Kind = CharacterLiteral::UTF16;
2478 else if (Literal.isUTF32())
2479 Kind = CharacterLiteral::UTF32;
2480
Richard Smith75b67d62012-03-08 01:34:56 +00002481 Expr *Lit = new (Context) CharacterLiteral(Literal.getValue(), Kind, Ty,
2482 Tok.getLocation());
2483
2484 if (Literal.getUDSuffix().empty())
2485 return Owned(Lit);
2486
2487 // We're building a user-defined literal.
2488 IdentifierInfo *UDSuffix = &Context.Idents.get(Literal.getUDSuffix());
2489 SourceLocation UDSuffixLoc =
2490 getUDSuffixLoc(*this, Tok.getLocation(), Literal.getUDSuffixOffset());
2491
Richard Smithbcc22fc2012-03-09 08:00:36 +00002492 // Make sure we're allowed user-defined literals here.
2493 if (!UDLScope)
2494 return ExprError(Diag(UDSuffixLoc, diag::err_invalid_character_udl));
2495
Richard Smith75b67d62012-03-08 01:34:56 +00002496 // C++11 [lex.ext]p6: The literal L is treated as a call of the form
2497 // operator "" X (ch)
Richard Smithbcc22fc2012-03-09 08:00:36 +00002498 return BuildCookedLiteralOperatorCall(*this, UDLScope, UDSuffix, UDSuffixLoc,
2499 llvm::makeArrayRef(&Lit, 1),
2500 Tok.getLocation());
Steve Naroffae4143e2007-04-26 20:39:23 +00002501}
2502
Ted Kremeneke65b0862012-03-06 20:05:56 +00002503ExprResult Sema::ActOnIntegerConstant(SourceLocation Loc, uint64_t Val) {
2504 unsigned IntSize = Context.getTargetInfo().getIntWidth();
2505 return Owned(IntegerLiteral::Create(Context, llvm::APInt(IntSize, Val),
2506 Context.IntTy, Loc));
2507}
2508
Richard Smith39570d002012-03-08 08:45:32 +00002509static Expr *BuildFloatingLiteral(Sema &S, NumericLiteralParser &Literal,
2510 QualType Ty, SourceLocation Loc) {
2511 const llvm::fltSemantics &Format = S.Context.getFloatTypeSemantics(Ty);
2512
2513 using llvm::APFloat;
2514 APFloat Val(Format);
2515
2516 APFloat::opStatus result = Literal.GetFloatValue(Val);
2517
2518 // Overflow is always an error, but underflow is only an error if
2519 // we underflowed to zero (APFloat reports denormals as underflow).
2520 if ((result & APFloat::opOverflow) ||
2521 ((result & APFloat::opUnderflow) && Val.isZero())) {
2522 unsigned diagnostic;
2523 SmallString<20> buffer;
2524 if (result & APFloat::opOverflow) {
2525 diagnostic = diag::warn_float_overflow;
2526 APFloat::getLargest(Format).toString(buffer);
2527 } else {
2528 diagnostic = diag::warn_float_underflow;
2529 APFloat::getSmallest(Format).toString(buffer);
2530 }
2531
2532 S.Diag(Loc, diagnostic)
2533 << Ty
2534 << StringRef(buffer.data(), buffer.size());
2535 }
2536
2537 bool isExact = (result == APFloat::opOK);
2538 return FloatingLiteral::Create(S.Context, Val, isExact, Ty, Loc);
2539}
2540
Richard Smithbcc22fc2012-03-09 08:00:36 +00002541ExprResult Sema::ActOnNumericConstant(const Token &Tok, Scope *UDLScope) {
Sebastian Redlffbcf962009-01-18 18:53:16 +00002542 // Fast path for a single digit (which is quite common). A single digit
Richard Smithbcc22fc2012-03-09 08:00:36 +00002543 // cannot have a trigraph, escaped newline, radix prefix, or suffix.
Steve Narofff2fb89e2007-03-13 20:29:44 +00002544 if (Tok.getLength() == 1) {
Chris Lattner9240b3e2009-01-26 22:36:52 +00002545 const char Val = PP.getSpellingOfSingleCharacterNumericConstant(Tok);
Ted Kremeneke65b0862012-03-06 20:05:56 +00002546 return ActOnIntegerConstant(Tok.getLocation(), Val-'0');
Steve Narofff2fb89e2007-03-13 20:29:44 +00002547 }
Ted Kremeneke9814182009-01-13 23:19:12 +00002548
Dylan Noblesmith2c1dd272012-02-05 02:13:05 +00002549 SmallString<512> IntegerBuffer;
Chris Lattnera1cf5f92008-09-30 20:53:45 +00002550 // Add padding so that NumericLiteralParser can overread by one character.
2551 IntegerBuffer.resize(Tok.getLength()+1);
Steve Naroff8160ea22007-03-06 01:09:46 +00002552 const char *ThisTokBegin = &IntegerBuffer[0];
Sebastian Redlffbcf962009-01-18 18:53:16 +00002553
Chris Lattner67ca9252007-05-21 01:08:44 +00002554 // Get the spelling of the token, which eliminates trigraphs, etc.
Douglas Gregordc970f02010-03-16 22:30:13 +00002555 bool Invalid = false;
2556 unsigned ActualLength = PP.getSpelling(Tok, ThisTokBegin, &Invalid);
2557 if (Invalid)
2558 return ExprError();
Sebastian Redlffbcf962009-01-18 18:53:16 +00002559
Mike Stump11289f42009-09-09 15:08:12 +00002560 NumericLiteralParser Literal(ThisTokBegin, ThisTokBegin+ActualLength,
Steve Naroff451d8f162007-03-12 23:22:38 +00002561 Tok.getLocation(), PP);
Steve Narofff2fb89e2007-03-13 20:29:44 +00002562 if (Literal.hadError)
Sebastian Redlffbcf962009-01-18 18:53:16 +00002563 return ExprError();
2564
Richard Smith39570d002012-03-08 08:45:32 +00002565 if (Literal.hasUDSuffix()) {
2566 // We're building a user-defined literal.
2567 IdentifierInfo *UDSuffix = &Context.Idents.get(Literal.getUDSuffix());
2568 SourceLocation UDSuffixLoc =
2569 getUDSuffixLoc(*this, Tok.getLocation(), Literal.getUDSuffixOffset());
2570
Richard Smithbcc22fc2012-03-09 08:00:36 +00002571 // Make sure we're allowed user-defined literals here.
2572 if (!UDLScope)
2573 return ExprError(Diag(UDSuffixLoc, diag::err_invalid_numeric_udl));
Richard Smith39570d002012-03-08 08:45:32 +00002574
Richard Smithbcc22fc2012-03-09 08:00:36 +00002575 QualType CookedTy;
Richard Smith39570d002012-03-08 08:45:32 +00002576 if (Literal.isFloatingLiteral()) {
2577 // C++11 [lex.ext]p4: If S contains a literal operator with parameter type
2578 // long double, the literal is treated as a call of the form
2579 // operator "" X (f L)
Richard Smithbcc22fc2012-03-09 08:00:36 +00002580 CookedTy = Context.LongDoubleTy;
Richard Smith39570d002012-03-08 08:45:32 +00002581 } else {
2582 // C++11 [lex.ext]p3: If S contains a literal operator with parameter type
2583 // unsigned long long, the literal is treated as a call of the form
2584 // operator "" X (n ULL)
Richard Smithbcc22fc2012-03-09 08:00:36 +00002585 CookedTy = Context.UnsignedLongLongTy;
Richard Smith39570d002012-03-08 08:45:32 +00002586 }
2587
Richard Smithbcc22fc2012-03-09 08:00:36 +00002588 DeclarationName OpName =
2589 Context.DeclarationNames.getCXXLiteralOperatorName(UDSuffix);
2590 DeclarationNameInfo OpNameInfo(OpName, UDSuffixLoc);
2591 OpNameInfo.setCXXLiteralOperatorNameLoc(UDSuffixLoc);
2592
2593 // Perform literal operator lookup to determine if we're building a raw
2594 // literal or a cooked one.
2595 LookupResult R(*this, OpName, UDSuffixLoc, LookupOrdinaryName);
2596 switch (LookupLiteralOperator(UDLScope, R, llvm::makeArrayRef(&CookedTy, 1),
2597 /*AllowRawAndTemplate*/true)) {
2598 case LOLR_Error:
2599 return ExprError();
2600
2601 case LOLR_Cooked: {
2602 Expr *Lit;
2603 if (Literal.isFloatingLiteral()) {
2604 Lit = BuildFloatingLiteral(*this, Literal, CookedTy, Tok.getLocation());
2605 } else {
2606 llvm::APInt ResultVal(Context.getTargetInfo().getLongLongWidth(), 0);
2607 if (Literal.GetIntegerValue(ResultVal))
2608 Diag(Tok.getLocation(), diag::warn_integer_too_large);
2609 Lit = IntegerLiteral::Create(Context, ResultVal, CookedTy,
2610 Tok.getLocation());
2611 }
2612 return BuildLiteralOperatorCall(R, OpNameInfo,
2613 llvm::makeArrayRef(&Lit, 1),
2614 Tok.getLocation());
2615 }
2616
2617 case LOLR_Raw: {
2618 // C++11 [lit.ext]p3, p4: If S contains a raw literal operator, the
2619 // literal is treated as a call of the form
2620 // operator "" X ("n")
2621 SourceLocation TokLoc = Tok.getLocation();
2622 unsigned Length = Literal.getUDSuffixOffset();
2623 QualType StrTy = Context.getConstantArrayType(
2624 Context.CharTy, llvm::APInt(32, Length + 1),
2625 ArrayType::Normal, 0);
2626 Expr *Lit = StringLiteral::Create(
2627 Context, StringRef(ThisTokBegin, Length), StringLiteral::Ascii,
2628 /*Pascal*/false, StrTy, &TokLoc, 1);
2629 return BuildLiteralOperatorCall(R, OpNameInfo,
2630 llvm::makeArrayRef(&Lit, 1), TokLoc);
2631 }
2632
2633 case LOLR_Template:
2634 // C++11 [lit.ext]p3, p4: Otherwise (S contains a literal operator
2635 // template), L is treated as a call fo the form
2636 // operator "" X <'c1', 'c2', ... 'ck'>()
2637 // where n is the source character sequence c1 c2 ... ck.
2638 TemplateArgumentListInfo ExplicitArgs;
2639 unsigned CharBits = Context.getIntWidth(Context.CharTy);
2640 bool CharIsUnsigned = Context.CharTy->isUnsignedIntegerType();
2641 llvm::APSInt Value(CharBits, CharIsUnsigned);
2642 for (unsigned I = 0, N = Literal.getUDSuffixOffset(); I != N; ++I) {
2643 Value = ThisTokBegin[I];
Benjamin Kramer6003ad52012-06-07 15:09:51 +00002644 TemplateArgument Arg(Context, Value, Context.CharTy);
Richard Smithbcc22fc2012-03-09 08:00:36 +00002645 TemplateArgumentLocInfo ArgInfo;
2646 ExplicitArgs.addArgument(TemplateArgumentLoc(Arg, ArgInfo));
2647 }
2648 return BuildLiteralOperatorCall(R, OpNameInfo, ArrayRef<Expr*>(),
2649 Tok.getLocation(), &ExplicitArgs);
2650 }
2651
2652 llvm_unreachable("unexpected literal operator lookup result");
Richard Smith39570d002012-03-08 08:45:32 +00002653 }
2654
Chris Lattner1c20a172007-08-26 03:42:43 +00002655 Expr *Res;
Sebastian Redlffbcf962009-01-18 18:53:16 +00002656
Chris Lattner1c20a172007-08-26 03:42:43 +00002657 if (Literal.isFloatingLiteral()) {
Chris Lattnerec0a6d92007-09-22 18:29:59 +00002658 QualType Ty;
Chris Lattner9a8d1d92008-06-30 18:32:54 +00002659 if (Literal.isFloat)
Chris Lattnerec0a6d92007-09-22 18:29:59 +00002660 Ty = Context.FloatTy;
Chris Lattner9a8d1d92008-06-30 18:32:54 +00002661 else if (!Literal.isLong)
Chris Lattnerec0a6d92007-09-22 18:29:59 +00002662 Ty = Context.DoubleTy;
Chris Lattner9a8d1d92008-06-30 18:32:54 +00002663 else
Chris Lattner7570e9c2008-03-08 08:52:55 +00002664 Ty = Context.LongDoubleTy;
Chris Lattner9a8d1d92008-06-30 18:32:54 +00002665
Richard Smith39570d002012-03-08 08:45:32 +00002666 Res = BuildFloatingLiteral(*this, Literal, Ty, Tok.getLocation());
Sebastian Redlffbcf962009-01-18 18:53:16 +00002667
Peter Collingbournec77f85b2011-03-11 19:24:59 +00002668 if (Ty == Context.DoubleTy) {
David Blaikiebbafb8a2012-03-11 07:00:24 +00002669 if (getLangOpts().SinglePrecisionConstants) {
John Wiegley01296292011-04-08 18:41:53 +00002670 Res = ImpCastExprToType(Res, Context.FloatTy, CK_FloatingCast).take();
David Blaikiebbafb8a2012-03-11 07:00:24 +00002671 } else if (getLangOpts().OpenCL && !getOpenCLOptions().cl_khr_fp64) {
Peter Collingbournec77f85b2011-03-11 19:24:59 +00002672 Diag(Tok.getLocation(), diag::warn_double_const_requires_fp64);
John Wiegley01296292011-04-08 18:41:53 +00002673 Res = ImpCastExprToType(Res, Context.FloatTy, CK_FloatingCast).take();
Peter Collingbournec77f85b2011-03-11 19:24:59 +00002674 }
2675 }
Chris Lattner1c20a172007-08-26 03:42:43 +00002676 } else if (!Literal.isIntegerLiteral()) {
Sebastian Redlffbcf962009-01-18 18:53:16 +00002677 return ExprError();
Chris Lattner1c20a172007-08-26 03:42:43 +00002678 } else {
Chris Lattner24d5bfe2008-04-02 04:24:33 +00002679 QualType Ty;
Chris Lattner67ca9252007-05-21 01:08:44 +00002680
Neil Boothac582c52007-08-29 22:00:19 +00002681 // long long is a C99 feature.
David Blaikiebbafb8a2012-03-11 07:00:24 +00002682 if (!getLangOpts().C99 && Literal.isLongLong)
Richard Smith0bf8a4922011-10-18 20:49:44 +00002683 Diag(Tok.getLocation(),
David Blaikiebbafb8a2012-03-11 07:00:24 +00002684 getLangOpts().CPlusPlus0x ?
Richard Smith0bf8a4922011-10-18 20:49:44 +00002685 diag::warn_cxx98_compat_longlong : diag::ext_longlong);
Neil Boothac582c52007-08-29 22:00:19 +00002686
Chris Lattner67ca9252007-05-21 01:08:44 +00002687 // Get the value in the widest-possible width.
Stephen Canonfdc6c1a2012-05-03 22:49:43 +00002688 unsigned MaxWidth = Context.getTargetInfo().getIntMaxTWidth();
2689 // The microsoft literal suffix extensions support 128-bit literals, which
2690 // may be wider than [u]intmax_t.
2691 if (Literal.isMicrosoftInteger && MaxWidth < 128)
2692 MaxWidth = 128;
2693 llvm::APInt ResultVal(MaxWidth, 0);
Sebastian Redlffbcf962009-01-18 18:53:16 +00002694
Chris Lattner67ca9252007-05-21 01:08:44 +00002695 if (Literal.GetIntegerValue(ResultVal)) {
2696 // If this value didn't fit into uintmax_t, warn and force to ull.
2697 Diag(Tok.getLocation(), diag::warn_integer_too_large);
Chris Lattner24d5bfe2008-04-02 04:24:33 +00002698 Ty = Context.UnsignedLongLongTy;
2699 assert(Context.getTypeSize(Ty) == ResultVal.getBitWidth() &&
Chris Lattner37e05872008-03-05 18:54:05 +00002700 "long long is not intmax_t?");
Steve Naroff09ef4742007-03-09 23:16:33 +00002701 } else {
Chris Lattner67ca9252007-05-21 01:08:44 +00002702 // If this value fits into a ULL, try to figure out what else it fits into
2703 // according to the rules of C99 6.4.4.1p5.
Sebastian Redlffbcf962009-01-18 18:53:16 +00002704
Chris Lattner67ca9252007-05-21 01:08:44 +00002705 // Octal, Hexadecimal, and integers with a U suffix are allowed to
2706 // be an unsigned int.
2707 bool AllowUnsigned = Literal.isUnsigned || Literal.getRadix() != 10;
2708
2709 // Check from smallest to largest, picking the smallest type we can.
Chris Lattner55258cf2008-05-09 05:59:00 +00002710 unsigned Width = 0;
Chris Lattner7b939cf2007-08-23 21:58:08 +00002711 if (!Literal.isLong && !Literal.isLongLong) {
2712 // Are int/unsigned possibilities?
Douglas Gregore8bbc122011-09-02 00:18:52 +00002713 unsigned IntSize = Context.getTargetInfo().getIntWidth();
Sebastian Redlffbcf962009-01-18 18:53:16 +00002714
Chris Lattner67ca9252007-05-21 01:08:44 +00002715 // Does it fit in a unsigned int?
2716 if (ResultVal.isIntN(IntSize)) {
2717 // Does it fit in a signed int?
2718 if (!Literal.isUnsigned && ResultVal[IntSize-1] == 0)
Chris Lattner24d5bfe2008-04-02 04:24:33 +00002719 Ty = Context.IntTy;
Chris Lattner67ca9252007-05-21 01:08:44 +00002720 else if (AllowUnsigned)
Chris Lattner24d5bfe2008-04-02 04:24:33 +00002721 Ty = Context.UnsignedIntTy;
Chris Lattner55258cf2008-05-09 05:59:00 +00002722 Width = IntSize;
Chris Lattner67ca9252007-05-21 01:08:44 +00002723 }
Chris Lattner67ca9252007-05-21 01:08:44 +00002724 }
Sebastian Redlffbcf962009-01-18 18:53:16 +00002725
Chris Lattner67ca9252007-05-21 01:08:44 +00002726 // Are long/unsigned long possibilities?
Chris Lattner24d5bfe2008-04-02 04:24:33 +00002727 if (Ty.isNull() && !Literal.isLongLong) {
Douglas Gregore8bbc122011-09-02 00:18:52 +00002728 unsigned LongSize = Context.getTargetInfo().getLongWidth();
Sebastian Redlffbcf962009-01-18 18:53:16 +00002729
Chris Lattner67ca9252007-05-21 01:08:44 +00002730 // Does it fit in a unsigned long?
2731 if (ResultVal.isIntN(LongSize)) {
2732 // Does it fit in a signed long?
2733 if (!Literal.isUnsigned && ResultVal[LongSize-1] == 0)
Chris Lattner24d5bfe2008-04-02 04:24:33 +00002734 Ty = Context.LongTy;
Chris Lattner67ca9252007-05-21 01:08:44 +00002735 else if (AllowUnsigned)
Chris Lattner24d5bfe2008-04-02 04:24:33 +00002736 Ty = Context.UnsignedLongTy;
Chris Lattner55258cf2008-05-09 05:59:00 +00002737 Width = LongSize;
Chris Lattner67ca9252007-05-21 01:08:44 +00002738 }
Sebastian Redlffbcf962009-01-18 18:53:16 +00002739 }
2740
Stephen Canonfdc6c1a2012-05-03 22:49:43 +00002741 // Check long long if needed.
Chris Lattner24d5bfe2008-04-02 04:24:33 +00002742 if (Ty.isNull()) {
Douglas Gregore8bbc122011-09-02 00:18:52 +00002743 unsigned LongLongSize = Context.getTargetInfo().getLongLongWidth();
Sebastian Redlffbcf962009-01-18 18:53:16 +00002744
Chris Lattner67ca9252007-05-21 01:08:44 +00002745 // Does it fit in a unsigned long long?
2746 if (ResultVal.isIntN(LongLongSize)) {
2747 // Does it fit in a signed long long?
Francois Pichetc3e73b32011-01-11 23:38:13 +00002748 // To be compatible with MSVC, hex integer literals ending with the
2749 // LL or i64 suffix are always signed in Microsoft mode.
Francois Pichetbf711d92011-01-11 12:23:00 +00002750 if (!Literal.isUnsigned && (ResultVal[LongLongSize-1] == 0 ||
David Blaikiebbafb8a2012-03-11 07:00:24 +00002751 (getLangOpts().MicrosoftExt && Literal.isLongLong)))
Chris Lattner24d5bfe2008-04-02 04:24:33 +00002752 Ty = Context.LongLongTy;
Chris Lattner67ca9252007-05-21 01:08:44 +00002753 else if (AllowUnsigned)
Chris Lattner24d5bfe2008-04-02 04:24:33 +00002754 Ty = Context.UnsignedLongLongTy;
Chris Lattner55258cf2008-05-09 05:59:00 +00002755 Width = LongLongSize;
Chris Lattner67ca9252007-05-21 01:08:44 +00002756 }
2757 }
Stephen Canonfdc6c1a2012-05-03 22:49:43 +00002758
2759 // If it doesn't fit in unsigned long long, and we're using Microsoft
2760 // extensions, then its a 128-bit integer literal.
2761 if (Ty.isNull() && Literal.isMicrosoftInteger) {
2762 if (Literal.isUnsigned)
2763 Ty = Context.UnsignedInt128Ty;
2764 else
2765 Ty = Context.Int128Ty;
2766 Width = 128;
2767 }
Sebastian Redlffbcf962009-01-18 18:53:16 +00002768
Chris Lattner67ca9252007-05-21 01:08:44 +00002769 // If we still couldn't decide a type, we probably have something that
2770 // does not fit in a signed long long, but has no U suffix.
Chris Lattner24d5bfe2008-04-02 04:24:33 +00002771 if (Ty.isNull()) {
Chris Lattner67ca9252007-05-21 01:08:44 +00002772 Diag(Tok.getLocation(), diag::warn_integer_too_large_for_signed);
Chris Lattner24d5bfe2008-04-02 04:24:33 +00002773 Ty = Context.UnsignedLongLongTy;
Douglas Gregore8bbc122011-09-02 00:18:52 +00002774 Width = Context.getTargetInfo().getLongLongWidth();
Chris Lattner67ca9252007-05-21 01:08:44 +00002775 }
Sebastian Redlffbcf962009-01-18 18:53:16 +00002776
Chris Lattner55258cf2008-05-09 05:59:00 +00002777 if (ResultVal.getBitWidth() != Width)
Jay Foad6d4db0c2010-12-07 08:25:34 +00002778 ResultVal = ResultVal.trunc(Width);
Steve Naroff09ef4742007-03-09 23:16:33 +00002779 }
Argyrios Kyrtzidis43b20572010-08-28 09:06:06 +00002780 Res = IntegerLiteral::Create(Context, ResultVal, Ty, Tok.getLocation());
Steve Naroff09ef4742007-03-09 23:16:33 +00002781 }
Sebastian Redlffbcf962009-01-18 18:53:16 +00002782
Chris Lattner1c20a172007-08-26 03:42:43 +00002783 // If this is an imaginary literal, create the ImaginaryLiteral wrapper.
2784 if (Literal.isImaginary)
Mike Stump11289f42009-09-09 15:08:12 +00002785 Res = new (Context) ImaginaryLiteral(Res,
Steve Narofff6009ed2009-01-21 00:14:39 +00002786 Context.getComplexType(Res->getType()));
Sebastian Redlffbcf962009-01-18 18:53:16 +00002787
2788 return Owned(Res);
Chris Lattnere168f762006-11-10 05:29:30 +00002789}
2790
Richard Trieuba63ce62011-09-09 01:45:06 +00002791ExprResult Sema::ActOnParenExpr(SourceLocation L, SourceLocation R, Expr *E) {
Chris Lattner24d5bfe2008-04-02 04:24:33 +00002792 assert((E != 0) && "ActOnParenExpr() missing expr");
Steve Narofff6009ed2009-01-21 00:14:39 +00002793 return Owned(new (Context) ParenExpr(L, R, E));
Chris Lattnere168f762006-11-10 05:29:30 +00002794}
2795
Chandler Carruth62da79c2011-05-26 08:53:12 +00002796static bool CheckVecStepTraitOperandType(Sema &S, QualType T,
2797 SourceLocation Loc,
2798 SourceRange ArgRange) {
2799 // [OpenCL 1.1 6.11.12] "The vec_step built-in function takes a built-in
2800 // scalar or vector data type argument..."
2801 // Every built-in scalar type (OpenCL 1.1 6.1.1) is either an arithmetic
2802 // type (C99 6.2.5p18) or void.
2803 if (!(T->isArithmeticType() || T->isVoidType() || T->isVectorType())) {
2804 S.Diag(Loc, diag::err_vecstep_non_scalar_vector_type)
2805 << T << ArgRange;
2806 return true;
2807 }
2808
2809 assert((T->isVoidType() || !T->isIncompleteType()) &&
2810 "Scalar types should always be complete");
2811 return false;
2812}
2813
Chandler Carruthcea1aac2011-05-26 08:53:16 +00002814static bool CheckExtensionTraitOperandType(Sema &S, QualType T,
2815 SourceLocation Loc,
2816 SourceRange ArgRange,
2817 UnaryExprOrTypeTrait TraitKind) {
2818 // C99 6.5.3.4p1:
2819 if (T->isFunctionType()) {
2820 // alignof(function) is allowed as an extension.
2821 if (TraitKind == UETT_SizeOf)
2822 S.Diag(Loc, diag::ext_sizeof_function_type) << ArgRange;
2823 return false;
2824 }
2825
2826 // Allow sizeof(void)/alignof(void) as an extension.
2827 if (T->isVoidType()) {
2828 S.Diag(Loc, diag::ext_sizeof_void_type) << TraitKind << ArgRange;
2829 return false;
2830 }
2831
2832 return true;
2833}
2834
2835static bool CheckObjCTraitOperandConstraints(Sema &S, QualType T,
2836 SourceLocation Loc,
2837 SourceRange ArgRange,
2838 UnaryExprOrTypeTrait TraitKind) {
2839 // Reject sizeof(interface) and sizeof(interface<proto>) in 64-bit mode.
2840 if (S.LangOpts.ObjCNonFragileABI && T->isObjCObjectType()) {
2841 S.Diag(Loc, diag::err_sizeof_nonfragile_interface)
2842 << T << (TraitKind == UETT_SizeOf)
2843 << ArgRange;
2844 return true;
2845 }
2846
2847 return false;
2848}
2849
Chandler Carruth14502c22011-05-26 08:53:10 +00002850/// \brief Check the constrains on expression operands to unary type expression
2851/// and type traits.
2852///
Chandler Carruth7c430c02011-05-27 01:33:31 +00002853/// Completes any types necessary and validates the constraints on the operand
2854/// expression. The logic mostly mirrors the type-based overload, but may modify
2855/// the expression as it completes the type for that expression through template
2856/// instantiation, etc.
Richard Trieuba63ce62011-09-09 01:45:06 +00002857bool Sema::CheckUnaryExprOrTypeTraitOperand(Expr *E,
Chandler Carruth14502c22011-05-26 08:53:10 +00002858 UnaryExprOrTypeTrait ExprKind) {
Richard Trieuba63ce62011-09-09 01:45:06 +00002859 QualType ExprTy = E->getType();
Chandler Carruth7c430c02011-05-27 01:33:31 +00002860
2861 // C++ [expr.sizeof]p2: "When applied to a reference or a reference type,
2862 // the result is the size of the referenced type."
2863 // C++ [expr.alignof]p3: "When alignof is applied to a reference type, the
2864 // result shall be the alignment of the referenced type."
2865 if (const ReferenceType *Ref = ExprTy->getAs<ReferenceType>())
2866 ExprTy = Ref->getPointeeType();
2867
2868 if (ExprKind == UETT_VecStep)
Richard Trieuba63ce62011-09-09 01:45:06 +00002869 return CheckVecStepTraitOperandType(*this, ExprTy, E->getExprLoc(),
2870 E->getSourceRange());
Chandler Carruth7c430c02011-05-27 01:33:31 +00002871
2872 // Whitelist some types as extensions
Richard Trieuba63ce62011-09-09 01:45:06 +00002873 if (!CheckExtensionTraitOperandType(*this, ExprTy, E->getExprLoc(),
2874 E->getSourceRange(), ExprKind))
Chandler Carruth7c430c02011-05-27 01:33:31 +00002875 return false;
2876
Richard Trieuba63ce62011-09-09 01:45:06 +00002877 if (RequireCompleteExprType(E,
Douglas Gregor7bfb2d02012-05-04 16:32:21 +00002878 diag::err_sizeof_alignof_incomplete_type,
2879 ExprKind, E->getSourceRange()))
Chandler Carruth7c430c02011-05-27 01:33:31 +00002880 return true;
2881
2882 // Completeing the expression's type may have changed it.
Richard Trieuba63ce62011-09-09 01:45:06 +00002883 ExprTy = E->getType();
Chandler Carruth7c430c02011-05-27 01:33:31 +00002884 if (const ReferenceType *Ref = ExprTy->getAs<ReferenceType>())
2885 ExprTy = Ref->getPointeeType();
2886
Richard Trieuba63ce62011-09-09 01:45:06 +00002887 if (CheckObjCTraitOperandConstraints(*this, ExprTy, E->getExprLoc(),
2888 E->getSourceRange(), ExprKind))
Chandler Carruth7c430c02011-05-27 01:33:31 +00002889 return true;
2890
Nico Weber0870deb2011-06-15 02:47:03 +00002891 if (ExprKind == UETT_SizeOf) {
Richard Trieuba63ce62011-09-09 01:45:06 +00002892 if (DeclRefExpr *DeclRef = dyn_cast<DeclRefExpr>(E->IgnoreParens())) {
Nico Weber0870deb2011-06-15 02:47:03 +00002893 if (ParmVarDecl *PVD = dyn_cast<ParmVarDecl>(DeclRef->getFoundDecl())) {
2894 QualType OType = PVD->getOriginalType();
2895 QualType Type = PVD->getType();
2896 if (Type->isPointerType() && OType->isArrayType()) {
Richard Trieuba63ce62011-09-09 01:45:06 +00002897 Diag(E->getExprLoc(), diag::warn_sizeof_array_param)
Nico Weber0870deb2011-06-15 02:47:03 +00002898 << Type << OType;
2899 Diag(PVD->getLocation(), diag::note_declared_at);
2900 }
2901 }
2902 }
2903 }
2904
Chandler Carruth7c430c02011-05-27 01:33:31 +00002905 return false;
Chandler Carruth14502c22011-05-26 08:53:10 +00002906}
2907
2908/// \brief Check the constraints on operands to unary expression and type
2909/// traits.
2910///
2911/// This will complete any types necessary, and validate the various constraints
2912/// on those operands.
2913///
Steve Naroff71b59a92007-06-04 22:22:31 +00002914/// The UsualUnaryConversions() function is *not* called by this routine.
Chandler Carruth14502c22011-05-26 08:53:10 +00002915/// C99 6.3.2.1p[2-4] all state:
2916/// Except when it is the operand of the sizeof operator ...
2917///
2918/// C++ [expr.sizeof]p4
2919/// The lvalue-to-rvalue, array-to-pointer, and function-to-pointer
2920/// standard conversions are not applied to the operand of sizeof.
2921///
2922/// This policy is followed for all of the unary trait expressions.
Richard Trieuba63ce62011-09-09 01:45:06 +00002923bool Sema::CheckUnaryExprOrTypeTraitOperand(QualType ExprType,
Peter Collingbournee190dee2011-03-11 19:24:49 +00002924 SourceLocation OpLoc,
2925 SourceRange ExprRange,
2926 UnaryExprOrTypeTrait ExprKind) {
Richard Trieuba63ce62011-09-09 01:45:06 +00002927 if (ExprType->isDependentType())
Sebastian Redl8d2ccae2009-02-26 14:39:58 +00002928 return false;
2929
Sebastian Redl22e2e5c2009-11-23 17:18:46 +00002930 // C++ [expr.sizeof]p2: "When applied to a reference or a reference type,
2931 // the result is the size of the referenced type."
2932 // C++ [expr.alignof]p3: "When alignof is applied to a reference type, the
2933 // result shall be the alignment of the referenced type."
Richard Trieuba63ce62011-09-09 01:45:06 +00002934 if (const ReferenceType *Ref = ExprType->getAs<ReferenceType>())
2935 ExprType = Ref->getPointeeType();
Sebastian Redl22e2e5c2009-11-23 17:18:46 +00002936
Chandler Carruth62da79c2011-05-26 08:53:12 +00002937 if (ExprKind == UETT_VecStep)
Richard Trieuba63ce62011-09-09 01:45:06 +00002938 return CheckVecStepTraitOperandType(*this, ExprType, OpLoc, ExprRange);
Peter Collingbournee190dee2011-03-11 19:24:49 +00002939
Chandler Carruthcea1aac2011-05-26 08:53:16 +00002940 // Whitelist some types as extensions
Richard Trieuba63ce62011-09-09 01:45:06 +00002941 if (!CheckExtensionTraitOperandType(*this, ExprType, OpLoc, ExprRange,
Chandler Carruthcea1aac2011-05-26 08:53:16 +00002942 ExprKind))
Chris Lattnerb1355b12009-01-24 19:46:37 +00002943 return false;
Mike Stump11289f42009-09-09 15:08:12 +00002944
Richard Trieuba63ce62011-09-09 01:45:06 +00002945 if (RequireCompleteType(OpLoc, ExprType,
Douglas Gregor7bfb2d02012-05-04 16:32:21 +00002946 diag::err_sizeof_alignof_incomplete_type,
2947 ExprKind, ExprRange))
Chris Lattner62975a72009-04-24 00:30:45 +00002948 return true;
Mike Stump11289f42009-09-09 15:08:12 +00002949
Richard Trieuba63ce62011-09-09 01:45:06 +00002950 if (CheckObjCTraitOperandConstraints(*this, ExprType, OpLoc, ExprRange,
Chandler Carruthcea1aac2011-05-26 08:53:16 +00002951 ExprKind))
Chris Lattnercd2a8c52009-04-24 22:30:50 +00002952 return true;
Mike Stump11289f42009-09-09 15:08:12 +00002953
Chris Lattner62975a72009-04-24 00:30:45 +00002954 return false;
Steve Naroff043d45d2007-05-15 02:32:35 +00002955}
2956
Chandler Carruth14502c22011-05-26 08:53:10 +00002957static bool CheckAlignOfExpr(Sema &S, Expr *E) {
Chris Lattner8dff0172009-01-24 20:17:12 +00002958 E = E->IgnoreParens();
Sebastian Redl8d2ccae2009-02-26 14:39:58 +00002959
Mike Stump11289f42009-09-09 15:08:12 +00002960 // alignof decl is always ok.
Chris Lattner8dff0172009-01-24 20:17:12 +00002961 if (isa<DeclRefExpr>(E))
2962 return false;
Sebastian Redl8d2ccae2009-02-26 14:39:58 +00002963
2964 // Cannot know anything else if the expression is dependent.
2965 if (E->isTypeDependent())
2966 return false;
2967
Douglas Gregor71235ec2009-05-02 02:18:30 +00002968 if (E->getBitField()) {
Chandler Carruth14502c22011-05-26 08:53:10 +00002969 S.Diag(E->getExprLoc(), diag::err_sizeof_alignof_bitfield)
2970 << 1 << E->getSourceRange();
Douglas Gregor71235ec2009-05-02 02:18:30 +00002971 return true;
Chris Lattner8dff0172009-01-24 20:17:12 +00002972 }
Douglas Gregor71235ec2009-05-02 02:18:30 +00002973
2974 // Alignment of a field access is always okay, so long as it isn't a
2975 // bit-field.
2976 if (MemberExpr *ME = dyn_cast<MemberExpr>(E))
Mike Stump212005c2009-07-22 18:58:19 +00002977 if (isa<FieldDecl>(ME->getMemberDecl()))
Douglas Gregor71235ec2009-05-02 02:18:30 +00002978 return false;
2979
Chandler Carruth14502c22011-05-26 08:53:10 +00002980 return S.CheckUnaryExprOrTypeTraitOperand(E, UETT_AlignOf);
Peter Collingbournee190dee2011-03-11 19:24:49 +00002981}
2982
Chandler Carruth14502c22011-05-26 08:53:10 +00002983bool Sema::CheckVecStepExpr(Expr *E) {
Peter Collingbournee190dee2011-03-11 19:24:49 +00002984 E = E->IgnoreParens();
2985
2986 // Cannot know anything else if the expression is dependent.
2987 if (E->isTypeDependent())
2988 return false;
2989
Chandler Carruth14502c22011-05-26 08:53:10 +00002990 return CheckUnaryExprOrTypeTraitOperand(E, UETT_VecStep);
Chris Lattner8dff0172009-01-24 20:17:12 +00002991}
2992
Douglas Gregor0950e412009-03-13 21:01:28 +00002993/// \brief Build a sizeof or alignof expression given a type operand.
John McCalldadc5752010-08-24 06:29:42 +00002994ExprResult
Peter Collingbournee190dee2011-03-11 19:24:49 +00002995Sema::CreateUnaryExprOrTypeTraitExpr(TypeSourceInfo *TInfo,
2996 SourceLocation OpLoc,
2997 UnaryExprOrTypeTrait ExprKind,
2998 SourceRange R) {
John McCallbcd03502009-12-07 02:54:59 +00002999 if (!TInfo)
Douglas Gregor0950e412009-03-13 21:01:28 +00003000 return ExprError();
3001
John McCallbcd03502009-12-07 02:54:59 +00003002 QualType T = TInfo->getType();
John McCall4c98fd82009-11-04 07:28:41 +00003003
Douglas Gregor0950e412009-03-13 21:01:28 +00003004 if (!T->isDependentType() &&
Peter Collingbournee190dee2011-03-11 19:24:49 +00003005 CheckUnaryExprOrTypeTraitOperand(T, OpLoc, R, ExprKind))
Douglas Gregor0950e412009-03-13 21:01:28 +00003006 return ExprError();
3007
3008 // C99 6.5.3.4p4: the type (an unsigned integer type) is size_t.
Peter Collingbournee190dee2011-03-11 19:24:49 +00003009 return Owned(new (Context) UnaryExprOrTypeTraitExpr(ExprKind, TInfo,
3010 Context.getSizeType(),
3011 OpLoc, R.getEnd()));
Douglas Gregor0950e412009-03-13 21:01:28 +00003012}
3013
3014/// \brief Build a sizeof or alignof expression given an expression
3015/// operand.
John McCalldadc5752010-08-24 06:29:42 +00003016ExprResult
Chandler Carrutha923fb22011-05-29 07:32:14 +00003017Sema::CreateUnaryExprOrTypeTraitExpr(Expr *E, SourceLocation OpLoc,
3018 UnaryExprOrTypeTrait ExprKind) {
Douglas Gregor835af982011-06-22 23:21:00 +00003019 ExprResult PE = CheckPlaceholderExpr(E);
3020 if (PE.isInvalid())
3021 return ExprError();
3022
3023 E = PE.get();
3024
Douglas Gregor0950e412009-03-13 21:01:28 +00003025 // Verify that the operand is valid.
3026 bool isInvalid = false;
3027 if (E->isTypeDependent()) {
3028 // Delay type-checking for type-dependent expressions.
Peter Collingbournee190dee2011-03-11 19:24:49 +00003029 } else if (ExprKind == UETT_AlignOf) {
Chandler Carruth14502c22011-05-26 08:53:10 +00003030 isInvalid = CheckAlignOfExpr(*this, E);
Peter Collingbournee190dee2011-03-11 19:24:49 +00003031 } else if (ExprKind == UETT_VecStep) {
Chandler Carruth14502c22011-05-26 08:53:10 +00003032 isInvalid = CheckVecStepExpr(E);
Douglas Gregor71235ec2009-05-02 02:18:30 +00003033 } else if (E->getBitField()) { // C99 6.5.3.4p1.
Chandler Carruth14502c22011-05-26 08:53:10 +00003034 Diag(E->getExprLoc(), diag::err_sizeof_alignof_bitfield) << 0;
Douglas Gregor0950e412009-03-13 21:01:28 +00003035 isInvalid = true;
3036 } else {
Chandler Carruth14502c22011-05-26 08:53:10 +00003037 isInvalid = CheckUnaryExprOrTypeTraitOperand(E, UETT_SizeOf);
Douglas Gregor0950e412009-03-13 21:01:28 +00003038 }
3039
3040 if (isInvalid)
3041 return ExprError();
3042
Eli Friedmane0afc982012-01-21 01:01:51 +00003043 if (ExprKind == UETT_SizeOf && E->getType()->isVariableArrayType()) {
3044 PE = TranformToPotentiallyEvaluated(E);
3045 if (PE.isInvalid()) return ExprError();
3046 E = PE.take();
3047 }
3048
Douglas Gregor0950e412009-03-13 21:01:28 +00003049 // C99 6.5.3.4p4: the type (an unsigned integer type) is size_t.
Chandler Carruth14502c22011-05-26 08:53:10 +00003050 return Owned(new (Context) UnaryExprOrTypeTraitExpr(
Chandler Carrutha923fb22011-05-29 07:32:14 +00003051 ExprKind, E, Context.getSizeType(), OpLoc,
Chandler Carruth14502c22011-05-26 08:53:10 +00003052 E->getSourceRange().getEnd()));
Douglas Gregor0950e412009-03-13 21:01:28 +00003053}
3054
Peter Collingbournee190dee2011-03-11 19:24:49 +00003055/// ActOnUnaryExprOrTypeTraitExpr - Handle @c sizeof(type) and @c sizeof @c
3056/// expr and the same for @c alignof and @c __alignof
Sebastian Redl6f282892008-11-11 17:56:53 +00003057/// Note that the ArgRange is invalid if isType is false.
John McCalldadc5752010-08-24 06:29:42 +00003058ExprResult
Peter Collingbournee190dee2011-03-11 19:24:49 +00003059Sema::ActOnUnaryExprOrTypeTraitExpr(SourceLocation OpLoc,
Richard Trieuba63ce62011-09-09 01:45:06 +00003060 UnaryExprOrTypeTrait ExprKind, bool IsType,
Peter Collingbournee190dee2011-03-11 19:24:49 +00003061 void *TyOrEx, const SourceRange &ArgRange) {
Chris Lattner0d8b1a12006-11-20 04:34:45 +00003062 // If error parsing type, ignore.
Sebastian Redlc215cfc2009-01-19 00:08:26 +00003063 if (TyOrEx == 0) return ExprError();
Steve Naroff043d45d2007-05-15 02:32:35 +00003064
Richard Trieuba63ce62011-09-09 01:45:06 +00003065 if (IsType) {
John McCallbcd03502009-12-07 02:54:59 +00003066 TypeSourceInfo *TInfo;
John McCallba7bf592010-08-24 05:47:05 +00003067 (void) GetTypeFromParser(ParsedType::getFromOpaquePtr(TyOrEx), &TInfo);
Peter Collingbournee190dee2011-03-11 19:24:49 +00003068 return CreateUnaryExprOrTypeTraitExpr(TInfo, OpLoc, ExprKind, ArgRange);
Mike Stump11289f42009-09-09 15:08:12 +00003069 }
Sebastian Redl6f282892008-11-11 17:56:53 +00003070
Douglas Gregor0950e412009-03-13 21:01:28 +00003071 Expr *ArgEx = (Expr *)TyOrEx;
Chandler Carrutha923fb22011-05-29 07:32:14 +00003072 ExprResult Result = CreateUnaryExprOrTypeTraitExpr(ArgEx, OpLoc, ExprKind);
Douglas Gregor0950e412009-03-13 21:01:28 +00003073 return move(Result);
Chris Lattnere168f762006-11-10 05:29:30 +00003074}
3075
John Wiegley01296292011-04-08 18:41:53 +00003076static QualType CheckRealImagOperand(Sema &S, ExprResult &V, SourceLocation Loc,
Richard Trieuba63ce62011-09-09 01:45:06 +00003077 bool IsReal) {
John Wiegley01296292011-04-08 18:41:53 +00003078 if (V.get()->isTypeDependent())
John McCall4bc41ae2010-11-18 19:01:18 +00003079 return S.Context.DependentTy;
Mike Stump11289f42009-09-09 15:08:12 +00003080
John McCall34376a62010-12-04 03:47:34 +00003081 // _Real and _Imag are only l-values for normal l-values.
John Wiegley01296292011-04-08 18:41:53 +00003082 if (V.get()->getObjectKind() != OK_Ordinary) {
3083 V = S.DefaultLvalueConversion(V.take());
3084 if (V.isInvalid())
3085 return QualType();
3086 }
John McCall34376a62010-12-04 03:47:34 +00003087
Chris Lattnere267f5d2007-08-26 05:39:26 +00003088 // These operators return the element type of a complex type.
John Wiegley01296292011-04-08 18:41:53 +00003089 if (const ComplexType *CT = V.get()->getType()->getAs<ComplexType>())
Chris Lattner30b5dd02007-08-24 21:16:53 +00003090 return CT->getElementType();
Mike Stump11289f42009-09-09 15:08:12 +00003091
Chris Lattnere267f5d2007-08-26 05:39:26 +00003092 // Otherwise they pass through real integer and floating point types here.
John Wiegley01296292011-04-08 18:41:53 +00003093 if (V.get()->getType()->isArithmeticType())
3094 return V.get()->getType();
Mike Stump11289f42009-09-09 15:08:12 +00003095
John McCall36226622010-10-12 02:09:17 +00003096 // Test for placeholders.
John McCall3aef3d82011-04-10 19:13:55 +00003097 ExprResult PR = S.CheckPlaceholderExpr(V.get());
John McCall36226622010-10-12 02:09:17 +00003098 if (PR.isInvalid()) return QualType();
John Wiegley01296292011-04-08 18:41:53 +00003099 if (PR.get() != V.get()) {
3100 V = move(PR);
Richard Trieuba63ce62011-09-09 01:45:06 +00003101 return CheckRealImagOperand(S, V, Loc, IsReal);
John McCall36226622010-10-12 02:09:17 +00003102 }
3103
Chris Lattnere267f5d2007-08-26 05:39:26 +00003104 // Reject anything else.
John Wiegley01296292011-04-08 18:41:53 +00003105 S.Diag(Loc, diag::err_realimag_invalid_type) << V.get()->getType()
Richard Trieuba63ce62011-09-09 01:45:06 +00003106 << (IsReal ? "__real" : "__imag");
Chris Lattnere267f5d2007-08-26 05:39:26 +00003107 return QualType();
Chris Lattner30b5dd02007-08-24 21:16:53 +00003108}
3109
3110
Chris Lattnere168f762006-11-10 05:29:30 +00003111
John McCalldadc5752010-08-24 06:29:42 +00003112ExprResult
Sebastian Redlc215cfc2009-01-19 00:08:26 +00003113Sema::ActOnPostfixUnaryOp(Scope *S, SourceLocation OpLoc,
John McCallb268a282010-08-23 23:25:46 +00003114 tok::TokenKind Kind, Expr *Input) {
John McCalle3027922010-08-25 11:45:40 +00003115 UnaryOperatorKind Opc;
Chris Lattnere168f762006-11-10 05:29:30 +00003116 switch (Kind) {
David Blaikie83d382b2011-09-23 05:06:16 +00003117 default: llvm_unreachable("Unknown unary op!");
John McCalle3027922010-08-25 11:45:40 +00003118 case tok::plusplus: Opc = UO_PostInc; break;
3119 case tok::minusminus: Opc = UO_PostDec; break;
Chris Lattnere168f762006-11-10 05:29:30 +00003120 }
Sebastian Redlc215cfc2009-01-19 00:08:26 +00003121
Sebastian Redla9351792012-02-11 23:51:47 +00003122 // Since this might is a postfix expression, get rid of ParenListExprs.
3123 ExprResult Result = MaybeConvertParenListExprToParenExpr(S, Input);
3124 if (Result.isInvalid()) return ExprError();
3125 Input = Result.take();
3126
John McCallb268a282010-08-23 23:25:46 +00003127 return BuildUnaryOp(S, OpLoc, Opc, Input);
Chris Lattnere168f762006-11-10 05:29:30 +00003128}
3129
John McCalldadc5752010-08-24 06:29:42 +00003130ExprResult
John McCallb268a282010-08-23 23:25:46 +00003131Sema::ActOnArraySubscriptExpr(Scope *S, Expr *Base, SourceLocation LLoc,
3132 Expr *Idx, SourceLocation RLoc) {
Nate Begeman5ec4b312009-08-10 23:49:36 +00003133 // Since this might be a postfix expression, get rid of ParenListExprs.
John McCalldadc5752010-08-24 06:29:42 +00003134 ExprResult Result = MaybeConvertParenListExprToParenExpr(S, Base);
John McCallb268a282010-08-23 23:25:46 +00003135 if (Result.isInvalid()) return ExprError();
3136 Base = Result.take();
Nate Begeman5ec4b312009-08-10 23:49:36 +00003137
John McCallb268a282010-08-23 23:25:46 +00003138 Expr *LHSExp = Base, *RHSExp = Idx;
Mike Stump11289f42009-09-09 15:08:12 +00003139
David Blaikiebbafb8a2012-03-11 07:00:24 +00003140 if (getLangOpts().CPlusPlus &&
Douglas Gregor7a77a6b2009-05-19 00:01:19 +00003141 (LHSExp->isTypeDependent() || RHSExp->isTypeDependent())) {
Douglas Gregor7a77a6b2009-05-19 00:01:19 +00003142 return Owned(new (Context) ArraySubscriptExpr(LHSExp, RHSExp,
John McCall7decc9e2010-11-18 06:31:45 +00003143 Context.DependentTy,
3144 VK_LValue, OK_Ordinary,
3145 RLoc));
Douglas Gregor7a77a6b2009-05-19 00:01:19 +00003146 }
3147
David Blaikiebbafb8a2012-03-11 07:00:24 +00003148 if (getLangOpts().CPlusPlus &&
Sebastian Redlc215cfc2009-01-19 00:08:26 +00003149 (LHSExp->getType()->isRecordType() ||
Eli Friedman254a1a22008-12-15 22:34:21 +00003150 LHSExp->getType()->isEnumeralType() ||
3151 RHSExp->getType()->isRecordType() ||
Ted Kremeneke65b0862012-03-06 20:05:56 +00003152 RHSExp->getType()->isEnumeralType()) &&
3153 !LHSExp->getType()->isObjCObjectPointerType()) {
John McCallb268a282010-08-23 23:25:46 +00003154 return CreateOverloadedArraySubscriptExpr(LLoc, RLoc, Base, Idx);
Douglas Gregor40412ac2008-11-19 17:17:41 +00003155 }
3156
John McCallb268a282010-08-23 23:25:46 +00003157 return CreateBuiltinArraySubscriptExpr(Base, LLoc, Idx, RLoc);
Sebastian Redladba46e2009-10-29 20:17:01 +00003158}
3159
3160
John McCalldadc5752010-08-24 06:29:42 +00003161ExprResult
John McCallb268a282010-08-23 23:25:46 +00003162Sema::CreateBuiltinArraySubscriptExpr(Expr *Base, SourceLocation LLoc,
Richard Trieuba63ce62011-09-09 01:45:06 +00003163 Expr *Idx, SourceLocation RLoc) {
John McCallb268a282010-08-23 23:25:46 +00003164 Expr *LHSExp = Base;
3165 Expr *RHSExp = Idx;
Sebastian Redladba46e2009-10-29 20:17:01 +00003166
Chris Lattner36d572b2007-07-16 00:14:47 +00003167 // Perform default conversions.
John Wiegley01296292011-04-08 18:41:53 +00003168 if (!LHSExp->getType()->getAs<VectorType>()) {
3169 ExprResult Result = DefaultFunctionArrayLvalueConversion(LHSExp);
3170 if (Result.isInvalid())
3171 return ExprError();
3172 LHSExp = Result.take();
3173 }
3174 ExprResult Result = DefaultFunctionArrayLvalueConversion(RHSExp);
3175 if (Result.isInvalid())
3176 return ExprError();
3177 RHSExp = Result.take();
Sebastian Redlc215cfc2009-01-19 00:08:26 +00003178
Chris Lattner36d572b2007-07-16 00:14:47 +00003179 QualType LHSTy = LHSExp->getType(), RHSTy = RHSExp->getType();
John McCall7decc9e2010-11-18 06:31:45 +00003180 ExprValueKind VK = VK_LValue;
3181 ExprObjectKind OK = OK_Ordinary;
Steve Narofff1e53692007-03-23 22:27:02 +00003182
Steve Naroffc1aadb12007-03-28 21:49:40 +00003183 // C99 6.5.2.1p2: the expression e1[e2] is by definition precisely equivalent
Chris Lattnerf17bd422007-08-30 17:45:32 +00003184 // to the expression *((e1)+(e2)). This means the array "Base" may actually be
Mike Stump4e1f26a2009-02-19 03:04:26 +00003185 // in the subscript position. As a result, we need to derive the array base
Steve Narofff1e53692007-03-23 22:27:02 +00003186 // and index from the expression types.
Chris Lattner36d572b2007-07-16 00:14:47 +00003187 Expr *BaseExpr, *IndexExpr;
3188 QualType ResultType;
Sebastian Redl8d2ccae2009-02-26 14:39:58 +00003189 if (LHSTy->isDependentType() || RHSTy->isDependentType()) {
3190 BaseExpr = LHSExp;
3191 IndexExpr = RHSExp;
3192 ResultType = Context.DependentTy;
Ted Kremenekc23c7e62009-07-29 21:53:49 +00003193 } else if (const PointerType *PTy = LHSTy->getAs<PointerType>()) {
Chris Lattner36d572b2007-07-16 00:14:47 +00003194 BaseExpr = LHSExp;
3195 IndexExpr = RHSExp;
Chris Lattner36d572b2007-07-16 00:14:47 +00003196 ResultType = PTy->getPointeeType();
Mike Stump11289f42009-09-09 15:08:12 +00003197 } else if (const ObjCObjectPointerType *PTy =
Fariborz Jahanianba0afde2012-03-28 17:56:49 +00003198 LHSTy->getAs<ObjCObjectPointerType>()) {
Steve Naroff7cae42b2009-07-10 23:34:53 +00003199 BaseExpr = LHSExp;
3200 IndexExpr = RHSExp;
Ted Kremeneke65b0862012-03-06 20:05:56 +00003201 Result = BuildObjCSubscriptExpression(RLoc, BaseExpr, IndexExpr, 0, 0);
3202 if (!Result.isInvalid())
3203 return Owned(Result.take());
Steve Naroff7cae42b2009-07-10 23:34:53 +00003204 ResultType = PTy->getPointeeType();
Fariborz Jahanianba0afde2012-03-28 17:56:49 +00003205 } else if (const PointerType *PTy = RHSTy->getAs<PointerType>()) {
3206 // Handle the uncommon case of "123[Ptr]".
3207 BaseExpr = RHSExp;
3208 IndexExpr = LHSExp;
3209 ResultType = PTy->getPointeeType();
Mike Stump11289f42009-09-09 15:08:12 +00003210 } else if (const ObjCObjectPointerType *PTy =
John McCall9dd450b2009-09-21 23:43:11 +00003211 RHSTy->getAs<ObjCObjectPointerType>()) {
Steve Naroff7cae42b2009-07-10 23:34:53 +00003212 // Handle the uncommon case of "123[Ptr]".
3213 BaseExpr = RHSExp;
3214 IndexExpr = LHSExp;
3215 ResultType = PTy->getPointeeType();
John McCall9dd450b2009-09-21 23:43:11 +00003216 } else if (const VectorType *VTy = LHSTy->getAs<VectorType>()) {
Chris Lattner41977962007-07-31 19:29:30 +00003217 BaseExpr = LHSExp; // vectors: V[123]
Chris Lattner36d572b2007-07-16 00:14:47 +00003218 IndexExpr = RHSExp;
John McCall7decc9e2010-11-18 06:31:45 +00003219 VK = LHSExp->getValueKind();
3220 if (VK != VK_RValue)
3221 OK = OK_VectorComponent;
Nate Begemanc1bf0612009-01-18 00:45:31 +00003222
Chris Lattner36d572b2007-07-16 00:14:47 +00003223 // FIXME: need to deal with const...
3224 ResultType = VTy->getElementType();
Eli Friedmanab2784f2009-04-25 23:46:54 +00003225 } else if (LHSTy->isArrayType()) {
3226 // If we see an array that wasn't promoted by
Douglas Gregorb92a1562010-02-03 00:27:59 +00003227 // DefaultFunctionArrayLvalueConversion, it must be an array that
Eli Friedmanab2784f2009-04-25 23:46:54 +00003228 // wasn't promoted because of the C90 rule that doesn't
3229 // allow promoting non-lvalue arrays. Warn, then
3230 // force the promotion here.
3231 Diag(LHSExp->getLocStart(), diag::ext_subscript_non_lvalue) <<
3232 LHSExp->getSourceRange();
John Wiegley01296292011-04-08 18:41:53 +00003233 LHSExp = ImpCastExprToType(LHSExp, Context.getArrayDecayedType(LHSTy),
3234 CK_ArrayToPointerDecay).take();
Eli Friedmanab2784f2009-04-25 23:46:54 +00003235 LHSTy = LHSExp->getType();
3236
3237 BaseExpr = LHSExp;
3238 IndexExpr = RHSExp;
Ted Kremenekc23c7e62009-07-29 21:53:49 +00003239 ResultType = LHSTy->getAs<PointerType>()->getPointeeType();
Eli Friedmanab2784f2009-04-25 23:46:54 +00003240 } else if (RHSTy->isArrayType()) {
3241 // Same as previous, except for 123[f().a] case
3242 Diag(RHSExp->getLocStart(), diag::ext_subscript_non_lvalue) <<
3243 RHSExp->getSourceRange();
John Wiegley01296292011-04-08 18:41:53 +00003244 RHSExp = ImpCastExprToType(RHSExp, Context.getArrayDecayedType(RHSTy),
3245 CK_ArrayToPointerDecay).take();
Eli Friedmanab2784f2009-04-25 23:46:54 +00003246 RHSTy = RHSExp->getType();
3247
3248 BaseExpr = RHSExp;
3249 IndexExpr = LHSExp;
Ted Kremenekc23c7e62009-07-29 21:53:49 +00003250 ResultType = RHSTy->getAs<PointerType>()->getPointeeType();
Steve Naroffb3096442007-06-09 03:47:53 +00003251 } else {
Chris Lattner003af242009-04-25 22:50:55 +00003252 return ExprError(Diag(LLoc, diag::err_typecheck_subscript_value)
3253 << LHSExp->getSourceRange() << RHSExp->getSourceRange());
Sebastian Redlc215cfc2009-01-19 00:08:26 +00003254 }
Steve Naroffc1aadb12007-03-28 21:49:40 +00003255 // C99 6.5.2.1p1
Douglas Gregor5cc2c8b2010-07-23 15:58:24 +00003256 if (!IndexExpr->getType()->isIntegerType() && !IndexExpr->isTypeDependent())
Chris Lattner003af242009-04-25 22:50:55 +00003257 return ExprError(Diag(LLoc, diag::err_typecheck_subscript_not_integer)
3258 << IndexExpr->getSourceRange());
Steve Naroffb29cdd52007-07-10 18:23:31 +00003259
Daniel Dunbar4782a6e2009-09-17 06:31:17 +00003260 if ((IndexExpr->getType()->isSpecificBuiltinType(BuiltinType::Char_S) ||
Sam Weinigb7608d72009-09-14 20:14:57 +00003261 IndexExpr->getType()->isSpecificBuiltinType(BuiltinType::Char_U))
3262 && !IndexExpr->isTypeDependent())
Sam Weinig914244e2009-09-14 01:58:58 +00003263 Diag(LLoc, diag::warn_subscript_is_char) << IndexExpr->getSourceRange();
3264
Douglas Gregorac1fb652009-03-24 19:52:54 +00003265 // C99 6.5.2.1p1: "shall have type "pointer to *object* type". Similarly,
Mike Stump11289f42009-09-09 15:08:12 +00003266 // C++ [expr.sub]p1: The type "T" shall be a completely-defined object
3267 // type. Note that Functions are not objects, and that (in C99 parlance)
Douglas Gregorac1fb652009-03-24 19:52:54 +00003268 // incomplete types are not object types.
3269 if (ResultType->isFunctionType()) {
3270 Diag(BaseExpr->getLocStart(), diag::err_subscript_function_type)
3271 << ResultType << BaseExpr->getSourceRange();
3272 return ExprError();
3273 }
Mike Stump11289f42009-09-09 15:08:12 +00003274
David Blaikiebbafb8a2012-03-11 07:00:24 +00003275 if (ResultType->isVoidType() && !getLangOpts().CPlusPlus) {
Abramo Bagnara3aabb4b2010-09-13 06:50:07 +00003276 // GNU extension: subscripting on pointer to void
Chandler Carruth4cc3f292011-06-27 16:32:27 +00003277 Diag(LLoc, diag::ext_gnu_subscript_void_type)
3278 << BaseExpr->getSourceRange();
John McCall4bc41ae2010-11-18 19:01:18 +00003279
3280 // C forbids expressions of unqualified void type from being l-values.
3281 // See IsCForbiddenLValueType.
3282 if (!ResultType.hasQualifiers()) VK = VK_RValue;
Abramo Bagnara3aabb4b2010-09-13 06:50:07 +00003283 } else if (!ResultType->isDependentType() &&
Mike Stump11289f42009-09-09 15:08:12 +00003284 RequireCompleteType(LLoc, ResultType,
Douglas Gregor7bfb2d02012-05-04 16:32:21 +00003285 diag::err_subscript_incomplete_type, BaseExpr))
Douglas Gregorac1fb652009-03-24 19:52:54 +00003286 return ExprError();
Mike Stump11289f42009-09-09 15:08:12 +00003287
Chris Lattner62975a72009-04-24 00:30:45 +00003288 // Diagnose bad cases where we step over interface counts.
John McCall8b07ec22010-05-15 11:32:37 +00003289 if (ResultType->isObjCObjectType() && LangOpts.ObjCNonFragileABI) {
Chris Lattner62975a72009-04-24 00:30:45 +00003290 Diag(LLoc, diag::err_subscript_nonfragile_interface)
3291 << ResultType << BaseExpr->getSourceRange();
3292 return ExprError();
3293 }
Mike Stump11289f42009-09-09 15:08:12 +00003294
John McCall4bc41ae2010-11-18 19:01:18 +00003295 assert(VK == VK_RValue || LangOpts.CPlusPlus ||
Douglas Gregor5476205b2011-06-23 00:49:38 +00003296 !ResultType.isCForbiddenLValueType());
John McCall4bc41ae2010-11-18 19:01:18 +00003297
Mike Stump4e1f26a2009-02-19 03:04:26 +00003298 return Owned(new (Context) ArraySubscriptExpr(LHSExp, RHSExp,
John McCall7decc9e2010-11-18 06:31:45 +00003299 ResultType, VK, OK, RLoc));
Chris Lattnere168f762006-11-10 05:29:30 +00003300}
3301
John McCalldadc5752010-08-24 06:29:42 +00003302ExprResult Sema::BuildCXXDefaultArgExpr(SourceLocation CallLoc,
Nico Weber44887f62010-11-29 18:19:25 +00003303 FunctionDecl *FD,
3304 ParmVarDecl *Param) {
Anders Carlsson355933d2009-08-25 03:49:14 +00003305 if (Param->hasUnparsedDefaultArg()) {
Douglas Gregor8a01b2a2010-09-11 20:24:53 +00003306 Diag(CallLoc,
Nico Weberebd45a02010-11-30 04:44:33 +00003307 diag::err_use_of_default_argument_to_function_declared_later) <<
Anders Carlsson355933d2009-08-25 03:49:14 +00003308 FD << cast<CXXRecordDecl>(FD->getDeclContext())->getDeclName();
Mike Stump11289f42009-09-09 15:08:12 +00003309 Diag(UnparsedDefaultArgLocs[Param],
Nico Weberebd45a02010-11-30 04:44:33 +00003310 diag::note_default_argument_declared_here);
Douglas Gregor8a01b2a2010-09-11 20:24:53 +00003311 return ExprError();
3312 }
3313
3314 if (Param->hasUninstantiatedDefaultArg()) {
3315 Expr *UninstExpr = Param->getUninstantiatedDefaultArg();
Anders Carlsson355933d2009-08-25 03:49:14 +00003316
Douglas Gregor8a01b2a2010-09-11 20:24:53 +00003317 // Instantiate the expression.
3318 MultiLevelTemplateArgumentList ArgList
3319 = getTemplateInstantiationArgs(FD, 0, /*RelativeToPrimary=*/true);
Anders Carlsson657bad42009-09-05 05:14:19 +00003320
Nico Weber44887f62010-11-29 18:19:25 +00003321 std::pair<const TemplateArgument *, unsigned> Innermost
Douglas Gregor8a01b2a2010-09-11 20:24:53 +00003322 = ArgList.getInnermost();
3323 InstantiatingTemplate Inst(*this, CallLoc, Param, Innermost.first,
3324 Innermost.second);
Anders Carlsson355933d2009-08-25 03:49:14 +00003325
Nico Weber44887f62010-11-29 18:19:25 +00003326 ExprResult Result;
3327 {
3328 // C++ [dcl.fct.default]p5:
3329 // The names in the [default argument] expression are bound, and
3330 // the semantic constraints are checked, at the point where the
3331 // default argument expression appears.
Nico Weberebd45a02010-11-30 04:44:33 +00003332 ContextRAII SavedContext(*this, FD);
Douglas Gregora86bc002012-02-16 21:36:18 +00003333 LocalInstantiationScope Local(*this);
Nico Weber44887f62010-11-29 18:19:25 +00003334 Result = SubstExpr(UninstExpr, ArgList);
3335 }
Douglas Gregor8a01b2a2010-09-11 20:24:53 +00003336 if (Result.isInvalid())
3337 return ExprError();
Mike Stump11289f42009-09-09 15:08:12 +00003338
Douglas Gregor8a01b2a2010-09-11 20:24:53 +00003339 // Check the expression as an initializer for the parameter.
3340 InitializedEntity Entity
Fariborz Jahanian8fb87ae2010-09-24 17:30:16 +00003341 = InitializedEntity::InitializeParameter(Context, Param);
Douglas Gregor8a01b2a2010-09-11 20:24:53 +00003342 InitializationKind Kind
3343 = InitializationKind::CreateCopy(Param->getLocation(),
Daniel Dunbar62ee6412012-03-09 18:35:03 +00003344 /*FIXME:EqualLoc*/UninstExpr->getLocStart());
Douglas Gregor8a01b2a2010-09-11 20:24:53 +00003345 Expr *ResultE = Result.takeAs<Expr>();
Douglas Gregor25ab25f2009-12-23 18:19:08 +00003346
Douglas Gregor8a01b2a2010-09-11 20:24:53 +00003347 InitializationSequence InitSeq(*this, Entity, Kind, &ResultE, 1);
3348 Result = InitSeq.Perform(*this, Entity, Kind,
3349 MultiExprArg(*this, &ResultE, 1));
3350 if (Result.isInvalid())
3351 return ExprError();
Kovarththanan Rajaratnamba2c6522010-03-13 10:17:05 +00003352
David Blaikief68e8092012-04-30 18:21:31 +00003353 Expr *Arg = Result.takeAs<Expr>();
David Blaikie18e9ac72012-05-15 21:57:38 +00003354 CheckImplicitConversions(Arg, Param->getOuterLocStart());
Douglas Gregor8a01b2a2010-09-11 20:24:53 +00003355 // Build the default argument expression.
David Blaikief68e8092012-04-30 18:21:31 +00003356 return Owned(CXXDefaultArgExpr::Create(Context, CallLoc, Param, Arg));
Anders Carlsson355933d2009-08-25 03:49:14 +00003357 }
3358
Douglas Gregor8a01b2a2010-09-11 20:24:53 +00003359 // If the default expression creates temporaries, we need to
3360 // push them to the current stack of expression temporaries so they'll
3361 // be properly destroyed.
3362 // FIXME: We should really be rebuilding the default argument with new
3363 // bound temporaries; see the comment in PR5810.
John McCall28fc7092011-11-10 05:35:25 +00003364 // We don't need to do that with block decls, though, because
3365 // blocks in default argument expression can never capture anything.
3366 if (isa<ExprWithCleanups>(Param->getInit())) {
3367 // Set the "needs cleanups" bit regardless of whether there are
3368 // any explicit objects.
John McCall31168b02011-06-15 23:02:42 +00003369 ExprNeedsCleanups = true;
John McCall28fc7092011-11-10 05:35:25 +00003370
3371 // Append all the objects to the cleanup list. Right now, this
3372 // should always be a no-op, because blocks in default argument
3373 // expressions should never be able to capture anything.
3374 assert(!cast<ExprWithCleanups>(Param->getInit())->getNumObjects() &&
3375 "default argument expression has capturing blocks?");
Douglas Gregor6ed2fee2010-09-14 22:55:20 +00003376 }
Douglas Gregor8a01b2a2010-09-11 20:24:53 +00003377
3378 // We already type-checked the argument, so we know it works.
Douglas Gregor32b3de52010-09-11 23:32:50 +00003379 // Just mark all of the declarations in this potentially-evaluated expression
3380 // as being "referenced".
Douglas Gregor680e9e02012-02-21 19:11:17 +00003381 MarkDeclarationsReferencedInExpr(Param->getDefaultArg(),
3382 /*SkipLocalVariables=*/true);
Douglas Gregor033f6752009-12-23 23:03:06 +00003383 return Owned(CXXDefaultArgExpr::Create(Context, CallLoc, Param));
Anders Carlsson355933d2009-08-25 03:49:14 +00003384}
3385
Douglas Gregor97fd6e22008-12-22 05:46:06 +00003386/// ConvertArgumentsForCall - Converts the arguments specified in
3387/// Args/NumArgs to the parameter types of the function FDecl with
3388/// function prototype Proto. Call is the call expression itself, and
3389/// Fn is the function expression. For a C++ member function, this
3390/// routine does not attempt to convert the object argument. Returns
3391/// true if the call is ill-formed.
Mike Stump4e1f26a2009-02-19 03:04:26 +00003392bool
3393Sema::ConvertArgumentsForCall(CallExpr *Call, Expr *Fn,
Douglas Gregor97fd6e22008-12-22 05:46:06 +00003394 FunctionDecl *FDecl,
Douglas Gregordeaad8c2009-02-26 23:50:07 +00003395 const FunctionProtoType *Proto,
Douglas Gregor97fd6e22008-12-22 05:46:06 +00003396 Expr **Args, unsigned NumArgs,
Peter Collingbourne619a8c72011-10-02 23:49:29 +00003397 SourceLocation RParenLoc,
3398 bool IsExecConfig) {
John McCallbebede42011-02-26 05:39:39 +00003399 // Bail out early if calling a builtin with custom typechecking.
3400 // We don't need to do this in the
3401 if (FDecl)
3402 if (unsigned ID = FDecl->getBuiltinID())
3403 if (Context.BuiltinInfo.hasCustomTypechecking(ID))
3404 return false;
3405
Mike Stump4e1f26a2009-02-19 03:04:26 +00003406 // C99 6.5.2.2p7 - the arguments are implicitly converted, as if by
Douglas Gregor97fd6e22008-12-22 05:46:06 +00003407 // assignment, to the types of the corresponding parameter, ...
3408 unsigned NumArgsInProto = Proto->getNumArgs();
Douglas Gregorb6b99612009-01-23 21:30:56 +00003409 bool Invalid = false;
Peter Collingbourne740afe22011-10-02 23:49:20 +00003410 unsigned MinArgs = FDecl ? FDecl->getMinRequiredArguments() : NumArgsInProto;
Peter Collingbourne619a8c72011-10-02 23:49:29 +00003411 unsigned FnKind = Fn->getType()->isBlockPointerType()
3412 ? 1 /* block */
3413 : (IsExecConfig ? 3 /* kernel function (exec config) */
3414 : 0 /* function */);
Kovarththanan Rajaratnamba2c6522010-03-13 10:17:05 +00003415
Douglas Gregor97fd6e22008-12-22 05:46:06 +00003416 // If too few arguments are available (and we don't have default
3417 // arguments for the remaining parameters), don't make the call.
3418 if (NumArgs < NumArgsInProto) {
Peter Collingbourne740afe22011-10-02 23:49:20 +00003419 if (NumArgs < MinArgs) {
Richard Smith10ff50d2012-05-11 05:16:41 +00003420 if (MinArgs == 1 && FDecl && FDecl->getParamDecl(0)->getDeclName())
3421 Diag(RParenLoc, MinArgs == NumArgsInProto && !Proto->isVariadic()
3422 ? diag::err_typecheck_call_too_few_args_one
3423 : diag::err_typecheck_call_too_few_args_at_least_one)
3424 << FnKind
3425 << FDecl->getParamDecl(0) << Fn->getSourceRange();
3426 else
3427 Diag(RParenLoc, MinArgs == NumArgsInProto && !Proto->isVariadic()
3428 ? diag::err_typecheck_call_too_few_args
3429 : diag::err_typecheck_call_too_few_args_at_least)
3430 << FnKind
3431 << MinArgs << NumArgs << Fn->getSourceRange();
Peter Collingbourne3bc84ca2011-07-29 00:24:42 +00003432
3433 // Emit the location of the prototype.
Peter Collingbourne619a8c72011-10-02 23:49:29 +00003434 if (FDecl && !FDecl->getBuiltinID() && !IsExecConfig)
Peter Collingbourne3bc84ca2011-07-29 00:24:42 +00003435 Diag(FDecl->getLocStart(), diag::note_callee_decl)
3436 << FDecl;
3437
3438 return true;
3439 }
Ted Kremenek5a201952009-02-07 01:47:29 +00003440 Call->setNumArgs(Context, NumArgsInProto);
Douglas Gregor97fd6e22008-12-22 05:46:06 +00003441 }
3442
3443 // If too many are passed and not variadic, error on the extras and drop
3444 // them.
3445 if (NumArgs > NumArgsInProto) {
3446 if (!Proto->isVariadic()) {
Richard Smithd72da152012-05-15 06:21:54 +00003447 if (NumArgsInProto == 1 && FDecl && FDecl->getParamDecl(0)->getDeclName())
3448 Diag(Args[NumArgsInProto]->getLocStart(),
3449 MinArgs == NumArgsInProto
3450 ? diag::err_typecheck_call_too_many_args_one
3451 : diag::err_typecheck_call_too_many_args_at_most_one)
3452 << FnKind
3453 << FDecl->getParamDecl(0) << NumArgs << Fn->getSourceRange()
3454 << SourceRange(Args[NumArgsInProto]->getLocStart(),
3455 Args[NumArgs-1]->getLocEnd());
3456 else
3457 Diag(Args[NumArgsInProto]->getLocStart(),
3458 MinArgs == NumArgsInProto
3459 ? diag::err_typecheck_call_too_many_args
3460 : diag::err_typecheck_call_too_many_args_at_most)
3461 << FnKind
3462 << NumArgsInProto << NumArgs << Fn->getSourceRange()
3463 << SourceRange(Args[NumArgsInProto]->getLocStart(),
3464 Args[NumArgs-1]->getLocEnd());
Ted Kremenek99a337e2011-04-04 17:22:27 +00003465
3466 // Emit the location of the prototype.
Peter Collingbourne619a8c72011-10-02 23:49:29 +00003467 if (FDecl && !FDecl->getBuiltinID() && !IsExecConfig)
Peter Collingbourne3bc84ca2011-07-29 00:24:42 +00003468 Diag(FDecl->getLocStart(), diag::note_callee_decl)
3469 << FDecl;
Ted Kremenek99a337e2011-04-04 17:22:27 +00003470
Douglas Gregor97fd6e22008-12-22 05:46:06 +00003471 // This deletes the extra arguments.
Ted Kremenek5a201952009-02-07 01:47:29 +00003472 Call->setNumArgs(Context, NumArgsInProto);
Fariborz Jahanian835026e2009-11-24 18:29:37 +00003473 return true;
Douglas Gregor97fd6e22008-12-22 05:46:06 +00003474 }
Douglas Gregor97fd6e22008-12-22 05:46:06 +00003475 }
Chris Lattner0e62c1c2011-07-23 10:55:15 +00003476 SmallVector<Expr *, 8> AllArgs;
Kovarththanan Rajaratnamba2c6522010-03-13 10:17:05 +00003477 VariadicCallType CallType =
Fariborz Jahanian6f2d25e2009-11-24 19:27:49 +00003478 Proto->isVariadic() ? VariadicFunction : VariadicDoesNotApply;
3479 if (Fn->getType()->isBlockPointerType())
3480 CallType = VariadicBlock; // Block
3481 else if (isa<MemberExpr>(Fn))
3482 CallType = VariadicMethod;
Daniel Dunbar62ee6412012-03-09 18:35:03 +00003483 Invalid = GatherArgumentsForCall(Call->getLocStart(), FDecl,
Fariborz Jahanian4fa66ce2009-11-24 21:37:28 +00003484 Proto, 0, Args, NumArgs, AllArgs, CallType);
Fariborz Jahanian835026e2009-11-24 18:29:37 +00003485 if (Invalid)
3486 return true;
3487 unsigned TotalNumArgs = AllArgs.size();
3488 for (unsigned i = 0; i < TotalNumArgs; ++i)
3489 Call->setArg(i, AllArgs[i]);
Kovarththanan Rajaratnamba2c6522010-03-13 10:17:05 +00003490
Fariborz Jahanian835026e2009-11-24 18:29:37 +00003491 return false;
3492}
Mike Stump4e1f26a2009-02-19 03:04:26 +00003493
Fariborz Jahanian835026e2009-11-24 18:29:37 +00003494bool Sema::GatherArgumentsForCall(SourceLocation CallLoc,
3495 FunctionDecl *FDecl,
3496 const FunctionProtoType *Proto,
3497 unsigned FirstProtoArg,
3498 Expr **Args, unsigned NumArgs,
Chris Lattner0e62c1c2011-07-23 10:55:15 +00003499 SmallVector<Expr *, 8> &AllArgs,
Douglas Gregor6073dca2012-02-24 23:56:31 +00003500 VariadicCallType CallType,
3501 bool AllowExplicit) {
Fariborz Jahanian835026e2009-11-24 18:29:37 +00003502 unsigned NumArgsInProto = Proto->getNumArgs();
3503 unsigned NumArgsToCheck = NumArgs;
3504 bool Invalid = false;
3505 if (NumArgs != NumArgsInProto)
3506 // Use default arguments for missing arguments
3507 NumArgsToCheck = NumArgsInProto;
3508 unsigned ArgIx = 0;
Douglas Gregor97fd6e22008-12-22 05:46:06 +00003509 // Continue to check argument types (even if we have too few/many args).
Fariborz Jahanian835026e2009-11-24 18:29:37 +00003510 for (unsigned i = FirstProtoArg; i != NumArgsToCheck; i++) {
Douglas Gregor97fd6e22008-12-22 05:46:06 +00003511 QualType ProtoArgType = Proto->getArgType(i);
Kovarththanan Rajaratnamba2c6522010-03-13 10:17:05 +00003512
Douglas Gregor97fd6e22008-12-22 05:46:06 +00003513 Expr *Arg;
Peter Collingbournea48f33f2011-10-19 00:16:45 +00003514 ParmVarDecl *Param;
Fariborz Jahanian835026e2009-11-24 18:29:37 +00003515 if (ArgIx < NumArgs) {
3516 Arg = Args[ArgIx++];
Kovarththanan Rajaratnamba2c6522010-03-13 10:17:05 +00003517
Daniel Dunbar62ee6412012-03-09 18:35:03 +00003518 if (RequireCompleteType(Arg->getLocStart(),
Eli Friedman3164fb12009-03-22 22:00:50 +00003519 ProtoArgType,
Douglas Gregor7bfb2d02012-05-04 16:32:21 +00003520 diag::err_call_incomplete_argument, Arg))
Eli Friedman3164fb12009-03-22 22:00:50 +00003521 return true;
Kovarththanan Rajaratnamba2c6522010-03-13 10:17:05 +00003522
Douglas Gregorbbeb5c32009-12-22 16:09:06 +00003523 // Pass the argument
Peter Collingbournea48f33f2011-10-19 00:16:45 +00003524 Param = 0;
Douglas Gregorbbeb5c32009-12-22 16:09:06 +00003525 if (FDecl && i < FDecl->getNumParams())
3526 Param = FDecl->getParamDecl(i);
Douglas Gregor96596c92009-12-22 07:24:36 +00003527
John McCall4124c492011-10-17 18:40:02 +00003528 // Strip the unbridged-cast placeholder expression off, if applicable.
3529 if (Arg->getType() == Context.ARCUnbridgedCastTy &&
3530 FDecl && FDecl->hasAttr<CFAuditedTransferAttr>() &&
3531 (!Param || !Param->hasAttr<CFConsumedAttr>()))
3532 Arg = stripARCUnbridgedCast(Arg);
3533
Douglas Gregorbbeb5c32009-12-22 16:09:06 +00003534 InitializedEntity Entity =
Fariborz Jahanian8fb87ae2010-09-24 17:30:16 +00003535 Param? InitializedEntity::InitializeParameter(Context, Param)
John McCall31168b02011-06-15 23:02:42 +00003536 : InitializedEntity::InitializeParameter(Context, ProtoArgType,
3537 Proto->isArgConsumed(i));
John McCalldadc5752010-08-24 06:29:42 +00003538 ExprResult ArgE = PerformCopyInitialization(Entity,
John McCall34376a62010-12-04 03:47:34 +00003539 SourceLocation(),
Douglas Gregor6073dca2012-02-24 23:56:31 +00003540 Owned(Arg),
3541 /*TopLevelOfInitList=*/false,
3542 AllowExplicit);
Douglas Gregorbbeb5c32009-12-22 16:09:06 +00003543 if (ArgE.isInvalid())
3544 return true;
3545
3546 Arg = ArgE.takeAs<Expr>();
Anders Carlsson84613c42009-06-12 16:51:40 +00003547 } else {
Peter Collingbournea48f33f2011-10-19 00:16:45 +00003548 Param = FDecl->getParamDecl(i);
Kovarththanan Rajaratnamba2c6522010-03-13 10:17:05 +00003549
John McCalldadc5752010-08-24 06:29:42 +00003550 ExprResult ArgExpr =
Fariborz Jahanian835026e2009-11-24 18:29:37 +00003551 BuildCXXDefaultArgExpr(CallLoc, FDecl, Param);
Anders Carlsson355933d2009-08-25 03:49:14 +00003552 if (ArgExpr.isInvalid())
3553 return true;
Kovarththanan Rajaratnamba2c6522010-03-13 10:17:05 +00003554
Anders Carlsson355933d2009-08-25 03:49:14 +00003555 Arg = ArgExpr.takeAs<Expr>();
Anders Carlsson84613c42009-06-12 16:51:40 +00003556 }
Kaelyn Uhrain2e7aa5a2011-08-05 23:18:04 +00003557
3558 // Check for array bounds violations for each argument to the call. This
3559 // check only triggers warnings when the argument isn't a more complex Expr
3560 // with its own checking, such as a BinaryOperator.
3561 CheckArrayAccess(Arg);
3562
Peter Collingbournea48f33f2011-10-19 00:16:45 +00003563 // Check for violations of C99 static array rules (C99 6.7.5.3p7).
3564 CheckStaticArrayArgument(CallLoc, Param, Arg);
3565
Fariborz Jahanian835026e2009-11-24 18:29:37 +00003566 AllArgs.push_back(Arg);
Douglas Gregor97fd6e22008-12-22 05:46:06 +00003567 }
Kovarththanan Rajaratnamba2c6522010-03-13 10:17:05 +00003568
Douglas Gregor97fd6e22008-12-22 05:46:06 +00003569 // If this is a variadic call, handle args passed through "...".
Fariborz Jahanian6f2d25e2009-11-24 19:27:49 +00003570 if (CallType != VariadicDoesNotApply) {
John McCall2979fe02011-04-12 00:42:48 +00003571
3572 // Assume that extern "C" functions with variadic arguments that
3573 // return __unknown_anytype aren't *really* variadic.
3574 if (Proto->getResultType() == Context.UnknownAnyTy &&
3575 FDecl && FDecl->isExternC()) {
3576 for (unsigned i = ArgIx; i != NumArgs; ++i) {
3577 ExprResult arg;
3578 if (isa<ExplicitCastExpr>(Args[i]->IgnoreParens()))
3579 arg = DefaultFunctionArrayLvalueConversion(Args[i]);
3580 else
3581 arg = DefaultVariadicArgumentPromotion(Args[i], CallType, FDecl);
3582 Invalid |= arg.isInvalid();
3583 AllArgs.push_back(arg.take());
3584 }
3585
3586 // Otherwise do argument promotion, (C99 6.5.2.2p7).
3587 } else {
3588 for (unsigned i = ArgIx; i != NumArgs; ++i) {
Richard Trieucfc491d2011-08-02 04:35:43 +00003589 ExprResult Arg = DefaultVariadicArgumentPromotion(Args[i], CallType,
3590 FDecl);
John McCall2979fe02011-04-12 00:42:48 +00003591 Invalid |= Arg.isInvalid();
3592 AllArgs.push_back(Arg.take());
3593 }
Douglas Gregor97fd6e22008-12-22 05:46:06 +00003594 }
Ted Kremenekd41f3462011-09-26 23:36:13 +00003595
3596 // Check for array bounds violations.
3597 for (unsigned i = ArgIx; i != NumArgs; ++i)
3598 CheckArrayAccess(Args[i]);
Douglas Gregor97fd6e22008-12-22 05:46:06 +00003599 }
Douglas Gregorb6b99612009-01-23 21:30:56 +00003600 return Invalid;
Douglas Gregor97fd6e22008-12-22 05:46:06 +00003601}
3602
Peter Collingbournea48f33f2011-10-19 00:16:45 +00003603static void DiagnoseCalleeStaticArrayParam(Sema &S, ParmVarDecl *PVD) {
3604 TypeLoc TL = PVD->getTypeSourceInfo()->getTypeLoc();
3605 if (ArrayTypeLoc *ATL = dyn_cast<ArrayTypeLoc>(&TL))
3606 S.Diag(PVD->getLocation(), diag::note_callee_static_array)
3607 << ATL->getLocalSourceRange();
3608}
3609
3610/// CheckStaticArrayArgument - If the given argument corresponds to a static
3611/// array parameter, check that it is non-null, and that if it is formed by
3612/// array-to-pointer decay, the underlying array is sufficiently large.
3613///
3614/// C99 6.7.5.3p7: If the keyword static also appears within the [ and ] of the
3615/// array type derivation, then for each call to the function, the value of the
3616/// corresponding actual argument shall provide access to the first element of
3617/// an array with at least as many elements as specified by the size expression.
3618void
3619Sema::CheckStaticArrayArgument(SourceLocation CallLoc,
3620 ParmVarDecl *Param,
3621 const Expr *ArgExpr) {
3622 // Static array parameters are not supported in C++.
David Blaikiebbafb8a2012-03-11 07:00:24 +00003623 if (!Param || getLangOpts().CPlusPlus)
Peter Collingbournea48f33f2011-10-19 00:16:45 +00003624 return;
3625
3626 QualType OrigTy = Param->getOriginalType();
3627
3628 const ArrayType *AT = Context.getAsArrayType(OrigTy);
3629 if (!AT || AT->getSizeModifier() != ArrayType::Static)
3630 return;
3631
3632 if (ArgExpr->isNullPointerConstant(Context,
3633 Expr::NPC_NeverValueDependent)) {
3634 Diag(CallLoc, diag::warn_null_arg) << ArgExpr->getSourceRange();
3635 DiagnoseCalleeStaticArrayParam(*this, Param);
3636 return;
3637 }
3638
3639 const ConstantArrayType *CAT = dyn_cast<ConstantArrayType>(AT);
3640 if (!CAT)
3641 return;
3642
3643 const ConstantArrayType *ArgCAT =
3644 Context.getAsConstantArrayType(ArgExpr->IgnoreParenImpCasts()->getType());
3645 if (!ArgCAT)
3646 return;
3647
3648 if (ArgCAT->getSize().ult(CAT->getSize())) {
3649 Diag(CallLoc, diag::warn_static_array_too_small)
3650 << ArgExpr->getSourceRange()
3651 << (unsigned) ArgCAT->getSize().getZExtValue()
3652 << (unsigned) CAT->getSize().getZExtValue();
3653 DiagnoseCalleeStaticArrayParam(*this, Param);
3654 }
3655}
3656
John McCall2979fe02011-04-12 00:42:48 +00003657/// Given a function expression of unknown-any type, try to rebuild it
3658/// to have a function type.
3659static ExprResult rebuildUnknownAnyFunction(Sema &S, Expr *fn);
3660
Steve Naroff83895f72007-09-16 03:34:24 +00003661/// ActOnCallExpr - Handle a call to Fn with the specified array of arguments.
Chris Lattnere168f762006-11-10 05:29:30 +00003662/// This provides the location of the left/right parens and a list of comma
3663/// locations.
John McCalldadc5752010-08-24 06:29:42 +00003664ExprResult
John McCallb268a282010-08-23 23:25:46 +00003665Sema::ActOnCallExpr(Scope *S, Expr *Fn, SourceLocation LParenLoc,
Richard Trieuba63ce62011-09-09 01:45:06 +00003666 MultiExprArg ArgExprs, SourceLocation RParenLoc,
Peter Collingbourne619a8c72011-10-02 23:49:29 +00003667 Expr *ExecConfig, bool IsExecConfig) {
Richard Trieuba63ce62011-09-09 01:45:06 +00003668 unsigned NumArgs = ArgExprs.size();
Nate Begeman5ec4b312009-08-10 23:49:36 +00003669
3670 // Since this might be a postfix expression, get rid of ParenListExprs.
John McCalldadc5752010-08-24 06:29:42 +00003671 ExprResult Result = MaybeConvertParenListExprToParenExpr(S, Fn);
John McCallb268a282010-08-23 23:25:46 +00003672 if (Result.isInvalid()) return ExprError();
3673 Fn = Result.take();
Mike Stump11289f42009-09-09 15:08:12 +00003674
Richard Trieuba63ce62011-09-09 01:45:06 +00003675 Expr **Args = ArgExprs.release();
Mike Stump11289f42009-09-09 15:08:12 +00003676
David Blaikiebbafb8a2012-03-11 07:00:24 +00003677 if (getLangOpts().CPlusPlus) {
Douglas Gregorad8a3362009-09-04 17:36:40 +00003678 // If this is a pseudo-destructor expression, build the call immediately.
3679 if (isa<CXXPseudoDestructorExpr>(Fn)) {
3680 if (NumArgs > 0) {
3681 // Pseudo-destructor calls should not have any arguments.
3682 Diag(Fn->getLocStart(), diag::err_pseudo_dtor_call_with_args)
Douglas Gregora771f462010-03-31 17:46:05 +00003683 << FixItHint::CreateRemoval(
Douglas Gregorad8a3362009-09-04 17:36:40 +00003684 SourceRange(Args[0]->getLocStart(),
3685 Args[NumArgs-1]->getLocEnd()));
Douglas Gregorad8a3362009-09-04 17:36:40 +00003686 }
Mike Stump11289f42009-09-09 15:08:12 +00003687
Douglas Gregorad8a3362009-09-04 17:36:40 +00003688 return Owned(new (Context) CallExpr(Context, Fn, 0, 0, Context.VoidTy,
John McCall7decc9e2010-11-18 06:31:45 +00003689 VK_RValue, RParenLoc));
Douglas Gregorad8a3362009-09-04 17:36:40 +00003690 }
Mike Stump11289f42009-09-09 15:08:12 +00003691
Douglas Gregorb8a9a412009-02-04 15:01:18 +00003692 // Determine whether this is a dependent call inside a C++ template,
Mike Stump4e1f26a2009-02-19 03:04:26 +00003693 // in which case we won't do any semantic analysis now.
Mike Stump87c57ac2009-05-16 07:39:55 +00003694 // FIXME: Will need to cache the results of name lookup (including ADL) in
3695 // Fn.
Douglas Gregorb8a9a412009-02-04 15:01:18 +00003696 bool Dependent = false;
3697 if (Fn->isTypeDependent())
3698 Dependent = true;
Ahmed Charlesb24b9aa2012-02-25 11:00:22 +00003699 else if (Expr::hasAnyTypeDependentArguments(
3700 llvm::makeArrayRef(Args, NumArgs)))
Douglas Gregorb8a9a412009-02-04 15:01:18 +00003701 Dependent = true;
3702
Peter Collingbourne41f85462011-02-09 21:07:24 +00003703 if (Dependent) {
3704 if (ExecConfig) {
3705 return Owned(new (Context) CUDAKernelCallExpr(
3706 Context, Fn, cast<CallExpr>(ExecConfig), Args, NumArgs,
3707 Context.DependentTy, VK_RValue, RParenLoc));
3708 } else {
3709 return Owned(new (Context) CallExpr(Context, Fn, Args, NumArgs,
3710 Context.DependentTy, VK_RValue,
3711 RParenLoc));
3712 }
3713 }
Douglas Gregorb8a9a412009-02-04 15:01:18 +00003714
3715 // Determine whether this is a call to an object (C++ [over.call.object]).
3716 if (Fn->getType()->isRecordType())
3717 return Owned(BuildCallToObjectOfClassType(S, Fn, LParenLoc, Args, NumArgs,
Douglas Gregorce5aa332010-09-09 16:33:13 +00003718 RParenLoc));
Douglas Gregorb8a9a412009-02-04 15:01:18 +00003719
John McCall2979fe02011-04-12 00:42:48 +00003720 if (Fn->getType() == Context.UnknownAnyTy) {
3721 ExprResult result = rebuildUnknownAnyFunction(*this, Fn);
3722 if (result.isInvalid()) return ExprError();
3723 Fn = result.take();
3724 }
3725
John McCall0009fcc2011-04-26 20:42:42 +00003726 if (Fn->getType() == Context.BoundMemberTy) {
John McCall2d74de92009-12-01 22:10:20 +00003727 return BuildCallToMemberFunction(S, Fn, LParenLoc, Args, NumArgs,
Douglas Gregorce5aa332010-09-09 16:33:13 +00003728 RParenLoc);
John McCall10eae182009-11-30 22:42:35 +00003729 }
John McCall0009fcc2011-04-26 20:42:42 +00003730 }
John McCall10eae182009-11-30 22:42:35 +00003731
John McCall0009fcc2011-04-26 20:42:42 +00003732 // Check for overloaded calls. This can happen even in C due to extensions.
3733 if (Fn->getType() == Context.OverloadTy) {
3734 OverloadExpr::FindResult find = OverloadExpr::find(Fn);
3735
Douglas Gregorcda22702011-10-13 18:10:35 +00003736 // We aren't supposed to apply this logic for if there's an '&' involved.
Douglas Gregorf4a06c22011-10-13 18:26:27 +00003737 if (!find.HasFormOfMemberPointer) {
John McCall0009fcc2011-04-26 20:42:42 +00003738 OverloadExpr *ovl = find.Expression;
3739 if (isa<UnresolvedLookupExpr>(ovl)) {
3740 UnresolvedLookupExpr *ULE = cast<UnresolvedLookupExpr>(ovl);
3741 return BuildOverloadedCallExpr(S, Fn, ULE, LParenLoc, Args, NumArgs,
3742 RParenLoc, ExecConfig);
3743 } else {
John McCall2d74de92009-12-01 22:10:20 +00003744 return BuildCallToMemberFunction(S, Fn, LParenLoc, Args, NumArgs,
Douglas Gregorce5aa332010-09-09 16:33:13 +00003745 RParenLoc);
Anders Carlsson61914b52009-10-03 17:40:22 +00003746 }
3747 }
Douglas Gregor97fd6e22008-12-22 05:46:06 +00003748 }
3749
Douglas Gregore254f902009-02-04 00:32:51 +00003750 // If we're directly calling a function, get the appropriate declaration.
Douglas Gregord8fb1e32011-12-01 01:37:36 +00003751 if (Fn->getType() == Context.UnknownAnyTy) {
3752 ExprResult result = rebuildUnknownAnyFunction(*this, Fn);
3753 if (result.isInvalid()) return ExprError();
3754 Fn = result.take();
3755 }
Mike Stump4e1f26a2009-02-19 03:04:26 +00003756
Eli Friedmane14b1992009-12-26 03:35:45 +00003757 Expr *NakedFn = Fn->IgnoreParens();
Douglas Gregor928479e2010-11-09 20:03:54 +00003758
John McCall57500772009-12-16 12:17:52 +00003759 NamedDecl *NDecl = 0;
Douglas Gregor59f16ed2010-10-25 20:48:33 +00003760 if (UnaryOperator *UnOp = dyn_cast<UnaryOperator>(NakedFn))
3761 if (UnOp->getOpcode() == UO_AddrOf)
3762 NakedFn = UnOp->getSubExpr()->IgnoreParens();
3763
John McCall57500772009-12-16 12:17:52 +00003764 if (isa<DeclRefExpr>(NakedFn))
3765 NDecl = cast<DeclRefExpr>(NakedFn)->getDecl();
John McCall0009fcc2011-04-26 20:42:42 +00003766 else if (isa<MemberExpr>(NakedFn))
3767 NDecl = cast<MemberExpr>(NakedFn)->getMemberDecl();
John McCall57500772009-12-16 12:17:52 +00003768
Peter Collingbourne41f85462011-02-09 21:07:24 +00003769 return BuildResolvedCallExpr(Fn, NDecl, LParenLoc, Args, NumArgs, RParenLoc,
Peter Collingbourne619a8c72011-10-02 23:49:29 +00003770 ExecConfig, IsExecConfig);
Peter Collingbourne41f85462011-02-09 21:07:24 +00003771}
3772
3773ExprResult
3774Sema::ActOnCUDAExecConfigExpr(Scope *S, SourceLocation LLLLoc,
Richard Trieuba63ce62011-09-09 01:45:06 +00003775 MultiExprArg ExecConfig, SourceLocation GGGLoc) {
Peter Collingbourne41f85462011-02-09 21:07:24 +00003776 FunctionDecl *ConfigDecl = Context.getcudaConfigureCallDecl();
3777 if (!ConfigDecl)
3778 return ExprError(Diag(LLLLoc, diag::err_undeclared_var_use)
3779 << "cudaConfigureCall");
3780 QualType ConfigQTy = ConfigDecl->getType();
3781
3782 DeclRefExpr *ConfigDR = new (Context) DeclRefExpr(
John McCall113bee02012-03-10 09:33:50 +00003783 ConfigDecl, false, ConfigQTy, VK_LValue, LLLLoc);
Eli Friedmanfa0df832012-02-02 03:46:19 +00003784 MarkFunctionReferenced(LLLLoc, ConfigDecl);
Peter Collingbourne41f85462011-02-09 21:07:24 +00003785
Peter Collingbourne619a8c72011-10-02 23:49:29 +00003786 return ActOnCallExpr(S, ConfigDR, LLLLoc, ExecConfig, GGGLoc, 0,
3787 /*IsExecConfig=*/true);
John McCall2d74de92009-12-01 22:10:20 +00003788}
3789
Tanya Lattner55808c12011-06-04 00:47:47 +00003790/// ActOnAsTypeExpr - create a new asType (bitcast) from the arguments.
3791///
3792/// __builtin_astype( value, dst type )
3793///
Richard Trieuba63ce62011-09-09 01:45:06 +00003794ExprResult Sema::ActOnAsTypeExpr(Expr *E, ParsedType ParsedDestTy,
Tanya Lattner55808c12011-06-04 00:47:47 +00003795 SourceLocation BuiltinLoc,
3796 SourceLocation RParenLoc) {
3797 ExprValueKind VK = VK_RValue;
3798 ExprObjectKind OK = OK_Ordinary;
Richard Trieuba63ce62011-09-09 01:45:06 +00003799 QualType DstTy = GetTypeFromParser(ParsedDestTy);
3800 QualType SrcTy = E->getType();
Tanya Lattner55808c12011-06-04 00:47:47 +00003801 if (Context.getTypeSize(DstTy) != Context.getTypeSize(SrcTy))
3802 return ExprError(Diag(BuiltinLoc,
3803 diag::err_invalid_astype_of_different_size)
Peter Collingbourne23f1bee2011-06-08 15:15:17 +00003804 << DstTy
3805 << SrcTy
Richard Trieuba63ce62011-09-09 01:45:06 +00003806 << E->getSourceRange());
3807 return Owned(new (Context) AsTypeExpr(E, DstTy, VK, OK, BuiltinLoc,
Richard Trieucfc491d2011-08-02 04:35:43 +00003808 RParenLoc));
Tanya Lattner55808c12011-06-04 00:47:47 +00003809}
3810
John McCall57500772009-12-16 12:17:52 +00003811/// BuildResolvedCallExpr - Build a call to a resolved expression,
3812/// i.e. an expression not of \p OverloadTy. The expression should
John McCall2d74de92009-12-01 22:10:20 +00003813/// unary-convert to an expression of function-pointer or
3814/// block-pointer type.
3815///
3816/// \param NDecl the declaration being called, if available
John McCalldadc5752010-08-24 06:29:42 +00003817ExprResult
John McCall2d74de92009-12-01 22:10:20 +00003818Sema::BuildResolvedCallExpr(Expr *Fn, NamedDecl *NDecl,
3819 SourceLocation LParenLoc,
3820 Expr **Args, unsigned NumArgs,
Peter Collingbourne41f85462011-02-09 21:07:24 +00003821 SourceLocation RParenLoc,
Peter Collingbourne619a8c72011-10-02 23:49:29 +00003822 Expr *Config, bool IsExecConfig) {
John McCall2d74de92009-12-01 22:10:20 +00003823 FunctionDecl *FDecl = dyn_cast_or_null<FunctionDecl>(NDecl);
3824
Chris Lattneraa9c7ae2008-04-08 04:40:51 +00003825 // Promote the function operand.
John Wiegley01296292011-04-08 18:41:53 +00003826 ExprResult Result = UsualUnaryConversions(Fn);
3827 if (Result.isInvalid())
3828 return ExprError();
3829 Fn = Result.take();
Chris Lattneraa9c7ae2008-04-08 04:40:51 +00003830
Chris Lattner08464942007-12-28 05:29:59 +00003831 // Make the call expr early, before semantic checks. This guarantees cleanup
3832 // of arguments and function on error.
Peter Collingbourne41f85462011-02-09 21:07:24 +00003833 CallExpr *TheCall;
Eric Christopher13586ab2012-05-30 01:14:28 +00003834 if (Config)
Peter Collingbourne41f85462011-02-09 21:07:24 +00003835 TheCall = new (Context) CUDAKernelCallExpr(Context, Fn,
3836 cast<CallExpr>(Config),
3837 Args, NumArgs,
3838 Context.BoolTy,
3839 VK_RValue,
3840 RParenLoc);
Eric Christopher13586ab2012-05-30 01:14:28 +00003841 else
Peter Collingbourne41f85462011-02-09 21:07:24 +00003842 TheCall = new (Context) CallExpr(Context, Fn,
3843 Args, NumArgs,
3844 Context.BoolTy,
3845 VK_RValue,
3846 RParenLoc);
Sebastian Redlc215cfc2009-01-19 00:08:26 +00003847
John McCallbebede42011-02-26 05:39:39 +00003848 unsigned BuiltinID = (FDecl ? FDecl->getBuiltinID() : 0);
3849
3850 // Bail out early if calling a builtin with custom typechecking.
3851 if (BuiltinID && Context.BuiltinInfo.hasCustomTypechecking(BuiltinID))
3852 return CheckBuiltinFunctionCall(BuiltinID, TheCall);
3853
John McCall31996342011-04-07 08:22:57 +00003854 retry:
Steve Naroff8de9c3a2008-09-05 22:11:13 +00003855 const FunctionType *FuncT;
John McCallbebede42011-02-26 05:39:39 +00003856 if (const PointerType *PT = Fn->getType()->getAs<PointerType>()) {
Steve Naroff8de9c3a2008-09-05 22:11:13 +00003857 // C99 6.5.2.2p1 - "The expression that denotes the called function shall
3858 // have type pointer to function".
John McCall9dd450b2009-09-21 23:43:11 +00003859 FuncT = PT->getPointeeType()->getAs<FunctionType>();
John McCallbebede42011-02-26 05:39:39 +00003860 if (FuncT == 0)
3861 return ExprError(Diag(LParenLoc, diag::err_typecheck_call_not_function)
3862 << Fn->getType() << Fn->getSourceRange());
3863 } else if (const BlockPointerType *BPT =
3864 Fn->getType()->getAs<BlockPointerType>()) {
3865 FuncT = BPT->getPointeeType()->castAs<FunctionType>();
3866 } else {
John McCall31996342011-04-07 08:22:57 +00003867 // Handle calls to expressions of unknown-any type.
3868 if (Fn->getType() == Context.UnknownAnyTy) {
John McCall2979fe02011-04-12 00:42:48 +00003869 ExprResult rewrite = rebuildUnknownAnyFunction(*this, Fn);
John McCall31996342011-04-07 08:22:57 +00003870 if (rewrite.isInvalid()) return ExprError();
3871 Fn = rewrite.take();
John McCall39439732011-04-09 22:50:59 +00003872 TheCall->setCallee(Fn);
John McCall31996342011-04-07 08:22:57 +00003873 goto retry;
3874 }
3875
Sebastian Redlc215cfc2009-01-19 00:08:26 +00003876 return ExprError(Diag(LParenLoc, diag::err_typecheck_call_not_function)
3877 << Fn->getType() << Fn->getSourceRange());
John McCallbebede42011-02-26 05:39:39 +00003878 }
Sebastian Redlc215cfc2009-01-19 00:08:26 +00003879
David Blaikiebbafb8a2012-03-11 07:00:24 +00003880 if (getLangOpts().CUDA) {
Peter Collingbourne4b66c472011-02-23 01:53:29 +00003881 if (Config) {
3882 // CUDA: Kernel calls must be to global functions
3883 if (FDecl && !FDecl->hasAttr<CUDAGlobalAttr>())
3884 return ExprError(Diag(LParenLoc,diag::err_kern_call_not_global_function)
3885 << FDecl->getName() << Fn->getSourceRange());
3886
3887 // CUDA: Kernel function must have 'void' return type
3888 if (!FuncT->getResultType()->isVoidType())
3889 return ExprError(Diag(LParenLoc, diag::err_kern_type_not_void_return)
3890 << Fn->getType() << Fn->getSourceRange());
Peter Collingbourne34a20b02011-10-02 23:49:15 +00003891 } else {
3892 // CUDA: Calls to global functions must be configured
3893 if (FDecl && FDecl->hasAttr<CUDAGlobalAttr>())
3894 return ExprError(Diag(LParenLoc, diag::err_global_call_not_config)
3895 << FDecl->getName() << Fn->getSourceRange());
Peter Collingbourne4b66c472011-02-23 01:53:29 +00003896 }
3897 }
3898
Eli Friedman3164fb12009-03-22 22:00:50 +00003899 // Check for a valid return type
Kovarththanan Rajaratnamba2c6522010-03-13 10:17:05 +00003900 if (CheckCallReturnType(FuncT->getResultType(),
Daniel Dunbar62ee6412012-03-09 18:35:03 +00003901 Fn->getLocStart(), TheCall,
Anders Carlsson7f84ed92009-10-09 23:51:55 +00003902 FDecl))
Eli Friedman3164fb12009-03-22 22:00:50 +00003903 return ExprError();
3904
Chris Lattner08464942007-12-28 05:29:59 +00003905 // We know the result type of the call, set it.
Douglas Gregor603d81b2010-07-13 08:18:22 +00003906 TheCall->setType(FuncT->getCallResultType(Context));
John McCall7decc9e2010-11-18 06:31:45 +00003907 TheCall->setValueKind(Expr::getValueKindForType(FuncT->getResultType()));
Sebastian Redlc215cfc2009-01-19 00:08:26 +00003908
Douglas Gregordeaad8c2009-02-26 23:50:07 +00003909 if (const FunctionProtoType *Proto = dyn_cast<FunctionProtoType>(FuncT)) {
John McCallb268a282010-08-23 23:25:46 +00003910 if (ConvertArgumentsForCall(TheCall, Fn, FDecl, Proto, Args, NumArgs,
Peter Collingbourne619a8c72011-10-02 23:49:29 +00003911 RParenLoc, IsExecConfig))
Sebastian Redlc215cfc2009-01-19 00:08:26 +00003912 return ExprError();
Chris Lattner08464942007-12-28 05:29:59 +00003913 } else {
Douglas Gregordeaad8c2009-02-26 23:50:07 +00003914 assert(isa<FunctionNoProtoType>(FuncT) && "Unknown FunctionType!");
Sebastian Redlc215cfc2009-01-19 00:08:26 +00003915
Douglas Gregord8e97de2009-04-02 15:37:10 +00003916 if (FDecl) {
3917 // Check if we have too few/too many template arguments, based
3918 // on our knowledge of the function definition.
3919 const FunctionDecl *Def = 0;
Argyrios Kyrtzidis36ea3222010-07-07 11:31:19 +00003920 if (FDecl->hasBody(Def) && NumArgs != Def->param_size()) {
Douglas Gregor8e09a722010-10-25 20:39:23 +00003921 const FunctionProtoType *Proto
3922 = Def->getType()->getAs<FunctionProtoType>();
3923 if (!Proto || !(Proto->isVariadic() && NumArgs >= Def->param_size()))
Eli Friedmanfcbf7d22009-06-01 09:24:59 +00003924 Diag(RParenLoc, diag::warn_call_wrong_number_of_arguments)
3925 << (NumArgs > Def->param_size()) << FDecl << Fn->getSourceRange();
Eli Friedmanfcbf7d22009-06-01 09:24:59 +00003926 }
Douglas Gregor8e09a722010-10-25 20:39:23 +00003927
3928 // If the function we're calling isn't a function prototype, but we have
3929 // a function prototype from a prior declaratiom, use that prototype.
3930 if (!FDecl->hasPrototype())
3931 Proto = FDecl->getType()->getAs<FunctionProtoType>();
Douglas Gregord8e97de2009-04-02 15:37:10 +00003932 }
3933
Steve Naroff0b661582007-08-28 23:30:39 +00003934 // Promote the arguments (C99 6.5.2.2p6).
Chris Lattner08464942007-12-28 05:29:59 +00003935 for (unsigned i = 0; i != NumArgs; i++) {
3936 Expr *Arg = Args[i];
Douglas Gregor8e09a722010-10-25 20:39:23 +00003937
3938 if (Proto && i < Proto->getNumArgs()) {
Douglas Gregor8e09a722010-10-25 20:39:23 +00003939 InitializedEntity Entity
3940 = InitializedEntity::InitializeParameter(Context,
John McCall31168b02011-06-15 23:02:42 +00003941 Proto->getArgType(i),
3942 Proto->isArgConsumed(i));
Douglas Gregor8e09a722010-10-25 20:39:23 +00003943 ExprResult ArgE = PerformCopyInitialization(Entity,
3944 SourceLocation(),
3945 Owned(Arg));
3946 if (ArgE.isInvalid())
3947 return true;
3948
3949 Arg = ArgE.takeAs<Expr>();
3950
3951 } else {
John Wiegley01296292011-04-08 18:41:53 +00003952 ExprResult ArgE = DefaultArgumentPromotion(Arg);
3953
3954 if (ArgE.isInvalid())
3955 return true;
3956
3957 Arg = ArgE.takeAs<Expr>();
Douglas Gregor8e09a722010-10-25 20:39:23 +00003958 }
3959
Daniel Dunbar62ee6412012-03-09 18:35:03 +00003960 if (RequireCompleteType(Arg->getLocStart(),
Douglas Gregor83025412010-10-26 05:45:40 +00003961 Arg->getType(),
Douglas Gregor7bfb2d02012-05-04 16:32:21 +00003962 diag::err_call_incomplete_argument, Arg))
Douglas Gregor83025412010-10-26 05:45:40 +00003963 return ExprError();
3964
Chris Lattner08464942007-12-28 05:29:59 +00003965 TheCall->setArg(i, Arg);
Steve Naroff0b661582007-08-28 23:30:39 +00003966 }
Steve Naroffae4143e2007-04-26 20:39:23 +00003967 }
Chris Lattner08464942007-12-28 05:29:59 +00003968
Douglas Gregor97fd6e22008-12-22 05:46:06 +00003969 if (CXXMethodDecl *Method = dyn_cast_or_null<CXXMethodDecl>(FDecl))
3970 if (!Method->isStatic())
Sebastian Redlc215cfc2009-01-19 00:08:26 +00003971 return ExprError(Diag(LParenLoc, diag::err_member_call_without_object)
3972 << Fn->getSourceRange());
Douglas Gregor97fd6e22008-12-22 05:46:06 +00003973
Fariborz Jahanian0aa5c452009-05-15 20:33:25 +00003974 // Check for sentinels
3975 if (NDecl)
3976 DiagnoseSentinelCalls(NDecl, LParenLoc, Args, NumArgs);
Mike Stump11289f42009-09-09 15:08:12 +00003977
Chris Lattnerb87b1b32007-08-10 20:18:51 +00003978 // Do special checking on direct calls to functions.
Anders Carlssonbc4c1072009-08-16 01:56:34 +00003979 if (FDecl) {
John McCallb268a282010-08-23 23:25:46 +00003980 if (CheckFunctionCall(FDecl, TheCall))
Anders Carlssonbc4c1072009-08-16 01:56:34 +00003981 return ExprError();
Mike Stump11289f42009-09-09 15:08:12 +00003982
John McCallbebede42011-02-26 05:39:39 +00003983 if (BuiltinID)
Fariborz Jahaniane8473c22010-11-30 17:35:24 +00003984 return CheckBuiltinFunctionCall(BuiltinID, TheCall);
Anders Carlssonbc4c1072009-08-16 01:56:34 +00003985 } else if (NDecl) {
John McCallb268a282010-08-23 23:25:46 +00003986 if (CheckBlockCall(NDecl, TheCall))
Anders Carlssonbc4c1072009-08-16 01:56:34 +00003987 return ExprError();
3988 }
Chris Lattnerb87b1b32007-08-10 20:18:51 +00003989
John McCallb268a282010-08-23 23:25:46 +00003990 return MaybeBindToTemporary(TheCall);
Chris Lattnere168f762006-11-10 05:29:30 +00003991}
3992
John McCalldadc5752010-08-24 06:29:42 +00003993ExprResult
John McCallba7bf592010-08-24 05:47:05 +00003994Sema::ActOnCompoundLiteral(SourceLocation LParenLoc, ParsedType Ty,
John McCallb268a282010-08-23 23:25:46 +00003995 SourceLocation RParenLoc, Expr *InitExpr) {
Steve Naroff83895f72007-09-16 03:34:24 +00003996 assert((Ty != 0) && "ActOnCompoundLiteral(): missing type");
Steve Naroff57eb2c52007-07-19 21:32:11 +00003997 // FIXME: put back this assert when initializers are worked out.
Steve Naroff83895f72007-09-16 03:34:24 +00003998 //assert((InitExpr != 0) && "ActOnCompoundLiteral(): missing expression");
John McCalle15bbff2010-01-18 19:35:47 +00003999
4000 TypeSourceInfo *TInfo;
4001 QualType literalType = GetTypeFromParser(Ty, &TInfo);
4002 if (!TInfo)
4003 TInfo = Context.getTrivialTypeSourceInfo(literalType);
4004
John McCallb268a282010-08-23 23:25:46 +00004005 return BuildCompoundLiteralExpr(LParenLoc, TInfo, RParenLoc, InitExpr);
John McCalle15bbff2010-01-18 19:35:47 +00004006}
4007
John McCalldadc5752010-08-24 06:29:42 +00004008ExprResult
John McCalle15bbff2010-01-18 19:35:47 +00004009Sema::BuildCompoundLiteralExpr(SourceLocation LParenLoc, TypeSourceInfo *TInfo,
Richard Trieuba63ce62011-09-09 01:45:06 +00004010 SourceLocation RParenLoc, Expr *LiteralExpr) {
John McCalle15bbff2010-01-18 19:35:47 +00004011 QualType literalType = TInfo->getType();
Anders Carlsson2c1ec6d2007-12-05 07:24:19 +00004012
Eli Friedman37a186d2008-05-20 05:22:08 +00004013 if (literalType->isArrayType()) {
Argyrios Kyrtzidis85663562010-11-08 19:14:19 +00004014 if (RequireCompleteType(LParenLoc, Context.getBaseElementType(literalType),
Douglas Gregor7bfb2d02012-05-04 16:32:21 +00004015 diag::err_illegal_decl_array_incomplete_type,
4016 SourceRange(LParenLoc,
4017 LiteralExpr->getSourceRange().getEnd())))
Argyrios Kyrtzidis85663562010-11-08 19:14:19 +00004018 return ExprError();
Chris Lattner7adf0762008-08-04 07:31:14 +00004019 if (literalType->isVariableArrayType())
Sebastian Redlb5d49352009-01-19 22:31:54 +00004020 return ExprError(Diag(LParenLoc, diag::err_variable_object_no_init)
Richard Trieuba63ce62011-09-09 01:45:06 +00004021 << SourceRange(LParenLoc, LiteralExpr->getSourceRange().getEnd()));
Douglas Gregor1c37d9e2009-05-21 23:48:18 +00004022 } else if (!literalType->isDependentType() &&
4023 RequireCompleteType(LParenLoc, literalType,
Douglas Gregor7bfb2d02012-05-04 16:32:21 +00004024 diag::err_typecheck_decl_incomplete_type,
4025 SourceRange(LParenLoc, LiteralExpr->getSourceRange().getEnd())))
Sebastian Redlb5d49352009-01-19 22:31:54 +00004026 return ExprError();
Eli Friedman37a186d2008-05-20 05:22:08 +00004027
Douglas Gregor85dabae2009-12-16 01:38:02 +00004028 InitializedEntity Entity
Douglas Gregor1b303932009-12-22 15:35:07 +00004029 = InitializedEntity::InitializeTemporary(literalType);
Douglas Gregor85dabae2009-12-16 01:38:02 +00004030 InitializationKind Kind
John McCall31168b02011-06-15 23:02:42 +00004031 = InitializationKind::CreateCStyleCast(LParenLoc,
Sebastian Redl0501c632012-02-12 16:37:36 +00004032 SourceRange(LParenLoc, RParenLoc),
4033 /*InitList=*/true);
Richard Trieuba63ce62011-09-09 01:45:06 +00004034 InitializationSequence InitSeq(*this, Entity, Kind, &LiteralExpr, 1);
John McCalldadc5752010-08-24 06:29:42 +00004035 ExprResult Result = InitSeq.Perform(*this, Entity, Kind,
Richard Trieuba63ce62011-09-09 01:45:06 +00004036 MultiExprArg(*this, &LiteralExpr, 1),
Eli Friedmana553d4a2009-12-22 02:35:53 +00004037 &literalType);
4038 if (Result.isInvalid())
Sebastian Redlb5d49352009-01-19 22:31:54 +00004039 return ExprError();
Richard Trieuba63ce62011-09-09 01:45:06 +00004040 LiteralExpr = Result.get();
Steve Naroffd32419d2008-01-14 18:19:28 +00004041
Chris Lattner79413952008-12-04 23:50:19 +00004042 bool isFileScope = getCurFunctionOrMethodDecl() == 0;
Steve Naroffd32419d2008-01-14 18:19:28 +00004043 if (isFileScope) { // 6.5.2.5p3
Richard Trieuba63ce62011-09-09 01:45:06 +00004044 if (CheckForConstantInitializer(LiteralExpr, literalType))
Sebastian Redlb5d49352009-01-19 22:31:54 +00004045 return ExprError();
Steve Naroff98f72032008-01-10 22:15:12 +00004046 }
Eli Friedmana553d4a2009-12-22 02:35:53 +00004047
John McCall7decc9e2010-11-18 06:31:45 +00004048 // In C, compound literals are l-values for some reason.
David Blaikiebbafb8a2012-03-11 07:00:24 +00004049 ExprValueKind VK = getLangOpts().CPlusPlus ? VK_RValue : VK_LValue;
John McCall7decc9e2010-11-18 06:31:45 +00004050
Douglas Gregor9b71f0c2011-06-17 04:59:12 +00004051 return MaybeBindToTemporary(
4052 new (Context) CompoundLiteralExpr(LParenLoc, TInfo, literalType,
Richard Trieuba63ce62011-09-09 01:45:06 +00004053 VK, LiteralExpr, isFileScope));
Steve Narofffbd09832007-07-19 01:06:55 +00004054}
4055
John McCalldadc5752010-08-24 06:29:42 +00004056ExprResult
Richard Trieuba63ce62011-09-09 01:45:06 +00004057Sema::ActOnInitList(SourceLocation LBraceLoc, MultiExprArg InitArgList,
Sebastian Redlb5d49352009-01-19 22:31:54 +00004058 SourceLocation RBraceLoc) {
Richard Trieuba63ce62011-09-09 01:45:06 +00004059 unsigned NumInit = InitArgList.size();
4060 Expr **InitList = InitArgList.release();
Anders Carlsson4692db02007-08-31 04:56:16 +00004061
John McCall526ab472011-10-25 17:37:35 +00004062 // Immediately handle non-overload placeholders. Overloads can be
4063 // resolved contextually, but everything else here can't.
4064 for (unsigned I = 0; I != NumInit; ++I) {
John McCalld5c98ae2011-11-15 01:35:18 +00004065 if (InitList[I]->getType()->isNonOverloadPlaceholderType()) {
John McCall526ab472011-10-25 17:37:35 +00004066 ExprResult result = CheckPlaceholderExpr(InitList[I]);
4067
4068 // Ignore failures; dropping the entire initializer list because
4069 // of one failure would be terrible for indexing/etc.
4070 if (result.isInvalid()) continue;
4071
4072 InitList[I] = result.take();
4073 }
4074 }
4075
Steve Naroff30d242c2007-09-15 18:49:24 +00004076 // Semantic analysis for initializers is done by ActOnDeclarator() and
Mike Stump4e1f26a2009-02-19 03:04:26 +00004077 // CheckInitializer() - it requires knowledge of the object being intialized.
Sebastian Redlb5d49352009-01-19 22:31:54 +00004078
Ted Kremenekac034612010-04-13 23:39:13 +00004079 InitListExpr *E = new (Context) InitListExpr(Context, LBraceLoc, InitList,
4080 NumInit, RBraceLoc);
Chris Lattner24d5bfe2008-04-02 04:24:33 +00004081 E->setType(Context.VoidTy); // FIXME: just a place holder for now.
Sebastian Redlb5d49352009-01-19 22:31:54 +00004082 return Owned(E);
Steve Narofffbd09832007-07-19 01:06:55 +00004083}
4084
John McCallcd78e802011-09-10 01:16:55 +00004085/// Do an explicit extend of the given block pointer if we're in ARC.
4086static void maybeExtendBlockObject(Sema &S, ExprResult &E) {
4087 assert(E.get()->getType()->isBlockPointerType());
4088 assert(E.get()->isRValue());
4089
4090 // Only do this in an r-value context.
David Blaikiebbafb8a2012-03-11 07:00:24 +00004091 if (!S.getLangOpts().ObjCAutoRefCount) return;
John McCallcd78e802011-09-10 01:16:55 +00004092
4093 E = ImplicitCastExpr::Create(S.Context, E.get()->getType(),
John McCall2d637d22011-09-10 06:18:15 +00004094 CK_ARCExtendBlockObject, E.get(),
John McCallcd78e802011-09-10 01:16:55 +00004095 /*base path*/ 0, VK_RValue);
4096 S.ExprNeedsCleanups = true;
4097}
4098
4099/// Prepare a conversion of the given expression to an ObjC object
4100/// pointer type.
4101CastKind Sema::PrepareCastToObjCObjectPointer(ExprResult &E) {
4102 QualType type = E.get()->getType();
4103 if (type->isObjCObjectPointerType()) {
4104 return CK_BitCast;
4105 } else if (type->isBlockPointerType()) {
4106 maybeExtendBlockObject(*this, E);
4107 return CK_BlockPointerToObjCPointerCast;
4108 } else {
4109 assert(type->isPointerType());
4110 return CK_CPointerToObjCPointerCast;
4111 }
4112}
4113
John McCalld7646252010-11-14 08:17:51 +00004114/// Prepares for a scalar cast, performing all the necessary stages
4115/// except the final cast and returning the kind required.
John McCall9776e432011-10-06 23:25:11 +00004116CastKind Sema::PrepareScalarCast(ExprResult &Src, QualType DestTy) {
John McCalld7646252010-11-14 08:17:51 +00004117 // Both Src and Dest are scalar types, i.e. arithmetic or pointer.
4118 // Also, callers should have filtered out the invalid cases with
4119 // pointers. Everything else should be possible.
4120
John Wiegley01296292011-04-08 18:41:53 +00004121 QualType SrcTy = Src.get()->getType();
John McCall9776e432011-10-06 23:25:11 +00004122 if (Context.hasSameUnqualifiedType(SrcTy, DestTy))
John McCalle3027922010-08-25 11:45:40 +00004123 return CK_NoOp;
Anders Carlsson094c4592009-10-18 18:12:03 +00004124
John McCall9320b872011-09-09 05:25:32 +00004125 switch (Type::ScalarTypeKind SrcKind = SrcTy->getScalarTypeKind()) {
John McCall8cb679e2010-11-15 09:13:47 +00004126 case Type::STK_MemberPointer:
4127 llvm_unreachable("member pointer type in C");
Abramo Bagnaraba854972011-01-04 09:50:03 +00004128
John McCall9320b872011-09-09 05:25:32 +00004129 case Type::STK_CPointer:
4130 case Type::STK_BlockPointer:
4131 case Type::STK_ObjCObjectPointer:
John McCall8cb679e2010-11-15 09:13:47 +00004132 switch (DestTy->getScalarTypeKind()) {
John McCall9320b872011-09-09 05:25:32 +00004133 case Type::STK_CPointer:
4134 return CK_BitCast;
4135 case Type::STK_BlockPointer:
4136 return (SrcKind == Type::STK_BlockPointer
4137 ? CK_BitCast : CK_AnyPointerToBlockPointerCast);
4138 case Type::STK_ObjCObjectPointer:
4139 if (SrcKind == Type::STK_ObjCObjectPointer)
4140 return CK_BitCast;
David Blaikie8a40f702012-01-17 06:56:22 +00004141 if (SrcKind == Type::STK_CPointer)
John McCall9320b872011-09-09 05:25:32 +00004142 return CK_CPointerToObjCPointerCast;
David Blaikie8a40f702012-01-17 06:56:22 +00004143 maybeExtendBlockObject(*this, Src);
4144 return CK_BlockPointerToObjCPointerCast;
John McCall8cb679e2010-11-15 09:13:47 +00004145 case Type::STK_Bool:
4146 return CK_PointerToBoolean;
4147 case Type::STK_Integral:
4148 return CK_PointerToIntegral;
4149 case Type::STK_Floating:
4150 case Type::STK_FloatingComplex:
4151 case Type::STK_IntegralComplex:
4152 case Type::STK_MemberPointer:
4153 llvm_unreachable("illegal cast from pointer");
4154 }
David Blaikie8a40f702012-01-17 06:56:22 +00004155 llvm_unreachable("Should have returned before this");
Kovarththanan Rajaratnamba2c6522010-03-13 10:17:05 +00004156
John McCall8cb679e2010-11-15 09:13:47 +00004157 case Type::STK_Bool: // casting from bool is like casting from an integer
4158 case Type::STK_Integral:
4159 switch (DestTy->getScalarTypeKind()) {
John McCall9320b872011-09-09 05:25:32 +00004160 case Type::STK_CPointer:
4161 case Type::STK_ObjCObjectPointer:
4162 case Type::STK_BlockPointer:
John McCall9776e432011-10-06 23:25:11 +00004163 if (Src.get()->isNullPointerConstant(Context,
Richard Trieucfc491d2011-08-02 04:35:43 +00004164 Expr::NPC_ValueDependentIsNull))
John McCalle84af4e2010-11-13 01:35:44 +00004165 return CK_NullToPointer;
John McCalle3027922010-08-25 11:45:40 +00004166 return CK_IntegralToPointer;
John McCall8cb679e2010-11-15 09:13:47 +00004167 case Type::STK_Bool:
4168 return CK_IntegralToBoolean;
4169 case Type::STK_Integral:
John McCalld7646252010-11-14 08:17:51 +00004170 return CK_IntegralCast;
John McCall8cb679e2010-11-15 09:13:47 +00004171 case Type::STK_Floating:
John McCalle3027922010-08-25 11:45:40 +00004172 return CK_IntegralToFloating;
John McCall8cb679e2010-11-15 09:13:47 +00004173 case Type::STK_IntegralComplex:
John McCall9776e432011-10-06 23:25:11 +00004174 Src = ImpCastExprToType(Src.take(),
4175 DestTy->castAs<ComplexType>()->getElementType(),
4176 CK_IntegralCast);
John McCalld7646252010-11-14 08:17:51 +00004177 return CK_IntegralRealToComplex;
John McCall8cb679e2010-11-15 09:13:47 +00004178 case Type::STK_FloatingComplex:
John McCall9776e432011-10-06 23:25:11 +00004179 Src = ImpCastExprToType(Src.take(),
4180 DestTy->castAs<ComplexType>()->getElementType(),
4181 CK_IntegralToFloating);
John McCalld7646252010-11-14 08:17:51 +00004182 return CK_FloatingRealToComplex;
John McCall8cb679e2010-11-15 09:13:47 +00004183 case Type::STK_MemberPointer:
4184 llvm_unreachable("member pointer type in C");
John McCalld7646252010-11-14 08:17:51 +00004185 }
David Blaikie8a40f702012-01-17 06:56:22 +00004186 llvm_unreachable("Should have returned before this");
Kovarththanan Rajaratnamba2c6522010-03-13 10:17:05 +00004187
John McCall8cb679e2010-11-15 09:13:47 +00004188 case Type::STK_Floating:
4189 switch (DestTy->getScalarTypeKind()) {
4190 case Type::STK_Floating:
John McCalle3027922010-08-25 11:45:40 +00004191 return CK_FloatingCast;
John McCall8cb679e2010-11-15 09:13:47 +00004192 case Type::STK_Bool:
4193 return CK_FloatingToBoolean;
4194 case Type::STK_Integral:
John McCalle3027922010-08-25 11:45:40 +00004195 return CK_FloatingToIntegral;
John McCall8cb679e2010-11-15 09:13:47 +00004196 case Type::STK_FloatingComplex:
John McCall9776e432011-10-06 23:25:11 +00004197 Src = ImpCastExprToType(Src.take(),
4198 DestTy->castAs<ComplexType>()->getElementType(),
4199 CK_FloatingCast);
John McCalld7646252010-11-14 08:17:51 +00004200 return CK_FloatingRealToComplex;
John McCall8cb679e2010-11-15 09:13:47 +00004201 case Type::STK_IntegralComplex:
John McCall9776e432011-10-06 23:25:11 +00004202 Src = ImpCastExprToType(Src.take(),
4203 DestTy->castAs<ComplexType>()->getElementType(),
4204 CK_FloatingToIntegral);
John McCalld7646252010-11-14 08:17:51 +00004205 return CK_IntegralRealToComplex;
John McCall9320b872011-09-09 05:25:32 +00004206 case Type::STK_CPointer:
4207 case Type::STK_ObjCObjectPointer:
4208 case Type::STK_BlockPointer:
John McCall8cb679e2010-11-15 09:13:47 +00004209 llvm_unreachable("valid float->pointer cast?");
4210 case Type::STK_MemberPointer:
4211 llvm_unreachable("member pointer type in C");
John McCalld7646252010-11-14 08:17:51 +00004212 }
David Blaikie8a40f702012-01-17 06:56:22 +00004213 llvm_unreachable("Should have returned before this");
John McCalld7646252010-11-14 08:17:51 +00004214
John McCall8cb679e2010-11-15 09:13:47 +00004215 case Type::STK_FloatingComplex:
4216 switch (DestTy->getScalarTypeKind()) {
4217 case Type::STK_FloatingComplex:
John McCalld7646252010-11-14 08:17:51 +00004218 return CK_FloatingComplexCast;
John McCall8cb679e2010-11-15 09:13:47 +00004219 case Type::STK_IntegralComplex:
John McCalld7646252010-11-14 08:17:51 +00004220 return CK_FloatingComplexToIntegralComplex;
John McCallfcef3cf2010-12-14 17:51:41 +00004221 case Type::STK_Floating: {
John McCall9776e432011-10-06 23:25:11 +00004222 QualType ET = SrcTy->castAs<ComplexType>()->getElementType();
4223 if (Context.hasSameType(ET, DestTy))
John McCallfcef3cf2010-12-14 17:51:41 +00004224 return CK_FloatingComplexToReal;
John McCall9776e432011-10-06 23:25:11 +00004225 Src = ImpCastExprToType(Src.take(), ET, CK_FloatingComplexToReal);
John McCallfcef3cf2010-12-14 17:51:41 +00004226 return CK_FloatingCast;
4227 }
John McCall8cb679e2010-11-15 09:13:47 +00004228 case Type::STK_Bool:
John McCalld7646252010-11-14 08:17:51 +00004229 return CK_FloatingComplexToBoolean;
John McCall8cb679e2010-11-15 09:13:47 +00004230 case Type::STK_Integral:
John McCall9776e432011-10-06 23:25:11 +00004231 Src = ImpCastExprToType(Src.take(),
4232 SrcTy->castAs<ComplexType>()->getElementType(),
4233 CK_FloatingComplexToReal);
John McCalld7646252010-11-14 08:17:51 +00004234 return CK_FloatingToIntegral;
John McCall9320b872011-09-09 05:25:32 +00004235 case Type::STK_CPointer:
4236 case Type::STK_ObjCObjectPointer:
4237 case Type::STK_BlockPointer:
John McCall8cb679e2010-11-15 09:13:47 +00004238 llvm_unreachable("valid complex float->pointer cast?");
4239 case Type::STK_MemberPointer:
4240 llvm_unreachable("member pointer type in C");
John McCalld7646252010-11-14 08:17:51 +00004241 }
David Blaikie8a40f702012-01-17 06:56:22 +00004242 llvm_unreachable("Should have returned before this");
John McCalld7646252010-11-14 08:17:51 +00004243
John McCall8cb679e2010-11-15 09:13:47 +00004244 case Type::STK_IntegralComplex:
4245 switch (DestTy->getScalarTypeKind()) {
4246 case Type::STK_FloatingComplex:
John McCalld7646252010-11-14 08:17:51 +00004247 return CK_IntegralComplexToFloatingComplex;
John McCall8cb679e2010-11-15 09:13:47 +00004248 case Type::STK_IntegralComplex:
John McCalld7646252010-11-14 08:17:51 +00004249 return CK_IntegralComplexCast;
John McCallfcef3cf2010-12-14 17:51:41 +00004250 case Type::STK_Integral: {
John McCall9776e432011-10-06 23:25:11 +00004251 QualType ET = SrcTy->castAs<ComplexType>()->getElementType();
4252 if (Context.hasSameType(ET, DestTy))
John McCallfcef3cf2010-12-14 17:51:41 +00004253 return CK_IntegralComplexToReal;
John McCall9776e432011-10-06 23:25:11 +00004254 Src = ImpCastExprToType(Src.take(), ET, CK_IntegralComplexToReal);
John McCallfcef3cf2010-12-14 17:51:41 +00004255 return CK_IntegralCast;
4256 }
John McCall8cb679e2010-11-15 09:13:47 +00004257 case Type::STK_Bool:
John McCalld7646252010-11-14 08:17:51 +00004258 return CK_IntegralComplexToBoolean;
John McCall8cb679e2010-11-15 09:13:47 +00004259 case Type::STK_Floating:
John McCall9776e432011-10-06 23:25:11 +00004260 Src = ImpCastExprToType(Src.take(),
4261 SrcTy->castAs<ComplexType>()->getElementType(),
4262 CK_IntegralComplexToReal);
John McCalld7646252010-11-14 08:17:51 +00004263 return CK_IntegralToFloating;
John McCall9320b872011-09-09 05:25:32 +00004264 case Type::STK_CPointer:
4265 case Type::STK_ObjCObjectPointer:
4266 case Type::STK_BlockPointer:
John McCall8cb679e2010-11-15 09:13:47 +00004267 llvm_unreachable("valid complex int->pointer cast?");
4268 case Type::STK_MemberPointer:
4269 llvm_unreachable("member pointer type in C");
John McCalld7646252010-11-14 08:17:51 +00004270 }
David Blaikie8a40f702012-01-17 06:56:22 +00004271 llvm_unreachable("Should have returned before this");
Anders Carlsson094c4592009-10-18 18:12:03 +00004272 }
Kovarththanan Rajaratnamba2c6522010-03-13 10:17:05 +00004273
John McCalld7646252010-11-14 08:17:51 +00004274 llvm_unreachable("Unhandled scalar cast");
Anders Carlsson094c4592009-10-18 18:12:03 +00004275}
4276
Anders Carlsson525b76b2009-10-16 02:48:28 +00004277bool Sema::CheckVectorCast(SourceRange R, QualType VectorTy, QualType Ty,
John McCalle3027922010-08-25 11:45:40 +00004278 CastKind &Kind) {
Anders Carlssonde71adf2007-11-27 05:51:55 +00004279 assert(VectorTy->isVectorType() && "Not a vector type!");
Mike Stump4e1f26a2009-02-19 03:04:26 +00004280
Anders Carlssonde71adf2007-11-27 05:51:55 +00004281 if (Ty->isVectorType() || Ty->isIntegerType()) {
Chris Lattner37e05872008-03-05 18:54:05 +00004282 if (Context.getTypeSize(VectorTy) != Context.getTypeSize(Ty))
Anders Carlssonde71adf2007-11-27 05:51:55 +00004283 return Diag(R.getBegin(),
Mike Stump4e1f26a2009-02-19 03:04:26 +00004284 Ty->isVectorType() ?
Anders Carlssonde71adf2007-11-27 05:51:55 +00004285 diag::err_invalid_conversion_between_vectors :
Chris Lattner3b054132008-11-19 05:08:23 +00004286 diag::err_invalid_conversion_between_vector_and_integer)
Chris Lattner1e5665e2008-11-24 06:25:27 +00004287 << VectorTy << Ty << R;
Anders Carlssonde71adf2007-11-27 05:51:55 +00004288 } else
4289 return Diag(R.getBegin(),
Chris Lattner3b054132008-11-19 05:08:23 +00004290 diag::err_invalid_conversion_between_vector_and_scalar)
Chris Lattner1e5665e2008-11-24 06:25:27 +00004291 << VectorTy << Ty << R;
Mike Stump4e1f26a2009-02-19 03:04:26 +00004292
John McCalle3027922010-08-25 11:45:40 +00004293 Kind = CK_BitCast;
Anders Carlssonde71adf2007-11-27 05:51:55 +00004294 return false;
4295}
4296
John Wiegley01296292011-04-08 18:41:53 +00004297ExprResult Sema::CheckExtVectorCast(SourceRange R, QualType DestTy,
4298 Expr *CastExpr, CastKind &Kind) {
Nate Begemanc69b7402009-06-26 00:50:28 +00004299 assert(DestTy->isExtVectorType() && "Not an extended vector type!");
Kovarththanan Rajaratnamba2c6522010-03-13 10:17:05 +00004300
Anders Carlsson43d70f82009-10-16 05:23:41 +00004301 QualType SrcTy = CastExpr->getType();
Kovarththanan Rajaratnamba2c6522010-03-13 10:17:05 +00004302
Nate Begemanc8961a42009-06-27 22:05:55 +00004303 // If SrcTy is a VectorType, the total size must match to explicitly cast to
4304 // an ExtVectorType.
Tobias Grosser766bcc22011-09-22 13:03:14 +00004305 // In OpenCL, casts between vectors of different types are not allowed.
4306 // (See OpenCL 6.2).
Nate Begemanc69b7402009-06-26 00:50:28 +00004307 if (SrcTy->isVectorType()) {
Tobias Grosser766bcc22011-09-22 13:03:14 +00004308 if (Context.getTypeSize(DestTy) != Context.getTypeSize(SrcTy)
David Blaikiebbafb8a2012-03-11 07:00:24 +00004309 || (getLangOpts().OpenCL &&
Tobias Grosser766bcc22011-09-22 13:03:14 +00004310 (DestTy.getCanonicalType() != SrcTy.getCanonicalType()))) {
John Wiegley01296292011-04-08 18:41:53 +00004311 Diag(R.getBegin(),diag::err_invalid_conversion_between_ext_vectors)
Nate Begemanc69b7402009-06-26 00:50:28 +00004312 << DestTy << SrcTy << R;
John Wiegley01296292011-04-08 18:41:53 +00004313 return ExprError();
4314 }
John McCalle3027922010-08-25 11:45:40 +00004315 Kind = CK_BitCast;
John Wiegley01296292011-04-08 18:41:53 +00004316 return Owned(CastExpr);
Nate Begemanc69b7402009-06-26 00:50:28 +00004317 }
4318
Nate Begemanbd956c42009-06-28 02:36:38 +00004319 // All non-pointer scalars can be cast to ExtVector type. The appropriate
Nate Begemanc69b7402009-06-26 00:50:28 +00004320 // conversion will take place first from scalar to elt type, and then
4321 // splat from elt type to vector.
Nate Begemanbd956c42009-06-28 02:36:38 +00004322 if (SrcTy->isPointerType())
4323 return Diag(R.getBegin(),
4324 diag::err_invalid_conversion_between_vector_and_scalar)
4325 << DestTy << SrcTy << R;
Eli Friedman06ed2a52009-10-20 08:27:19 +00004326
4327 QualType DestElemTy = DestTy->getAs<ExtVectorType>()->getElementType();
John Wiegley01296292011-04-08 18:41:53 +00004328 ExprResult CastExprRes = Owned(CastExpr);
John McCall9776e432011-10-06 23:25:11 +00004329 CastKind CK = PrepareScalarCast(CastExprRes, DestElemTy);
John Wiegley01296292011-04-08 18:41:53 +00004330 if (CastExprRes.isInvalid())
4331 return ExprError();
4332 CastExpr = ImpCastExprToType(CastExprRes.take(), DestElemTy, CK).take();
Kovarththanan Rajaratnamba2c6522010-03-13 10:17:05 +00004333
John McCalle3027922010-08-25 11:45:40 +00004334 Kind = CK_VectorSplat;
John Wiegley01296292011-04-08 18:41:53 +00004335 return Owned(CastExpr);
Nate Begemanc69b7402009-06-26 00:50:28 +00004336}
4337
John McCalldadc5752010-08-24 06:29:42 +00004338ExprResult
Argyrios Kyrtzidis7192a3b2011-07-01 22:22:59 +00004339Sema::ActOnCastExpr(Scope *S, SourceLocation LParenLoc,
4340 Declarator &D, ParsedType &Ty,
Richard Trieuba63ce62011-09-09 01:45:06 +00004341 SourceLocation RParenLoc, Expr *CastExpr) {
4342 assert(!D.isInvalidType() && (CastExpr != 0) &&
Sebastian Redlb5d49352009-01-19 22:31:54 +00004343 "ActOnCastExpr(): missing type or expr");
Steve Naroff1a2cf6b2007-07-16 23:25:18 +00004344
Richard Trieuba63ce62011-09-09 01:45:06 +00004345 TypeSourceInfo *castTInfo = GetTypeForDeclaratorCast(D, CastExpr->getType());
Argyrios Kyrtzidis7192a3b2011-07-01 22:22:59 +00004346 if (D.isInvalidType())
4347 return ExprError();
4348
David Blaikiebbafb8a2012-03-11 07:00:24 +00004349 if (getLangOpts().CPlusPlus) {
Argyrios Kyrtzidis7192a3b2011-07-01 22:22:59 +00004350 // Check that there are no default arguments (C++ only).
4351 CheckExtraCXXDefaultArguments(D);
4352 }
4353
John McCall42856de2011-10-01 05:17:03 +00004354 checkUnusedDeclAttributes(D);
4355
Argyrios Kyrtzidis7192a3b2011-07-01 22:22:59 +00004356 QualType castType = castTInfo->getType();
4357 Ty = CreateParsedType(castType, castTInfo);
Mike Stump11289f42009-09-09 15:08:12 +00004358
Argyrios Kyrtzidisd8701b62011-07-01 22:22:54 +00004359 bool isVectorLiteral = false;
4360
4361 // Check for an altivec or OpenCL literal,
4362 // i.e. all the elements are integer constants.
Richard Trieuba63ce62011-09-09 01:45:06 +00004363 ParenExpr *PE = dyn_cast<ParenExpr>(CastExpr);
4364 ParenListExpr *PLE = dyn_cast<ParenListExpr>(CastExpr);
David Blaikiebbafb8a2012-03-11 07:00:24 +00004365 if ((getLangOpts().AltiVec || getLangOpts().OpenCL)
Tobias Grosser0a3a22f2011-09-21 18:28:29 +00004366 && castType->isVectorType() && (PE || PLE)) {
Argyrios Kyrtzidisd8701b62011-07-01 22:22:54 +00004367 if (PLE && PLE->getNumExprs() == 0) {
4368 Diag(PLE->getExprLoc(), diag::err_altivec_empty_initializer);
4369 return ExprError();
4370 }
4371 if (PE || PLE->getNumExprs() == 1) {
4372 Expr *E = (PE ? PE->getSubExpr() : PLE->getExpr(0));
4373 if (!E->getType()->isVectorType())
4374 isVectorLiteral = true;
4375 }
4376 else
4377 isVectorLiteral = true;
4378 }
4379
4380 // If this is a vector initializer, '(' type ')' '(' init, ..., init ')'
4381 // then handle it as such.
4382 if (isVectorLiteral)
Richard Trieuba63ce62011-09-09 01:45:06 +00004383 return BuildVectorLiteral(LParenLoc, RParenLoc, CastExpr, castTInfo);
Argyrios Kyrtzidisd8701b62011-07-01 22:22:54 +00004384
Nate Begeman5ec4b312009-08-10 23:49:36 +00004385 // If the Expr being casted is a ParenListExpr, handle it specially.
Argyrios Kyrtzidisd8701b62011-07-01 22:22:54 +00004386 // This is not an AltiVec-style cast, so turn the ParenListExpr into a
4387 // sequence of BinOp comma operators.
Richard Trieuba63ce62011-09-09 01:45:06 +00004388 if (isa<ParenListExpr>(CastExpr)) {
4389 ExprResult Result = MaybeConvertParenListExprToParenExpr(S, CastExpr);
Argyrios Kyrtzidisd8701b62011-07-01 22:22:54 +00004390 if (Result.isInvalid()) return ExprError();
Richard Trieuba63ce62011-09-09 01:45:06 +00004391 CastExpr = Result.take();
Argyrios Kyrtzidisd8701b62011-07-01 22:22:54 +00004392 }
John McCallebe54742010-01-15 18:56:44 +00004393
Richard Trieuba63ce62011-09-09 01:45:06 +00004394 return BuildCStyleCastExpr(LParenLoc, castTInfo, RParenLoc, CastExpr);
John McCallebe54742010-01-15 18:56:44 +00004395}
4396
Argyrios Kyrtzidisd8701b62011-07-01 22:22:54 +00004397ExprResult Sema::BuildVectorLiteral(SourceLocation LParenLoc,
4398 SourceLocation RParenLoc, Expr *E,
4399 TypeSourceInfo *TInfo) {
4400 assert((isa<ParenListExpr>(E) || isa<ParenExpr>(E)) &&
4401 "Expected paren or paren list expression");
4402
4403 Expr **exprs;
4404 unsigned numExprs;
4405 Expr *subExpr;
4406 if (ParenListExpr *PE = dyn_cast<ParenListExpr>(E)) {
4407 exprs = PE->getExprs();
4408 numExprs = PE->getNumExprs();
4409 } else {
4410 subExpr = cast<ParenExpr>(E)->getSubExpr();
4411 exprs = &subExpr;
4412 numExprs = 1;
4413 }
4414
4415 QualType Ty = TInfo->getType();
4416 assert(Ty->isVectorType() && "Expected vector type");
4417
Chris Lattner0e62c1c2011-07-23 10:55:15 +00004418 SmallVector<Expr *, 8> initExprs;
Tanya Lattner83559382011-07-15 23:07:01 +00004419 const VectorType *VTy = Ty->getAs<VectorType>();
4420 unsigned numElems = Ty->getAs<VectorType>()->getNumElements();
4421
Argyrios Kyrtzidisd8701b62011-07-01 22:22:54 +00004422 // '(...)' form of vector initialization in AltiVec: the number of
4423 // initializers must be one or must match the size of the vector.
4424 // If a single value is specified in the initializer then it will be
4425 // replicated to all the components of the vector
Tanya Lattner83559382011-07-15 23:07:01 +00004426 if (VTy->getVectorKind() == VectorType::AltiVecVector) {
Argyrios Kyrtzidisd8701b62011-07-01 22:22:54 +00004427 // The number of initializers must be one or must match the size of the
4428 // vector. If a single value is specified in the initializer then it will
4429 // be replicated to all the components of the vector
4430 if (numExprs == 1) {
4431 QualType ElemTy = Ty->getAs<VectorType>()->getElementType();
Richard Smith01ebacd2011-10-27 23:31:58 +00004432 ExprResult Literal = DefaultLvalueConversion(exprs[0]);
4433 if (Literal.isInvalid())
4434 return ExprError();
Argyrios Kyrtzidisd8701b62011-07-01 22:22:54 +00004435 Literal = ImpCastExprToType(Literal.take(), ElemTy,
John McCall9776e432011-10-06 23:25:11 +00004436 PrepareScalarCast(Literal, ElemTy));
Argyrios Kyrtzidisd8701b62011-07-01 22:22:54 +00004437 return BuildCStyleCastExpr(LParenLoc, TInfo, RParenLoc, Literal.take());
4438 }
4439 else if (numExprs < numElems) {
4440 Diag(E->getExprLoc(),
4441 diag::err_incorrect_number_of_vector_initializers);
4442 return ExprError();
4443 }
4444 else
Benjamin Kramer8001f742012-02-14 12:06:21 +00004445 initExprs.append(exprs, exprs + numExprs);
Argyrios Kyrtzidisd8701b62011-07-01 22:22:54 +00004446 }
Tanya Lattner83559382011-07-15 23:07:01 +00004447 else {
4448 // For OpenCL, when the number of initializers is a single value,
4449 // it will be replicated to all components of the vector.
David Blaikiebbafb8a2012-03-11 07:00:24 +00004450 if (getLangOpts().OpenCL &&
Tanya Lattner83559382011-07-15 23:07:01 +00004451 VTy->getVectorKind() == VectorType::GenericVector &&
4452 numExprs == 1) {
4453 QualType ElemTy = Ty->getAs<VectorType>()->getElementType();
Richard Smith01ebacd2011-10-27 23:31:58 +00004454 ExprResult Literal = DefaultLvalueConversion(exprs[0]);
4455 if (Literal.isInvalid())
4456 return ExprError();
Tanya Lattner83559382011-07-15 23:07:01 +00004457 Literal = ImpCastExprToType(Literal.take(), ElemTy,
John McCall9776e432011-10-06 23:25:11 +00004458 PrepareScalarCast(Literal, ElemTy));
Tanya Lattner83559382011-07-15 23:07:01 +00004459 return BuildCStyleCastExpr(LParenLoc, TInfo, RParenLoc, Literal.take());
4460 }
4461
Benjamin Kramer8001f742012-02-14 12:06:21 +00004462 initExprs.append(exprs, exprs + numExprs);
Tanya Lattner83559382011-07-15 23:07:01 +00004463 }
Argyrios Kyrtzidisd8701b62011-07-01 22:22:54 +00004464 // FIXME: This means that pretty-printing the final AST will produce curly
4465 // braces instead of the original commas.
4466 InitListExpr *initE = new (Context) InitListExpr(Context, LParenLoc,
4467 &initExprs[0],
4468 initExprs.size(), RParenLoc);
4469 initE->setType(Ty);
4470 return BuildCompoundLiteralExpr(LParenLoc, TInfo, RParenLoc, initE);
4471}
4472
Sebastian Redla9351792012-02-11 23:51:47 +00004473/// This is not an AltiVec-style cast or or C++ direct-initialization, so turn
4474/// the ParenListExpr into a sequence of comma binary operators.
John McCalldadc5752010-08-24 06:29:42 +00004475ExprResult
Richard Trieuba63ce62011-09-09 01:45:06 +00004476Sema::MaybeConvertParenListExprToParenExpr(Scope *S, Expr *OrigExpr) {
4477 ParenListExpr *E = dyn_cast<ParenListExpr>(OrigExpr);
Nate Begeman5ec4b312009-08-10 23:49:36 +00004478 if (!E)
Richard Trieuba63ce62011-09-09 01:45:06 +00004479 return Owned(OrigExpr);
Mike Stump11289f42009-09-09 15:08:12 +00004480
John McCalldadc5752010-08-24 06:29:42 +00004481 ExprResult Result(E->getExpr(0));
Mike Stump11289f42009-09-09 15:08:12 +00004482
Nate Begeman5ec4b312009-08-10 23:49:36 +00004483 for (unsigned i = 1, e = E->getNumExprs(); i != e && !Result.isInvalid(); ++i)
John McCallb268a282010-08-23 23:25:46 +00004484 Result = ActOnBinOp(S, E->getExprLoc(), tok::comma, Result.get(),
4485 E->getExpr(i));
Mike Stump11289f42009-09-09 15:08:12 +00004486
John McCallb268a282010-08-23 23:25:46 +00004487 if (Result.isInvalid()) return ExprError();
4488
4489 return ActOnParenExpr(E->getLParenLoc(), E->getRParenLoc(), Result.get());
Nate Begeman5ec4b312009-08-10 23:49:36 +00004490}
4491
Sebastian Redla9351792012-02-11 23:51:47 +00004492ExprResult Sema::ActOnParenListExpr(SourceLocation L,
4493 SourceLocation R,
4494 MultiExprArg Val) {
Nate Begeman5ec4b312009-08-10 23:49:36 +00004495 unsigned nexprs = Val.size();
4496 Expr **exprs = reinterpret_cast<Expr**>(Val.release());
Fariborz Jahanian906d8712009-11-25 01:26:41 +00004497 assert((exprs != 0) && "ActOnParenOrParenListExpr() missing expr list");
Sebastian Redla9351792012-02-11 23:51:47 +00004498 Expr *expr = new (Context) ParenListExpr(Context, L, exprs, nexprs, R);
Nate Begeman5ec4b312009-08-10 23:49:36 +00004499 return Owned(expr);
4500}
4501
Chandler Carrutha8bea4b2011-02-18 23:54:50 +00004502/// \brief Emit a specialized diagnostic when one expression is a null pointer
Richard Trieu27ae4cb2011-09-02 01:51:02 +00004503/// constant and the other is not a pointer. Returns true if a diagnostic is
4504/// emitted.
Richard Trieud33e46e2011-09-06 20:06:39 +00004505bool Sema::DiagnoseConditionalForNull(Expr *LHSExpr, Expr *RHSExpr,
Chandler Carrutha8bea4b2011-02-18 23:54:50 +00004506 SourceLocation QuestionLoc) {
Richard Trieud33e46e2011-09-06 20:06:39 +00004507 Expr *NullExpr = LHSExpr;
4508 Expr *NonPointerExpr = RHSExpr;
Chandler Carrutha8bea4b2011-02-18 23:54:50 +00004509 Expr::NullPointerConstantKind NullKind =
4510 NullExpr->isNullPointerConstant(Context,
4511 Expr::NPC_ValueDependentIsNotNull);
4512
4513 if (NullKind == Expr::NPCK_NotNull) {
Richard Trieud33e46e2011-09-06 20:06:39 +00004514 NullExpr = RHSExpr;
4515 NonPointerExpr = LHSExpr;
Chandler Carrutha8bea4b2011-02-18 23:54:50 +00004516 NullKind =
4517 NullExpr->isNullPointerConstant(Context,
4518 Expr::NPC_ValueDependentIsNotNull);
4519 }
4520
4521 if (NullKind == Expr::NPCK_NotNull)
4522 return false;
4523
4524 if (NullKind == Expr::NPCK_ZeroInteger) {
4525 // In this case, check to make sure that we got here from a "NULL"
4526 // string in the source code.
4527 NullExpr = NullExpr->IgnoreParenImpCasts();
John McCall462c0552011-03-08 07:59:04 +00004528 SourceLocation loc = NullExpr->getExprLoc();
4529 if (!findMacroSpelling(loc, "NULL"))
Chandler Carrutha8bea4b2011-02-18 23:54:50 +00004530 return false;
4531 }
4532
4533 int DiagType = (NullKind == Expr::NPCK_CXX0X_nullptr);
4534 Diag(QuestionLoc, diag::err_typecheck_cond_incompatible_operands_null)
4535 << NonPointerExpr->getType() << DiagType
4536 << NonPointerExpr->getSourceRange();
4537 return true;
4538}
4539
Richard Trieu27ae4cb2011-09-02 01:51:02 +00004540/// \brief Return false if the condition expression is valid, true otherwise.
4541static bool checkCondition(Sema &S, Expr *Cond) {
4542 QualType CondTy = Cond->getType();
4543
4544 // C99 6.5.15p2
4545 if (CondTy->isScalarType()) return false;
4546
4547 // OpenCL: Sec 6.3.i says the condition is allowed to be a vector or scalar.
David Blaikiebbafb8a2012-03-11 07:00:24 +00004548 if (S.getLangOpts().OpenCL && CondTy->isVectorType())
Richard Trieu27ae4cb2011-09-02 01:51:02 +00004549 return false;
4550
4551 // Emit the proper error message.
David Blaikiebbafb8a2012-03-11 07:00:24 +00004552 S.Diag(Cond->getLocStart(), S.getLangOpts().OpenCL ?
Richard Trieu27ae4cb2011-09-02 01:51:02 +00004553 diag::err_typecheck_cond_expect_scalar :
4554 diag::err_typecheck_cond_expect_scalar_or_vector)
4555 << CondTy;
4556 return true;
4557}
4558
4559/// \brief Return false if the two expressions can be converted to a vector,
4560/// true otherwise
4561static bool checkConditionalConvertScalarsToVectors(Sema &S, ExprResult &LHS,
4562 ExprResult &RHS,
4563 QualType CondTy) {
4564 // Both operands should be of scalar type.
4565 if (!LHS.get()->getType()->isScalarType()) {
4566 S.Diag(LHS.get()->getLocStart(), diag::err_typecheck_cond_expect_scalar)
4567 << CondTy;
4568 return true;
4569 }
4570 if (!RHS.get()->getType()->isScalarType()) {
4571 S.Diag(RHS.get()->getLocStart(), diag::err_typecheck_cond_expect_scalar)
4572 << CondTy;
4573 return true;
4574 }
4575
4576 // Implicity convert these scalars to the type of the condition.
4577 LHS = S.ImpCastExprToType(LHS.take(), CondTy, CK_IntegralCast);
4578 RHS = S.ImpCastExprToType(RHS.take(), CondTy, CK_IntegralCast);
4579 return false;
4580}
4581
4582/// \brief Handle when one or both operands are void type.
4583static QualType checkConditionalVoidType(Sema &S, ExprResult &LHS,
4584 ExprResult &RHS) {
4585 Expr *LHSExpr = LHS.get();
4586 Expr *RHSExpr = RHS.get();
4587
4588 if (!LHSExpr->getType()->isVoidType())
4589 S.Diag(RHSExpr->getLocStart(), diag::ext_typecheck_cond_one_void)
4590 << RHSExpr->getSourceRange();
4591 if (!RHSExpr->getType()->isVoidType())
4592 S.Diag(LHSExpr->getLocStart(), diag::ext_typecheck_cond_one_void)
4593 << LHSExpr->getSourceRange();
4594 LHS = S.ImpCastExprToType(LHS.take(), S.Context.VoidTy, CK_ToVoid);
4595 RHS = S.ImpCastExprToType(RHS.take(), S.Context.VoidTy, CK_ToVoid);
4596 return S.Context.VoidTy;
4597}
4598
4599/// \brief Return false if the NullExpr can be promoted to PointerTy,
4600/// true otherwise.
4601static bool checkConditionalNullPointer(Sema &S, ExprResult &NullExpr,
4602 QualType PointerTy) {
4603 if ((!PointerTy->isAnyPointerType() && !PointerTy->isBlockPointerType()) ||
4604 !NullExpr.get()->isNullPointerConstant(S.Context,
4605 Expr::NPC_ValueDependentIsNull))
4606 return true;
4607
4608 NullExpr = S.ImpCastExprToType(NullExpr.take(), PointerTy, CK_NullToPointer);
4609 return false;
4610}
4611
4612/// \brief Checks compatibility between two pointers and return the resulting
4613/// type.
4614static QualType checkConditionalPointerCompatibility(Sema &S, ExprResult &LHS,
4615 ExprResult &RHS,
4616 SourceLocation Loc) {
4617 QualType LHSTy = LHS.get()->getType();
4618 QualType RHSTy = RHS.get()->getType();
4619
4620 if (S.Context.hasSameType(LHSTy, RHSTy)) {
4621 // Two identical pointers types are always compatible.
4622 return LHSTy;
4623 }
4624
4625 QualType lhptee, rhptee;
4626
4627 // Get the pointee types.
John McCall9320b872011-09-09 05:25:32 +00004628 if (const BlockPointerType *LHSBTy = LHSTy->getAs<BlockPointerType>()) {
4629 lhptee = LHSBTy->getPointeeType();
4630 rhptee = RHSTy->castAs<BlockPointerType>()->getPointeeType();
Richard Trieu27ae4cb2011-09-02 01:51:02 +00004631 } else {
John McCall9320b872011-09-09 05:25:32 +00004632 lhptee = LHSTy->castAs<PointerType>()->getPointeeType();
4633 rhptee = RHSTy->castAs<PointerType>()->getPointeeType();
Richard Trieu27ae4cb2011-09-02 01:51:02 +00004634 }
4635
Eli Friedman57a75392012-04-05 22:30:04 +00004636 // C99 6.5.15p6: If both operands are pointers to compatible types or to
4637 // differently qualified versions of compatible types, the result type is
4638 // a pointer to an appropriately qualified version of the composite
4639 // type.
4640
4641 // Only CVR-qualifiers exist in the standard, and the differently-qualified
4642 // clause doesn't make sense for our extensions. E.g. address space 2 should
4643 // be incompatible with address space 3: they may live on different devices or
4644 // anything.
4645 Qualifiers lhQual = lhptee.getQualifiers();
4646 Qualifiers rhQual = rhptee.getQualifiers();
4647
4648 unsigned MergedCVRQual = lhQual.getCVRQualifiers() | rhQual.getCVRQualifiers();
4649 lhQual.removeCVRQualifiers();
4650 rhQual.removeCVRQualifiers();
4651
4652 lhptee = S.Context.getQualifiedType(lhptee.getUnqualifiedType(), lhQual);
4653 rhptee = S.Context.getQualifiedType(rhptee.getUnqualifiedType(), rhQual);
4654
4655 QualType CompositeTy = S.Context.mergeTypes(lhptee, rhptee);
4656
4657 if (CompositeTy.isNull()) {
Richard Trieu27ae4cb2011-09-02 01:51:02 +00004658 S.Diag(Loc, diag::warn_typecheck_cond_incompatible_pointers)
4659 << LHSTy << RHSTy << LHS.get()->getSourceRange()
4660 << RHS.get()->getSourceRange();
4661 // In this situation, we assume void* type. No especially good
4662 // reason, but this is what gcc does, and we do have to pick
4663 // to get a consistent AST.
4664 QualType incompatTy = S.Context.getPointerType(S.Context.VoidTy);
4665 LHS = S.ImpCastExprToType(LHS.take(), incompatTy, CK_BitCast);
4666 RHS = S.ImpCastExprToType(RHS.take(), incompatTy, CK_BitCast);
4667 return incompatTy;
4668 }
4669
4670 // The pointer types are compatible.
Eli Friedman57a75392012-04-05 22:30:04 +00004671 QualType ResultTy = CompositeTy.withCVRQualifiers(MergedCVRQual);
4672 ResultTy = S.Context.getPointerType(ResultTy);
Richard Trieu27ae4cb2011-09-02 01:51:02 +00004673
Eli Friedman57a75392012-04-05 22:30:04 +00004674 LHS = S.ImpCastExprToType(LHS.take(), ResultTy, CK_BitCast);
4675 RHS = S.ImpCastExprToType(RHS.take(), ResultTy, CK_BitCast);
4676 return ResultTy;
Richard Trieu27ae4cb2011-09-02 01:51:02 +00004677}
4678
4679/// \brief Return the resulting type when the operands are both block pointers.
4680static QualType checkConditionalBlockPointerCompatibility(Sema &S,
4681 ExprResult &LHS,
4682 ExprResult &RHS,
4683 SourceLocation Loc) {
4684 QualType LHSTy = LHS.get()->getType();
4685 QualType RHSTy = RHS.get()->getType();
4686
4687 if (!LHSTy->isBlockPointerType() || !RHSTy->isBlockPointerType()) {
4688 if (LHSTy->isVoidPointerType() || RHSTy->isVoidPointerType()) {
4689 QualType destType = S.Context.getPointerType(S.Context.VoidTy);
4690 LHS = S.ImpCastExprToType(LHS.take(), destType, CK_BitCast);
4691 RHS = S.ImpCastExprToType(RHS.take(), destType, CK_BitCast);
4692 return destType;
4693 }
4694 S.Diag(Loc, diag::err_typecheck_cond_incompatible_operands)
4695 << LHSTy << RHSTy << LHS.get()->getSourceRange()
4696 << RHS.get()->getSourceRange();
4697 return QualType();
4698 }
4699
4700 // We have 2 block pointer types.
4701 return checkConditionalPointerCompatibility(S, LHS, RHS, Loc);
4702}
4703
4704/// \brief Return the resulting type when the operands are both pointers.
4705static QualType
4706checkConditionalObjectPointersCompatibility(Sema &S, ExprResult &LHS,
4707 ExprResult &RHS,
4708 SourceLocation Loc) {
4709 // get the pointer types
4710 QualType LHSTy = LHS.get()->getType();
4711 QualType RHSTy = RHS.get()->getType();
4712
4713 // get the "pointed to" types
4714 QualType lhptee = LHSTy->getAs<PointerType>()->getPointeeType();
4715 QualType rhptee = RHSTy->getAs<PointerType>()->getPointeeType();
4716
4717 // ignore qualifiers on void (C99 6.5.15p3, clause 6)
4718 if (lhptee->isVoidType() && rhptee->isIncompleteOrObjectType()) {
4719 // Figure out necessary qualifiers (C99 6.5.15p6)
4720 QualType destPointee
4721 = S.Context.getQualifiedType(lhptee, rhptee.getQualifiers());
4722 QualType destType = S.Context.getPointerType(destPointee);
4723 // Add qualifiers if necessary.
4724 LHS = S.ImpCastExprToType(LHS.take(), destType, CK_NoOp);
4725 // Promote to void*.
4726 RHS = S.ImpCastExprToType(RHS.take(), destType, CK_BitCast);
4727 return destType;
4728 }
4729 if (rhptee->isVoidType() && lhptee->isIncompleteOrObjectType()) {
4730 QualType destPointee
4731 = S.Context.getQualifiedType(rhptee, lhptee.getQualifiers());
4732 QualType destType = S.Context.getPointerType(destPointee);
4733 // Add qualifiers if necessary.
4734 RHS = S.ImpCastExprToType(RHS.take(), destType, CK_NoOp);
4735 // Promote to void*.
4736 LHS = S.ImpCastExprToType(LHS.take(), destType, CK_BitCast);
4737 return destType;
4738 }
4739
4740 return checkConditionalPointerCompatibility(S, LHS, RHS, Loc);
4741}
4742
4743/// \brief Return false if the first expression is not an integer and the second
4744/// expression is not a pointer, true otherwise.
4745static bool checkPointerIntegerMismatch(Sema &S, ExprResult &Int,
4746 Expr* PointerExpr, SourceLocation Loc,
Richard Trieuba63ce62011-09-09 01:45:06 +00004747 bool IsIntFirstExpr) {
Richard Trieu27ae4cb2011-09-02 01:51:02 +00004748 if (!PointerExpr->getType()->isPointerType() ||
4749 !Int.get()->getType()->isIntegerType())
4750 return false;
4751
Richard Trieuba63ce62011-09-09 01:45:06 +00004752 Expr *Expr1 = IsIntFirstExpr ? Int.get() : PointerExpr;
4753 Expr *Expr2 = IsIntFirstExpr ? PointerExpr : Int.get();
Richard Trieu27ae4cb2011-09-02 01:51:02 +00004754
4755 S.Diag(Loc, diag::warn_typecheck_cond_pointer_integer_mismatch)
4756 << Expr1->getType() << Expr2->getType()
4757 << Expr1->getSourceRange() << Expr2->getSourceRange();
4758 Int = S.ImpCastExprToType(Int.take(), PointerExpr->getType(),
4759 CK_IntegralToPointer);
4760 return true;
4761}
4762
Richard Trieud33e46e2011-09-06 20:06:39 +00004763/// Note that LHS is not null here, even if this is the gnu "x ?: y" extension.
4764/// In that case, LHS = cond.
Chris Lattner2c486602009-02-18 04:38:20 +00004765/// C99 6.5.15
Richard Trieucfc491d2011-08-02 04:35:43 +00004766QualType Sema::CheckConditionalOperands(ExprResult &Cond, ExprResult &LHS,
4767 ExprResult &RHS, ExprValueKind &VK,
4768 ExprObjectKind &OK,
Chris Lattner2c486602009-02-18 04:38:20 +00004769 SourceLocation QuestionLoc) {
Douglas Gregor1beec452011-03-12 01:48:56 +00004770
Richard Trieud33e46e2011-09-06 20:06:39 +00004771 ExprResult LHSResult = CheckPlaceholderExpr(LHS.get());
4772 if (!LHSResult.isUsable()) return QualType();
4773 LHS = move(LHSResult);
Douglas Gregor0124e9b2010-11-09 21:07:58 +00004774
Richard Trieud33e46e2011-09-06 20:06:39 +00004775 ExprResult RHSResult = CheckPlaceholderExpr(RHS.get());
4776 if (!RHSResult.isUsable()) return QualType();
4777 RHS = move(RHSResult);
Douglas Gregor0124e9b2010-11-09 21:07:58 +00004778
Sebastian Redl1a99f442009-04-16 17:51:27 +00004779 // C++ is sufficiently different to merit its own checker.
David Blaikiebbafb8a2012-03-11 07:00:24 +00004780 if (getLangOpts().CPlusPlus)
John McCallc07a0c72011-02-17 10:25:35 +00004781 return CXXCheckConditionalOperands(Cond, LHS, RHS, VK, OK, QuestionLoc);
John McCall7decc9e2010-11-18 06:31:45 +00004782
4783 VK = VK_RValue;
John McCall4bc41ae2010-11-18 19:01:18 +00004784 OK = OK_Ordinary;
Sebastian Redl1a99f442009-04-16 17:51:27 +00004785
John Wiegley01296292011-04-08 18:41:53 +00004786 Cond = UsualUnaryConversions(Cond.take());
4787 if (Cond.isInvalid())
4788 return QualType();
4789 LHS = UsualUnaryConversions(LHS.take());
4790 if (LHS.isInvalid())
4791 return QualType();
4792 RHS = UsualUnaryConversions(RHS.take());
4793 if (RHS.isInvalid())
4794 return QualType();
4795
4796 QualType CondTy = Cond.get()->getType();
4797 QualType LHSTy = LHS.get()->getType();
4798 QualType RHSTy = RHS.get()->getType();
Steve Naroff31090012007-07-16 21:54:35 +00004799
Steve Naroffa78fe7e2007-05-16 19:47:19 +00004800 // first, check the condition.
Richard Trieu27ae4cb2011-09-02 01:51:02 +00004801 if (checkCondition(*this, Cond.get()))
4802 return QualType();
Mike Stump4e1f26a2009-02-19 03:04:26 +00004803
Chris Lattnere2949f42008-01-06 22:42:25 +00004804 // Now check the two expressions.
Nate Begeman5ec4b312009-08-10 23:49:36 +00004805 if (LHSTy->isVectorType() || RHSTy->isVectorType())
Eli Friedman1408bc92011-06-23 18:10:35 +00004806 return CheckVectorOperands(LHS, RHS, QuestionLoc, /*isCompAssign*/false);
Douglas Gregor4619e432008-12-05 23:32:09 +00004807
Nate Begemanabb5a732010-09-20 22:41:17 +00004808 // OpenCL: If the condition is a vector, and both operands are scalar,
4809 // attempt to implicity convert them to the vector type to act like the
4810 // built in select.
David Blaikiebbafb8a2012-03-11 07:00:24 +00004811 if (getLangOpts().OpenCL && CondTy->isVectorType())
Richard Trieu27ae4cb2011-09-02 01:51:02 +00004812 if (checkConditionalConvertScalarsToVectors(*this, LHS, RHS, CondTy))
Nate Begemanabb5a732010-09-20 22:41:17 +00004813 return QualType();
Nate Begemanabb5a732010-09-20 22:41:17 +00004814
Chris Lattnere2949f42008-01-06 22:42:25 +00004815 // If both operands have arithmetic type, do the usual arithmetic conversions
4816 // to find a common type: C99 6.5.15p3,5.
Chris Lattner432cff52009-02-18 04:28:32 +00004817 if (LHSTy->isArithmeticType() && RHSTy->isArithmeticType()) {
4818 UsualArithmeticConversions(LHS, RHS);
John Wiegley01296292011-04-08 18:41:53 +00004819 if (LHS.isInvalid() || RHS.isInvalid())
4820 return QualType();
4821 return LHS.get()->getType();
Steve Naroffdbd9e892007-07-17 00:58:39 +00004822 }
Mike Stump4e1f26a2009-02-19 03:04:26 +00004823
Chris Lattnere2949f42008-01-06 22:42:25 +00004824 // If both operands are the same structure or union type, the result is that
4825 // type.
Ted Kremenekc23c7e62009-07-29 21:53:49 +00004826 if (const RecordType *LHSRT = LHSTy->getAs<RecordType>()) { // C99 6.5.15p3
4827 if (const RecordType *RHSRT = RHSTy->getAs<RecordType>())
Chris Lattner2ab40a62007-11-26 01:40:58 +00004828 if (LHSRT->getDecl() == RHSRT->getDecl())
Mike Stump4e1f26a2009-02-19 03:04:26 +00004829 // "If both the operands have structure or union type, the result has
Chris Lattnere2949f42008-01-06 22:42:25 +00004830 // that type." This implies that CV qualifiers are dropped.
Chris Lattner432cff52009-02-18 04:28:32 +00004831 return LHSTy.getUnqualifiedType();
Eli Friedmanba961a92009-03-23 00:24:07 +00004832 // FIXME: Type of conditional expression must be complete in C mode.
Steve Naroffa78fe7e2007-05-16 19:47:19 +00004833 }
Mike Stump4e1f26a2009-02-19 03:04:26 +00004834
Chris Lattnere2949f42008-01-06 22:42:25 +00004835 // C99 6.5.15p5: "If both operands have void type, the result has void type."
Steve Naroffbf1516c2008-05-12 21:44:38 +00004836 // The following || allows only one side to be void (a GCC-ism).
Chris Lattner432cff52009-02-18 04:28:32 +00004837 if (LHSTy->isVoidType() || RHSTy->isVoidType()) {
Richard Trieu27ae4cb2011-09-02 01:51:02 +00004838 return checkConditionalVoidType(*this, LHS, RHS);
Steve Naroffbf1516c2008-05-12 21:44:38 +00004839 }
Richard Trieu27ae4cb2011-09-02 01:51:02 +00004840
Steve Naroff039ad3c2008-01-08 01:11:38 +00004841 // C99 6.5.15p6 - "if one operand is a null pointer constant, the result has
4842 // the type of the other operand."
Richard Trieu27ae4cb2011-09-02 01:51:02 +00004843 if (!checkConditionalNullPointer(*this, RHS, LHSTy)) return LHSTy;
4844 if (!checkConditionalNullPointer(*this, LHS, RHSTy)) return RHSTy;
Kovarththanan Rajaratnamba2c6522010-03-13 10:17:05 +00004845
Fariborz Jahaniana430f712009-12-10 19:47:41 +00004846 // All objective-c pointer type analysis is done here.
4847 QualType compositeType = FindCompositeObjCPointerType(LHS, RHS,
4848 QuestionLoc);
John Wiegley01296292011-04-08 18:41:53 +00004849 if (LHS.isInvalid() || RHS.isInvalid())
4850 return QualType();
Fariborz Jahaniana430f712009-12-10 19:47:41 +00004851 if (!compositeType.isNull())
4852 return compositeType;
Kovarththanan Rajaratnamba2c6522010-03-13 10:17:05 +00004853
4854
Steve Naroff05efa972009-07-01 14:36:47 +00004855 // Handle block pointer types.
Richard Trieu27ae4cb2011-09-02 01:51:02 +00004856 if (LHSTy->isBlockPointerType() || RHSTy->isBlockPointerType())
4857 return checkConditionalBlockPointerCompatibility(*this, LHS, RHS,
4858 QuestionLoc);
Kovarththanan Rajaratnamba2c6522010-03-13 10:17:05 +00004859
Steve Naroff05efa972009-07-01 14:36:47 +00004860 // Check constraints for C object pointers types (C99 6.5.15p3,6).
Richard Trieu27ae4cb2011-09-02 01:51:02 +00004861 if (LHSTy->isPointerType() && RHSTy->isPointerType())
4862 return checkConditionalObjectPointersCompatibility(*this, LHS, RHS,
4863 QuestionLoc);
Mike Stump11289f42009-09-09 15:08:12 +00004864
John McCalle84af4e2010-11-13 01:35:44 +00004865 // GCC compatibility: soften pointer/integer mismatch. Note that
4866 // null pointers have been filtered out by this point.
Richard Trieu27ae4cb2011-09-02 01:51:02 +00004867 if (checkPointerIntegerMismatch(*this, LHS, RHS.get(), QuestionLoc,
4868 /*isIntFirstExpr=*/true))
Steve Naroff05efa972009-07-01 14:36:47 +00004869 return RHSTy;
Richard Trieu27ae4cb2011-09-02 01:51:02 +00004870 if (checkPointerIntegerMismatch(*this, RHS, LHS.get(), QuestionLoc,
4871 /*isIntFirstExpr=*/false))
Steve Naroff05efa972009-07-01 14:36:47 +00004872 return LHSTy;
Daniel Dunbar484603b2008-09-11 23:12:46 +00004873
Chandler Carrutha8bea4b2011-02-18 23:54:50 +00004874 // Emit a better diagnostic if one of the expressions is a null pointer
4875 // constant and the other is not a pointer type. In this case, the user most
4876 // likely forgot to take the address of the other expression.
John Wiegley01296292011-04-08 18:41:53 +00004877 if (DiagnoseConditionalForNull(LHS.get(), RHS.get(), QuestionLoc))
Chandler Carrutha8bea4b2011-02-18 23:54:50 +00004878 return QualType();
4879
Chris Lattnere2949f42008-01-06 22:42:25 +00004880 // Otherwise, the operands are not compatible.
Chris Lattner432cff52009-02-18 04:28:32 +00004881 Diag(QuestionLoc, diag::err_typecheck_cond_incompatible_operands)
Richard Trieucfc491d2011-08-02 04:35:43 +00004882 << LHSTy << RHSTy << LHS.get()->getSourceRange()
4883 << RHS.get()->getSourceRange();
Steve Naroffa78fe7e2007-05-16 19:47:19 +00004884 return QualType();
Steve Narofff8a28c52007-05-15 20:29:32 +00004885}
4886
Fariborz Jahaniana430f712009-12-10 19:47:41 +00004887/// FindCompositeObjCPointerType - Helper method to find composite type of
4888/// two objective-c pointer types of the two input expressions.
John Wiegley01296292011-04-08 18:41:53 +00004889QualType Sema::FindCompositeObjCPointerType(ExprResult &LHS, ExprResult &RHS,
Richard Trieucfc491d2011-08-02 04:35:43 +00004890 SourceLocation QuestionLoc) {
John Wiegley01296292011-04-08 18:41:53 +00004891 QualType LHSTy = LHS.get()->getType();
4892 QualType RHSTy = RHS.get()->getType();
Kovarththanan Rajaratnamba2c6522010-03-13 10:17:05 +00004893
Fariborz Jahaniana430f712009-12-10 19:47:41 +00004894 // Handle things like Class and struct objc_class*. Here we case the result
4895 // to the pseudo-builtin, because that will be implicitly cast back to the
4896 // redefinition type if an attempt is made to access its fields.
4897 if (LHSTy->isObjCClassType() &&
Douglas Gregor97673472011-08-11 20:58:55 +00004898 (Context.hasSameType(RHSTy, Context.getObjCClassRedefinitionType()))) {
John McCall9320b872011-09-09 05:25:32 +00004899 RHS = ImpCastExprToType(RHS.take(), LHSTy, CK_CPointerToObjCPointerCast);
Fariborz Jahaniana430f712009-12-10 19:47:41 +00004900 return LHSTy;
4901 }
4902 if (RHSTy->isObjCClassType() &&
Douglas Gregor97673472011-08-11 20:58:55 +00004903 (Context.hasSameType(LHSTy, Context.getObjCClassRedefinitionType()))) {
John McCall9320b872011-09-09 05:25:32 +00004904 LHS = ImpCastExprToType(LHS.take(), RHSTy, CK_CPointerToObjCPointerCast);
Fariborz Jahaniana430f712009-12-10 19:47:41 +00004905 return RHSTy;
4906 }
4907 // And the same for struct objc_object* / id
4908 if (LHSTy->isObjCIdType() &&
Douglas Gregor97673472011-08-11 20:58:55 +00004909 (Context.hasSameType(RHSTy, Context.getObjCIdRedefinitionType()))) {
John McCall9320b872011-09-09 05:25:32 +00004910 RHS = ImpCastExprToType(RHS.take(), LHSTy, CK_CPointerToObjCPointerCast);
Fariborz Jahaniana430f712009-12-10 19:47:41 +00004911 return LHSTy;
4912 }
4913 if (RHSTy->isObjCIdType() &&
Douglas Gregor97673472011-08-11 20:58:55 +00004914 (Context.hasSameType(LHSTy, Context.getObjCIdRedefinitionType()))) {
John McCall9320b872011-09-09 05:25:32 +00004915 LHS = ImpCastExprToType(LHS.take(), RHSTy, CK_CPointerToObjCPointerCast);
Fariborz Jahaniana430f712009-12-10 19:47:41 +00004916 return RHSTy;
4917 }
4918 // And the same for struct objc_selector* / SEL
4919 if (Context.isObjCSelType(LHSTy) &&
Douglas Gregor97673472011-08-11 20:58:55 +00004920 (Context.hasSameType(RHSTy, Context.getObjCSelRedefinitionType()))) {
John Wiegley01296292011-04-08 18:41:53 +00004921 RHS = ImpCastExprToType(RHS.take(), LHSTy, CK_BitCast);
Fariborz Jahaniana430f712009-12-10 19:47:41 +00004922 return LHSTy;
4923 }
4924 if (Context.isObjCSelType(RHSTy) &&
Douglas Gregor97673472011-08-11 20:58:55 +00004925 (Context.hasSameType(LHSTy, Context.getObjCSelRedefinitionType()))) {
John Wiegley01296292011-04-08 18:41:53 +00004926 LHS = ImpCastExprToType(LHS.take(), RHSTy, CK_BitCast);
Fariborz Jahaniana430f712009-12-10 19:47:41 +00004927 return RHSTy;
4928 }
4929 // Check constraints for Objective-C object pointers types.
4930 if (LHSTy->isObjCObjectPointerType() && RHSTy->isObjCObjectPointerType()) {
Kovarththanan Rajaratnamba2c6522010-03-13 10:17:05 +00004931
Fariborz Jahaniana430f712009-12-10 19:47:41 +00004932 if (Context.getCanonicalType(LHSTy) == Context.getCanonicalType(RHSTy)) {
4933 // Two identical object pointer types are always compatible.
4934 return LHSTy;
4935 }
John McCall9320b872011-09-09 05:25:32 +00004936 const ObjCObjectPointerType *LHSOPT = LHSTy->castAs<ObjCObjectPointerType>();
4937 const ObjCObjectPointerType *RHSOPT = RHSTy->castAs<ObjCObjectPointerType>();
Fariborz Jahaniana430f712009-12-10 19:47:41 +00004938 QualType compositeType = LHSTy;
Kovarththanan Rajaratnamba2c6522010-03-13 10:17:05 +00004939
Fariborz Jahaniana430f712009-12-10 19:47:41 +00004940 // If both operands are interfaces and either operand can be
4941 // assigned to the other, use that type as the composite
4942 // type. This allows
4943 // xxx ? (A*) a : (B*) b
4944 // where B is a subclass of A.
4945 //
4946 // Additionally, as for assignment, if either type is 'id'
4947 // allow silent coercion. Finally, if the types are
4948 // incompatible then make sure to use 'id' as the composite
4949 // type so the result is acceptable for sending messages to.
Kovarththanan Rajaratnamba2c6522010-03-13 10:17:05 +00004950
Fariborz Jahaniana430f712009-12-10 19:47:41 +00004951 // FIXME: Consider unifying with 'areComparableObjCPointerTypes'.
4952 // It could return the composite type.
4953 if (Context.canAssignObjCInterfaces(LHSOPT, RHSOPT)) {
4954 compositeType = RHSOPT->isObjCBuiltinType() ? RHSTy : LHSTy;
4955 } else if (Context.canAssignObjCInterfaces(RHSOPT, LHSOPT)) {
4956 compositeType = LHSOPT->isObjCBuiltinType() ? LHSTy : RHSTy;
4957 } else if ((LHSTy->isObjCQualifiedIdType() ||
4958 RHSTy->isObjCQualifiedIdType()) &&
4959 Context.ObjCQualifiedIdTypesAreCompatible(LHSTy, RHSTy, true)) {
4960 // Need to handle "id<xx>" explicitly.
4961 // GCC allows qualified id and any Objective-C type to devolve to
4962 // id. Currently localizing to here until clear this should be
4963 // part of ObjCQualifiedIdTypesAreCompatible.
4964 compositeType = Context.getObjCIdType();
4965 } else if (LHSTy->isObjCIdType() || RHSTy->isObjCIdType()) {
4966 compositeType = Context.getObjCIdType();
Kovarththanan Rajaratnamba2c6522010-03-13 10:17:05 +00004967 } else if (!(compositeType =
Fariborz Jahaniana430f712009-12-10 19:47:41 +00004968 Context.areCommonBaseCompatible(LHSOPT, RHSOPT)).isNull())
4969 ;
4970 else {
4971 Diag(QuestionLoc, diag::ext_typecheck_cond_incompatible_operands)
4972 << LHSTy << RHSTy
John Wiegley01296292011-04-08 18:41:53 +00004973 << LHS.get()->getSourceRange() << RHS.get()->getSourceRange();
Fariborz Jahaniana430f712009-12-10 19:47:41 +00004974 QualType incompatTy = Context.getObjCIdType();
John Wiegley01296292011-04-08 18:41:53 +00004975 LHS = ImpCastExprToType(LHS.take(), incompatTy, CK_BitCast);
4976 RHS = ImpCastExprToType(RHS.take(), incompatTy, CK_BitCast);
Fariborz Jahaniana430f712009-12-10 19:47:41 +00004977 return incompatTy;
4978 }
4979 // The object pointer types are compatible.
John Wiegley01296292011-04-08 18:41:53 +00004980 LHS = ImpCastExprToType(LHS.take(), compositeType, CK_BitCast);
4981 RHS = ImpCastExprToType(RHS.take(), compositeType, CK_BitCast);
Fariborz Jahaniana430f712009-12-10 19:47:41 +00004982 return compositeType;
4983 }
4984 // Check Objective-C object pointer types and 'void *'
4985 if (LHSTy->isVoidPointerType() && RHSTy->isObjCObjectPointerType()) {
David Blaikiebbafb8a2012-03-11 07:00:24 +00004986 if (getLangOpts().ObjCAutoRefCount) {
Eli Friedman8a78a582012-02-25 00:23:44 +00004987 // ARC forbids the implicit conversion of object pointers to 'void *',
4988 // so these types are not compatible.
4989 Diag(QuestionLoc, diag::err_cond_voidptr_arc) << LHSTy << RHSTy
4990 << LHS.get()->getSourceRange() << RHS.get()->getSourceRange();
4991 LHS = RHS = true;
4992 return QualType();
4993 }
Fariborz Jahaniana430f712009-12-10 19:47:41 +00004994 QualType lhptee = LHSTy->getAs<PointerType>()->getPointeeType();
4995 QualType rhptee = RHSTy->getAs<ObjCObjectPointerType>()->getPointeeType();
4996 QualType destPointee
4997 = Context.getQualifiedType(lhptee, rhptee.getQualifiers());
4998 QualType destType = Context.getPointerType(destPointee);
4999 // Add qualifiers if necessary.
John Wiegley01296292011-04-08 18:41:53 +00005000 LHS = ImpCastExprToType(LHS.take(), destType, CK_NoOp);
Fariborz Jahaniana430f712009-12-10 19:47:41 +00005001 // Promote to void*.
John Wiegley01296292011-04-08 18:41:53 +00005002 RHS = ImpCastExprToType(RHS.take(), destType, CK_BitCast);
Fariborz Jahaniana430f712009-12-10 19:47:41 +00005003 return destType;
5004 }
5005 if (LHSTy->isObjCObjectPointerType() && RHSTy->isVoidPointerType()) {
David Blaikiebbafb8a2012-03-11 07:00:24 +00005006 if (getLangOpts().ObjCAutoRefCount) {
Eli Friedman8a78a582012-02-25 00:23:44 +00005007 // ARC forbids the implicit conversion of object pointers to 'void *',
5008 // so these types are not compatible.
5009 Diag(QuestionLoc, diag::err_cond_voidptr_arc) << LHSTy << RHSTy
5010 << LHS.get()->getSourceRange() << RHS.get()->getSourceRange();
5011 LHS = RHS = true;
5012 return QualType();
5013 }
Fariborz Jahaniana430f712009-12-10 19:47:41 +00005014 QualType lhptee = LHSTy->getAs<ObjCObjectPointerType>()->getPointeeType();
5015 QualType rhptee = RHSTy->getAs<PointerType>()->getPointeeType();
5016 QualType destPointee
5017 = Context.getQualifiedType(rhptee, lhptee.getQualifiers());
5018 QualType destType = Context.getPointerType(destPointee);
5019 // Add qualifiers if necessary.
John Wiegley01296292011-04-08 18:41:53 +00005020 RHS = ImpCastExprToType(RHS.take(), destType, CK_NoOp);
Fariborz Jahaniana430f712009-12-10 19:47:41 +00005021 // Promote to void*.
John Wiegley01296292011-04-08 18:41:53 +00005022 LHS = ImpCastExprToType(LHS.take(), destType, CK_BitCast);
Fariborz Jahaniana430f712009-12-10 19:47:41 +00005023 return destType;
5024 }
5025 return QualType();
5026}
5027
Chandler Carruthb00e8c02011-06-16 01:05:14 +00005028/// SuggestParentheses - Emit a note with a fixit hint that wraps
Hans Wennborgcf9bac42011-06-03 18:00:36 +00005029/// ParenRange in parentheses.
5030static void SuggestParentheses(Sema &Self, SourceLocation Loc,
Chandler Carruthb00e8c02011-06-16 01:05:14 +00005031 const PartialDiagnostic &Note,
5032 SourceRange ParenRange) {
5033 SourceLocation EndLoc = Self.PP.getLocForEndOfToken(ParenRange.getEnd());
5034 if (ParenRange.getBegin().isFileID() && ParenRange.getEnd().isFileID() &&
5035 EndLoc.isValid()) {
5036 Self.Diag(Loc, Note)
5037 << FixItHint::CreateInsertion(ParenRange.getBegin(), "(")
5038 << FixItHint::CreateInsertion(EndLoc, ")");
5039 } else {
5040 // We can't display the parentheses, so just show the bare note.
5041 Self.Diag(Loc, Note) << ParenRange;
Hans Wennborgcf9bac42011-06-03 18:00:36 +00005042 }
Hans Wennborgcf9bac42011-06-03 18:00:36 +00005043}
5044
5045static bool IsArithmeticOp(BinaryOperatorKind Opc) {
5046 return Opc >= BO_Mul && Opc <= BO_Shr;
5047}
5048
Hans Wennborgde2e67e2011-06-09 17:06:51 +00005049/// IsArithmeticBinaryExpr - Returns true if E is an arithmetic binary
5050/// expression, either using a built-in or overloaded operator,
Richard Trieud33e46e2011-09-06 20:06:39 +00005051/// and sets *OpCode to the opcode and *RHSExprs to the right-hand side
5052/// expression.
Hans Wennborgde2e67e2011-06-09 17:06:51 +00005053static bool IsArithmeticBinaryExpr(Expr *E, BinaryOperatorKind *Opcode,
Richard Trieud33e46e2011-09-06 20:06:39 +00005054 Expr **RHSExprs) {
Hans Wennborgbe207b32011-09-12 12:07:30 +00005055 // Don't strip parenthesis: we should not warn if E is in parenthesis.
5056 E = E->IgnoreImpCasts();
Hans Wennborgde2e67e2011-06-09 17:06:51 +00005057 E = E->IgnoreConversionOperator();
Hans Wennborgbe207b32011-09-12 12:07:30 +00005058 E = E->IgnoreImpCasts();
Hans Wennborgde2e67e2011-06-09 17:06:51 +00005059
5060 // Built-in binary operator.
5061 if (BinaryOperator *OP = dyn_cast<BinaryOperator>(E)) {
5062 if (IsArithmeticOp(OP->getOpcode())) {
5063 *Opcode = OP->getOpcode();
Richard Trieud33e46e2011-09-06 20:06:39 +00005064 *RHSExprs = OP->getRHS();
Hans Wennborgde2e67e2011-06-09 17:06:51 +00005065 return true;
5066 }
5067 }
5068
5069 // Overloaded operator.
5070 if (CXXOperatorCallExpr *Call = dyn_cast<CXXOperatorCallExpr>(E)) {
5071 if (Call->getNumArgs() != 2)
5072 return false;
5073
5074 // Make sure this is really a binary operator that is safe to pass into
5075 // BinaryOperator::getOverloadedOpcode(), e.g. it's not a subscript op.
5076 OverloadedOperatorKind OO = Call->getOperator();
5077 if (OO < OO_Plus || OO > OO_Arrow)
5078 return false;
5079
5080 BinaryOperatorKind OpKind = BinaryOperator::getOverloadedOpcode(OO);
5081 if (IsArithmeticOp(OpKind)) {
5082 *Opcode = OpKind;
Richard Trieud33e46e2011-09-06 20:06:39 +00005083 *RHSExprs = Call->getArg(1);
Hans Wennborgde2e67e2011-06-09 17:06:51 +00005084 return true;
5085 }
5086 }
5087
5088 return false;
5089}
5090
Hans Wennborgcf9bac42011-06-03 18:00:36 +00005091static bool IsLogicOp(BinaryOperatorKind Opc) {
5092 return (Opc >= BO_LT && Opc <= BO_NE) || (Opc >= BO_LAnd && Opc <= BO_LOr);
5093}
5094
Hans Wennborgde2e67e2011-06-09 17:06:51 +00005095/// ExprLooksBoolean - Returns true if E looks boolean, i.e. it has boolean type
5096/// or is a logical expression such as (x==y) which has int type, but is
5097/// commonly interpreted as boolean.
5098static bool ExprLooksBoolean(Expr *E) {
5099 E = E->IgnoreParenImpCasts();
5100
5101 if (E->getType()->isBooleanType())
5102 return true;
5103 if (BinaryOperator *OP = dyn_cast<BinaryOperator>(E))
5104 return IsLogicOp(OP->getOpcode());
5105 if (UnaryOperator *OP = dyn_cast<UnaryOperator>(E))
5106 return OP->getOpcode() == UO_LNot;
5107
5108 return false;
5109}
5110
Hans Wennborgcf9bac42011-06-03 18:00:36 +00005111/// DiagnoseConditionalPrecedence - Emit a warning when a conditional operator
5112/// and binary operator are mixed in a way that suggests the programmer assumed
5113/// the conditional operator has higher precedence, for example:
5114/// "int x = a + someBinaryCondition ? 1 : 2".
5115static void DiagnoseConditionalPrecedence(Sema &Self,
5116 SourceLocation OpLoc,
Chandler Carruth08dc2ba2011-06-16 01:05:08 +00005117 Expr *Condition,
Richard Trieud33e46e2011-09-06 20:06:39 +00005118 Expr *LHSExpr,
5119 Expr *RHSExpr) {
Hans Wennborgde2e67e2011-06-09 17:06:51 +00005120 BinaryOperatorKind CondOpcode;
5121 Expr *CondRHS;
Hans Wennborgcf9bac42011-06-03 18:00:36 +00005122
Chandler Carruth08dc2ba2011-06-16 01:05:08 +00005123 if (!IsArithmeticBinaryExpr(Condition, &CondOpcode, &CondRHS))
Hans Wennborgde2e67e2011-06-09 17:06:51 +00005124 return;
5125 if (!ExprLooksBoolean(CondRHS))
5126 return;
Hans Wennborgcf9bac42011-06-03 18:00:36 +00005127
Hans Wennborgde2e67e2011-06-09 17:06:51 +00005128 // The condition is an arithmetic binary expression, with a right-
5129 // hand side that looks boolean, so warn.
Hans Wennborgcf9bac42011-06-03 18:00:36 +00005130
Chandler Carruthb00e8c02011-06-16 01:05:14 +00005131 Self.Diag(OpLoc, diag::warn_precedence_conditional)
Chandler Carruth08dc2ba2011-06-16 01:05:08 +00005132 << Condition->getSourceRange()
Hans Wennborgde2e67e2011-06-09 17:06:51 +00005133 << BinaryOperator::getOpcodeStr(CondOpcode);
Hans Wennborgcf9bac42011-06-03 18:00:36 +00005134
Chandler Carruthb00e8c02011-06-16 01:05:14 +00005135 SuggestParentheses(Self, OpLoc,
5136 Self.PDiag(diag::note_precedence_conditional_silence)
5137 << BinaryOperator::getOpcodeStr(CondOpcode),
5138 SourceRange(Condition->getLocStart(), Condition->getLocEnd()));
Chandler Carruthf51c5a52011-06-21 23:04:18 +00005139
5140 SuggestParentheses(Self, OpLoc,
5141 Self.PDiag(diag::note_precedence_conditional_first),
Richard Trieud33e46e2011-09-06 20:06:39 +00005142 SourceRange(CondRHS->getLocStart(), RHSExpr->getLocEnd()));
Hans Wennborgcf9bac42011-06-03 18:00:36 +00005143}
5144
Steve Naroff83895f72007-09-16 03:34:24 +00005145/// ActOnConditionalOp - Parse a ?: operation. Note that 'LHS' may be null
Chris Lattnere168f762006-11-10 05:29:30 +00005146/// in the case of a the GNU conditional expr extension.
John McCalldadc5752010-08-24 06:29:42 +00005147ExprResult Sema::ActOnConditionalOp(SourceLocation QuestionLoc,
John McCallc07a0c72011-02-17 10:25:35 +00005148 SourceLocation ColonLoc,
5149 Expr *CondExpr, Expr *LHSExpr,
5150 Expr *RHSExpr) {
Chris Lattner2ab40a62007-11-26 01:40:58 +00005151 // If this is the gnu "x ?: y" extension, analyze the types as though the LHS
5152 // was the condition.
John McCallc07a0c72011-02-17 10:25:35 +00005153 OpaqueValueExpr *opaqueValue = 0;
5154 Expr *commonExpr = 0;
5155 if (LHSExpr == 0) {
5156 commonExpr = CondExpr;
5157
5158 // We usually want to apply unary conversions *before* saving, except
5159 // in the special case of a C++ l-value conditional.
David Blaikiebbafb8a2012-03-11 07:00:24 +00005160 if (!(getLangOpts().CPlusPlus
John McCallc07a0c72011-02-17 10:25:35 +00005161 && !commonExpr->isTypeDependent()
5162 && commonExpr->getValueKind() == RHSExpr->getValueKind()
5163 && commonExpr->isGLValue()
5164 && commonExpr->isOrdinaryOrBitFieldObject()
5165 && RHSExpr->isOrdinaryOrBitFieldObject()
5166 && Context.hasSameType(commonExpr->getType(), RHSExpr->getType()))) {
John Wiegley01296292011-04-08 18:41:53 +00005167 ExprResult commonRes = UsualUnaryConversions(commonExpr);
5168 if (commonRes.isInvalid())
5169 return ExprError();
5170 commonExpr = commonRes.take();
John McCallc07a0c72011-02-17 10:25:35 +00005171 }
5172
5173 opaqueValue = new (Context) OpaqueValueExpr(commonExpr->getExprLoc(),
5174 commonExpr->getType(),
5175 commonExpr->getValueKind(),
Douglas Gregor2d5aea02012-02-23 22:17:26 +00005176 commonExpr->getObjectKind(),
5177 commonExpr);
John McCallc07a0c72011-02-17 10:25:35 +00005178 LHSExpr = CondExpr = opaqueValue;
Fariborz Jahanianc6bf0bd2010-08-31 18:02:20 +00005179 }
Sebastian Redlb5d49352009-01-19 22:31:54 +00005180
John McCall7decc9e2010-11-18 06:31:45 +00005181 ExprValueKind VK = VK_RValue;
John McCall4bc41ae2010-11-18 19:01:18 +00005182 ExprObjectKind OK = OK_Ordinary;
John Wiegley01296292011-04-08 18:41:53 +00005183 ExprResult Cond = Owned(CondExpr), LHS = Owned(LHSExpr), RHS = Owned(RHSExpr);
5184 QualType result = CheckConditionalOperands(Cond, LHS, RHS,
John McCallc07a0c72011-02-17 10:25:35 +00005185 VK, OK, QuestionLoc);
John Wiegley01296292011-04-08 18:41:53 +00005186 if (result.isNull() || Cond.isInvalid() || LHS.isInvalid() ||
5187 RHS.isInvalid())
Sebastian Redlb5d49352009-01-19 22:31:54 +00005188 return ExprError();
5189
Hans Wennborgcf9bac42011-06-03 18:00:36 +00005190 DiagnoseConditionalPrecedence(*this, QuestionLoc, Cond.get(), LHS.get(),
5191 RHS.get());
5192
John McCallc07a0c72011-02-17 10:25:35 +00005193 if (!commonExpr)
John Wiegley01296292011-04-08 18:41:53 +00005194 return Owned(new (Context) ConditionalOperator(Cond.take(), QuestionLoc,
5195 LHS.take(), ColonLoc,
5196 RHS.take(), result, VK, OK));
John McCallc07a0c72011-02-17 10:25:35 +00005197
5198 return Owned(new (Context)
John Wiegley01296292011-04-08 18:41:53 +00005199 BinaryConditionalOperator(commonExpr, opaqueValue, Cond.take(), LHS.take(),
Richard Trieucfc491d2011-08-02 04:35:43 +00005200 RHS.take(), QuestionLoc, ColonLoc, result, VK,
5201 OK));
Chris Lattnere168f762006-11-10 05:29:30 +00005202}
5203
John McCallaba90822011-01-31 23:13:11 +00005204// checkPointerTypesForAssignment - This is a very tricky routine (despite
Mike Stump4e1f26a2009-02-19 03:04:26 +00005205// being closely modeled after the C99 spec:-). The odd characteristic of this
Steve Naroff3f597292007-05-11 22:18:03 +00005206// routine is it effectively iqnores the qualifiers on the top level pointee.
5207// This circumvents the usual type rules specified in 6.2.7p1 & 6.7.5.[1-3].
5208// FIXME: add a couple examples in this comment.
John McCallaba90822011-01-31 23:13:11 +00005209static Sema::AssignConvertType
Richard Trieua871b972011-09-06 20:21:22 +00005210checkPointerTypesForAssignment(Sema &S, QualType LHSType, QualType RHSType) {
5211 assert(LHSType.isCanonical() && "LHS not canonicalized!");
5212 assert(RHSType.isCanonical() && "RHS not canonicalized!");
Mike Stump4e1f26a2009-02-19 03:04:26 +00005213
Steve Naroff1f4d7272007-05-11 04:00:31 +00005214 // get the "pointed to" type (ignoring qualifiers at the top level)
John McCall4fff8f62011-02-01 00:10:29 +00005215 const Type *lhptee, *rhptee;
5216 Qualifiers lhq, rhq;
Richard Trieua871b972011-09-06 20:21:22 +00005217 llvm::tie(lhptee, lhq) = cast<PointerType>(LHSType)->getPointeeType().split();
5218 llvm::tie(rhptee, rhq) = cast<PointerType>(RHSType)->getPointeeType().split();
Mike Stump4e1f26a2009-02-19 03:04:26 +00005219
John McCallaba90822011-01-31 23:13:11 +00005220 Sema::AssignConvertType ConvTy = Sema::Compatible;
Mike Stump4e1f26a2009-02-19 03:04:26 +00005221
5222 // C99 6.5.16.1p1: This following citation is common to constraints
5223 // 3 & 4 (below). ...and the type *pointed to* by the left has all the
5224 // qualifiers of the type *pointed to* by the right;
John McCall4fff8f62011-02-01 00:10:29 +00005225 Qualifiers lq;
5226
John McCall31168b02011-06-15 23:02:42 +00005227 // As a special case, 'non-__weak A *' -> 'non-__weak const *' is okay.
5228 if (lhq.getObjCLifetime() != rhq.getObjCLifetime() &&
5229 lhq.compatiblyIncludesObjCLifetime(rhq)) {
5230 // Ignore lifetime for further calculation.
5231 lhq.removeObjCLifetime();
5232 rhq.removeObjCLifetime();
5233 }
5234
John McCall4fff8f62011-02-01 00:10:29 +00005235 if (!lhq.compatiblyIncludes(rhq)) {
5236 // Treat address-space mismatches as fatal. TODO: address subspaces
5237 if (lhq.getAddressSpace() != rhq.getAddressSpace())
5238 ConvTy = Sema::IncompatiblePointerDiscardsQualifiers;
5239
John McCall31168b02011-06-15 23:02:42 +00005240 // It's okay to add or remove GC or lifetime qualifiers when converting to
John McCall78535952011-03-26 02:56:45 +00005241 // and from void*.
John McCall18ce25e2012-02-08 00:46:36 +00005242 else if (lhq.withoutObjCGCAttr().withoutObjCLifetime()
John McCall31168b02011-06-15 23:02:42 +00005243 .compatiblyIncludes(
John McCall18ce25e2012-02-08 00:46:36 +00005244 rhq.withoutObjCGCAttr().withoutObjCLifetime())
John McCall78535952011-03-26 02:56:45 +00005245 && (lhptee->isVoidType() || rhptee->isVoidType()))
5246 ; // keep old
5247
John McCall31168b02011-06-15 23:02:42 +00005248 // Treat lifetime mismatches as fatal.
5249 else if (lhq.getObjCLifetime() != rhq.getObjCLifetime())
5250 ConvTy = Sema::IncompatiblePointerDiscardsQualifiers;
5251
John McCall4fff8f62011-02-01 00:10:29 +00005252 // For GCC compatibility, other qualifier mismatches are treated
5253 // as still compatible in C.
5254 else ConvTy = Sema::CompatiblePointerDiscardsQualifiers;
5255 }
Steve Naroff3f597292007-05-11 22:18:03 +00005256
Mike Stump4e1f26a2009-02-19 03:04:26 +00005257 // C99 6.5.16.1p1 (constraint 4): If one operand is a pointer to an object or
5258 // incomplete type and the other is a pointer to a qualified or unqualified
Steve Naroff3f597292007-05-11 22:18:03 +00005259 // version of void...
Chris Lattner0a788432008-01-03 22:56:36 +00005260 if (lhptee->isVoidType()) {
Chris Lattnerb3a176d2008-04-02 06:59:01 +00005261 if (rhptee->isIncompleteOrObjectType())
Chris Lattner9bad62c2008-01-04 18:04:52 +00005262 return ConvTy;
Mike Stump4e1f26a2009-02-19 03:04:26 +00005263
Chris Lattner0a788432008-01-03 22:56:36 +00005264 // As an extension, we allow cast to/from void* to function pointer.
Chris Lattnerb3a176d2008-04-02 06:59:01 +00005265 assert(rhptee->isFunctionType());
John McCallaba90822011-01-31 23:13:11 +00005266 return Sema::FunctionVoidPointer;
Chris Lattner0a788432008-01-03 22:56:36 +00005267 }
Mike Stump4e1f26a2009-02-19 03:04:26 +00005268
Chris Lattner0a788432008-01-03 22:56:36 +00005269 if (rhptee->isVoidType()) {
Chris Lattnerb3a176d2008-04-02 06:59:01 +00005270 if (lhptee->isIncompleteOrObjectType())
Chris Lattner9bad62c2008-01-04 18:04:52 +00005271 return ConvTy;
Chris Lattner0a788432008-01-03 22:56:36 +00005272
5273 // As an extension, we allow cast to/from void* to function pointer.
Chris Lattnerb3a176d2008-04-02 06:59:01 +00005274 assert(lhptee->isFunctionType());
John McCallaba90822011-01-31 23:13:11 +00005275 return Sema::FunctionVoidPointer;
Chris Lattner0a788432008-01-03 22:56:36 +00005276 }
John McCall4fff8f62011-02-01 00:10:29 +00005277
Mike Stump4e1f26a2009-02-19 03:04:26 +00005278 // C99 6.5.16.1p1 (constraint 3): both operands are pointers to qualified or
Steve Naroff3f597292007-05-11 22:18:03 +00005279 // unqualified versions of compatible types, ...
John McCall4fff8f62011-02-01 00:10:29 +00005280 QualType ltrans = QualType(lhptee, 0), rtrans = QualType(rhptee, 0);
5281 if (!S.Context.typesAreCompatible(ltrans, rtrans)) {
Eli Friedman80160bd2009-03-22 23:59:44 +00005282 // Check if the pointee types are compatible ignoring the sign.
5283 // We explicitly check for char so that we catch "char" vs
5284 // "unsigned char" on systems where "char" is unsigned.
Chris Lattnerec3a1562009-10-17 20:33:28 +00005285 if (lhptee->isCharType())
John McCall4fff8f62011-02-01 00:10:29 +00005286 ltrans = S.Context.UnsignedCharTy;
Douglas Gregor5cc2c8b2010-07-23 15:58:24 +00005287 else if (lhptee->hasSignedIntegerRepresentation())
John McCall4fff8f62011-02-01 00:10:29 +00005288 ltrans = S.Context.getCorrespondingUnsignedType(ltrans);
Kovarththanan Rajaratnamba2c6522010-03-13 10:17:05 +00005289
Chris Lattnerec3a1562009-10-17 20:33:28 +00005290 if (rhptee->isCharType())
John McCall4fff8f62011-02-01 00:10:29 +00005291 rtrans = S.Context.UnsignedCharTy;
Douglas Gregor5cc2c8b2010-07-23 15:58:24 +00005292 else if (rhptee->hasSignedIntegerRepresentation())
John McCall4fff8f62011-02-01 00:10:29 +00005293 rtrans = S.Context.getCorrespondingUnsignedType(rtrans);
Chris Lattnerec3a1562009-10-17 20:33:28 +00005294
John McCall4fff8f62011-02-01 00:10:29 +00005295 if (ltrans == rtrans) {
Eli Friedman80160bd2009-03-22 23:59:44 +00005296 // Types are compatible ignoring the sign. Qualifier incompatibility
5297 // takes priority over sign incompatibility because the sign
5298 // warning can be disabled.
John McCallaba90822011-01-31 23:13:11 +00005299 if (ConvTy != Sema::Compatible)
Eli Friedman80160bd2009-03-22 23:59:44 +00005300 return ConvTy;
John McCall4fff8f62011-02-01 00:10:29 +00005301
John McCallaba90822011-01-31 23:13:11 +00005302 return Sema::IncompatiblePointerSign;
Eli Friedman80160bd2009-03-22 23:59:44 +00005303 }
Kovarththanan Rajaratnamba2c6522010-03-13 10:17:05 +00005304
Fariborz Jahaniand7aa9d82009-11-07 20:20:40 +00005305 // If we are a multi-level pointer, it's possible that our issue is simply
5306 // one of qualification - e.g. char ** -> const char ** is not allowed. If
5307 // the eventual target type is the same and the pointers have the same
5308 // level of indirection, this must be the issue.
John McCallaba90822011-01-31 23:13:11 +00005309 if (isa<PointerType>(lhptee) && isa<PointerType>(rhptee)) {
Fariborz Jahaniand7aa9d82009-11-07 20:20:40 +00005310 do {
John McCall4fff8f62011-02-01 00:10:29 +00005311 lhptee = cast<PointerType>(lhptee)->getPointeeType().getTypePtr();
5312 rhptee = cast<PointerType>(rhptee)->getPointeeType().getTypePtr();
John McCallaba90822011-01-31 23:13:11 +00005313 } while (isa<PointerType>(lhptee) && isa<PointerType>(rhptee));
Kovarththanan Rajaratnamba2c6522010-03-13 10:17:05 +00005314
John McCall4fff8f62011-02-01 00:10:29 +00005315 if (lhptee == rhptee)
John McCallaba90822011-01-31 23:13:11 +00005316 return Sema::IncompatibleNestedPointerQualifiers;
Fariborz Jahaniand7aa9d82009-11-07 20:20:40 +00005317 }
Kovarththanan Rajaratnamba2c6522010-03-13 10:17:05 +00005318
Eli Friedman80160bd2009-03-22 23:59:44 +00005319 // General pointer incompatibility takes priority over qualifiers.
John McCallaba90822011-01-31 23:13:11 +00005320 return Sema::IncompatiblePointer;
Eli Friedman80160bd2009-03-22 23:59:44 +00005321 }
David Blaikiebbafb8a2012-03-11 07:00:24 +00005322 if (!S.getLangOpts().CPlusPlus &&
Fariborz Jahanian48c69102011-10-05 00:05:34 +00005323 S.IsNoReturnConversion(ltrans, rtrans, ltrans))
5324 return Sema::IncompatiblePointer;
Chris Lattner9bad62c2008-01-04 18:04:52 +00005325 return ConvTy;
Steve Naroff1f4d7272007-05-11 04:00:31 +00005326}
5327
John McCallaba90822011-01-31 23:13:11 +00005328/// checkBlockPointerTypesForAssignment - This routine determines whether two
Steve Naroff081c7422008-09-04 15:10:53 +00005329/// block pointer types are compatible or whether a block and normal pointer
5330/// are compatible. It is more restrict than comparing two function pointer
5331// types.
John McCallaba90822011-01-31 23:13:11 +00005332static Sema::AssignConvertType
Richard Trieua871b972011-09-06 20:21:22 +00005333checkBlockPointerTypesForAssignment(Sema &S, QualType LHSType,
5334 QualType RHSType) {
5335 assert(LHSType.isCanonical() && "LHS not canonicalized!");
5336 assert(RHSType.isCanonical() && "RHS not canonicalized!");
John McCallaba90822011-01-31 23:13:11 +00005337
Steve Naroff081c7422008-09-04 15:10:53 +00005338 QualType lhptee, rhptee;
Mike Stump4e1f26a2009-02-19 03:04:26 +00005339
Steve Naroff081c7422008-09-04 15:10:53 +00005340 // get the "pointed to" type (ignoring qualifiers at the top level)
Richard Trieua871b972011-09-06 20:21:22 +00005341 lhptee = cast<BlockPointerType>(LHSType)->getPointeeType();
5342 rhptee = cast<BlockPointerType>(RHSType)->getPointeeType();
Mike Stump4e1f26a2009-02-19 03:04:26 +00005343
John McCallaba90822011-01-31 23:13:11 +00005344 // In C++, the types have to match exactly.
David Blaikiebbafb8a2012-03-11 07:00:24 +00005345 if (S.getLangOpts().CPlusPlus)
John McCallaba90822011-01-31 23:13:11 +00005346 return Sema::IncompatibleBlockPointer;
Mike Stump4e1f26a2009-02-19 03:04:26 +00005347
John McCallaba90822011-01-31 23:13:11 +00005348 Sema::AssignConvertType ConvTy = Sema::Compatible;
Mike Stump4e1f26a2009-02-19 03:04:26 +00005349
Steve Naroff081c7422008-09-04 15:10:53 +00005350 // For blocks we enforce that qualifiers are identical.
John McCallaba90822011-01-31 23:13:11 +00005351 if (lhptee.getLocalQualifiers() != rhptee.getLocalQualifiers())
5352 ConvTy = Sema::CompatiblePointerDiscardsQualifiers;
Mike Stump4e1f26a2009-02-19 03:04:26 +00005353
Richard Trieua871b972011-09-06 20:21:22 +00005354 if (!S.Context.typesAreBlockPointerCompatible(LHSType, RHSType))
John McCallaba90822011-01-31 23:13:11 +00005355 return Sema::IncompatibleBlockPointer;
5356
Steve Naroff081c7422008-09-04 15:10:53 +00005357 return ConvTy;
5358}
5359
John McCallaba90822011-01-31 23:13:11 +00005360/// checkObjCPointerTypesForAssignment - Compares two objective-c pointer types
Fariborz Jahanian410f2eb2009-12-08 18:24:49 +00005361/// for assignment compatibility.
John McCallaba90822011-01-31 23:13:11 +00005362static Sema::AssignConvertType
Richard Trieua871b972011-09-06 20:21:22 +00005363checkObjCPointerTypesForAssignment(Sema &S, QualType LHSType,
5364 QualType RHSType) {
5365 assert(LHSType.isCanonical() && "LHS was not canonicalized!");
5366 assert(RHSType.isCanonical() && "RHS was not canonicalized!");
John McCallaba90822011-01-31 23:13:11 +00005367
Richard Trieua871b972011-09-06 20:21:22 +00005368 if (LHSType->isObjCBuiltinType()) {
Fariborz Jahaniand5bb8cb2010-03-19 18:06:10 +00005369 // Class is not compatible with ObjC object pointers.
Richard Trieua871b972011-09-06 20:21:22 +00005370 if (LHSType->isObjCClassType() && !RHSType->isObjCBuiltinType() &&
5371 !RHSType->isObjCQualifiedClassType())
John McCallaba90822011-01-31 23:13:11 +00005372 return Sema::IncompatiblePointer;
5373 return Sema::Compatible;
Fariborz Jahaniand5bb8cb2010-03-19 18:06:10 +00005374 }
Richard Trieua871b972011-09-06 20:21:22 +00005375 if (RHSType->isObjCBuiltinType()) {
Richard Trieua871b972011-09-06 20:21:22 +00005376 if (RHSType->isObjCClassType() && !LHSType->isObjCBuiltinType() &&
5377 !LHSType->isObjCQualifiedClassType())
Fariborz Jahaniand923eb02011-09-15 20:40:18 +00005378 return Sema::IncompatiblePointer;
John McCallaba90822011-01-31 23:13:11 +00005379 return Sema::Compatible;
Fariborz Jahaniand5bb8cb2010-03-19 18:06:10 +00005380 }
Richard Trieua871b972011-09-06 20:21:22 +00005381 QualType lhptee = LHSType->getAs<ObjCObjectPointerType>()->getPointeeType();
5382 QualType rhptee = RHSType->getAs<ObjCObjectPointerType>()->getPointeeType();
Kovarththanan Rajaratnamba2c6522010-03-13 10:17:05 +00005383
Fariborz Jahaniane74d47e2012-01-12 22:12:08 +00005384 if (!lhptee.isAtLeastAsQualifiedAs(rhptee) &&
5385 // make an exception for id<P>
5386 !LHSType->isObjCQualifiedIdType())
John McCallaba90822011-01-31 23:13:11 +00005387 return Sema::CompatiblePointerDiscardsQualifiers;
5388
Richard Trieua871b972011-09-06 20:21:22 +00005389 if (S.Context.typesAreCompatible(LHSType, RHSType))
John McCallaba90822011-01-31 23:13:11 +00005390 return Sema::Compatible;
Richard Trieua871b972011-09-06 20:21:22 +00005391 if (LHSType->isObjCQualifiedIdType() || RHSType->isObjCQualifiedIdType())
John McCallaba90822011-01-31 23:13:11 +00005392 return Sema::IncompatibleObjCQualifiedId;
5393 return Sema::IncompatiblePointer;
Fariborz Jahanian410f2eb2009-12-08 18:24:49 +00005394}
5395
John McCall29600e12010-11-16 02:32:08 +00005396Sema::AssignConvertType
Douglas Gregorc03a1082011-01-28 02:26:04 +00005397Sema::CheckAssignmentConstraints(SourceLocation Loc,
Richard Trieua871b972011-09-06 20:21:22 +00005398 QualType LHSType, QualType RHSType) {
John McCall29600e12010-11-16 02:32:08 +00005399 // Fake up an opaque expression. We don't actually care about what
5400 // cast operations are required, so if CheckAssignmentConstraints
5401 // adds casts to this they'll be wasted, but fortunately that doesn't
5402 // usually happen on valid code.
Richard Trieua871b972011-09-06 20:21:22 +00005403 OpaqueValueExpr RHSExpr(Loc, RHSType, VK_RValue);
5404 ExprResult RHSPtr = &RHSExpr;
John McCall29600e12010-11-16 02:32:08 +00005405 CastKind K = CK_Invalid;
5406
Richard Trieua871b972011-09-06 20:21:22 +00005407 return CheckAssignmentConstraints(LHSType, RHSPtr, K);
John McCall29600e12010-11-16 02:32:08 +00005408}
5409
Mike Stump4e1f26a2009-02-19 03:04:26 +00005410/// CheckAssignmentConstraints (C99 6.5.16) - This routine currently
5411/// has code to accommodate several GCC extensions when type checking
Steve Naroff17f76e02007-05-03 21:03:48 +00005412/// pointers. Here are some objectionable examples that GCC considers warnings:
5413///
5414/// int a, *pint;
5415/// short *pshort;
5416/// struct foo *pfoo;
5417///
5418/// pint = pshort; // warning: assignment from incompatible pointer type
5419/// a = pint; // warning: assignment makes integer from pointer without a cast
5420/// pint = a; // warning: assignment makes pointer from integer without a cast
5421/// pint = pfoo; // warning: assignment from incompatible pointer type
5422///
5423/// As a result, the code for dealing with pointers is more complex than the
Mike Stump4e1f26a2009-02-19 03:04:26 +00005424/// C99 spec dictates.
Steve Naroff17f76e02007-05-03 21:03:48 +00005425///
John McCall8cb679e2010-11-15 09:13:47 +00005426/// Sets 'Kind' for any result kind except Incompatible.
Chris Lattner9bad62c2008-01-04 18:04:52 +00005427Sema::AssignConvertType
Richard Trieude4958f2011-09-06 20:30:53 +00005428Sema::CheckAssignmentConstraints(QualType LHSType, ExprResult &RHS,
John McCall8cb679e2010-11-15 09:13:47 +00005429 CastKind &Kind) {
Richard Trieude4958f2011-09-06 20:30:53 +00005430 QualType RHSType = RHS.get()->getType();
5431 QualType OrigLHSType = LHSType;
John McCall29600e12010-11-16 02:32:08 +00005432
Chris Lattnera52c2f22008-01-04 23:18:45 +00005433 // Get canonical types. We're not formatting these types, just comparing
5434 // them.
Richard Trieude4958f2011-09-06 20:30:53 +00005435 LHSType = Context.getCanonicalType(LHSType).getUnqualifiedType();
5436 RHSType = Context.getCanonicalType(RHSType).getUnqualifiedType();
Eli Friedman3360d892008-05-30 18:07:22 +00005437
Eli Friedman0dfb8892011-10-06 23:00:33 +00005438
John McCalle5255932011-01-31 22:28:28 +00005439 // Common case: no conversion required.
Richard Trieude4958f2011-09-06 20:30:53 +00005440 if (LHSType == RHSType) {
John McCall8cb679e2010-11-15 09:13:47 +00005441 Kind = CK_NoOp;
John McCall8cb679e2010-11-15 09:13:47 +00005442 return Compatible;
David Chisnall9f57c292009-08-17 16:35:33 +00005443 }
5444
Eli Friedman93ee5ca2012-06-16 02:19:17 +00005445 // If we have an atomic type, try a non-atomic assignment, then just add an
5446 // atomic qualification step.
David Chisnallfa35df62012-01-16 17:27:18 +00005447 if (const AtomicType *AtomicTy = dyn_cast<AtomicType>(LHSType)) {
Eli Friedman93ee5ca2012-06-16 02:19:17 +00005448 Sema::AssignConvertType result =
5449 CheckAssignmentConstraints(AtomicTy->getValueType(), RHS, Kind);
5450 if (result != Compatible)
5451 return result;
5452 if (Kind != CK_NoOp)
5453 RHS = ImpCastExprToType(RHS.take(), AtomicTy->getValueType(), Kind);
5454 Kind = CK_NonAtomicToAtomic;
5455 return Compatible;
David Chisnallfa35df62012-01-16 17:27:18 +00005456 }
5457
Douglas Gregor6b754842008-10-28 00:22:11 +00005458 // If the left-hand side is a reference type, then we are in a
5459 // (rare!) case where we've allowed the use of references in C,
5460 // e.g., as a parameter type in a built-in function. In this case,
5461 // just make sure that the type referenced is compatible with the
5462 // right-hand side type. The caller is responsible for adjusting
Richard Trieude4958f2011-09-06 20:30:53 +00005463 // LHSType so that the resulting expression does not have reference
Douglas Gregor6b754842008-10-28 00:22:11 +00005464 // type.
Richard Trieude4958f2011-09-06 20:30:53 +00005465 if (const ReferenceType *LHSTypeRef = LHSType->getAs<ReferenceType>()) {
5466 if (Context.typesAreCompatible(LHSTypeRef->getPointeeType(), RHSType)) {
John McCall8cb679e2010-11-15 09:13:47 +00005467 Kind = CK_LValueBitCast;
Anders Carlsson24ebce62007-10-12 23:56:29 +00005468 return Compatible;
John McCall8cb679e2010-11-15 09:13:47 +00005469 }
Chris Lattnera52c2f22008-01-04 23:18:45 +00005470 return Incompatible;
Fariborz Jahaniana1e34202007-12-19 17:45:58 +00005471 }
John McCalle5255932011-01-31 22:28:28 +00005472
Nate Begemanbd956c42009-06-28 02:36:38 +00005473 // Allow scalar to ExtVector assignments, and assignments of an ExtVector type
5474 // to the same ExtVector type.
Richard Trieude4958f2011-09-06 20:30:53 +00005475 if (LHSType->isExtVectorType()) {
5476 if (RHSType->isExtVectorType())
John McCall8cb679e2010-11-15 09:13:47 +00005477 return Incompatible;
Richard Trieude4958f2011-09-06 20:30:53 +00005478 if (RHSType->isArithmeticType()) {
John McCall29600e12010-11-16 02:32:08 +00005479 // CK_VectorSplat does T -> vector T, so first cast to the
5480 // element type.
Richard Trieude4958f2011-09-06 20:30:53 +00005481 QualType elType = cast<ExtVectorType>(LHSType)->getElementType();
5482 if (elType != RHSType) {
John McCall9776e432011-10-06 23:25:11 +00005483 Kind = PrepareScalarCast(RHS, elType);
Richard Trieude4958f2011-09-06 20:30:53 +00005484 RHS = ImpCastExprToType(RHS.take(), elType, Kind);
John McCall29600e12010-11-16 02:32:08 +00005485 }
5486 Kind = CK_VectorSplat;
Nate Begemanbd956c42009-06-28 02:36:38 +00005487 return Compatible;
John McCall8cb679e2010-11-15 09:13:47 +00005488 }
Nate Begemanbd956c42009-06-28 02:36:38 +00005489 }
Mike Stump11289f42009-09-09 15:08:12 +00005490
John McCalle5255932011-01-31 22:28:28 +00005491 // Conversions to or from vector type.
Richard Trieude4958f2011-09-06 20:30:53 +00005492 if (LHSType->isVectorType() || RHSType->isVectorType()) {
5493 if (LHSType->isVectorType() && RHSType->isVectorType()) {
Bob Wilson01856f32010-12-02 00:25:15 +00005494 // Allow assignments of an AltiVec vector type to an equivalent GCC
5495 // vector type and vice versa
Richard Trieude4958f2011-09-06 20:30:53 +00005496 if (Context.areCompatibleVectorTypes(LHSType, RHSType)) {
Bob Wilson01856f32010-12-02 00:25:15 +00005497 Kind = CK_BitCast;
5498 return Compatible;
5499 }
5500
Douglas Gregor59e8b3b2010-08-06 10:14:59 +00005501 // If we are allowing lax vector conversions, and LHS and RHS are both
5502 // vectors, the total size only needs to be the same. This is a bitcast;
5503 // no bits are changed but the result type is different.
David Blaikiebbafb8a2012-03-11 07:00:24 +00005504 if (getLangOpts().LaxVectorConversions &&
Richard Trieude4958f2011-09-06 20:30:53 +00005505 (Context.getTypeSize(LHSType) == Context.getTypeSize(RHSType))) {
John McCall3065d042010-11-15 10:08:00 +00005506 Kind = CK_BitCast;
Anders Carlssondb5a9b62009-01-30 23:17:46 +00005507 return IncompatibleVectors;
John McCall8cb679e2010-11-15 09:13:47 +00005508 }
Chris Lattner881a2122008-01-04 23:32:24 +00005509 }
5510 return Incompatible;
Mike Stump4e1f26a2009-02-19 03:04:26 +00005511 }
Eli Friedman3360d892008-05-30 18:07:22 +00005512
John McCalle5255932011-01-31 22:28:28 +00005513 // Arithmetic conversions.
Richard Trieude4958f2011-09-06 20:30:53 +00005514 if (LHSType->isArithmeticType() && RHSType->isArithmeticType() &&
David Blaikiebbafb8a2012-03-11 07:00:24 +00005515 !(getLangOpts().CPlusPlus && LHSType->isEnumeralType())) {
John McCall9776e432011-10-06 23:25:11 +00005516 Kind = PrepareScalarCast(RHS, LHSType);
Steve Naroff98cf3e92007-06-06 18:38:38 +00005517 return Compatible;
John McCall8cb679e2010-11-15 09:13:47 +00005518 }
Eli Friedman3360d892008-05-30 18:07:22 +00005519
John McCalle5255932011-01-31 22:28:28 +00005520 // Conversions to normal pointers.
Richard Trieude4958f2011-09-06 20:30:53 +00005521 if (const PointerType *LHSPointer = dyn_cast<PointerType>(LHSType)) {
John McCalle5255932011-01-31 22:28:28 +00005522 // U* -> T*
Richard Trieude4958f2011-09-06 20:30:53 +00005523 if (isa<PointerType>(RHSType)) {
John McCall8cb679e2010-11-15 09:13:47 +00005524 Kind = CK_BitCast;
Richard Trieude4958f2011-09-06 20:30:53 +00005525 return checkPointerTypesForAssignment(*this, LHSType, RHSType);
John McCall8cb679e2010-11-15 09:13:47 +00005526 }
Mike Stump4e1f26a2009-02-19 03:04:26 +00005527
John McCalle5255932011-01-31 22:28:28 +00005528 // int -> T*
Richard Trieude4958f2011-09-06 20:30:53 +00005529 if (RHSType->isIntegerType()) {
John McCalle5255932011-01-31 22:28:28 +00005530 Kind = CK_IntegralToPointer; // FIXME: null?
5531 return IntToPointer;
Steve Naroff7cae42b2009-07-10 23:34:53 +00005532 }
John McCalle5255932011-01-31 22:28:28 +00005533
5534 // C pointers are not compatible with ObjC object pointers,
5535 // with two exceptions:
Richard Trieude4958f2011-09-06 20:30:53 +00005536 if (isa<ObjCObjectPointerType>(RHSType)) {
John McCalle5255932011-01-31 22:28:28 +00005537 // - conversions to void*
Richard Trieude4958f2011-09-06 20:30:53 +00005538 if (LHSPointer->getPointeeType()->isVoidType()) {
John McCall9320b872011-09-09 05:25:32 +00005539 Kind = CK_BitCast;
John McCalle5255932011-01-31 22:28:28 +00005540 return Compatible;
5541 }
5542
5543 // - conversions from 'Class' to the redefinition type
Richard Trieude4958f2011-09-06 20:30:53 +00005544 if (RHSType->isObjCClassType() &&
5545 Context.hasSameType(LHSType,
Douglas Gregor97673472011-08-11 20:58:55 +00005546 Context.getObjCClassRedefinitionType())) {
John McCall8cb679e2010-11-15 09:13:47 +00005547 Kind = CK_BitCast;
Douglas Gregore7dd1452008-11-27 00:44:28 +00005548 return Compatible;
John McCall8cb679e2010-11-15 09:13:47 +00005549 }
Douglas Gregor486b74e2011-09-27 16:10:05 +00005550
John McCalle5255932011-01-31 22:28:28 +00005551 Kind = CK_BitCast;
5552 return IncompatiblePointer;
5553 }
5554
5555 // U^ -> void*
Richard Trieude4958f2011-09-06 20:30:53 +00005556 if (RHSType->getAs<BlockPointerType>()) {
5557 if (LHSPointer->getPointeeType()->isVoidType()) {
John McCalle5255932011-01-31 22:28:28 +00005558 Kind = CK_BitCast;
Steve Naroff32d072c2008-09-29 18:10:17 +00005559 return Compatible;
John McCall8cb679e2010-11-15 09:13:47 +00005560 }
Steve Naroff32d072c2008-09-29 18:10:17 +00005561 }
John McCalle5255932011-01-31 22:28:28 +00005562
Steve Naroff081c7422008-09-04 15:10:53 +00005563 return Incompatible;
5564 }
5565
John McCalle5255932011-01-31 22:28:28 +00005566 // Conversions to block pointers.
Richard Trieude4958f2011-09-06 20:30:53 +00005567 if (isa<BlockPointerType>(LHSType)) {
John McCalle5255932011-01-31 22:28:28 +00005568 // U^ -> T^
Richard Trieude4958f2011-09-06 20:30:53 +00005569 if (RHSType->isBlockPointerType()) {
John McCall9320b872011-09-09 05:25:32 +00005570 Kind = CK_BitCast;
Richard Trieude4958f2011-09-06 20:30:53 +00005571 return checkBlockPointerTypesForAssignment(*this, LHSType, RHSType);
John McCalle5255932011-01-31 22:28:28 +00005572 }
5573
5574 // int or null -> T^
Richard Trieude4958f2011-09-06 20:30:53 +00005575 if (RHSType->isIntegerType()) {
John McCall8cb679e2010-11-15 09:13:47 +00005576 Kind = CK_IntegralToPointer; // FIXME: null
Eli Friedman8163b7a2009-02-25 04:20:42 +00005577 return IntToBlockPointer;
John McCall8cb679e2010-11-15 09:13:47 +00005578 }
5579
John McCalle5255932011-01-31 22:28:28 +00005580 // id -> T^
David Blaikiebbafb8a2012-03-11 07:00:24 +00005581 if (getLangOpts().ObjC1 && RHSType->isObjCIdType()) {
John McCalle5255932011-01-31 22:28:28 +00005582 Kind = CK_AnyPointerToBlockPointerCast;
Steve Naroff32d072c2008-09-29 18:10:17 +00005583 return Compatible;
John McCalle5255932011-01-31 22:28:28 +00005584 }
Steve Naroff32d072c2008-09-29 18:10:17 +00005585
John McCalle5255932011-01-31 22:28:28 +00005586 // void* -> T^
Richard Trieude4958f2011-09-06 20:30:53 +00005587 if (const PointerType *RHSPT = RHSType->getAs<PointerType>())
John McCalle5255932011-01-31 22:28:28 +00005588 if (RHSPT->getPointeeType()->isVoidType()) {
5589 Kind = CK_AnyPointerToBlockPointerCast;
Douglas Gregore7dd1452008-11-27 00:44:28 +00005590 return Compatible;
John McCalle5255932011-01-31 22:28:28 +00005591 }
John McCall8cb679e2010-11-15 09:13:47 +00005592
Chris Lattnera52c2f22008-01-04 23:18:45 +00005593 return Incompatible;
5594 }
5595
John McCalle5255932011-01-31 22:28:28 +00005596 // Conversions to Objective-C pointers.
Richard Trieude4958f2011-09-06 20:30:53 +00005597 if (isa<ObjCObjectPointerType>(LHSType)) {
John McCalle5255932011-01-31 22:28:28 +00005598 // A* -> B*
Richard Trieude4958f2011-09-06 20:30:53 +00005599 if (RHSType->isObjCObjectPointerType()) {
John McCalle5255932011-01-31 22:28:28 +00005600 Kind = CK_BitCast;
Fariborz Jahanian6f472e82011-07-07 18:55:47 +00005601 Sema::AssignConvertType result =
Richard Trieude4958f2011-09-06 20:30:53 +00005602 checkObjCPointerTypesForAssignment(*this, LHSType, RHSType);
David Blaikiebbafb8a2012-03-11 07:00:24 +00005603 if (getLangOpts().ObjCAutoRefCount &&
Fariborz Jahanian6f472e82011-07-07 18:55:47 +00005604 result == Compatible &&
Richard Trieude4958f2011-09-06 20:30:53 +00005605 !CheckObjCARCUnavailableWeakConversion(OrigLHSType, RHSType))
Fariborz Jahanian7fcce682011-07-07 23:04:17 +00005606 result = IncompatibleObjCWeakRef;
Fariborz Jahanian6f472e82011-07-07 18:55:47 +00005607 return result;
John McCalle5255932011-01-31 22:28:28 +00005608 }
5609
5610 // int or null -> A*
Richard Trieude4958f2011-09-06 20:30:53 +00005611 if (RHSType->isIntegerType()) {
John McCall8cb679e2010-11-15 09:13:47 +00005612 Kind = CK_IntegralToPointer; // FIXME: null
Steve Naroff7cae42b2009-07-10 23:34:53 +00005613 return IntToPointer;
John McCall8cb679e2010-11-15 09:13:47 +00005614 }
5615
John McCalle5255932011-01-31 22:28:28 +00005616 // In general, C pointers are not compatible with ObjC object pointers,
5617 // with two exceptions:
Richard Trieude4958f2011-09-06 20:30:53 +00005618 if (isa<PointerType>(RHSType)) {
John McCall9320b872011-09-09 05:25:32 +00005619 Kind = CK_CPointerToObjCPointerCast;
5620
John McCalle5255932011-01-31 22:28:28 +00005621 // - conversions from 'void*'
Richard Trieude4958f2011-09-06 20:30:53 +00005622 if (RHSType->isVoidPointerType()) {
Steve Naroffaccc4882009-07-20 17:56:53 +00005623 return Compatible;
John McCalle5255932011-01-31 22:28:28 +00005624 }
5625
5626 // - conversions to 'Class' from its redefinition type
Richard Trieude4958f2011-09-06 20:30:53 +00005627 if (LHSType->isObjCClassType() &&
5628 Context.hasSameType(RHSType,
Douglas Gregor97673472011-08-11 20:58:55 +00005629 Context.getObjCClassRedefinitionType())) {
John McCalle5255932011-01-31 22:28:28 +00005630 return Compatible;
5631 }
5632
Steve Naroffaccc4882009-07-20 17:56:53 +00005633 return IncompatiblePointer;
Steve Naroff7cae42b2009-07-10 23:34:53 +00005634 }
John McCalle5255932011-01-31 22:28:28 +00005635
5636 // T^ -> A*
Richard Trieude4958f2011-09-06 20:30:53 +00005637 if (RHSType->isBlockPointerType()) {
John McCallcd78e802011-09-10 01:16:55 +00005638 maybeExtendBlockObject(*this, RHS);
John McCall9320b872011-09-09 05:25:32 +00005639 Kind = CK_BlockPointerToObjCPointerCast;
Steve Naroff7cae42b2009-07-10 23:34:53 +00005640 return Compatible;
John McCalle5255932011-01-31 22:28:28 +00005641 }
5642
Steve Naroff7cae42b2009-07-10 23:34:53 +00005643 return Incompatible;
5644 }
John McCalle5255932011-01-31 22:28:28 +00005645
5646 // Conversions from pointers that are not covered by the above.
Richard Trieude4958f2011-09-06 20:30:53 +00005647 if (isa<PointerType>(RHSType)) {
John McCalle5255932011-01-31 22:28:28 +00005648 // T* -> _Bool
Richard Trieude4958f2011-09-06 20:30:53 +00005649 if (LHSType == Context.BoolTy) {
John McCall8cb679e2010-11-15 09:13:47 +00005650 Kind = CK_PointerToBoolean;
Eli Friedman3360d892008-05-30 18:07:22 +00005651 return Compatible;
John McCall8cb679e2010-11-15 09:13:47 +00005652 }
Eli Friedman3360d892008-05-30 18:07:22 +00005653
John McCalle5255932011-01-31 22:28:28 +00005654 // T* -> int
Richard Trieude4958f2011-09-06 20:30:53 +00005655 if (LHSType->isIntegerType()) {
John McCall8cb679e2010-11-15 09:13:47 +00005656 Kind = CK_PointerToIntegral;
Chris Lattner940cfeb2008-01-04 18:22:42 +00005657 return PointerToInt;
John McCall8cb679e2010-11-15 09:13:47 +00005658 }
Mike Stump4e1f26a2009-02-19 03:04:26 +00005659
Chris Lattnera52c2f22008-01-04 23:18:45 +00005660 return Incompatible;
Chris Lattnera52c2f22008-01-04 23:18:45 +00005661 }
John McCalle5255932011-01-31 22:28:28 +00005662
5663 // Conversions from Objective-C pointers that are not covered by the above.
Richard Trieude4958f2011-09-06 20:30:53 +00005664 if (isa<ObjCObjectPointerType>(RHSType)) {
John McCalle5255932011-01-31 22:28:28 +00005665 // T* -> _Bool
Richard Trieude4958f2011-09-06 20:30:53 +00005666 if (LHSType == Context.BoolTy) {
John McCall8cb679e2010-11-15 09:13:47 +00005667 Kind = CK_PointerToBoolean;
Steve Naroff7cae42b2009-07-10 23:34:53 +00005668 return Compatible;
John McCall8cb679e2010-11-15 09:13:47 +00005669 }
Steve Naroff7cae42b2009-07-10 23:34:53 +00005670
John McCalle5255932011-01-31 22:28:28 +00005671 // T* -> int
Richard Trieude4958f2011-09-06 20:30:53 +00005672 if (LHSType->isIntegerType()) {
John McCall8cb679e2010-11-15 09:13:47 +00005673 Kind = CK_PointerToIntegral;
Steve Naroff7cae42b2009-07-10 23:34:53 +00005674 return PointerToInt;
John McCall8cb679e2010-11-15 09:13:47 +00005675 }
5676
Steve Naroff7cae42b2009-07-10 23:34:53 +00005677 return Incompatible;
5678 }
Eli Friedman3360d892008-05-30 18:07:22 +00005679
John McCalle5255932011-01-31 22:28:28 +00005680 // struct A -> struct B
Richard Trieude4958f2011-09-06 20:30:53 +00005681 if (isa<TagType>(LHSType) && isa<TagType>(RHSType)) {
5682 if (Context.typesAreCompatible(LHSType, RHSType)) {
John McCall8cb679e2010-11-15 09:13:47 +00005683 Kind = CK_NoOp;
Steve Naroff98cf3e92007-06-06 18:38:38 +00005684 return Compatible;
John McCall8cb679e2010-11-15 09:13:47 +00005685 }
Bill Wendling216423b2007-05-30 06:30:29 +00005686 }
John McCalle5255932011-01-31 22:28:28 +00005687
Steve Naroff98cf3e92007-06-06 18:38:38 +00005688 return Incompatible;
Steve Naroff9eb24652007-05-02 21:58:15 +00005689}
5690
Douglas Gregor0cfbdab2009-04-29 22:16:16 +00005691/// \brief Constructs a transparent union from an expression that is
5692/// used to initialize the transparent union.
Richard Trieucfc491d2011-08-02 04:35:43 +00005693static void ConstructTransparentUnion(Sema &S, ASTContext &C,
5694 ExprResult &EResult, QualType UnionType,
5695 FieldDecl *Field) {
Douglas Gregor0cfbdab2009-04-29 22:16:16 +00005696 // Build an initializer list that designates the appropriate member
5697 // of the transparent union.
John Wiegley01296292011-04-08 18:41:53 +00005698 Expr *E = EResult.take();
Ted Kremenekac034612010-04-13 23:39:13 +00005699 InitListExpr *Initializer = new (C) InitListExpr(C, SourceLocation(),
Ted Kremenek013041e2010-02-19 01:50:18 +00005700 &E, 1,
Douglas Gregor0cfbdab2009-04-29 22:16:16 +00005701 SourceLocation());
5702 Initializer->setType(UnionType);
5703 Initializer->setInitializedFieldInUnion(Field);
5704
5705 // Build a compound literal constructing a value of the transparent
5706 // union type from this initializer list.
John McCalle15bbff2010-01-18 19:35:47 +00005707 TypeSourceInfo *unionTInfo = C.getTrivialTypeSourceInfo(UnionType);
John Wiegley01296292011-04-08 18:41:53 +00005708 EResult = S.Owned(
5709 new (C) CompoundLiteralExpr(SourceLocation(), unionTInfo, UnionType,
5710 VK_RValue, Initializer, false));
Douglas Gregor0cfbdab2009-04-29 22:16:16 +00005711}
5712
5713Sema::AssignConvertType
Richard Trieucfc491d2011-08-02 04:35:43 +00005714Sema::CheckTransparentUnionArgumentConstraints(QualType ArgType,
Richard Trieueb299142011-09-06 20:40:12 +00005715 ExprResult &RHS) {
5716 QualType RHSType = RHS.get()->getType();
Douglas Gregor0cfbdab2009-04-29 22:16:16 +00005717
Mike Stump11289f42009-09-09 15:08:12 +00005718 // If the ArgType is a Union type, we want to handle a potential
Douglas Gregor0cfbdab2009-04-29 22:16:16 +00005719 // transparent_union GCC extension.
5720 const RecordType *UT = ArgType->getAsUnionType();
Argyrios Kyrtzidisb4b64ca2009-06-30 02:34:44 +00005721 if (!UT || !UT->getDecl()->hasAttr<TransparentUnionAttr>())
Douglas Gregor0cfbdab2009-04-29 22:16:16 +00005722 return Incompatible;
5723
5724 // The field to initialize within the transparent union.
5725 RecordDecl *UD = UT->getDecl();
5726 FieldDecl *InitField = 0;
5727 // It's compatible if the expression matches any of the fields.
Argyrios Kyrtzidiscfbfe782009-06-30 02:36:12 +00005728 for (RecordDecl::field_iterator it = UD->field_begin(),
5729 itend = UD->field_end();
Douglas Gregor0cfbdab2009-04-29 22:16:16 +00005730 it != itend; ++it) {
5731 if (it->getType()->isPointerType()) {
5732 // If the transparent union contains a pointer type, we allow:
5733 // 1) void pointer
5734 // 2) null pointer constant
Richard Trieueb299142011-09-06 20:40:12 +00005735 if (RHSType->isPointerType())
John McCall9320b872011-09-09 05:25:32 +00005736 if (RHSType->castAs<PointerType>()->getPointeeType()->isVoidType()) {
Richard Trieueb299142011-09-06 20:40:12 +00005737 RHS = ImpCastExprToType(RHS.take(), it->getType(), CK_BitCast);
David Blaikie40ed2972012-06-06 20:45:41 +00005738 InitField = *it;
Douglas Gregor0cfbdab2009-04-29 22:16:16 +00005739 break;
5740 }
Mike Stump11289f42009-09-09 15:08:12 +00005741
Richard Trieueb299142011-09-06 20:40:12 +00005742 if (RHS.get()->isNullPointerConstant(Context,
5743 Expr::NPC_ValueDependentIsNull)) {
5744 RHS = ImpCastExprToType(RHS.take(), it->getType(),
5745 CK_NullToPointer);
David Blaikie40ed2972012-06-06 20:45:41 +00005746 InitField = *it;
Douglas Gregor0cfbdab2009-04-29 22:16:16 +00005747 break;
5748 }
5749 }
5750
John McCall8cb679e2010-11-15 09:13:47 +00005751 CastKind Kind = CK_Invalid;
Richard Trieueb299142011-09-06 20:40:12 +00005752 if (CheckAssignmentConstraints(it->getType(), RHS, Kind)
Douglas Gregor0cfbdab2009-04-29 22:16:16 +00005753 == Compatible) {
Richard Trieueb299142011-09-06 20:40:12 +00005754 RHS = ImpCastExprToType(RHS.take(), it->getType(), Kind);
David Blaikie40ed2972012-06-06 20:45:41 +00005755 InitField = *it;
Douglas Gregor0cfbdab2009-04-29 22:16:16 +00005756 break;
5757 }
5758 }
5759
5760 if (!InitField)
5761 return Incompatible;
5762
Richard Trieueb299142011-09-06 20:40:12 +00005763 ConstructTransparentUnion(*this, Context, RHS, ArgType, InitField);
Douglas Gregor0cfbdab2009-04-29 22:16:16 +00005764 return Compatible;
5765}
5766
Chris Lattner9bad62c2008-01-04 18:04:52 +00005767Sema::AssignConvertType
Sebastian Redlb49c46c2011-09-24 17:48:00 +00005768Sema::CheckSingleAssignmentConstraints(QualType LHSType, ExprResult &RHS,
5769 bool Diagnose) {
David Blaikiebbafb8a2012-03-11 07:00:24 +00005770 if (getLangOpts().CPlusPlus) {
Eli Friedman0dfb8892011-10-06 23:00:33 +00005771 if (!LHSType->isRecordType() && !LHSType->isAtomicType()) {
Douglas Gregor9a657932008-10-21 23:43:52 +00005772 // C++ 5.17p3: If the left operand is not of class type, the
5773 // expression is implicitly converted (C++ 4) to the
5774 // cv-unqualified type of the left operand.
Sebastian Redlcc152642011-10-16 18:19:06 +00005775 ExprResult Res;
5776 if (Diagnose) {
5777 Res = PerformImplicitConversion(RHS.get(), LHSType.getUnqualifiedType(),
5778 AA_Assigning);
5779 } else {
5780 ImplicitConversionSequence ICS =
5781 TryImplicitConversion(RHS.get(), LHSType.getUnqualifiedType(),
5782 /*SuppressUserConversions=*/false,
5783 /*AllowExplicit=*/false,
5784 /*InOverloadResolution=*/false,
5785 /*CStyle=*/false,
5786 /*AllowObjCWritebackConversion=*/false);
5787 if (ICS.isFailure())
5788 return Incompatible;
5789 Res = PerformImplicitConversion(RHS.get(), LHSType.getUnqualifiedType(),
5790 ICS, AA_Assigning);
5791 }
John Wiegley01296292011-04-08 18:41:53 +00005792 if (Res.isInvalid())
Douglas Gregor9a657932008-10-21 23:43:52 +00005793 return Incompatible;
Fariborz Jahanian7fcce682011-07-07 23:04:17 +00005794 Sema::AssignConvertType result = Compatible;
David Blaikiebbafb8a2012-03-11 07:00:24 +00005795 if (getLangOpts().ObjCAutoRefCount &&
Richard Trieueb299142011-09-06 20:40:12 +00005796 !CheckObjCARCUnavailableWeakConversion(LHSType,
5797 RHS.get()->getType()))
Fariborz Jahanian7fcce682011-07-07 23:04:17 +00005798 result = IncompatibleObjCWeakRef;
Richard Trieueb299142011-09-06 20:40:12 +00005799 RHS = move(Res);
Fariborz Jahanian7fcce682011-07-07 23:04:17 +00005800 return result;
Douglas Gregor9a657932008-10-21 23:43:52 +00005801 }
5802
5803 // FIXME: Currently, we fall through and treat C++ classes like C
5804 // structures.
Eli Friedman0dfb8892011-10-06 23:00:33 +00005805 // FIXME: We also fall through for atomics; not sure what should
5806 // happen there, though.
Sebastian Redlb49c46c2011-09-24 17:48:00 +00005807 }
Douglas Gregor9a657932008-10-21 23:43:52 +00005808
Steve Naroff0ee0b0a2007-11-27 17:58:44 +00005809 // C99 6.5.16.1p1: the left operand is a pointer and the right is
5810 // a null pointer constant.
Richard Trieueb299142011-09-06 20:40:12 +00005811 if ((LHSType->isPointerType() ||
5812 LHSType->isObjCObjectPointerType() ||
5813 LHSType->isBlockPointerType())
5814 && RHS.get()->isNullPointerConstant(Context,
5815 Expr::NPC_ValueDependentIsNull)) {
5816 RHS = ImpCastExprToType(RHS.take(), LHSType, CK_NullToPointer);
Steve Naroff0ee0b0a2007-11-27 17:58:44 +00005817 return Compatible;
5818 }
Mike Stump4e1f26a2009-02-19 03:04:26 +00005819
Chris Lattnere6dcd502007-10-16 02:55:40 +00005820 // This check seems unnatural, however it is necessary to ensure the proper
Steve Naroffb8ea4fb2007-07-13 23:32:42 +00005821 // conversion of functions/arrays. If the conversion were done for all
Douglas Gregora121b752009-11-03 16:56:39 +00005822 // DeclExpr's (created by ActOnIdExpression), it would mess up the unary
Nick Lewyckyef7c0ff2010-08-05 06:27:49 +00005823 // expressions that suppress this implicit conversion (&, sizeof).
Chris Lattnere6dcd502007-10-16 02:55:40 +00005824 //
Mike Stump4e1f26a2009-02-19 03:04:26 +00005825 // Suppress this for references: C++ 8.5.3p5.
Richard Trieueb299142011-09-06 20:40:12 +00005826 if (!LHSType->isReferenceType()) {
5827 RHS = DefaultFunctionArrayLvalueConversion(RHS.take());
5828 if (RHS.isInvalid())
John Wiegley01296292011-04-08 18:41:53 +00005829 return Incompatible;
5830 }
Steve Naroff0c1c7ed2007-08-24 22:33:52 +00005831
John McCall8cb679e2010-11-15 09:13:47 +00005832 CastKind Kind = CK_Invalid;
Chris Lattner9bad62c2008-01-04 18:04:52 +00005833 Sema::AssignConvertType result =
Richard Trieueb299142011-09-06 20:40:12 +00005834 CheckAssignmentConstraints(LHSType, RHS, Kind);
Mike Stump4e1f26a2009-02-19 03:04:26 +00005835
Steve Naroff0c1c7ed2007-08-24 22:33:52 +00005836 // C99 6.5.16.1p2: The value of the right operand is converted to the
5837 // type of the assignment expression.
Douglas Gregor6b754842008-10-28 00:22:11 +00005838 // CheckAssignmentConstraints allows the left-hand side to be a reference,
5839 // so that we can use references in built-in functions even in C.
5840 // The getNonReferenceType() call makes sure that the resulting expression
5841 // does not have reference type.
Richard Trieueb299142011-09-06 20:40:12 +00005842 if (result != Incompatible && RHS.get()->getType() != LHSType)
5843 RHS = ImpCastExprToType(RHS.take(),
5844 LHSType.getNonLValueExprType(Context), Kind);
Steve Naroff0c1c7ed2007-08-24 22:33:52 +00005845 return result;
Steve Naroffb8ea4fb2007-07-13 23:32:42 +00005846}
5847
Richard Trieueb299142011-09-06 20:40:12 +00005848QualType Sema::InvalidOperands(SourceLocation Loc, ExprResult &LHS,
5849 ExprResult &RHS) {
Chris Lattner377d1f82008-11-18 22:52:51 +00005850 Diag(Loc, diag::err_typecheck_invalid_operands)
Richard Trieueb299142011-09-06 20:40:12 +00005851 << LHS.get()->getType() << RHS.get()->getType()
5852 << LHS.get()->getSourceRange() << RHS.get()->getSourceRange();
Chris Lattner5c11c412007-12-12 05:47:28 +00005853 return QualType();
Steve Naroff6f49f5d2007-05-29 14:23:36 +00005854}
5855
Richard Trieu859d23f2011-09-06 21:01:04 +00005856QualType Sema::CheckVectorOperands(ExprResult &LHS, ExprResult &RHS,
Richard Trieuba63ce62011-09-09 01:45:06 +00005857 SourceLocation Loc, bool IsCompAssign) {
Richard Smith508ebf32011-10-28 03:31:48 +00005858 if (!IsCompAssign) {
5859 LHS = DefaultFunctionArrayLvalueConversion(LHS.take());
5860 if (LHS.isInvalid())
5861 return QualType();
5862 }
5863 RHS = DefaultFunctionArrayLvalueConversion(RHS.take());
5864 if (RHS.isInvalid())
5865 return QualType();
5866
Mike Stump4e1f26a2009-02-19 03:04:26 +00005867 // For conversion purposes, we ignore any qualifiers.
Nate Begeman002e4bd2008-04-04 01:30:25 +00005868 // For example, "const float" and "float" are equivalent.
Richard Trieu859d23f2011-09-06 21:01:04 +00005869 QualType LHSType =
5870 Context.getCanonicalType(LHS.get()->getType()).getUnqualifiedType();
5871 QualType RHSType =
5872 Context.getCanonicalType(RHS.get()->getType()).getUnqualifiedType();
Mike Stump4e1f26a2009-02-19 03:04:26 +00005873
Nate Begeman191a6b12008-07-14 18:02:46 +00005874 // If the vector types are identical, return.
Richard Trieu859d23f2011-09-06 21:01:04 +00005875 if (LHSType == RHSType)
5876 return LHSType;
Nate Begeman330aaa72007-12-30 02:59:45 +00005877
Douglas Gregor59e8b3b2010-08-06 10:14:59 +00005878 // Handle the case of equivalent AltiVec and GCC vector types
Richard Trieu859d23f2011-09-06 21:01:04 +00005879 if (LHSType->isVectorType() && RHSType->isVectorType() &&
5880 Context.areCompatibleVectorTypes(LHSType, RHSType)) {
5881 if (LHSType->isExtVectorType()) {
5882 RHS = ImpCastExprToType(RHS.take(), LHSType, CK_BitCast);
5883 return LHSType;
Eli Friedman1408bc92011-06-23 18:10:35 +00005884 }
5885
Richard Trieuba63ce62011-09-09 01:45:06 +00005886 if (!IsCompAssign)
Richard Trieu859d23f2011-09-06 21:01:04 +00005887 LHS = ImpCastExprToType(LHS.take(), RHSType, CK_BitCast);
5888 return RHSType;
Douglas Gregor59e8b3b2010-08-06 10:14:59 +00005889 }
5890
David Blaikiebbafb8a2012-03-11 07:00:24 +00005891 if (getLangOpts().LaxVectorConversions &&
Richard Trieu859d23f2011-09-06 21:01:04 +00005892 Context.getTypeSize(LHSType) == Context.getTypeSize(RHSType)) {
Eli Friedman1408bc92011-06-23 18:10:35 +00005893 // If we are allowing lax vector conversions, and LHS and RHS are both
5894 // vectors, the total size only needs to be the same. This is a
5895 // bitcast; no bits are changed but the result type is different.
5896 // FIXME: Should we really be allowing this?
Richard Trieu859d23f2011-09-06 21:01:04 +00005897 RHS = ImpCastExprToType(RHS.take(), LHSType, CK_BitCast);
5898 return LHSType;
Eli Friedman1408bc92011-06-23 18:10:35 +00005899 }
5900
Nate Begemanbd956c42009-06-28 02:36:38 +00005901 // Canonicalize the ExtVector to the LHS, remember if we swapped so we can
5902 // swap back (so that we don't reverse the inputs to a subtract, for instance.
5903 bool swapped = false;
Richard Trieuba63ce62011-09-09 01:45:06 +00005904 if (RHSType->isExtVectorType() && !IsCompAssign) {
Nate Begemanbd956c42009-06-28 02:36:38 +00005905 swapped = true;
Richard Trieu859d23f2011-09-06 21:01:04 +00005906 std::swap(RHS, LHS);
5907 std::swap(RHSType, LHSType);
Nate Begemanbd956c42009-06-28 02:36:38 +00005908 }
Mike Stump11289f42009-09-09 15:08:12 +00005909
Nate Begeman886448d2009-06-28 19:12:57 +00005910 // Handle the case of an ext vector and scalar.
Richard Trieu859d23f2011-09-06 21:01:04 +00005911 if (const ExtVectorType *LV = LHSType->getAs<ExtVectorType>()) {
Nate Begemanbd956c42009-06-28 02:36:38 +00005912 QualType EltTy = LV->getElementType();
Richard Trieu859d23f2011-09-06 21:01:04 +00005913 if (EltTy->isIntegralType(Context) && RHSType->isIntegralType(Context)) {
5914 int order = Context.getIntegerTypeOrder(EltTy, RHSType);
John McCall8cb679e2010-11-15 09:13:47 +00005915 if (order > 0)
Richard Trieu859d23f2011-09-06 21:01:04 +00005916 RHS = ImpCastExprToType(RHS.take(), EltTy, CK_IntegralCast);
John McCall8cb679e2010-11-15 09:13:47 +00005917 if (order >= 0) {
Richard Trieu859d23f2011-09-06 21:01:04 +00005918 RHS = ImpCastExprToType(RHS.take(), LHSType, CK_VectorSplat);
5919 if (swapped) std::swap(RHS, LHS);
5920 return LHSType;
Nate Begemanbd956c42009-06-28 02:36:38 +00005921 }
5922 }
Richard Trieu859d23f2011-09-06 21:01:04 +00005923 if (EltTy->isRealFloatingType() && RHSType->isScalarType() &&
5924 RHSType->isRealFloatingType()) {
5925 int order = Context.getFloatingTypeOrder(EltTy, RHSType);
John McCall8cb679e2010-11-15 09:13:47 +00005926 if (order > 0)
Richard Trieu859d23f2011-09-06 21:01:04 +00005927 RHS = ImpCastExprToType(RHS.take(), EltTy, CK_FloatingCast);
John McCall8cb679e2010-11-15 09:13:47 +00005928 if (order >= 0) {
Richard Trieu859d23f2011-09-06 21:01:04 +00005929 RHS = ImpCastExprToType(RHS.take(), LHSType, CK_VectorSplat);
5930 if (swapped) std::swap(RHS, LHS);
5931 return LHSType;
Nate Begemanbd956c42009-06-28 02:36:38 +00005932 }
Nate Begeman330aaa72007-12-30 02:59:45 +00005933 }
5934 }
Mike Stump11289f42009-09-09 15:08:12 +00005935
Nate Begeman886448d2009-06-28 19:12:57 +00005936 // Vectors of different size or scalar and non-ext-vector are errors.
Richard Trieu859d23f2011-09-06 21:01:04 +00005937 if (swapped) std::swap(RHS, LHS);
Chris Lattner377d1f82008-11-18 22:52:51 +00005938 Diag(Loc, diag::err_typecheck_vector_not_convertable)
Richard Trieu859d23f2011-09-06 21:01:04 +00005939 << LHS.get()->getType() << RHS.get()->getType()
5940 << LHS.get()->getSourceRange() << RHS.get()->getSourceRange();
Steve Naroff84ff4b42007-07-09 21:31:10 +00005941 return QualType();
Sebastian Redl112a97662009-02-07 00:15:38 +00005942}
5943
Richard Trieuf8916e12011-09-16 00:53:10 +00005944// checkArithmeticNull - Detect when a NULL constant is used improperly in an
5945// expression. These are mainly cases where the null pointer is used as an
5946// integer instead of a pointer.
5947static void checkArithmeticNull(Sema &S, ExprResult &LHS, ExprResult &RHS,
5948 SourceLocation Loc, bool IsCompare) {
5949 // The canonical way to check for a GNU null is with isNullPointerConstant,
5950 // but we use a bit of a hack here for speed; this is a relatively
5951 // hot path, and isNullPointerConstant is slow.
5952 bool LHSNull = isa<GNUNullExpr>(LHS.get()->IgnoreParenImpCasts());
5953 bool RHSNull = isa<GNUNullExpr>(RHS.get()->IgnoreParenImpCasts());
5954
5955 QualType NonNullType = LHSNull ? RHS.get()->getType() : LHS.get()->getType();
5956
5957 // Avoid analyzing cases where the result will either be invalid (and
5958 // diagnosed as such) or entirely valid and not something to warn about.
5959 if ((!LHSNull && !RHSNull) || NonNullType->isBlockPointerType() ||
5960 NonNullType->isMemberPointerType() || NonNullType->isFunctionType())
5961 return;
5962
5963 // Comparison operations would not make sense with a null pointer no matter
5964 // what the other expression is.
5965 if (!IsCompare) {
5966 S.Diag(Loc, diag::warn_null_in_arithmetic_operation)
5967 << (LHSNull ? LHS.get()->getSourceRange() : SourceRange())
5968 << (RHSNull ? RHS.get()->getSourceRange() : SourceRange());
5969 return;
5970 }
5971
5972 // The rest of the operations only make sense with a null pointer
5973 // if the other expression is a pointer.
5974 if (LHSNull == RHSNull || NonNullType->isAnyPointerType() ||
5975 NonNullType->canDecayToPointerType())
5976 return;
5977
5978 S.Diag(Loc, diag::warn_null_in_comparison_operation)
5979 << LHSNull /* LHS is NULL */ << NonNullType
5980 << LHS.get()->getSourceRange() << RHS.get()->getSourceRange();
5981}
5982
Richard Trieu859d23f2011-09-06 21:01:04 +00005983QualType Sema::CheckMultiplyDivideOperands(ExprResult &LHS, ExprResult &RHS,
Richard Trieucfc491d2011-08-02 04:35:43 +00005984 SourceLocation Loc,
Richard Trieuba63ce62011-09-09 01:45:06 +00005985 bool IsCompAssign, bool IsDiv) {
Richard Trieuf8916e12011-09-16 00:53:10 +00005986 checkArithmeticNull(*this, LHS, RHS, Loc, /*isCompare=*/false);
5987
Richard Trieu859d23f2011-09-06 21:01:04 +00005988 if (LHS.get()->getType()->isVectorType() ||
5989 RHS.get()->getType()->isVectorType())
Richard Trieuba63ce62011-09-09 01:45:06 +00005990 return CheckVectorOperands(LHS, RHS, Loc, IsCompAssign);
Mike Stump4e1f26a2009-02-19 03:04:26 +00005991
Richard Trieuba63ce62011-09-09 01:45:06 +00005992 QualType compType = UsualArithmeticConversions(LHS, RHS, IsCompAssign);
Richard Trieu859d23f2011-09-06 21:01:04 +00005993 if (LHS.isInvalid() || RHS.isInvalid())
John Wiegley01296292011-04-08 18:41:53 +00005994 return QualType();
Mike Stump4e1f26a2009-02-19 03:04:26 +00005995
David Chisnallfa35df62012-01-16 17:27:18 +00005996
Eli Friedman93ee5ca2012-06-16 02:19:17 +00005997 if (compType.isNull() || !compType->isArithmeticType())
Richard Trieu859d23f2011-09-06 21:01:04 +00005998 return InvalidOperands(Loc, LHS, RHS);
Kovarththanan Rajaratnamba2c6522010-03-13 10:17:05 +00005999
Chris Lattnerfaa54172010-01-12 21:23:57 +00006000 // Check for division by zero.
Richard Trieuba63ce62011-09-09 01:45:06 +00006001 if (IsDiv &&
Richard Trieu859d23f2011-09-06 21:01:04 +00006002 RHS.get()->isNullPointerConstant(Context,
Richard Trieucfc491d2011-08-02 04:35:43 +00006003 Expr::NPC_ValueDependentIsNotNull))
Richard Trieu859d23f2011-09-06 21:01:04 +00006004 DiagRuntimeBehavior(Loc, RHS.get(), PDiag(diag::warn_division_by_zero)
6005 << RHS.get()->getSourceRange());
Kovarththanan Rajaratnamba2c6522010-03-13 10:17:05 +00006006
Chris Lattnerfaa54172010-01-12 21:23:57 +00006007 return compType;
Steve Naroff26c8ea52007-03-21 21:08:52 +00006008}
6009
Chris Lattnerfaa54172010-01-12 21:23:57 +00006010QualType Sema::CheckRemainderOperands(
Richard Trieuba63ce62011-09-09 01:45:06 +00006011 ExprResult &LHS, ExprResult &RHS, SourceLocation Loc, bool IsCompAssign) {
Richard Trieuf8916e12011-09-16 00:53:10 +00006012 checkArithmeticNull(*this, LHS, RHS, Loc, /*isCompare=*/false);
6013
Richard Trieu859d23f2011-09-06 21:01:04 +00006014 if (LHS.get()->getType()->isVectorType() ||
6015 RHS.get()->getType()->isVectorType()) {
6016 if (LHS.get()->getType()->hasIntegerRepresentation() &&
6017 RHS.get()->getType()->hasIntegerRepresentation())
Richard Trieuba63ce62011-09-09 01:45:06 +00006018 return CheckVectorOperands(LHS, RHS, Loc, IsCompAssign);
Richard Trieu859d23f2011-09-06 21:01:04 +00006019 return InvalidOperands(Loc, LHS, RHS);
Daniel Dunbar0d2bfec2009-01-05 22:55:36 +00006020 }
Steve Naroffb8ea4fb2007-07-13 23:32:42 +00006021
Richard Trieuba63ce62011-09-09 01:45:06 +00006022 QualType compType = UsualArithmeticConversions(LHS, RHS, IsCompAssign);
Richard Trieu859d23f2011-09-06 21:01:04 +00006023 if (LHS.isInvalid() || RHS.isInvalid())
John Wiegley01296292011-04-08 18:41:53 +00006024 return QualType();
Mike Stump4e1f26a2009-02-19 03:04:26 +00006025
Eli Friedman93ee5ca2012-06-16 02:19:17 +00006026 if (compType.isNull() || !compType->isIntegerType())
Richard Trieu859d23f2011-09-06 21:01:04 +00006027 return InvalidOperands(Loc, LHS, RHS);
Kovarththanan Rajaratnamba2c6522010-03-13 10:17:05 +00006028
Chris Lattnerfaa54172010-01-12 21:23:57 +00006029 // Check for remainder by zero.
Richard Trieu859d23f2011-09-06 21:01:04 +00006030 if (RHS.get()->isNullPointerConstant(Context,
Richard Trieucfc491d2011-08-02 04:35:43 +00006031 Expr::NPC_ValueDependentIsNotNull))
Richard Trieu859d23f2011-09-06 21:01:04 +00006032 DiagRuntimeBehavior(Loc, RHS.get(), PDiag(diag::warn_remainder_by_zero)
6033 << RHS.get()->getSourceRange());
Kovarththanan Rajaratnamba2c6522010-03-13 10:17:05 +00006034
Chris Lattnerfaa54172010-01-12 21:23:57 +00006035 return compType;
Steve Naroff218bc2b2007-05-04 21:54:46 +00006036}
6037
Chandler Carruthc9332212011-06-27 08:02:19 +00006038/// \brief Diagnose invalid arithmetic on two void pointers.
6039static void diagnoseArithmeticOnTwoVoidPointers(Sema &S, SourceLocation Loc,
Richard Trieu4ae7e972011-09-06 21:13:51 +00006040 Expr *LHSExpr, Expr *RHSExpr) {
David Blaikiebbafb8a2012-03-11 07:00:24 +00006041 S.Diag(Loc, S.getLangOpts().CPlusPlus
Chandler Carruthc9332212011-06-27 08:02:19 +00006042 ? diag::err_typecheck_pointer_arith_void_type
6043 : diag::ext_gnu_void_ptr)
Richard Trieu4ae7e972011-09-06 21:13:51 +00006044 << 1 /* two pointers */ << LHSExpr->getSourceRange()
6045 << RHSExpr->getSourceRange();
Chandler Carruthc9332212011-06-27 08:02:19 +00006046}
6047
6048/// \brief Diagnose invalid arithmetic on a void pointer.
6049static void diagnoseArithmeticOnVoidPointer(Sema &S, SourceLocation Loc,
6050 Expr *Pointer) {
David Blaikiebbafb8a2012-03-11 07:00:24 +00006051 S.Diag(Loc, S.getLangOpts().CPlusPlus
Chandler Carruthc9332212011-06-27 08:02:19 +00006052 ? diag::err_typecheck_pointer_arith_void_type
6053 : diag::ext_gnu_void_ptr)
6054 << 0 /* one pointer */ << Pointer->getSourceRange();
6055}
6056
6057/// \brief Diagnose invalid arithmetic on two function pointers.
6058static void diagnoseArithmeticOnTwoFunctionPointers(Sema &S, SourceLocation Loc,
6059 Expr *LHS, Expr *RHS) {
6060 assert(LHS->getType()->isAnyPointerType());
6061 assert(RHS->getType()->isAnyPointerType());
David Blaikiebbafb8a2012-03-11 07:00:24 +00006062 S.Diag(Loc, S.getLangOpts().CPlusPlus
Chandler Carruthc9332212011-06-27 08:02:19 +00006063 ? diag::err_typecheck_pointer_arith_function_type
6064 : diag::ext_gnu_ptr_func_arith)
6065 << 1 /* two pointers */ << LHS->getType()->getPointeeType()
6066 // We only show the second type if it differs from the first.
6067 << (unsigned)!S.Context.hasSameUnqualifiedType(LHS->getType(),
6068 RHS->getType())
6069 << RHS->getType()->getPointeeType()
6070 << LHS->getSourceRange() << RHS->getSourceRange();
6071}
6072
6073/// \brief Diagnose invalid arithmetic on a function pointer.
6074static void diagnoseArithmeticOnFunctionPointer(Sema &S, SourceLocation Loc,
6075 Expr *Pointer) {
6076 assert(Pointer->getType()->isAnyPointerType());
David Blaikiebbafb8a2012-03-11 07:00:24 +00006077 S.Diag(Loc, S.getLangOpts().CPlusPlus
Chandler Carruthc9332212011-06-27 08:02:19 +00006078 ? diag::err_typecheck_pointer_arith_function_type
6079 : diag::ext_gnu_ptr_func_arith)
6080 << 0 /* one pointer */ << Pointer->getType()->getPointeeType()
6081 << 0 /* one pointer, so only one type */
6082 << Pointer->getSourceRange();
6083}
6084
Richard Trieu993f3ab2011-09-12 18:08:02 +00006085/// \brief Emit error if Operand is incomplete pointer type
Richard Trieuaba22802011-09-02 02:15:37 +00006086///
6087/// \returns True if pointer has incomplete type
6088static bool checkArithmeticIncompletePointerType(Sema &S, SourceLocation Loc,
6089 Expr *Operand) {
6090 if ((Operand->getType()->isPointerType() &&
6091 !Operand->getType()->isDependentType()) ||
6092 Operand->getType()->isObjCObjectPointerType()) {
6093 QualType PointeeTy = Operand->getType()->getPointeeType();
6094 if (S.RequireCompleteType(
6095 Loc, PointeeTy,
Douglas Gregor7bfb2d02012-05-04 16:32:21 +00006096 diag::err_typecheck_arithmetic_incomplete_type,
6097 PointeeTy, Operand->getSourceRange()))
Richard Trieuaba22802011-09-02 02:15:37 +00006098 return true;
6099 }
6100 return false;
6101}
6102
Chandler Carruthc9332212011-06-27 08:02:19 +00006103/// \brief Check the validity of an arithmetic pointer operand.
6104///
6105/// If the operand has pointer type, this code will check for pointer types
6106/// which are invalid in arithmetic operations. These will be diagnosed
6107/// appropriately, including whether or not the use is supported as an
6108/// extension.
6109///
6110/// \returns True when the operand is valid to use (even if as an extension).
6111static bool checkArithmeticOpPointerOperand(Sema &S, SourceLocation Loc,
6112 Expr *Operand) {
6113 if (!Operand->getType()->isAnyPointerType()) return true;
6114
6115 QualType PointeeTy = Operand->getType()->getPointeeType();
6116 if (PointeeTy->isVoidType()) {
6117 diagnoseArithmeticOnVoidPointer(S, Loc, Operand);
David Blaikiebbafb8a2012-03-11 07:00:24 +00006118 return !S.getLangOpts().CPlusPlus;
Chandler Carruthc9332212011-06-27 08:02:19 +00006119 }
6120 if (PointeeTy->isFunctionType()) {
6121 diagnoseArithmeticOnFunctionPointer(S, Loc, Operand);
David Blaikiebbafb8a2012-03-11 07:00:24 +00006122 return !S.getLangOpts().CPlusPlus;
Chandler Carruthc9332212011-06-27 08:02:19 +00006123 }
6124
Richard Trieuaba22802011-09-02 02:15:37 +00006125 if (checkArithmeticIncompletePointerType(S, Loc, Operand)) return false;
Chandler Carruthc9332212011-06-27 08:02:19 +00006126
6127 return true;
6128}
6129
6130/// \brief Check the validity of a binary arithmetic operation w.r.t. pointer
6131/// operands.
6132///
6133/// This routine will diagnose any invalid arithmetic on pointer operands much
6134/// like \see checkArithmeticOpPointerOperand. However, it has special logic
6135/// for emitting a single diagnostic even for operations where both LHS and RHS
6136/// are (potentially problematic) pointers.
6137///
6138/// \returns True when the operand is valid to use (even if as an extension).
6139static bool checkArithmeticBinOpPointerOperands(Sema &S, SourceLocation Loc,
Richard Trieu4ae7e972011-09-06 21:13:51 +00006140 Expr *LHSExpr, Expr *RHSExpr) {
6141 bool isLHSPointer = LHSExpr->getType()->isAnyPointerType();
6142 bool isRHSPointer = RHSExpr->getType()->isAnyPointerType();
Chandler Carruthc9332212011-06-27 08:02:19 +00006143 if (!isLHSPointer && !isRHSPointer) return true;
6144
6145 QualType LHSPointeeTy, RHSPointeeTy;
Richard Trieu4ae7e972011-09-06 21:13:51 +00006146 if (isLHSPointer) LHSPointeeTy = LHSExpr->getType()->getPointeeType();
6147 if (isRHSPointer) RHSPointeeTy = RHSExpr->getType()->getPointeeType();
Chandler Carruthc9332212011-06-27 08:02:19 +00006148
6149 // Check for arithmetic on pointers to incomplete types.
6150 bool isLHSVoidPtr = isLHSPointer && LHSPointeeTy->isVoidType();
6151 bool isRHSVoidPtr = isRHSPointer && RHSPointeeTy->isVoidType();
6152 if (isLHSVoidPtr || isRHSVoidPtr) {
Richard Trieu4ae7e972011-09-06 21:13:51 +00006153 if (!isRHSVoidPtr) diagnoseArithmeticOnVoidPointer(S, Loc, LHSExpr);
6154 else if (!isLHSVoidPtr) diagnoseArithmeticOnVoidPointer(S, Loc, RHSExpr);
6155 else diagnoseArithmeticOnTwoVoidPointers(S, Loc, LHSExpr, RHSExpr);
Chandler Carruthc9332212011-06-27 08:02:19 +00006156
David Blaikiebbafb8a2012-03-11 07:00:24 +00006157 return !S.getLangOpts().CPlusPlus;
Chandler Carruthc9332212011-06-27 08:02:19 +00006158 }
6159
6160 bool isLHSFuncPtr = isLHSPointer && LHSPointeeTy->isFunctionType();
6161 bool isRHSFuncPtr = isRHSPointer && RHSPointeeTy->isFunctionType();
6162 if (isLHSFuncPtr || isRHSFuncPtr) {
Richard Trieu4ae7e972011-09-06 21:13:51 +00006163 if (!isRHSFuncPtr) diagnoseArithmeticOnFunctionPointer(S, Loc, LHSExpr);
6164 else if (!isLHSFuncPtr) diagnoseArithmeticOnFunctionPointer(S, Loc,
6165 RHSExpr);
6166 else diagnoseArithmeticOnTwoFunctionPointers(S, Loc, LHSExpr, RHSExpr);
Chandler Carruthc9332212011-06-27 08:02:19 +00006167
David Blaikiebbafb8a2012-03-11 07:00:24 +00006168 return !S.getLangOpts().CPlusPlus;
Chandler Carruthc9332212011-06-27 08:02:19 +00006169 }
6170
Richard Trieu4ae7e972011-09-06 21:13:51 +00006171 if (checkArithmeticIncompletePointerType(S, Loc, LHSExpr)) return false;
6172 if (checkArithmeticIncompletePointerType(S, Loc, RHSExpr)) return false;
Richard Trieuaba22802011-09-02 02:15:37 +00006173
Chandler Carruthc9332212011-06-27 08:02:19 +00006174 return true;
6175}
6176
Richard Trieub10c6312011-09-01 22:53:23 +00006177/// \brief Check bad cases where we step over interface counts.
6178static bool checkArithmethicPointerOnNonFragileABI(Sema &S,
6179 SourceLocation OpLoc,
6180 Expr *Op) {
6181 assert(Op->getType()->isAnyPointerType());
6182 QualType PointeeTy = Op->getType()->getPointeeType();
6183 if (!PointeeTy->isObjCObjectType() || !S.LangOpts.ObjCNonFragileABI)
6184 return true;
6185
6186 S.Diag(OpLoc, diag::err_arithmetic_nonfragile_interface)
6187 << PointeeTy << Op->getSourceRange();
6188 return false;
6189}
6190
Nico Weberccec40d2012-03-02 22:01:22 +00006191/// diagnoseStringPlusInt - Emit a warning when adding an integer to a string
6192/// literal.
6193static void diagnoseStringPlusInt(Sema &Self, SourceLocation OpLoc,
6194 Expr *LHSExpr, Expr *RHSExpr) {
6195 StringLiteral* StrExpr = dyn_cast<StringLiteral>(LHSExpr->IgnoreImpCasts());
6196 Expr* IndexExpr = RHSExpr;
6197 if (!StrExpr) {
6198 StrExpr = dyn_cast<StringLiteral>(RHSExpr->IgnoreImpCasts());
6199 IndexExpr = LHSExpr;
6200 }
6201
6202 bool IsStringPlusInt = StrExpr &&
6203 IndexExpr->getType()->isIntegralOrUnscopedEnumerationType();
6204 if (!IsStringPlusInt)
6205 return;
6206
6207 llvm::APSInt index;
6208 if (IndexExpr->EvaluateAsInt(index, Self.getASTContext())) {
6209 unsigned StrLenWithNull = StrExpr->getLength() + 1;
6210 if (index.isNonNegative() &&
6211 index <= llvm::APSInt(llvm::APInt(index.getBitWidth(), StrLenWithNull),
6212 index.isUnsigned()))
6213 return;
6214 }
6215
6216 SourceRange DiagRange(LHSExpr->getLocStart(), RHSExpr->getLocEnd());
6217 Self.Diag(OpLoc, diag::warn_string_plus_int)
6218 << DiagRange << IndexExpr->IgnoreImpCasts()->getType();
6219
6220 // Only print a fixit for "str" + int, not for int + "str".
6221 if (IndexExpr == RHSExpr) {
6222 SourceLocation EndLoc = Self.PP.getLocForEndOfToken(RHSExpr->getLocEnd());
6223 Self.Diag(OpLoc, diag::note_string_plus_int_silence)
6224 << FixItHint::CreateInsertion(LHSExpr->getLocStart(), "&")
6225 << FixItHint::CreateReplacement(SourceRange(OpLoc), "[")
6226 << FixItHint::CreateInsertion(EndLoc, "]");
6227 } else
6228 Self.Diag(OpLoc, diag::note_string_plus_int_silence);
6229}
6230
Richard Trieu993f3ab2011-09-12 18:08:02 +00006231/// \brief Emit error when two pointers are incompatible.
Richard Trieub10c6312011-09-01 22:53:23 +00006232static void diagnosePointerIncompatibility(Sema &S, SourceLocation Loc,
Richard Trieu4ae7e972011-09-06 21:13:51 +00006233 Expr *LHSExpr, Expr *RHSExpr) {
6234 assert(LHSExpr->getType()->isAnyPointerType());
6235 assert(RHSExpr->getType()->isAnyPointerType());
Richard Trieub10c6312011-09-01 22:53:23 +00006236 S.Diag(Loc, diag::err_typecheck_sub_ptr_compatible)
Richard Trieu4ae7e972011-09-06 21:13:51 +00006237 << LHSExpr->getType() << RHSExpr->getType() << LHSExpr->getSourceRange()
6238 << RHSExpr->getSourceRange();
Richard Trieub10c6312011-09-01 22:53:23 +00006239}
6240
Chris Lattnerfaa54172010-01-12 21:23:57 +00006241QualType Sema::CheckAdditionOperands( // C99 6.5.6
Nico Weberccec40d2012-03-02 22:01:22 +00006242 ExprResult &LHS, ExprResult &RHS, SourceLocation Loc, unsigned Opc,
6243 QualType* CompLHSTy) {
Richard Trieuf8916e12011-09-16 00:53:10 +00006244 checkArithmeticNull(*this, LHS, RHS, Loc, /*isCompare=*/false);
6245
Richard Trieu4ae7e972011-09-06 21:13:51 +00006246 if (LHS.get()->getType()->isVectorType() ||
6247 RHS.get()->getType()->isVectorType()) {
6248 QualType compType = CheckVectorOperands(LHS, RHS, Loc, CompLHSTy);
Eli Friedman8b7b1b12009-03-28 01:22:36 +00006249 if (CompLHSTy) *CompLHSTy = compType;
6250 return compType;
6251 }
Steve Naroff7a5af782007-07-13 16:58:59 +00006252
Richard Trieu4ae7e972011-09-06 21:13:51 +00006253 QualType compType = UsualArithmeticConversions(LHS, RHS, CompLHSTy);
6254 if (LHS.isInvalid() || RHS.isInvalid())
John Wiegley01296292011-04-08 18:41:53 +00006255 return QualType();
Eli Friedman8e122982008-05-18 18:08:51 +00006256
Nico Weberccec40d2012-03-02 22:01:22 +00006257 // Diagnose "string literal" '+' int.
6258 if (Opc == BO_Add)
6259 diagnoseStringPlusInt(*this, Loc, LHS.get(), RHS.get());
6260
Steve Naroffe4718892007-04-27 18:30:00 +00006261 // handle the common case first (both operands are arithmetic).
Eli Friedman93ee5ca2012-06-16 02:19:17 +00006262 if (!compType.isNull() && compType->isArithmeticType()) {
Eli Friedman8b7b1b12009-03-28 01:22:36 +00006263 if (CompLHSTy) *CompLHSTy = compType;
Steve Naroffbe4c4d12007-08-24 19:07:16 +00006264 return compType;
Eli Friedman8b7b1b12009-03-28 01:22:36 +00006265 }
Steve Naroff218bc2b2007-05-04 21:54:46 +00006266
Eli Friedman8e122982008-05-18 18:08:51 +00006267 // Put any potential pointer into PExp
Richard Trieu4ae7e972011-09-06 21:13:51 +00006268 Expr* PExp = LHS.get(), *IExp = RHS.get();
Steve Naroff6b712a72009-07-14 18:25:06 +00006269 if (IExp->getType()->isAnyPointerType())
Eli Friedman8e122982008-05-18 18:08:51 +00006270 std::swap(PExp, IExp);
6271
Richard Trieub420bca2011-09-12 18:37:54 +00006272 if (!PExp->getType()->isAnyPointerType())
6273 return InvalidOperands(Loc, LHS, RHS);
Chandler Carruthc9332212011-06-27 08:02:19 +00006274
Richard Trieub420bca2011-09-12 18:37:54 +00006275 if (!IExp->getType()->isIntegerType())
6276 return InvalidOperands(Loc, LHS, RHS);
Mike Stump11289f42009-09-09 15:08:12 +00006277
Richard Trieub420bca2011-09-12 18:37:54 +00006278 if (!checkArithmeticOpPointerOperand(*this, Loc, PExp))
6279 return QualType();
Kaelyn Uhrain2e7aa5a2011-08-05 23:18:04 +00006280
Richard Trieub420bca2011-09-12 18:37:54 +00006281 // Diagnose bad cases where we step over interface counts.
6282 if (!checkArithmethicPointerOnNonFragileABI(*this, Loc, PExp))
6283 return QualType();
6284
6285 // Check array bounds for pointer arithemtic
6286 CheckArrayAccess(PExp, IExp);
6287
6288 if (CompLHSTy) {
6289 QualType LHSTy = Context.isPromotableBitField(LHS.get());
6290 if (LHSTy.isNull()) {
6291 LHSTy = LHS.get()->getType();
6292 if (LHSTy->isPromotableIntegerType())
6293 LHSTy = Context.getPromotedIntegerType(LHSTy);
Eli Friedman8e122982008-05-18 18:08:51 +00006294 }
Richard Trieub420bca2011-09-12 18:37:54 +00006295 *CompLHSTy = LHSTy;
Eli Friedman8e122982008-05-18 18:08:51 +00006296 }
6297
Richard Trieub420bca2011-09-12 18:37:54 +00006298 return PExp->getType();
Steve Naroff26c8ea52007-03-21 21:08:52 +00006299}
6300
Chris Lattner2a3569b2008-04-07 05:30:13 +00006301// C99 6.5.6
Richard Trieu4ae7e972011-09-06 21:13:51 +00006302QualType Sema::CheckSubtractionOperands(ExprResult &LHS, ExprResult &RHS,
Richard Trieucfc491d2011-08-02 04:35:43 +00006303 SourceLocation Loc,
6304 QualType* CompLHSTy) {
Richard Trieuf8916e12011-09-16 00:53:10 +00006305 checkArithmeticNull(*this, LHS, RHS, Loc, /*isCompare=*/false);
6306
Richard Trieu4ae7e972011-09-06 21:13:51 +00006307 if (LHS.get()->getType()->isVectorType() ||
6308 RHS.get()->getType()->isVectorType()) {
6309 QualType compType = CheckVectorOperands(LHS, RHS, Loc, CompLHSTy);
Eli Friedman8b7b1b12009-03-28 01:22:36 +00006310 if (CompLHSTy) *CompLHSTy = compType;
6311 return compType;
6312 }
Mike Stump4e1f26a2009-02-19 03:04:26 +00006313
Richard Trieu4ae7e972011-09-06 21:13:51 +00006314 QualType compType = UsualArithmeticConversions(LHS, RHS, CompLHSTy);
6315 if (LHS.isInvalid() || RHS.isInvalid())
John Wiegley01296292011-04-08 18:41:53 +00006316 return QualType();
Mike Stump4e1f26a2009-02-19 03:04:26 +00006317
Chris Lattner4d62f422007-12-09 21:53:25 +00006318 // Enforce type constraints: C99 6.5.6p3.
Mike Stump4e1f26a2009-02-19 03:04:26 +00006319
Chris Lattner4d62f422007-12-09 21:53:25 +00006320 // Handle the common case first (both operands are arithmetic).
Eli Friedman93ee5ca2012-06-16 02:19:17 +00006321 if (!compType.isNull() && compType->isArithmeticType()) {
Eli Friedman8b7b1b12009-03-28 01:22:36 +00006322 if (CompLHSTy) *CompLHSTy = compType;
Steve Naroffbe4c4d12007-08-24 19:07:16 +00006323 return compType;
Eli Friedman8b7b1b12009-03-28 01:22:36 +00006324 }
Mike Stump11289f42009-09-09 15:08:12 +00006325
Chris Lattner4d62f422007-12-09 21:53:25 +00006326 // Either ptr - int or ptr - ptr.
Richard Trieu4ae7e972011-09-06 21:13:51 +00006327 if (LHS.get()->getType()->isAnyPointerType()) {
6328 QualType lpointee = LHS.get()->getType()->getPointeeType();
Mike Stump4e1f26a2009-02-19 03:04:26 +00006329
Chris Lattner12bdebb2009-04-24 23:50:08 +00006330 // Diagnose bad cases where we step over interface counts.
Richard Trieu4ae7e972011-09-06 21:13:51 +00006331 if (!checkArithmethicPointerOnNonFragileABI(*this, Loc, LHS.get()))
Chris Lattner12bdebb2009-04-24 23:50:08 +00006332 return QualType();
Mike Stump11289f42009-09-09 15:08:12 +00006333
Chris Lattner4d62f422007-12-09 21:53:25 +00006334 // The result type of a pointer-int computation is the pointer type.
Richard Trieu4ae7e972011-09-06 21:13:51 +00006335 if (RHS.get()->getType()->isIntegerType()) {
6336 if (!checkArithmeticOpPointerOperand(*this, Loc, LHS.get()))
Chandler Carruthc9332212011-06-27 08:02:19 +00006337 return QualType();
Douglas Gregorac1fb652009-03-24 19:52:54 +00006338
Kaelyn Uhrain2e7aa5a2011-08-05 23:18:04 +00006339 // Check array bounds for pointer arithemtic
Richard Smith13f67182011-12-16 19:31:14 +00006340 CheckArrayAccess(LHS.get(), RHS.get(), /*ArraySubscriptExpr*/0,
6341 /*AllowOnePastEnd*/true, /*IndexNegated*/true);
Kaelyn Uhrain2e7aa5a2011-08-05 23:18:04 +00006342
Richard Trieu4ae7e972011-09-06 21:13:51 +00006343 if (CompLHSTy) *CompLHSTy = LHS.get()->getType();
6344 return LHS.get()->getType();
Douglas Gregorac1fb652009-03-24 19:52:54 +00006345 }
Mike Stump4e1f26a2009-02-19 03:04:26 +00006346
Chris Lattner4d62f422007-12-09 21:53:25 +00006347 // Handle pointer-pointer subtractions.
Richard Trieucfc491d2011-08-02 04:35:43 +00006348 if (const PointerType *RHSPTy
Richard Trieu4ae7e972011-09-06 21:13:51 +00006349 = RHS.get()->getType()->getAs<PointerType>()) {
Eli Friedman1974e532008-02-08 01:19:44 +00006350 QualType rpointee = RHSPTy->getPointeeType();
Mike Stump4e1f26a2009-02-19 03:04:26 +00006351
David Blaikiebbafb8a2012-03-11 07:00:24 +00006352 if (getLangOpts().CPlusPlus) {
Eli Friedman168fe152009-05-16 13:54:38 +00006353 // Pointee types must be the same: C++ [expr.add]
6354 if (!Context.hasSameUnqualifiedType(lpointee, rpointee)) {
Richard Trieu4ae7e972011-09-06 21:13:51 +00006355 diagnosePointerIncompatibility(*this, Loc, LHS.get(), RHS.get());
Eli Friedman168fe152009-05-16 13:54:38 +00006356 }
6357 } else {
6358 // Pointee types must be compatible C99 6.5.6p3
6359 if (!Context.typesAreCompatible(
6360 Context.getCanonicalType(lpointee).getUnqualifiedType(),
6361 Context.getCanonicalType(rpointee).getUnqualifiedType())) {
Richard Trieu4ae7e972011-09-06 21:13:51 +00006362 diagnosePointerIncompatibility(*this, Loc, LHS.get(), RHS.get());
Eli Friedman168fe152009-05-16 13:54:38 +00006363 return QualType();
6364 }
Chris Lattner4d62f422007-12-09 21:53:25 +00006365 }
Mike Stump4e1f26a2009-02-19 03:04:26 +00006366
Chandler Carruthc9332212011-06-27 08:02:19 +00006367 if (!checkArithmeticBinOpPointerOperands(*this, Loc,
Richard Trieu4ae7e972011-09-06 21:13:51 +00006368 LHS.get(), RHS.get()))
Chandler Carruthc9332212011-06-27 08:02:19 +00006369 return QualType();
Eli Friedman8b7b1b12009-03-28 01:22:36 +00006370
Richard Trieu4ae7e972011-09-06 21:13:51 +00006371 if (CompLHSTy) *CompLHSTy = LHS.get()->getType();
Chris Lattner4d62f422007-12-09 21:53:25 +00006372 return Context.getPointerDiffType();
6373 }
6374 }
Mike Stump4e1f26a2009-02-19 03:04:26 +00006375
Richard Trieu4ae7e972011-09-06 21:13:51 +00006376 return InvalidOperands(Loc, LHS, RHS);
Steve Naroff218bc2b2007-05-04 21:54:46 +00006377}
6378
Douglas Gregor0bf31402010-10-08 23:50:27 +00006379static bool isScopedEnumerationType(QualType T) {
6380 if (const EnumType *ET = dyn_cast<EnumType>(T))
6381 return ET->getDecl()->isScoped();
6382 return false;
6383}
6384
Richard Trieue4a19fb2011-09-06 21:21:28 +00006385static void DiagnoseBadShiftValues(Sema& S, ExprResult &LHS, ExprResult &RHS,
Chandler Carruth4c6fdca2011-02-23 23:34:11 +00006386 SourceLocation Loc, unsigned Opc,
Richard Trieue4a19fb2011-09-06 21:21:28 +00006387 QualType LHSType) {
Chandler Carruth4c6fdca2011-02-23 23:34:11 +00006388 llvm::APSInt Right;
6389 // Check right/shifter operand
Richard Trieue4a19fb2011-09-06 21:21:28 +00006390 if (RHS.get()->isValueDependent() ||
6391 !RHS.get()->isIntegerConstantExpr(Right, S.Context))
Chandler Carruth4c6fdca2011-02-23 23:34:11 +00006392 return;
6393
6394 if (Right.isNegative()) {
Richard Trieue4a19fb2011-09-06 21:21:28 +00006395 S.DiagRuntimeBehavior(Loc, RHS.get(),
Ted Kremenek63657fe2011-03-01 18:09:31 +00006396 S.PDiag(diag::warn_shift_negative)
Richard Trieue4a19fb2011-09-06 21:21:28 +00006397 << RHS.get()->getSourceRange());
Chandler Carruth4c6fdca2011-02-23 23:34:11 +00006398 return;
6399 }
6400 llvm::APInt LeftBits(Right.getBitWidth(),
Richard Trieue4a19fb2011-09-06 21:21:28 +00006401 S.Context.getTypeSize(LHS.get()->getType()));
Chandler Carruth4c6fdca2011-02-23 23:34:11 +00006402 if (Right.uge(LeftBits)) {
Richard Trieue4a19fb2011-09-06 21:21:28 +00006403 S.DiagRuntimeBehavior(Loc, RHS.get(),
Ted Kremenek26bbc3d2011-03-01 19:13:22 +00006404 S.PDiag(diag::warn_shift_gt_typewidth)
Richard Trieue4a19fb2011-09-06 21:21:28 +00006405 << RHS.get()->getSourceRange());
Chandler Carruth4c6fdca2011-02-23 23:34:11 +00006406 return;
6407 }
6408 if (Opc != BO_Shl)
6409 return;
6410
6411 // When left shifting an ICE which is signed, we can check for overflow which
6412 // according to C++ has undefined behavior ([expr.shift] 5.8/2). Unsigned
6413 // integers have defined behavior modulo one more than the maximum value
6414 // representable in the result type, so never warn for those.
6415 llvm::APSInt Left;
Richard Trieue4a19fb2011-09-06 21:21:28 +00006416 if (LHS.get()->isValueDependent() ||
6417 !LHS.get()->isIntegerConstantExpr(Left, S.Context) ||
6418 LHSType->hasUnsignedIntegerRepresentation())
Chandler Carruth4c6fdca2011-02-23 23:34:11 +00006419 return;
6420 llvm::APInt ResultBits =
6421 static_cast<llvm::APInt&>(Right) + Left.getMinSignedBits();
6422 if (LeftBits.uge(ResultBits))
6423 return;
6424 llvm::APSInt Result = Left.extend(ResultBits.getLimitedValue());
6425 Result = Result.shl(Right);
6426
Ted Kremenek70f05fd2011-06-15 00:54:52 +00006427 // Print the bit representation of the signed integer as an unsigned
6428 // hexadecimal number.
Dylan Noblesmith2c1dd272012-02-05 02:13:05 +00006429 SmallString<40> HexResult;
Ted Kremenek70f05fd2011-06-15 00:54:52 +00006430 Result.toString(HexResult, 16, /*Signed =*/false, /*Literal =*/true);
6431
Chandler Carruth4c6fdca2011-02-23 23:34:11 +00006432 // If we are only missing a sign bit, this is less likely to result in actual
6433 // bugs -- if the result is cast back to an unsigned type, it will have the
6434 // expected value. Thus we place this behind a different warning that can be
6435 // turned off separately if needed.
6436 if (LeftBits == ResultBits - 1) {
Ted Kremenek70f05fd2011-06-15 00:54:52 +00006437 S.Diag(Loc, diag::warn_shift_result_sets_sign_bit)
Richard Trieue4a19fb2011-09-06 21:21:28 +00006438 << HexResult.str() << LHSType
6439 << LHS.get()->getSourceRange() << RHS.get()->getSourceRange();
Chandler Carruth4c6fdca2011-02-23 23:34:11 +00006440 return;
6441 }
6442
6443 S.Diag(Loc, diag::warn_shift_result_gt_typewidth)
Richard Trieue4a19fb2011-09-06 21:21:28 +00006444 << HexResult.str() << Result.getMinSignedBits() << LHSType
6445 << Left.getBitWidth() << LHS.get()->getSourceRange()
6446 << RHS.get()->getSourceRange();
Chandler Carruth4c6fdca2011-02-23 23:34:11 +00006447}
6448
Chris Lattner2a3569b2008-04-07 05:30:13 +00006449// C99 6.5.7
Richard Trieue4a19fb2011-09-06 21:21:28 +00006450QualType Sema::CheckShiftOperands(ExprResult &LHS, ExprResult &RHS,
Richard Trieucfc491d2011-08-02 04:35:43 +00006451 SourceLocation Loc, unsigned Opc,
Richard Trieuba63ce62011-09-09 01:45:06 +00006452 bool IsCompAssign) {
Richard Trieuf8916e12011-09-16 00:53:10 +00006453 checkArithmeticNull(*this, LHS, RHS, Loc, /*isCompare=*/false);
6454
Chris Lattner5c11c412007-12-12 05:47:28 +00006455 // C99 6.5.7p2: Each of the operands shall have integer type.
Richard Trieue4a19fb2011-09-06 21:21:28 +00006456 if (!LHS.get()->getType()->hasIntegerRepresentation() ||
6457 !RHS.get()->getType()->hasIntegerRepresentation())
6458 return InvalidOperands(Loc, LHS, RHS);
Mike Stump4e1f26a2009-02-19 03:04:26 +00006459
Douglas Gregor0bf31402010-10-08 23:50:27 +00006460 // C++0x: Don't allow scoped enums. FIXME: Use something better than
6461 // hasIntegerRepresentation() above instead of this.
Richard Trieue4a19fb2011-09-06 21:21:28 +00006462 if (isScopedEnumerationType(LHS.get()->getType()) ||
6463 isScopedEnumerationType(RHS.get()->getType())) {
6464 return InvalidOperands(Loc, LHS, RHS);
Douglas Gregor0bf31402010-10-08 23:50:27 +00006465 }
6466
Nate Begemane46ee9a2009-10-25 02:26:48 +00006467 // Vector shifts promote their scalar inputs to vector type.
Richard Trieue4a19fb2011-09-06 21:21:28 +00006468 if (LHS.get()->getType()->isVectorType() ||
6469 RHS.get()->getType()->isVectorType())
Richard Trieuba63ce62011-09-09 01:45:06 +00006470 return CheckVectorOperands(LHS, RHS, Loc, IsCompAssign);
Nate Begemane46ee9a2009-10-25 02:26:48 +00006471
Chris Lattner5c11c412007-12-12 05:47:28 +00006472 // Shifts don't perform usual arithmetic conversions, they just do integer
6473 // promotions on each operand. C99 6.5.7p3
Eli Friedman8b7b1b12009-03-28 01:22:36 +00006474
John McCall57cdd882010-12-16 19:28:59 +00006475 // For the LHS, do usual unary conversions, but then reset them away
6476 // if this is a compound assignment.
Richard Trieue4a19fb2011-09-06 21:21:28 +00006477 ExprResult OldLHS = LHS;
6478 LHS = UsualUnaryConversions(LHS.take());
6479 if (LHS.isInvalid())
John Wiegley01296292011-04-08 18:41:53 +00006480 return QualType();
Richard Trieue4a19fb2011-09-06 21:21:28 +00006481 QualType LHSType = LHS.get()->getType();
Richard Trieuba63ce62011-09-09 01:45:06 +00006482 if (IsCompAssign) LHS = OldLHS;
John McCall57cdd882010-12-16 19:28:59 +00006483
6484 // The RHS is simpler.
Richard Trieue4a19fb2011-09-06 21:21:28 +00006485 RHS = UsualUnaryConversions(RHS.take());
6486 if (RHS.isInvalid())
John Wiegley01296292011-04-08 18:41:53 +00006487 return QualType();
Mike Stump4e1f26a2009-02-19 03:04:26 +00006488
Ryan Flynnf53fab82009-08-07 16:20:20 +00006489 // Sanity-check shift operands
Richard Trieue4a19fb2011-09-06 21:21:28 +00006490 DiagnoseBadShiftValues(*this, LHS, RHS, Loc, Opc, LHSType);
Ryan Flynnf53fab82009-08-07 16:20:20 +00006491
Chris Lattner5c11c412007-12-12 05:47:28 +00006492 // "The type of the result is that of the promoted left operand."
Richard Trieue4a19fb2011-09-06 21:21:28 +00006493 return LHSType;
Steve Naroff26c8ea52007-03-21 21:08:52 +00006494}
6495
Chandler Carruth17773fc2010-07-10 12:30:03 +00006496static bool IsWithinTemplateSpecialization(Decl *D) {
6497 if (DeclContext *DC = D->getDeclContext()) {
6498 if (isa<ClassTemplateSpecializationDecl>(DC))
6499 return true;
6500 if (FunctionDecl *FD = dyn_cast<FunctionDecl>(DC))
6501 return FD->isFunctionTemplateSpecialization();
6502 }
6503 return false;
6504}
6505
Richard Trieueea56f72011-09-02 03:48:46 +00006506/// If two different enums are compared, raise a warning.
Richard Trieu1762d7c2011-09-06 21:27:33 +00006507static void checkEnumComparison(Sema &S, SourceLocation Loc, ExprResult &LHS,
6508 ExprResult &RHS) {
6509 QualType LHSStrippedType = LHS.get()->IgnoreParenImpCasts()->getType();
6510 QualType RHSStrippedType = RHS.get()->IgnoreParenImpCasts()->getType();
Richard Trieueea56f72011-09-02 03:48:46 +00006511
6512 const EnumType *LHSEnumType = LHSStrippedType->getAs<EnumType>();
6513 if (!LHSEnumType)
6514 return;
6515 const EnumType *RHSEnumType = RHSStrippedType->getAs<EnumType>();
6516 if (!RHSEnumType)
6517 return;
6518
6519 // Ignore anonymous enums.
6520 if (!LHSEnumType->getDecl()->getIdentifier())
6521 return;
6522 if (!RHSEnumType->getDecl()->getIdentifier())
6523 return;
6524
6525 if (S.Context.hasSameUnqualifiedType(LHSStrippedType, RHSStrippedType))
6526 return;
6527
6528 S.Diag(Loc, diag::warn_comparison_of_mixed_enum_types)
6529 << LHSStrippedType << RHSStrippedType
Richard Trieu1762d7c2011-09-06 21:27:33 +00006530 << LHS.get()->getSourceRange() << RHS.get()->getSourceRange();
Richard Trieueea56f72011-09-02 03:48:46 +00006531}
6532
Richard Trieudd82a5c2011-09-02 02:55:45 +00006533/// \brief Diagnose bad pointer comparisons.
6534static void diagnoseDistinctPointerComparison(Sema &S, SourceLocation Loc,
Richard Trieu1762d7c2011-09-06 21:27:33 +00006535 ExprResult &LHS, ExprResult &RHS,
Richard Trieuba63ce62011-09-09 01:45:06 +00006536 bool IsError) {
6537 S.Diag(Loc, IsError ? diag::err_typecheck_comparison_of_distinct_pointers
Richard Trieudd82a5c2011-09-02 02:55:45 +00006538 : diag::ext_typecheck_comparison_of_distinct_pointers)
Richard Trieu1762d7c2011-09-06 21:27:33 +00006539 << LHS.get()->getType() << RHS.get()->getType()
6540 << LHS.get()->getSourceRange() << RHS.get()->getSourceRange();
Richard Trieudd82a5c2011-09-02 02:55:45 +00006541}
6542
6543/// \brief Returns false if the pointers are converted to a composite type,
6544/// true otherwise.
6545static bool convertPointersToCompositeType(Sema &S, SourceLocation Loc,
Richard Trieu1762d7c2011-09-06 21:27:33 +00006546 ExprResult &LHS, ExprResult &RHS) {
Richard Trieudd82a5c2011-09-02 02:55:45 +00006547 // C++ [expr.rel]p2:
6548 // [...] Pointer conversions (4.10) and qualification
6549 // conversions (4.4) are performed on pointer operands (or on
6550 // a pointer operand and a null pointer constant) to bring
6551 // them to their composite pointer type. [...]
6552 //
6553 // C++ [expr.eq]p1 uses the same notion for (in)equality
6554 // comparisons of pointers.
6555
6556 // C++ [expr.eq]p2:
6557 // In addition, pointers to members can be compared, or a pointer to
6558 // member and a null pointer constant. Pointer to member conversions
6559 // (4.11) and qualification conversions (4.4) are performed to bring
6560 // them to a common type. If one operand is a null pointer constant,
6561 // the common type is the type of the other operand. Otherwise, the
6562 // common type is a pointer to member type similar (4.4) to the type
6563 // of one of the operands, with a cv-qualification signature (4.4)
6564 // that is the union of the cv-qualification signatures of the operand
6565 // types.
6566
Richard Trieu1762d7c2011-09-06 21:27:33 +00006567 QualType LHSType = LHS.get()->getType();
6568 QualType RHSType = RHS.get()->getType();
6569 assert((LHSType->isPointerType() && RHSType->isPointerType()) ||
6570 (LHSType->isMemberPointerType() && RHSType->isMemberPointerType()));
Richard Trieudd82a5c2011-09-02 02:55:45 +00006571
6572 bool NonStandardCompositeType = false;
Richard Trieu48277e52011-09-02 21:44:27 +00006573 bool *BoolPtr = S.isSFINAEContext() ? 0 : &NonStandardCompositeType;
Richard Trieu1762d7c2011-09-06 21:27:33 +00006574 QualType T = S.FindCompositePointerType(Loc, LHS, RHS, BoolPtr);
Richard Trieudd82a5c2011-09-02 02:55:45 +00006575 if (T.isNull()) {
Richard Trieu1762d7c2011-09-06 21:27:33 +00006576 diagnoseDistinctPointerComparison(S, Loc, LHS, RHS, /*isError*/true);
Richard Trieudd82a5c2011-09-02 02:55:45 +00006577 return true;
6578 }
6579
6580 if (NonStandardCompositeType)
6581 S.Diag(Loc, diag::ext_typecheck_comparison_of_distinct_pointers_nonstandard)
Richard Trieu1762d7c2011-09-06 21:27:33 +00006582 << LHSType << RHSType << T << LHS.get()->getSourceRange()
6583 << RHS.get()->getSourceRange();
Richard Trieudd82a5c2011-09-02 02:55:45 +00006584
Richard Trieu1762d7c2011-09-06 21:27:33 +00006585 LHS = S.ImpCastExprToType(LHS.take(), T, CK_BitCast);
6586 RHS = S.ImpCastExprToType(RHS.take(), T, CK_BitCast);
Richard Trieudd82a5c2011-09-02 02:55:45 +00006587 return false;
6588}
6589
6590static void diagnoseFunctionPointerToVoidComparison(Sema &S, SourceLocation Loc,
Richard Trieu1762d7c2011-09-06 21:27:33 +00006591 ExprResult &LHS,
6592 ExprResult &RHS,
Richard Trieuba63ce62011-09-09 01:45:06 +00006593 bool IsError) {
6594 S.Diag(Loc, IsError ? diag::err_typecheck_comparison_of_fptr_to_void
6595 : diag::ext_typecheck_comparison_of_fptr_to_void)
Richard Trieu1762d7c2011-09-06 21:27:33 +00006596 << LHS.get()->getType() << RHS.get()->getType()
6597 << LHS.get()->getSourceRange() << RHS.get()->getSourceRange();
Richard Trieudd82a5c2011-09-02 02:55:45 +00006598}
6599
Jordan Rosed49a33e2012-06-08 21:14:25 +00006600static bool isObjCObjectLiteral(ExprResult &E) {
6601 switch (E.get()->getStmtClass()) {
6602 case Stmt::ObjCArrayLiteralClass:
6603 case Stmt::ObjCDictionaryLiteralClass:
6604 case Stmt::ObjCStringLiteralClass:
6605 case Stmt::ObjCBoxedExprClass:
6606 return true;
6607 default:
6608 // Note that ObjCBoolLiteral is NOT an object literal!
6609 return false;
6610 }
6611}
6612
6613static DiagnosticBuilder diagnoseObjCLiteralComparison(Sema &S,
6614 SourceLocation Loc,
6615 ExprResult &LHS,
6616 ExprResult &RHS,
6617 bool CanFix = false) {
6618 Expr *Literal = (isObjCObjectLiteral(LHS) ? LHS : RHS).get();
6619
6620 unsigned LiteralKind;
6621 switch (Literal->getStmtClass()) {
6622 case Stmt::ObjCStringLiteralClass:
6623 // "string literal"
6624 LiteralKind = 0;
6625 break;
6626 case Stmt::ObjCArrayLiteralClass:
6627 // "array literal"
6628 LiteralKind = 1;
6629 break;
6630 case Stmt::ObjCDictionaryLiteralClass:
6631 // "dictionary literal"
6632 LiteralKind = 2;
6633 break;
6634 case Stmt::ObjCBoxedExprClass: {
6635 Expr *Inner = cast<ObjCBoxedExpr>(Literal)->getSubExpr();
6636 switch (Inner->getStmtClass()) {
6637 case Stmt::IntegerLiteralClass:
6638 case Stmt::FloatingLiteralClass:
6639 case Stmt::CharacterLiteralClass:
6640 case Stmt::ObjCBoolLiteralExprClass:
6641 case Stmt::CXXBoolLiteralExprClass:
6642 // "numeric literal"
6643 LiteralKind = 3;
6644 break;
6645 case Stmt::ImplicitCastExprClass: {
6646 CastKind CK = cast<CastExpr>(Inner)->getCastKind();
6647 // Boolean literals can be represented by implicit casts.
6648 if (CK == CK_IntegralToBoolean || CK == CK_IntegralCast) {
6649 LiteralKind = 3;
6650 break;
6651 }
6652 // FALLTHROUGH
6653 }
6654 default:
6655 // "boxed expression"
6656 LiteralKind = 4;
6657 break;
6658 }
6659 break;
6660 }
6661 default:
6662 llvm_unreachable("Unknown Objective-C object literal kind");
6663 }
6664
6665 return S.Diag(Loc, diag::err_objc_literal_comparison)
6666 << LiteralKind << CanFix << Literal->getSourceRange();
6667}
6668
6669static ExprResult fixObjCLiteralComparison(Sema &S, SourceLocation OpLoc,
6670 ExprResult &LHS,
6671 ExprResult &RHS,
6672 BinaryOperatorKind Op) {
6673 assert((Op == BO_EQ || Op == BO_NE) && "Cannot fix other operations.");
6674
6675 // Get the LHS object's interface type.
6676 QualType Type = LHS.get()->getType();
6677 QualType InterfaceType;
6678 if (const ObjCObjectPointerType *PTy = Type->getAs<ObjCObjectPointerType>()) {
6679 InterfaceType = PTy->getPointeeType();
6680 if (const ObjCObjectType *iQFaceTy =
6681 InterfaceType->getAsObjCQualifiedInterfaceType())
6682 InterfaceType = iQFaceTy->getBaseType();
6683 } else {
6684 // If this is not actually an Objective-C object, bail out.
6685 return ExprEmpty();
6686 }
6687
6688 // If the RHS isn't an Objective-C object, bail out.
6689 if (!RHS.get()->getType()->isObjCObjectPointerType())
6690 return ExprEmpty();
6691
6692 // Try to find the -isEqual: method.
6693 Selector IsEqualSel = S.NSAPIObj->getIsEqualSelector();
6694 ObjCMethodDecl *Method = S.LookupMethodInObjectType(IsEqualSel,
6695 InterfaceType,
6696 /*instance=*/true);
6697 bool ReceiverIsId = (Type->isObjCIdType() || Type->isObjCQualifiedIdType());
6698
6699 if (!Method && ReceiverIsId) {
6700 Method = S.LookupInstanceMethodInGlobalPool(IsEqualSel, SourceRange(),
6701 /*receiverId=*/true,
6702 /*warn=*/false);
6703 }
6704
6705 if (!Method)
6706 return ExprEmpty();
6707
6708 QualType T = Method->param_begin()[0]->getType();
6709 if (!T->isObjCObjectPointerType())
6710 return ExprEmpty();
6711
6712 QualType R = Method->getResultType();
6713 if (!R->isScalarType())
6714 return ExprEmpty();
6715
6716 // At this point we know we have a good -isEqual: method.
6717 // Emit the diagnostic and fixit.
6718 DiagnosticBuilder Diag = diagnoseObjCLiteralComparison(S, OpLoc,
6719 LHS, RHS, true);
6720
6721 Expr *LHSExpr = LHS.take();
6722 Expr *RHSExpr = RHS.take();
6723
6724 SourceLocation Start = LHSExpr->getLocStart();
6725 SourceLocation End = S.PP.getLocForEndOfToken(RHSExpr->getLocEnd());
6726 SourceRange OpRange(OpLoc, S.PP.getLocForEndOfToken(OpLoc));
6727
6728 Diag << FixItHint::CreateInsertion(Start, Op == BO_EQ ? "[" : "![")
6729 << FixItHint::CreateReplacement(OpRange, "isEqual:")
6730 << FixItHint::CreateInsertion(End, "]");
6731
6732 // Finally, build the call to -isEqual: (and possible logical not).
6733 ExprResult Call = S.BuildInstanceMessage(LHSExpr, LHSExpr->getType(),
6734 /*SuperLoc=*/SourceLocation(),
6735 IsEqualSel, Method,
6736 OpLoc, OpLoc, OpLoc,
6737 MultiExprArg(S, &RHSExpr, 1),
6738 /*isImplicit=*/false);
6739
6740 ExprResult CallCond = S.CheckBooleanCondition(Call.get(), OpLoc);
6741
6742 if (Op == BO_NE)
6743 return S.CreateBuiltinUnaryOp(OpLoc, UO_LNot, CallCond.get());
6744 return CallCond;
6745}
6746
Douglas Gregor5b07c7e2009-05-04 06:07:12 +00006747// C99 6.5.8, C++ [expr.rel]
Richard Trieub80728f2011-09-06 21:43:51 +00006748QualType Sema::CheckCompareOperands(ExprResult &LHS, ExprResult &RHS,
Richard Trieucfc491d2011-08-02 04:35:43 +00006749 SourceLocation Loc, unsigned OpaqueOpc,
Richard Trieuba63ce62011-09-09 01:45:06 +00006750 bool IsRelational) {
Richard Trieuf8916e12011-09-16 00:53:10 +00006751 checkArithmeticNull(*this, LHS, RHS, Loc, /*isCompare=*/true);
6752
John McCalle3027922010-08-25 11:45:40 +00006753 BinaryOperatorKind Opc = (BinaryOperatorKind) OpaqueOpc;
Douglas Gregor7a5bc762009-04-06 18:45:53 +00006754
Chris Lattner9a152e22009-12-05 05:40:13 +00006755 // Handle vector comparisons separately.
Richard Trieub80728f2011-09-06 21:43:51 +00006756 if (LHS.get()->getType()->isVectorType() ||
6757 RHS.get()->getType()->isVectorType())
Richard Trieuba63ce62011-09-09 01:45:06 +00006758 return CheckVectorCompareOperands(LHS, RHS, Loc, IsRelational);
Mike Stump4e1f26a2009-02-19 03:04:26 +00006759
Richard Trieub80728f2011-09-06 21:43:51 +00006760 QualType LHSType = LHS.get()->getType();
6761 QualType RHSType = RHS.get()->getType();
Benjamin Kramera66aaa92011-09-03 08:46:20 +00006762
Richard Trieub80728f2011-09-06 21:43:51 +00006763 Expr *LHSStripped = LHS.get()->IgnoreParenImpCasts();
6764 Expr *RHSStripped = RHS.get()->IgnoreParenImpCasts();
Chandler Carruth712563b2011-02-17 08:37:06 +00006765
Richard Trieub80728f2011-09-06 21:43:51 +00006766 checkEnumComparison(*this, Loc, LHS, RHS);
Chandler Carruth712563b2011-02-17 08:37:06 +00006767
Richard Trieub80728f2011-09-06 21:43:51 +00006768 if (!LHSType->hasFloatingRepresentation() &&
Richard Trieuba63ce62011-09-09 01:45:06 +00006769 !(LHSType->isBlockPointerType() && IsRelational) &&
Richard Trieub80728f2011-09-06 21:43:51 +00006770 !LHS.get()->getLocStart().isMacroID() &&
6771 !RHS.get()->getLocStart().isMacroID()) {
Chris Lattner222b8bd2009-03-08 19:39:53 +00006772 // For non-floating point types, check for self-comparisons of the form
6773 // x == x, x != x, x < x, etc. These always evaluate to a constant, and
6774 // often indicate logic errors in the program.
Chandler Carruth65a38182010-07-12 06:23:38 +00006775 //
6776 // NOTE: Don't warn about comparison expressions resulting from macro
6777 // expansion. Also don't warn about comparisons which are only self
6778 // comparisons within a template specialization. The warnings should catch
6779 // obvious cases in the definition of the template anyways. The idea is to
6780 // warn when the typed comparison operator will always evaluate to the same
6781 // result.
Chandler Carruth17773fc2010-07-10 12:30:03 +00006782 if (DeclRefExpr* DRL = dyn_cast<DeclRefExpr>(LHSStripped)) {
Douglas Gregorec170db2010-06-08 19:50:34 +00006783 if (DeclRefExpr* DRR = dyn_cast<DeclRefExpr>(RHSStripped)) {
Ted Kremenek853734e2010-09-16 00:03:01 +00006784 if (DRL->getDecl() == DRR->getDecl() &&
Chandler Carruth17773fc2010-07-10 12:30:03 +00006785 !IsWithinTemplateSpecialization(DRL->getDecl())) {
Ted Kremenek3427fac2011-02-23 01:52:04 +00006786 DiagRuntimeBehavior(Loc, 0, PDiag(diag::warn_comparison_always)
Douglas Gregorec170db2010-06-08 19:50:34 +00006787 << 0 // self-
John McCalle3027922010-08-25 11:45:40 +00006788 << (Opc == BO_EQ
6789 || Opc == BO_LE
6790 || Opc == BO_GE));
Richard Trieub80728f2011-09-06 21:43:51 +00006791 } else if (LHSType->isArrayType() && RHSType->isArrayType() &&
Douglas Gregorec170db2010-06-08 19:50:34 +00006792 !DRL->getDecl()->getType()->isReferenceType() &&
6793 !DRR->getDecl()->getType()->isReferenceType()) {
6794 // what is it always going to eval to?
6795 char always_evals_to;
6796 switch(Opc) {
John McCalle3027922010-08-25 11:45:40 +00006797 case BO_EQ: // e.g. array1 == array2
Douglas Gregorec170db2010-06-08 19:50:34 +00006798 always_evals_to = 0; // false
6799 break;
John McCalle3027922010-08-25 11:45:40 +00006800 case BO_NE: // e.g. array1 != array2
Douglas Gregorec170db2010-06-08 19:50:34 +00006801 always_evals_to = 1; // true
6802 break;
6803 default:
6804 // best we can say is 'a constant'
6805 always_evals_to = 2; // e.g. array1 <= array2
6806 break;
6807 }
Ted Kremenek3427fac2011-02-23 01:52:04 +00006808 DiagRuntimeBehavior(Loc, 0, PDiag(diag::warn_comparison_always)
Douglas Gregorec170db2010-06-08 19:50:34 +00006809 << 1 // array
6810 << always_evals_to);
6811 }
6812 }
Chandler Carruth17773fc2010-07-10 12:30:03 +00006813 }
Mike Stump11289f42009-09-09 15:08:12 +00006814
Chris Lattner222b8bd2009-03-08 19:39:53 +00006815 if (isa<CastExpr>(LHSStripped))
6816 LHSStripped = LHSStripped->IgnoreParenCasts();
6817 if (isa<CastExpr>(RHSStripped))
6818 RHSStripped = RHSStripped->IgnoreParenCasts();
Mike Stump11289f42009-09-09 15:08:12 +00006819
Chris Lattner222b8bd2009-03-08 19:39:53 +00006820 // Warn about comparisons against a string constant (unless the other
6821 // operand is null), the user probably wants strcmp.
Douglas Gregor7a5bc762009-04-06 18:45:53 +00006822 Expr *literalString = 0;
6823 Expr *literalStringStripped = 0;
Chris Lattner222b8bd2009-03-08 19:39:53 +00006824 if ((isa<StringLiteral>(LHSStripped) || isa<ObjCEncodeExpr>(LHSStripped)) &&
Kovarththanan Rajaratnamba2c6522010-03-13 10:17:05 +00006825 !RHSStripped->isNullPointerConstant(Context,
Douglas Gregor56751b52009-09-25 04:25:58 +00006826 Expr::NPC_ValueDependentIsNull)) {
Richard Trieub80728f2011-09-06 21:43:51 +00006827 literalString = LHS.get();
Douglas Gregor7a5bc762009-04-06 18:45:53 +00006828 literalStringStripped = LHSStripped;
Mike Stump12b8ce12009-08-04 21:02:39 +00006829 } else if ((isa<StringLiteral>(RHSStripped) ||
6830 isa<ObjCEncodeExpr>(RHSStripped)) &&
Kovarththanan Rajaratnamba2c6522010-03-13 10:17:05 +00006831 !LHSStripped->isNullPointerConstant(Context,
Douglas Gregor56751b52009-09-25 04:25:58 +00006832 Expr::NPC_ValueDependentIsNull)) {
Richard Trieub80728f2011-09-06 21:43:51 +00006833 literalString = RHS.get();
Douglas Gregor7a5bc762009-04-06 18:45:53 +00006834 literalStringStripped = RHSStripped;
6835 }
6836
6837 if (literalString) {
6838 std::string resultComparison;
6839 switch (Opc) {
John McCalle3027922010-08-25 11:45:40 +00006840 case BO_LT: resultComparison = ") < 0"; break;
6841 case BO_GT: resultComparison = ") > 0"; break;
6842 case BO_LE: resultComparison = ") <= 0"; break;
6843 case BO_GE: resultComparison = ") >= 0"; break;
6844 case BO_EQ: resultComparison = ") == 0"; break;
6845 case BO_NE: resultComparison = ") != 0"; break;
David Blaikie83d382b2011-09-23 05:06:16 +00006846 default: llvm_unreachable("Invalid comparison operator");
Douglas Gregor7a5bc762009-04-06 18:45:53 +00006847 }
Kovarththanan Rajaratnamba2c6522010-03-13 10:17:05 +00006848
Ted Kremenek3427fac2011-02-23 01:52:04 +00006849 DiagRuntimeBehavior(Loc, 0,
Douglas Gregor49862b82010-01-12 23:18:54 +00006850 PDiag(diag::warn_stringcompare)
6851 << isa<ObjCEncodeExpr>(literalStringStripped)
Ted Kremenek800b66b2010-04-09 20:26:53 +00006852 << literalString->getSourceRange());
Douglas Gregor7a5bc762009-04-06 18:45:53 +00006853 }
Ted Kremeneke451eae2007-10-29 16:58:49 +00006854 }
Mike Stump4e1f26a2009-02-19 03:04:26 +00006855
Douglas Gregorec170db2010-06-08 19:50:34 +00006856 // C99 6.5.8p3 / C99 6.5.9p4
Richard Trieub80728f2011-09-06 21:43:51 +00006857 if (LHS.get()->getType()->isArithmeticType() &&
6858 RHS.get()->getType()->isArithmeticType()) {
6859 UsualArithmeticConversions(LHS, RHS);
6860 if (LHS.isInvalid() || RHS.isInvalid())
John Wiegley01296292011-04-08 18:41:53 +00006861 return QualType();
6862 }
Douglas Gregorec170db2010-06-08 19:50:34 +00006863 else {
Richard Trieub80728f2011-09-06 21:43:51 +00006864 LHS = UsualUnaryConversions(LHS.take());
6865 if (LHS.isInvalid())
John Wiegley01296292011-04-08 18:41:53 +00006866 return QualType();
6867
Richard Trieub80728f2011-09-06 21:43:51 +00006868 RHS = UsualUnaryConversions(RHS.take());
6869 if (RHS.isInvalid())
John Wiegley01296292011-04-08 18:41:53 +00006870 return QualType();
Douglas Gregorec170db2010-06-08 19:50:34 +00006871 }
6872
Richard Trieub80728f2011-09-06 21:43:51 +00006873 LHSType = LHS.get()->getType();
6874 RHSType = RHS.get()->getType();
Douglas Gregorec170db2010-06-08 19:50:34 +00006875
Douglas Gregorca63811b2008-11-19 03:25:36 +00006876 // The result of comparisons is 'bool' in C++, 'int' in C.
Argyrios Kyrtzidis1bdd6882011-02-18 20:55:15 +00006877 QualType ResultTy = Context.getLogicalOperationType();
Douglas Gregorca63811b2008-11-19 03:25:36 +00006878
Richard Trieuba63ce62011-09-09 01:45:06 +00006879 if (IsRelational) {
Richard Trieub80728f2011-09-06 21:43:51 +00006880 if (LHSType->isRealType() && RHSType->isRealType())
Douglas Gregorca63811b2008-11-19 03:25:36 +00006881 return ResultTy;
Chris Lattnerb620c342007-08-26 01:18:55 +00006882 } else {
Ted Kremeneke2763b02007-10-29 17:13:39 +00006883 // Check for comparisons of floating point operands using != and ==.
Richard Trieub80728f2011-09-06 21:43:51 +00006884 if (LHSType->hasFloatingRepresentation())
6885 CheckFloatComparison(Loc, LHS.get(), RHS.get());
Mike Stump4e1f26a2009-02-19 03:04:26 +00006886
Richard Trieub80728f2011-09-06 21:43:51 +00006887 if (LHSType->isArithmeticType() && RHSType->isArithmeticType())
Douglas Gregorca63811b2008-11-19 03:25:36 +00006888 return ResultTy;
Chris Lattnerb620c342007-08-26 01:18:55 +00006889 }
Mike Stump4e1f26a2009-02-19 03:04:26 +00006890
Richard Trieub80728f2011-09-06 21:43:51 +00006891 bool LHSIsNull = LHS.get()->isNullPointerConstant(Context,
Douglas Gregor56751b52009-09-25 04:25:58 +00006892 Expr::NPC_ValueDependentIsNull);
Richard Trieub80728f2011-09-06 21:43:51 +00006893 bool RHSIsNull = RHS.get()->isNullPointerConstant(Context,
Douglas Gregor56751b52009-09-25 04:25:58 +00006894 Expr::NPC_ValueDependentIsNull);
Mike Stump4e1f26a2009-02-19 03:04:26 +00006895
Douglas Gregorf267edd2010-06-15 21:38:40 +00006896 // All of the following pointer-related warnings are GCC extensions, except
6897 // when handling null pointer constants.
Richard Trieub80728f2011-09-06 21:43:51 +00006898 if (LHSType->isPointerType() && RHSType->isPointerType()) { // C99 6.5.8p2
Chris Lattner3a0702e2008-04-03 05:07:25 +00006899 QualType LCanPointeeTy =
John McCall9320b872011-09-09 05:25:32 +00006900 LHSType->castAs<PointerType>()->getPointeeType().getCanonicalType();
Chris Lattner3a0702e2008-04-03 05:07:25 +00006901 QualType RCanPointeeTy =
John McCall9320b872011-09-09 05:25:32 +00006902 RHSType->castAs<PointerType>()->getPointeeType().getCanonicalType();
Mike Stump4e1f26a2009-02-19 03:04:26 +00006903
David Blaikiebbafb8a2012-03-11 07:00:24 +00006904 if (getLangOpts().CPlusPlus) {
Eli Friedman16c209612009-08-23 00:27:47 +00006905 if (LCanPointeeTy == RCanPointeeTy)
6906 return ResultTy;
Richard Trieuba63ce62011-09-09 01:45:06 +00006907 if (!IsRelational &&
Fariborz Jahanianffc420c2009-12-21 18:19:17 +00006908 (LCanPointeeTy->isVoidType() || RCanPointeeTy->isVoidType())) {
6909 // Valid unless comparison between non-null pointer and function pointer
6910 // This is a gcc extension compatibility comparison.
Douglas Gregorf267edd2010-06-15 21:38:40 +00006911 // In a SFINAE context, we treat this as a hard error to maintain
6912 // conformance with the C++ standard.
Fariborz Jahanianffc420c2009-12-21 18:19:17 +00006913 if ((LCanPointeeTy->isFunctionType() || RCanPointeeTy->isFunctionType())
6914 && !LHSIsNull && !RHSIsNull) {
Richard Trieudd82a5c2011-09-02 02:55:45 +00006915 diagnoseFunctionPointerToVoidComparison(
Richard Trieub80728f2011-09-06 21:43:51 +00006916 *this, Loc, LHS, RHS, /*isError*/ isSFINAEContext());
Douglas Gregorf267edd2010-06-15 21:38:40 +00006917
6918 if (isSFINAEContext())
6919 return QualType();
6920
Richard Trieub80728f2011-09-06 21:43:51 +00006921 RHS = ImpCastExprToType(RHS.take(), LHSType, CK_BitCast);
Fariborz Jahanianffc420c2009-12-21 18:19:17 +00006922 return ResultTy;
6923 }
6924 }
Anders Carlssona95069c2010-11-04 03:17:43 +00006925
Richard Trieub80728f2011-09-06 21:43:51 +00006926 if (convertPointersToCompositeType(*this, Loc, LHS, RHS))
Douglas Gregor5b07c7e2009-05-04 06:07:12 +00006927 return QualType();
Richard Trieudd82a5c2011-09-02 02:55:45 +00006928 else
6929 return ResultTy;
Douglas Gregor5b07c7e2009-05-04 06:07:12 +00006930 }
Eli Friedman16c209612009-08-23 00:27:47 +00006931 // C99 6.5.9p2 and C99 6.5.8p2
6932 if (Context.typesAreCompatible(LCanPointeeTy.getUnqualifiedType(),
6933 RCanPointeeTy.getUnqualifiedType())) {
6934 // Valid unless a relational comparison of function pointers
Richard Trieuba63ce62011-09-09 01:45:06 +00006935 if (IsRelational && LCanPointeeTy->isFunctionType()) {
Eli Friedman16c209612009-08-23 00:27:47 +00006936 Diag(Loc, diag::ext_typecheck_ordered_comparison_of_function_pointers)
Richard Trieub80728f2011-09-06 21:43:51 +00006937 << LHSType << RHSType << LHS.get()->getSourceRange()
6938 << RHS.get()->getSourceRange();
Eli Friedman16c209612009-08-23 00:27:47 +00006939 }
Richard Trieuba63ce62011-09-09 01:45:06 +00006940 } else if (!IsRelational &&
Eli Friedman16c209612009-08-23 00:27:47 +00006941 (LCanPointeeTy->isVoidType() || RCanPointeeTy->isVoidType())) {
6942 // Valid unless comparison between non-null pointer and function pointer
6943 if ((LCanPointeeTy->isFunctionType() || RCanPointeeTy->isFunctionType())
Richard Trieudd82a5c2011-09-02 02:55:45 +00006944 && !LHSIsNull && !RHSIsNull)
Richard Trieub80728f2011-09-06 21:43:51 +00006945 diagnoseFunctionPointerToVoidComparison(*this, Loc, LHS, RHS,
Richard Trieudd82a5c2011-09-02 02:55:45 +00006946 /*isError*/false);
Eli Friedman16c209612009-08-23 00:27:47 +00006947 } else {
6948 // Invalid
Richard Trieub80728f2011-09-06 21:43:51 +00006949 diagnoseDistinctPointerComparison(*this, Loc, LHS, RHS, /*isError*/false);
Steve Naroff75c17232007-06-13 21:41:08 +00006950 }
John McCall7684dde2011-03-11 04:25:25 +00006951 if (LCanPointeeTy != RCanPointeeTy) {
6952 if (LHSIsNull && !RHSIsNull)
Richard Trieub80728f2011-09-06 21:43:51 +00006953 LHS = ImpCastExprToType(LHS.take(), RHSType, CK_BitCast);
John McCall7684dde2011-03-11 04:25:25 +00006954 else
Richard Trieub80728f2011-09-06 21:43:51 +00006955 RHS = ImpCastExprToType(RHS.take(), LHSType, CK_BitCast);
John McCall7684dde2011-03-11 04:25:25 +00006956 }
Douglas Gregorca63811b2008-11-19 03:25:36 +00006957 return ResultTy;
Steve Naroffcdee44c2007-08-16 21:48:38 +00006958 }
Mike Stump11289f42009-09-09 15:08:12 +00006959
David Blaikiebbafb8a2012-03-11 07:00:24 +00006960 if (getLangOpts().CPlusPlus) {
Anders Carlssona95069c2010-11-04 03:17:43 +00006961 // Comparison of nullptr_t with itself.
Richard Trieub80728f2011-09-06 21:43:51 +00006962 if (LHSType->isNullPtrType() && RHSType->isNullPtrType())
Anders Carlssona95069c2010-11-04 03:17:43 +00006963 return ResultTy;
6964
Mike Stump11289f42009-09-09 15:08:12 +00006965 // Comparison of pointers with null pointer constants and equality
Douglas Gregorb00b10e2009-08-24 17:42:35 +00006966 // comparisons of member pointers to null pointer constants.
Mike Stump11289f42009-09-09 15:08:12 +00006967 if (RHSIsNull &&
Richard Trieub80728f2011-09-06 21:43:51 +00006968 ((LHSType->isAnyPointerType() || LHSType->isNullPtrType()) ||
Richard Trieuba63ce62011-09-09 01:45:06 +00006969 (!IsRelational &&
Richard Trieub80728f2011-09-06 21:43:51 +00006970 (LHSType->isMemberPointerType() || LHSType->isBlockPointerType())))) {
6971 RHS = ImpCastExprToType(RHS.take(), LHSType,
6972 LHSType->isMemberPointerType()
John McCalle3027922010-08-25 11:45:40 +00006973 ? CK_NullToMemberPointer
John McCalle84af4e2010-11-13 01:35:44 +00006974 : CK_NullToPointer);
Sebastian Redl576fd422009-05-10 18:38:11 +00006975 return ResultTy;
6976 }
Douglas Gregorb00b10e2009-08-24 17:42:35 +00006977 if (LHSIsNull &&
Richard Trieub80728f2011-09-06 21:43:51 +00006978 ((RHSType->isAnyPointerType() || RHSType->isNullPtrType()) ||
Richard Trieuba63ce62011-09-09 01:45:06 +00006979 (!IsRelational &&
Richard Trieub80728f2011-09-06 21:43:51 +00006980 (RHSType->isMemberPointerType() || RHSType->isBlockPointerType())))) {
6981 LHS = ImpCastExprToType(LHS.take(), RHSType,
6982 RHSType->isMemberPointerType()
John McCalle3027922010-08-25 11:45:40 +00006983 ? CK_NullToMemberPointer
John McCalle84af4e2010-11-13 01:35:44 +00006984 : CK_NullToPointer);
Sebastian Redl576fd422009-05-10 18:38:11 +00006985 return ResultTy;
6986 }
Douglas Gregorb00b10e2009-08-24 17:42:35 +00006987
6988 // Comparison of member pointers.
Richard Trieuba63ce62011-09-09 01:45:06 +00006989 if (!IsRelational &&
Richard Trieub80728f2011-09-06 21:43:51 +00006990 LHSType->isMemberPointerType() && RHSType->isMemberPointerType()) {
6991 if (convertPointersToCompositeType(*this, Loc, LHS, RHS))
Douglas Gregorb00b10e2009-08-24 17:42:35 +00006992 return QualType();
Richard Trieudd82a5c2011-09-02 02:55:45 +00006993 else
6994 return ResultTy;
Douglas Gregorb00b10e2009-08-24 17:42:35 +00006995 }
Douglas Gregor48e6bbf2011-03-01 17:16:20 +00006996
6997 // Handle scoped enumeration types specifically, since they don't promote
6998 // to integers.
Richard Trieub80728f2011-09-06 21:43:51 +00006999 if (LHS.get()->getType()->isEnumeralType() &&
7000 Context.hasSameUnqualifiedType(LHS.get()->getType(),
7001 RHS.get()->getType()))
Douglas Gregor48e6bbf2011-03-01 17:16:20 +00007002 return ResultTy;
Sebastian Redl576fd422009-05-10 18:38:11 +00007003 }
Mike Stump11289f42009-09-09 15:08:12 +00007004
Steve Naroff081c7422008-09-04 15:10:53 +00007005 // Handle block pointer types.
Richard Trieuba63ce62011-09-09 01:45:06 +00007006 if (!IsRelational && LHSType->isBlockPointerType() &&
Richard Trieub80728f2011-09-06 21:43:51 +00007007 RHSType->isBlockPointerType()) {
John McCall9320b872011-09-09 05:25:32 +00007008 QualType lpointee = LHSType->castAs<BlockPointerType>()->getPointeeType();
7009 QualType rpointee = RHSType->castAs<BlockPointerType>()->getPointeeType();
Mike Stump4e1f26a2009-02-19 03:04:26 +00007010
Steve Naroff081c7422008-09-04 15:10:53 +00007011 if (!LHSIsNull && !RHSIsNull &&
Eli Friedmana6638ca2009-06-08 05:08:54 +00007012 !Context.typesAreCompatible(lpointee, rpointee)) {
Chris Lattner377d1f82008-11-18 22:52:51 +00007013 Diag(Loc, diag::err_typecheck_comparison_of_distinct_blocks)
Richard Trieub80728f2011-09-06 21:43:51 +00007014 << LHSType << RHSType << LHS.get()->getSourceRange()
7015 << RHS.get()->getSourceRange();
Steve Naroff081c7422008-09-04 15:10:53 +00007016 }
Richard Trieub80728f2011-09-06 21:43:51 +00007017 RHS = ImpCastExprToType(RHS.take(), LHSType, CK_BitCast);
Douglas Gregorca63811b2008-11-19 03:25:36 +00007018 return ResultTy;
Steve Naroff081c7422008-09-04 15:10:53 +00007019 }
John Wiegley01296292011-04-08 18:41:53 +00007020
Steve Naroffe18f94c2008-09-28 01:11:11 +00007021 // Allow block pointers to be compared with null pointer constants.
Richard Trieuba63ce62011-09-09 01:45:06 +00007022 if (!IsRelational
Richard Trieub80728f2011-09-06 21:43:51 +00007023 && ((LHSType->isBlockPointerType() && RHSType->isPointerType())
7024 || (LHSType->isPointerType() && RHSType->isBlockPointerType()))) {
Steve Naroffe18f94c2008-09-28 01:11:11 +00007025 if (!LHSIsNull && !RHSIsNull) {
Richard Trieub80728f2011-09-06 21:43:51 +00007026 if (!((RHSType->isPointerType() && RHSType->castAs<PointerType>()
Mike Stump1b821b42009-05-07 03:14:14 +00007027 ->getPointeeType()->isVoidType())
Richard Trieub80728f2011-09-06 21:43:51 +00007028 || (LHSType->isPointerType() && LHSType->castAs<PointerType>()
Mike Stump1b821b42009-05-07 03:14:14 +00007029 ->getPointeeType()->isVoidType())))
7030 Diag(Loc, diag::err_typecheck_comparison_of_distinct_blocks)
Richard Trieub80728f2011-09-06 21:43:51 +00007031 << LHSType << RHSType << LHS.get()->getSourceRange()
7032 << RHS.get()->getSourceRange();
Steve Naroffe18f94c2008-09-28 01:11:11 +00007033 }
John McCall7684dde2011-03-11 04:25:25 +00007034 if (LHSIsNull && !RHSIsNull)
John McCall9320b872011-09-09 05:25:32 +00007035 LHS = ImpCastExprToType(LHS.take(), RHSType,
7036 RHSType->isPointerType() ? CK_BitCast
7037 : CK_AnyPointerToBlockPointerCast);
John McCall7684dde2011-03-11 04:25:25 +00007038 else
John McCall9320b872011-09-09 05:25:32 +00007039 RHS = ImpCastExprToType(RHS.take(), LHSType,
7040 LHSType->isPointerType() ? CK_BitCast
7041 : CK_AnyPointerToBlockPointerCast);
Douglas Gregorca63811b2008-11-19 03:25:36 +00007042 return ResultTy;
Steve Naroffe18f94c2008-09-28 01:11:11 +00007043 }
Steve Naroff081c7422008-09-04 15:10:53 +00007044
Richard Trieub80728f2011-09-06 21:43:51 +00007045 if (LHSType->isObjCObjectPointerType() ||
7046 RHSType->isObjCObjectPointerType()) {
7047 const PointerType *LPT = LHSType->getAs<PointerType>();
7048 const PointerType *RPT = RHSType->getAs<PointerType>();
John McCall7684dde2011-03-11 04:25:25 +00007049 if (LPT || RPT) {
7050 bool LPtrToVoid = LPT ? LPT->getPointeeType()->isVoidType() : false;
7051 bool RPtrToVoid = RPT ? RPT->getPointeeType()->isVoidType() : false;
Mike Stump4e1f26a2009-02-19 03:04:26 +00007052
Steve Naroff753567f2008-11-17 19:49:16 +00007053 if (!LPtrToVoid && !RPtrToVoid &&
Richard Trieub80728f2011-09-06 21:43:51 +00007054 !Context.typesAreCompatible(LHSType, RHSType)) {
7055 diagnoseDistinctPointerComparison(*this, Loc, LHS, RHS,
Richard Trieudd82a5c2011-09-02 02:55:45 +00007056 /*isError*/false);
Steve Naroff1d4a9a32008-10-27 10:33:19 +00007057 }
John McCall7684dde2011-03-11 04:25:25 +00007058 if (LHSIsNull && !RHSIsNull)
John McCall9320b872011-09-09 05:25:32 +00007059 LHS = ImpCastExprToType(LHS.take(), RHSType,
7060 RPT ? CK_BitCast :CK_CPointerToObjCPointerCast);
John McCall7684dde2011-03-11 04:25:25 +00007061 else
John McCall9320b872011-09-09 05:25:32 +00007062 RHS = ImpCastExprToType(RHS.take(), LHSType,
7063 LPT ? CK_BitCast :CK_CPointerToObjCPointerCast);
Douglas Gregorca63811b2008-11-19 03:25:36 +00007064 return ResultTy;
Steve Naroffea54d9e2008-10-20 18:19:10 +00007065 }
Richard Trieub80728f2011-09-06 21:43:51 +00007066 if (LHSType->isObjCObjectPointerType() &&
7067 RHSType->isObjCObjectPointerType()) {
7068 if (!Context.areComparableObjCPointerTypes(LHSType, RHSType))
7069 diagnoseDistinctPointerComparison(*this, Loc, LHS, RHS,
Richard Trieudd82a5c2011-09-02 02:55:45 +00007070 /*isError*/false);
Jordan Rosed49a33e2012-06-08 21:14:25 +00007071 if (isObjCObjectLiteral(LHS) || isObjCObjectLiteral(RHS))
7072 diagnoseObjCLiteralComparison(*this, Loc, LHS, RHS);
7073
John McCall7684dde2011-03-11 04:25:25 +00007074 if (LHSIsNull && !RHSIsNull)
Richard Trieub80728f2011-09-06 21:43:51 +00007075 LHS = ImpCastExprToType(LHS.take(), RHSType, CK_BitCast);
John McCall7684dde2011-03-11 04:25:25 +00007076 else
Richard Trieub80728f2011-09-06 21:43:51 +00007077 RHS = ImpCastExprToType(RHS.take(), LHSType, CK_BitCast);
Douglas Gregorca63811b2008-11-19 03:25:36 +00007078 return ResultTy;
Steve Naroffb788d9b2008-06-03 14:04:54 +00007079 }
Fariborz Jahanian134cbef2007-12-20 01:06:58 +00007080 }
Richard Trieub80728f2011-09-06 21:43:51 +00007081 if ((LHSType->isAnyPointerType() && RHSType->isIntegerType()) ||
7082 (LHSType->isIntegerType() && RHSType->isAnyPointerType())) {
Chris Lattnerd99bd522009-08-23 00:03:44 +00007083 unsigned DiagID = 0;
Douglas Gregorf267edd2010-06-15 21:38:40 +00007084 bool isError = false;
Richard Trieub80728f2011-09-06 21:43:51 +00007085 if ((LHSIsNull && LHSType->isIntegerType()) ||
7086 (RHSIsNull && RHSType->isIntegerType())) {
David Blaikiebbafb8a2012-03-11 07:00:24 +00007087 if (IsRelational && !getLangOpts().CPlusPlus)
Chris Lattnerd99bd522009-08-23 00:03:44 +00007088 DiagID = diag::ext_typecheck_ordered_comparison_of_pointer_and_zero;
David Blaikiebbafb8a2012-03-11 07:00:24 +00007089 } else if (IsRelational && !getLangOpts().CPlusPlus)
Chris Lattnerd99bd522009-08-23 00:03:44 +00007090 DiagID = diag::ext_typecheck_ordered_comparison_of_pointer_integer;
David Blaikiebbafb8a2012-03-11 07:00:24 +00007091 else if (getLangOpts().CPlusPlus) {
Douglas Gregorf267edd2010-06-15 21:38:40 +00007092 DiagID = diag::err_typecheck_comparison_of_pointer_integer;
7093 isError = true;
7094 } else
Chris Lattnerd99bd522009-08-23 00:03:44 +00007095 DiagID = diag::ext_typecheck_comparison_of_pointer_integer;
Mike Stump11289f42009-09-09 15:08:12 +00007096
Chris Lattnerd99bd522009-08-23 00:03:44 +00007097 if (DiagID) {
Chris Lattnerf8344db2009-08-22 18:58:31 +00007098 Diag(Loc, DiagID)
Richard Trieub80728f2011-09-06 21:43:51 +00007099 << LHSType << RHSType << LHS.get()->getSourceRange()
7100 << RHS.get()->getSourceRange();
Douglas Gregorf267edd2010-06-15 21:38:40 +00007101 if (isError)
7102 return QualType();
Chris Lattnerf8344db2009-08-22 18:58:31 +00007103 }
Douglas Gregorf267edd2010-06-15 21:38:40 +00007104
Richard Trieub80728f2011-09-06 21:43:51 +00007105 if (LHSType->isIntegerType())
7106 LHS = ImpCastExprToType(LHS.take(), RHSType,
John McCalle84af4e2010-11-13 01:35:44 +00007107 LHSIsNull ? CK_NullToPointer : CK_IntegralToPointer);
Chris Lattnerd99bd522009-08-23 00:03:44 +00007108 else
Richard Trieub80728f2011-09-06 21:43:51 +00007109 RHS = ImpCastExprToType(RHS.take(), LHSType,
John McCalle84af4e2010-11-13 01:35:44 +00007110 RHSIsNull ? CK_NullToPointer : CK_IntegralToPointer);
Douglas Gregorca63811b2008-11-19 03:25:36 +00007111 return ResultTy;
Steve Naroff043d45d2007-05-15 02:32:35 +00007112 }
Douglas Gregorf267edd2010-06-15 21:38:40 +00007113
Steve Naroff4b191572008-09-04 16:56:14 +00007114 // Handle block pointers.
Richard Trieuba63ce62011-09-09 01:45:06 +00007115 if (!IsRelational && RHSIsNull
Richard Trieub80728f2011-09-06 21:43:51 +00007116 && LHSType->isBlockPointerType() && RHSType->isIntegerType()) {
7117 RHS = ImpCastExprToType(RHS.take(), LHSType, CK_NullToPointer);
Douglas Gregorca63811b2008-11-19 03:25:36 +00007118 return ResultTy;
Steve Naroff4b191572008-09-04 16:56:14 +00007119 }
Richard Trieuba63ce62011-09-09 01:45:06 +00007120 if (!IsRelational && LHSIsNull
Richard Trieub80728f2011-09-06 21:43:51 +00007121 && LHSType->isIntegerType() && RHSType->isBlockPointerType()) {
7122 LHS = ImpCastExprToType(LHS.take(), RHSType, CK_NullToPointer);
Douglas Gregorca63811b2008-11-19 03:25:36 +00007123 return ResultTy;
Steve Naroff4b191572008-09-04 16:56:14 +00007124 }
Douglas Gregor48e6bbf2011-03-01 17:16:20 +00007125
Richard Trieub80728f2011-09-06 21:43:51 +00007126 return InvalidOperands(Loc, LHS, RHS);
Steve Naroff26c8ea52007-03-21 21:08:52 +00007127}
7128
Tanya Lattner20248222012-01-16 21:02:28 +00007129
7130// Return a signed type that is of identical size and number of elements.
7131// For floating point vectors, return an integer type of identical size
7132// and number of elements.
7133QualType Sema::GetSignedVectorType(QualType V) {
7134 const VectorType *VTy = V->getAs<VectorType>();
7135 unsigned TypeSize = Context.getTypeSize(VTy->getElementType());
7136 if (TypeSize == Context.getTypeSize(Context.CharTy))
7137 return Context.getExtVectorType(Context.CharTy, VTy->getNumElements());
7138 else if (TypeSize == Context.getTypeSize(Context.ShortTy))
7139 return Context.getExtVectorType(Context.ShortTy, VTy->getNumElements());
7140 else if (TypeSize == Context.getTypeSize(Context.IntTy))
7141 return Context.getExtVectorType(Context.IntTy, VTy->getNumElements());
7142 else if (TypeSize == Context.getTypeSize(Context.LongTy))
7143 return Context.getExtVectorType(Context.LongTy, VTy->getNumElements());
7144 assert(TypeSize == Context.getTypeSize(Context.LongLongTy) &&
7145 "Unhandled vector element size in vector compare");
7146 return Context.getExtVectorType(Context.LongLongTy, VTy->getNumElements());
7147}
7148
Nate Begeman191a6b12008-07-14 18:02:46 +00007149/// CheckVectorCompareOperands - vector comparisons are a clang extension that
Mike Stump4e1f26a2009-02-19 03:04:26 +00007150/// operates on extended vector types. Instead of producing an IntTy result,
Nate Begeman191a6b12008-07-14 18:02:46 +00007151/// like a scalar comparison, a vector comparison produces a vector of integer
7152/// types.
Richard Trieubcce2f72011-09-07 01:19:57 +00007153QualType Sema::CheckVectorCompareOperands(ExprResult &LHS, ExprResult &RHS,
Chris Lattner326f7572008-11-18 01:30:42 +00007154 SourceLocation Loc,
Richard Trieuba63ce62011-09-09 01:45:06 +00007155 bool IsRelational) {
Nate Begeman191a6b12008-07-14 18:02:46 +00007156 // Check to make sure we're operating on vectors of the same type and width,
7157 // Allowing one side to be a scalar of element type.
Richard Trieubcce2f72011-09-07 01:19:57 +00007158 QualType vType = CheckVectorOperands(LHS, RHS, Loc, /*isCompAssign*/false);
Nate Begeman191a6b12008-07-14 18:02:46 +00007159 if (vType.isNull())
7160 return vType;
Mike Stump4e1f26a2009-02-19 03:04:26 +00007161
Richard Trieubcce2f72011-09-07 01:19:57 +00007162 QualType LHSType = LHS.get()->getType();
Mike Stump4e1f26a2009-02-19 03:04:26 +00007163
Anton Yartsev530deb92011-03-27 15:36:07 +00007164 // If AltiVec, the comparison results in a numeric type, i.e.
7165 // bool for C++, int for C
Anton Yartsev93900c72011-03-28 21:00:05 +00007166 if (vType->getAs<VectorType>()->getVectorKind() == VectorType::AltiVecVector)
Anton Yartsev530deb92011-03-27 15:36:07 +00007167 return Context.getLogicalOperationType();
7168
Nate Begeman191a6b12008-07-14 18:02:46 +00007169 // For non-floating point types, check for self-comparisons of the form
7170 // x == x, x != x, x < x, etc. These always evaluate to a constant, and
7171 // often indicate logic errors in the program.
Richard Trieubcce2f72011-09-07 01:19:57 +00007172 if (!LHSType->hasFloatingRepresentation()) {
Richard Smith508ebf32011-10-28 03:31:48 +00007173 if (DeclRefExpr* DRL
7174 = dyn_cast<DeclRefExpr>(LHS.get()->IgnoreParenImpCasts()))
7175 if (DeclRefExpr* DRR
7176 = dyn_cast<DeclRefExpr>(RHS.get()->IgnoreParenImpCasts()))
Nate Begeman191a6b12008-07-14 18:02:46 +00007177 if (DRL->getDecl() == DRR->getDecl())
Ted Kremenek3427fac2011-02-23 01:52:04 +00007178 DiagRuntimeBehavior(Loc, 0,
Douglas Gregorec170db2010-06-08 19:50:34 +00007179 PDiag(diag::warn_comparison_always)
7180 << 0 // self-
7181 << 2 // "a constant"
7182 );
Nate Begeman191a6b12008-07-14 18:02:46 +00007183 }
Mike Stump4e1f26a2009-02-19 03:04:26 +00007184
Nate Begeman191a6b12008-07-14 18:02:46 +00007185 // Check for comparisons of floating point operands using != and ==.
Richard Trieuba63ce62011-09-09 01:45:06 +00007186 if (!IsRelational && LHSType->hasFloatingRepresentation()) {
David Blaikieca043222012-01-16 05:16:03 +00007187 assert (RHS.get()->getType()->hasFloatingRepresentation());
Richard Trieubcce2f72011-09-07 01:19:57 +00007188 CheckFloatComparison(Loc, LHS.get(), RHS.get());
Nate Begeman191a6b12008-07-14 18:02:46 +00007189 }
Tanya Lattner20248222012-01-16 21:02:28 +00007190
7191 // Return a signed type for the vector.
7192 return GetSignedVectorType(LHSType);
7193}
Mike Stump4e1f26a2009-02-19 03:04:26 +00007194
Tanya Lattner3dd33b22012-01-19 01:16:16 +00007195QualType Sema::CheckVectorLogicalOperands(ExprResult &LHS, ExprResult &RHS,
7196 SourceLocation Loc) {
Tanya Lattner20248222012-01-16 21:02:28 +00007197 // Ensure that either both operands are of the same vector type, or
7198 // one operand is of a vector type and the other is of its element type.
7199 QualType vType = CheckVectorOperands(LHS, RHS, Loc, false);
7200 if (vType.isNull() || vType->isFloatingType())
7201 return InvalidOperands(Loc, LHS, RHS);
7202
7203 return GetSignedVectorType(LHS.get()->getType());
Nate Begeman191a6b12008-07-14 18:02:46 +00007204}
7205
Steve Naroff218bc2b2007-05-04 21:54:46 +00007206inline QualType Sema::CheckBitwiseOperands(
Richard Trieuba63ce62011-09-09 01:45:06 +00007207 ExprResult &LHS, ExprResult &RHS, SourceLocation Loc, bool IsCompAssign) {
Richard Trieuf8916e12011-09-16 00:53:10 +00007208 checkArithmeticNull(*this, LHS, RHS, Loc, /*isCompare=*/false);
7209
Richard Trieubcce2f72011-09-07 01:19:57 +00007210 if (LHS.get()->getType()->isVectorType() ||
7211 RHS.get()->getType()->isVectorType()) {
7212 if (LHS.get()->getType()->hasIntegerRepresentation() &&
7213 RHS.get()->getType()->hasIntegerRepresentation())
Richard Trieuba63ce62011-09-09 01:45:06 +00007214 return CheckVectorOperands(LHS, RHS, Loc, IsCompAssign);
Douglas Gregor5cc2c8b2010-07-23 15:58:24 +00007215
Richard Trieubcce2f72011-09-07 01:19:57 +00007216 return InvalidOperands(Loc, LHS, RHS);
Douglas Gregor5cc2c8b2010-07-23 15:58:24 +00007217 }
Steve Naroffb8ea4fb2007-07-13 23:32:42 +00007218
Richard Trieubcce2f72011-09-07 01:19:57 +00007219 ExprResult LHSResult = Owned(LHS), RHSResult = Owned(RHS);
7220 QualType compType = UsualArithmeticConversions(LHSResult, RHSResult,
Richard Trieuba63ce62011-09-09 01:45:06 +00007221 IsCompAssign);
Richard Trieubcce2f72011-09-07 01:19:57 +00007222 if (LHSResult.isInvalid() || RHSResult.isInvalid())
John Wiegley01296292011-04-08 18:41:53 +00007223 return QualType();
Richard Trieubcce2f72011-09-07 01:19:57 +00007224 LHS = LHSResult.take();
7225 RHS = RHSResult.take();
Mike Stump4e1f26a2009-02-19 03:04:26 +00007226
Eli Friedman93ee5ca2012-06-16 02:19:17 +00007227 if (!compType.isNull() && compType->isIntegralOrUnscopedEnumerationType())
Steve Naroffbe4c4d12007-08-24 19:07:16 +00007228 return compType;
Richard Trieubcce2f72011-09-07 01:19:57 +00007229 return InvalidOperands(Loc, LHS, RHS);
Steve Naroff26c8ea52007-03-21 21:08:52 +00007230}
7231
Steve Naroff218bc2b2007-05-04 21:54:46 +00007232inline QualType Sema::CheckLogicalOperands( // C99 6.5.[13,14]
Richard Trieubcce2f72011-09-07 01:19:57 +00007233 ExprResult &LHS, ExprResult &RHS, SourceLocation Loc, unsigned Opc) {
Chris Lattner8406c512010-07-13 19:41:32 +00007234
Tanya Lattner20248222012-01-16 21:02:28 +00007235 // Check vector operands differently.
7236 if (LHS.get()->getType()->isVectorType() || RHS.get()->getType()->isVectorType())
7237 return CheckVectorLogicalOperands(LHS, RHS, Loc);
7238
Chris Lattner8406c512010-07-13 19:41:32 +00007239 // Diagnose cases where the user write a logical and/or but probably meant a
7240 // bitwise one. We do this when the LHS is a non-bool integer and the RHS
7241 // is a constant.
Richard Trieubcce2f72011-09-07 01:19:57 +00007242 if (LHS.get()->getType()->isIntegerType() &&
7243 !LHS.get()->getType()->isBooleanType() &&
7244 RHS.get()->getType()->isIntegerType() && !RHS.get()->isValueDependent() &&
Richard Trieucfe39262011-07-15 00:00:51 +00007245 // Don't warn in macros or template instantiations.
7246 !Loc.isMacroID() && ActiveTemplateInstantiations.empty()) {
Chris Lattner938533d2010-07-24 01:10:11 +00007247 // If the RHS can be constant folded, and if it constant folds to something
7248 // that isn't 0 or 1 (which indicate a potential logical operation that
7249 // happened to fold to true/false) then warn.
Chandler Carruthe54ff6c2011-05-31 05:41:42 +00007250 // Parens on the RHS are ignored.
Richard Smith00ab3ae2011-10-16 23:01:09 +00007251 llvm::APSInt Result;
7252 if (RHS.get()->EvaluateAsInt(Result, Context))
David Blaikiebbafb8a2012-03-11 07:00:24 +00007253 if ((getLangOpts().Bool && !RHS.get()->getType()->isBooleanType()) ||
Richard Smith00ab3ae2011-10-16 23:01:09 +00007254 (Result != 0 && Result != 1)) {
Chandler Carruthe54ff6c2011-05-31 05:41:42 +00007255 Diag(Loc, diag::warn_logical_instead_of_bitwise)
Richard Trieubcce2f72011-09-07 01:19:57 +00007256 << RHS.get()->getSourceRange()
Matt Beaumont-Gay0a0ba9d2011-08-15 17:50:06 +00007257 << (Opc == BO_LAnd ? "&&" : "||");
7258 // Suggest replacing the logical operator with the bitwise version
7259 Diag(Loc, diag::note_logical_instead_of_bitwise_change_operator)
7260 << (Opc == BO_LAnd ? "&" : "|")
7261 << FixItHint::CreateReplacement(SourceRange(
7262 Loc, Lexer::getLocForEndOfToken(Loc, 0, getSourceManager(),
David Blaikiebbafb8a2012-03-11 07:00:24 +00007263 getLangOpts())),
Matt Beaumont-Gay0a0ba9d2011-08-15 17:50:06 +00007264 Opc == BO_LAnd ? "&" : "|");
7265 if (Opc == BO_LAnd)
7266 // Suggest replacing "Foo() && kNonZero" with "Foo()"
7267 Diag(Loc, diag::note_logical_instead_of_bitwise_remove_constant)
7268 << FixItHint::CreateRemoval(
7269 SourceRange(
Richard Trieubcce2f72011-09-07 01:19:57 +00007270 Lexer::getLocForEndOfToken(LHS.get()->getLocEnd(),
Matt Beaumont-Gay0a0ba9d2011-08-15 17:50:06 +00007271 0, getSourceManager(),
David Blaikiebbafb8a2012-03-11 07:00:24 +00007272 getLangOpts()),
Richard Trieubcce2f72011-09-07 01:19:57 +00007273 RHS.get()->getLocEnd()));
Matt Beaumont-Gay0a0ba9d2011-08-15 17:50:06 +00007274 }
Chris Lattner938533d2010-07-24 01:10:11 +00007275 }
Chris Lattner8406c512010-07-13 19:41:32 +00007276
David Blaikiebbafb8a2012-03-11 07:00:24 +00007277 if (!Context.getLangOpts().CPlusPlus) {
Richard Trieubcce2f72011-09-07 01:19:57 +00007278 LHS = UsualUnaryConversions(LHS.take());
7279 if (LHS.isInvalid())
John Wiegley01296292011-04-08 18:41:53 +00007280 return QualType();
Mike Stump4e1f26a2009-02-19 03:04:26 +00007281
Richard Trieubcce2f72011-09-07 01:19:57 +00007282 RHS = UsualUnaryConversions(RHS.take());
7283 if (RHS.isInvalid())
John Wiegley01296292011-04-08 18:41:53 +00007284 return QualType();
7285
Richard Trieubcce2f72011-09-07 01:19:57 +00007286 if (!LHS.get()->getType()->isScalarType() ||
7287 !RHS.get()->getType()->isScalarType())
7288 return InvalidOperands(Loc, LHS, RHS);
Kovarththanan Rajaratnamba2c6522010-03-13 10:17:05 +00007289
Anders Carlsson2e7bc112009-11-23 21:47:44 +00007290 return Context.IntTy;
Anders Carlsson35a99d92009-10-16 01:44:21 +00007291 }
Kovarththanan Rajaratnamba2c6522010-03-13 10:17:05 +00007292
John McCall4a2429a2010-06-04 00:29:51 +00007293 // The following is safe because we only use this method for
7294 // non-overloadable operands.
7295
Anders Carlsson2e7bc112009-11-23 21:47:44 +00007296 // C++ [expr.log.and]p1
7297 // C++ [expr.log.or]p1
John McCall4a2429a2010-06-04 00:29:51 +00007298 // The operands are both contextually converted to type bool.
Richard Trieubcce2f72011-09-07 01:19:57 +00007299 ExprResult LHSRes = PerformContextuallyConvertToBool(LHS.get());
7300 if (LHSRes.isInvalid())
7301 return InvalidOperands(Loc, LHS, RHS);
7302 LHS = move(LHSRes);
John Wiegley01296292011-04-08 18:41:53 +00007303
Richard Trieubcce2f72011-09-07 01:19:57 +00007304 ExprResult RHSRes = PerformContextuallyConvertToBool(RHS.get());
7305 if (RHSRes.isInvalid())
7306 return InvalidOperands(Loc, LHS, RHS);
7307 RHS = move(RHSRes);
Kovarththanan Rajaratnamba2c6522010-03-13 10:17:05 +00007308
Anders Carlsson2e7bc112009-11-23 21:47:44 +00007309 // C++ [expr.log.and]p2
7310 // C++ [expr.log.or]p2
7311 // The result is a bool.
7312 return Context.BoolTy;
Steve Naroffae4143e2007-04-26 20:39:23 +00007313}
7314
Fariborz Jahanian8e1555c2009-01-12 19:55:42 +00007315/// IsReadonlyProperty - Verify that otherwise a valid l-value expression
7316/// is a read-only property; return true if so. A readonly property expression
7317/// depends on various declarations and thus must be treated specially.
7318///
Mike Stump11289f42009-09-09 15:08:12 +00007319static bool IsReadonlyProperty(Expr *E, Sema &S) {
John McCall526ab472011-10-25 17:37:35 +00007320 const ObjCPropertyRefExpr *PropExpr = dyn_cast<ObjCPropertyRefExpr>(E);
7321 if (!PropExpr) return false;
7322 if (PropExpr->isImplicitProperty()) return false;
John McCallb7bd14f2010-12-02 01:19:52 +00007323
John McCall526ab472011-10-25 17:37:35 +00007324 ObjCPropertyDecl *PDecl = PropExpr->getExplicitProperty();
7325 QualType BaseType = PropExpr->isSuperReceiver() ?
John McCallb7bd14f2010-12-02 01:19:52 +00007326 PropExpr->getSuperReceiverType() :
Fariborz Jahanian681c0752010-10-14 16:04:05 +00007327 PropExpr->getBase()->getType();
7328
John McCall526ab472011-10-25 17:37:35 +00007329 if (const ObjCObjectPointerType *OPT =
7330 BaseType->getAsObjCInterfacePointerType())
7331 if (ObjCInterfaceDecl *IFace = OPT->getInterfaceDecl())
7332 if (S.isPropertyReadonly(PDecl, IFace))
7333 return true;
Fariborz Jahanian8e1555c2009-01-12 19:55:42 +00007334 return false;
7335}
7336
Fariborz Jahanian071caef2011-03-26 19:48:30 +00007337static bool IsReadonlyMessage(Expr *E, Sema &S) {
John McCall526ab472011-10-25 17:37:35 +00007338 const MemberExpr *ME = dyn_cast<MemberExpr>(E);
7339 if (!ME) return false;
7340 if (!isa<FieldDecl>(ME->getMemberDecl())) return false;
7341 ObjCMessageExpr *Base =
7342 dyn_cast<ObjCMessageExpr>(ME->getBase()->IgnoreParenImpCasts());
7343 if (!Base) return false;
7344 return Base->getMethodDecl() != 0;
Fariborz Jahanian071caef2011-03-26 19:48:30 +00007345}
7346
John McCall5fa2ef42012-03-13 00:37:01 +00007347/// Is the given expression (which must be 'const') a reference to a
7348/// variable which was originally non-const, but which has become
7349/// 'const' due to being captured within a block?
7350enum NonConstCaptureKind { NCCK_None, NCCK_Block, NCCK_Lambda };
7351static NonConstCaptureKind isReferenceToNonConstCapture(Sema &S, Expr *E) {
7352 assert(E->isLValue() && E->getType().isConstQualified());
7353 E = E->IgnoreParens();
7354
7355 // Must be a reference to a declaration from an enclosing scope.
7356 DeclRefExpr *DRE = dyn_cast<DeclRefExpr>(E);
7357 if (!DRE) return NCCK_None;
7358 if (!DRE->refersToEnclosingLocal()) return NCCK_None;
7359
7360 // The declaration must be a variable which is not declared 'const'.
7361 VarDecl *var = dyn_cast<VarDecl>(DRE->getDecl());
7362 if (!var) return NCCK_None;
7363 if (var->getType().isConstQualified()) return NCCK_None;
7364 assert(var->hasLocalStorage() && "capture added 'const' to non-local?");
7365
7366 // Decide whether the first capture was for a block or a lambda.
7367 DeclContext *DC = S.CurContext;
7368 while (DC->getParent() != var->getDeclContext())
7369 DC = DC->getParent();
7370 return (isa<BlockDecl>(DC) ? NCCK_Block : NCCK_Lambda);
7371}
7372
Chris Lattner30bd3272008-11-18 01:22:49 +00007373/// CheckForModifiableLvalue - Verify that E is a modifiable lvalue. If not,
7374/// emit an error and return true. If so, return false.
7375static bool CheckForModifiableLvalue(Expr *E, SourceLocation Loc, Sema &S) {
Fariborz Jahanianca5c5972012-04-10 17:30:10 +00007376 assert(!E->hasPlaceholderType(BuiltinType::PseudoObject));
Daniel Dunbarc2223ab2009-04-15 00:08:05 +00007377 SourceLocation OrigLoc = Loc;
Mike Stump11289f42009-09-09 15:08:12 +00007378 Expr::isModifiableLvalueResult IsLV = E->isModifiableLvalue(S.Context,
Daniel Dunbarc2223ab2009-04-15 00:08:05 +00007379 &Loc);
Fariborz Jahanian8e1555c2009-01-12 19:55:42 +00007380 if (IsLV == Expr::MLV_Valid && IsReadonlyProperty(E, S))
7381 IsLV = Expr::MLV_ReadonlyProperty;
Fariborz Jahanian071caef2011-03-26 19:48:30 +00007382 else if (IsLV == Expr::MLV_ClassTemporary && IsReadonlyMessage(E, S))
7383 IsLV = Expr::MLV_InvalidMessageExpression;
Chris Lattner30bd3272008-11-18 01:22:49 +00007384 if (IsLV == Expr::MLV_Valid)
7385 return false;
Mike Stump4e1f26a2009-02-19 03:04:26 +00007386
Chris Lattner30bd3272008-11-18 01:22:49 +00007387 unsigned Diag = 0;
7388 bool NeedType = false;
7389 switch (IsLV) { // C99 6.5.16p2
John McCall31168b02011-06-15 23:02:42 +00007390 case Expr::MLV_ConstQualified:
7391 Diag = diag::err_typecheck_assign_const;
7392
John McCall5fa2ef42012-03-13 00:37:01 +00007393 // Use a specialized diagnostic when we're assigning to an object
7394 // from an enclosing function or block.
7395 if (NonConstCaptureKind NCCK = isReferenceToNonConstCapture(S, E)) {
7396 if (NCCK == NCCK_Block)
7397 Diag = diag::err_block_decl_ref_not_modifiable_lvalue;
7398 else
7399 Diag = diag::err_lambda_decl_ref_not_modifiable_lvalue;
7400 break;
7401 }
7402
John McCalld4631322011-06-17 06:42:21 +00007403 // In ARC, use some specialized diagnostics for occasions where we
7404 // infer 'const'. These are always pseudo-strong variables.
David Blaikiebbafb8a2012-03-11 07:00:24 +00007405 if (S.getLangOpts().ObjCAutoRefCount) {
John McCall31168b02011-06-15 23:02:42 +00007406 DeclRefExpr *declRef = dyn_cast<DeclRefExpr>(E->IgnoreParenCasts());
7407 if (declRef && isa<VarDecl>(declRef->getDecl())) {
7408 VarDecl *var = cast<VarDecl>(declRef->getDecl());
7409
John McCalld4631322011-06-17 06:42:21 +00007410 // Use the normal diagnostic if it's pseudo-__strong but the
7411 // user actually wrote 'const'.
7412 if (var->isARCPseudoStrong() &&
7413 (!var->getTypeSourceInfo() ||
7414 !var->getTypeSourceInfo()->getType().isConstQualified())) {
7415 // There are two pseudo-strong cases:
7416 // - self
John McCall31168b02011-06-15 23:02:42 +00007417 ObjCMethodDecl *method = S.getCurMethodDecl();
7418 if (method && var == method->getSelfDecl())
Ted Kremenek1fcdaa92011-11-14 21:59:25 +00007419 Diag = method->isClassMethod()
7420 ? diag::err_typecheck_arc_assign_self_class_method
7421 : diag::err_typecheck_arc_assign_self;
John McCalld4631322011-06-17 06:42:21 +00007422
7423 // - fast enumeration variables
7424 else
John McCall31168b02011-06-15 23:02:42 +00007425 Diag = diag::err_typecheck_arr_assign_enumeration;
John McCalld4631322011-06-17 06:42:21 +00007426
John McCall31168b02011-06-15 23:02:42 +00007427 SourceRange Assign;
7428 if (Loc != OrigLoc)
7429 Assign = SourceRange(OrigLoc, OrigLoc);
7430 S.Diag(Loc, Diag) << E->getSourceRange() << Assign;
7431 // We need to preserve the AST regardless, so migration tool
7432 // can do its job.
7433 return false;
7434 }
7435 }
7436 }
7437
7438 break;
Mike Stump4e1f26a2009-02-19 03:04:26 +00007439 case Expr::MLV_ArrayType:
Richard Smitheb3cad52012-06-04 22:27:30 +00007440 case Expr::MLV_ArrayTemporary:
Chris Lattner30bd3272008-11-18 01:22:49 +00007441 Diag = diag::err_typecheck_array_not_modifiable_lvalue;
7442 NeedType = true;
7443 break;
Mike Stump4e1f26a2009-02-19 03:04:26 +00007444 case Expr::MLV_NotObjectType:
Chris Lattner30bd3272008-11-18 01:22:49 +00007445 Diag = diag::err_typecheck_non_object_not_modifiable_lvalue;
7446 NeedType = true;
7447 break;
Chris Lattner9b3bbe92008-11-17 19:51:54 +00007448 case Expr::MLV_LValueCast:
Chris Lattner30bd3272008-11-18 01:22:49 +00007449 Diag = diag::err_typecheck_lvalue_casts_not_supported;
7450 break;
Douglas Gregorb154fdc2010-02-16 21:39:57 +00007451 case Expr::MLV_Valid:
7452 llvm_unreachable("did not take early return for MLV_Valid");
Chris Lattner9bad62c2008-01-04 18:04:52 +00007453 case Expr::MLV_InvalidExpression:
Douglas Gregorb154fdc2010-02-16 21:39:57 +00007454 case Expr::MLV_MemberFunction:
7455 case Expr::MLV_ClassTemporary:
Chris Lattner30bd3272008-11-18 01:22:49 +00007456 Diag = diag::err_typecheck_expression_not_modifiable_lvalue;
7457 break;
Chris Lattner9bad62c2008-01-04 18:04:52 +00007458 case Expr::MLV_IncompleteType:
7459 case Expr::MLV_IncompleteVoidType:
Douglas Gregored0cfbd2009-03-09 16:13:40 +00007460 return S.RequireCompleteType(Loc, E->getType(),
Douglas Gregor7bfb2d02012-05-04 16:32:21 +00007461 diag::err_typecheck_incomplete_type_not_modifiable_lvalue, E);
Chris Lattner9bad62c2008-01-04 18:04:52 +00007462 case Expr::MLV_DuplicateVectorComponents:
Chris Lattner30bd3272008-11-18 01:22:49 +00007463 Diag = diag::err_typecheck_duplicate_vector_components_not_mlvalue;
7464 break;
Fariborz Jahanian8a1810f2008-11-22 18:39:36 +00007465 case Expr::MLV_ReadonlyProperty:
Fariborz Jahanian5118c412008-11-22 20:25:50 +00007466 case Expr::MLV_NoSetterProperty:
John McCall526ab472011-10-25 17:37:35 +00007467 llvm_unreachable("readonly properties should be processed differently");
Fariborz Jahanian071caef2011-03-26 19:48:30 +00007468 case Expr::MLV_InvalidMessageExpression:
7469 Diag = diag::error_readonly_message_assignment;
7470 break;
Fariborz Jahaniane8d28902009-12-15 23:59:41 +00007471 case Expr::MLV_SubObjCPropertySetting:
7472 Diag = diag::error_no_subobject_property_setting;
7473 break;
Steve Naroff218bc2b2007-05-04 21:54:46 +00007474 }
Steve Naroffad373bd2007-07-31 12:34:36 +00007475
Daniel Dunbarc2223ab2009-04-15 00:08:05 +00007476 SourceRange Assign;
7477 if (Loc != OrigLoc)
7478 Assign = SourceRange(OrigLoc, OrigLoc);
Chris Lattner30bd3272008-11-18 01:22:49 +00007479 if (NeedType)
Daniel Dunbarc2223ab2009-04-15 00:08:05 +00007480 S.Diag(Loc, Diag) << E->getType() << E->getSourceRange() << Assign;
Chris Lattner30bd3272008-11-18 01:22:49 +00007481 else
Mike Stump11289f42009-09-09 15:08:12 +00007482 S.Diag(Loc, Diag) << E->getSourceRange() << Assign;
Chris Lattner30bd3272008-11-18 01:22:49 +00007483 return true;
7484}
7485
7486
7487
7488// C99 6.5.16.1
Richard Trieuda4f43a62011-09-07 01:33:52 +00007489QualType Sema::CheckAssignmentOperands(Expr *LHSExpr, ExprResult &RHS,
Chris Lattner326f7572008-11-18 01:30:42 +00007490 SourceLocation Loc,
7491 QualType CompoundType) {
John McCall526ab472011-10-25 17:37:35 +00007492 assert(!LHSExpr->hasPlaceholderType(BuiltinType::PseudoObject));
7493
Chris Lattner326f7572008-11-18 01:30:42 +00007494 // Verify that LHS is a modifiable lvalue, and emit error if not.
Richard Trieuda4f43a62011-09-07 01:33:52 +00007495 if (CheckForModifiableLvalue(LHSExpr, Loc, *this))
Chris Lattner30bd3272008-11-18 01:22:49 +00007496 return QualType();
Chris Lattner326f7572008-11-18 01:30:42 +00007497
Richard Trieuda4f43a62011-09-07 01:33:52 +00007498 QualType LHSType = LHSExpr->getType();
Richard Trieucfc491d2011-08-02 04:35:43 +00007499 QualType RHSType = CompoundType.isNull() ? RHS.get()->getType() :
7500 CompoundType;
Chris Lattner9bad62c2008-01-04 18:04:52 +00007501 AssignConvertType ConvTy;
Chris Lattner326f7572008-11-18 01:30:42 +00007502 if (CompoundType.isNull()) {
Fariborz Jahanianbe21aa32010-06-07 22:02:01 +00007503 QualType LHSTy(LHSType);
Fariborz Jahanianbe21aa32010-06-07 22:02:01 +00007504 ConvTy = CheckSingleAssignmentConstraints(LHSTy, RHS);
John Wiegley01296292011-04-08 18:41:53 +00007505 if (RHS.isInvalid())
7506 return QualType();
Fariborz Jahanian255c0952009-01-13 23:34:40 +00007507 // Special case of NSObject attributes on c-style pointer types.
7508 if (ConvTy == IncompatiblePointer &&
7509 ((Context.isObjCNSObjectType(LHSType) &&
Steve Naroff79d12152009-07-16 15:41:00 +00007510 RHSType->isObjCObjectPointerType()) ||
Fariborz Jahanian255c0952009-01-13 23:34:40 +00007511 (Context.isObjCNSObjectType(RHSType) &&
Steve Naroff79d12152009-07-16 15:41:00 +00007512 LHSType->isObjCObjectPointerType())))
Fariborz Jahanian255c0952009-01-13 23:34:40 +00007513 ConvTy = Compatible;
Mike Stump4e1f26a2009-02-19 03:04:26 +00007514
John McCall7decc9e2010-11-18 06:31:45 +00007515 if (ConvTy == Compatible &&
Fariborz Jahaniane2a77762012-01-24 19:40:13 +00007516 LHSType->isObjCObjectType())
Fariborz Jahanian3c4225a2012-01-24 18:05:45 +00007517 Diag(Loc, diag::err_objc_object_assignment)
7518 << LHSType;
John McCall7decc9e2010-11-18 06:31:45 +00007519
Chris Lattnerea714382008-08-21 18:04:13 +00007520 // If the RHS is a unary plus or minus, check to see if they = and + are
7521 // right next to each other. If so, the user may have typo'd "x =+ 4"
7522 // instead of "x += 4".
John Wiegley01296292011-04-08 18:41:53 +00007523 Expr *RHSCheck = RHS.get();
Chris Lattnerea714382008-08-21 18:04:13 +00007524 if (ImplicitCastExpr *ICE = dyn_cast<ImplicitCastExpr>(RHSCheck))
7525 RHSCheck = ICE->getSubExpr();
7526 if (UnaryOperator *UO = dyn_cast<UnaryOperator>(RHSCheck)) {
John McCalle3027922010-08-25 11:45:40 +00007527 if ((UO->getOpcode() == UO_Plus ||
7528 UO->getOpcode() == UO_Minus) &&
Chris Lattner326f7572008-11-18 01:30:42 +00007529 Loc.isFileID() && UO->getOperatorLoc().isFileID() &&
Chris Lattnerea714382008-08-21 18:04:13 +00007530 // Only if the two operators are exactly adjacent.
Argyrios Kyrtzidise6e67de2011-09-19 20:40:19 +00007531 Loc.getLocWithOffset(1) == UO->getOperatorLoc() &&
Chris Lattner36c39c92009-03-08 06:51:10 +00007532 // And there is a space or other character before the subexpr of the
7533 // unary +/-. We don't want to warn on "x=-1".
Argyrios Kyrtzidise6e67de2011-09-19 20:40:19 +00007534 Loc.getLocWithOffset(2) != UO->getSubExpr()->getLocStart() &&
Chris Lattnered9f14c2009-03-09 07:11:10 +00007535 UO->getSubExpr()->getLocStart().isFileID()) {
Chris Lattner29e812b2008-11-20 06:06:08 +00007536 Diag(Loc, diag::warn_not_compound_assign)
John McCalle3027922010-08-25 11:45:40 +00007537 << (UO->getOpcode() == UO_Plus ? "+" : "-")
Chris Lattner29e812b2008-11-20 06:06:08 +00007538 << SourceRange(UO->getOperatorLoc(), UO->getOperatorLoc());
Chris Lattner36c39c92009-03-08 06:51:10 +00007539 }
Chris Lattnerea714382008-08-21 18:04:13 +00007540 }
John McCall31168b02011-06-15 23:02:42 +00007541
7542 if (ConvTy == Compatible) {
7543 if (LHSType.getObjCLifetime() == Qualifiers::OCL_Strong)
Richard Trieuda4f43a62011-09-07 01:33:52 +00007544 checkRetainCycles(LHSExpr, RHS.get());
David Blaikiebbafb8a2012-03-11 07:00:24 +00007545 else if (getLangOpts().ObjCAutoRefCount)
Richard Trieuda4f43a62011-09-07 01:33:52 +00007546 checkUnsafeExprAssigns(Loc, LHSExpr, RHS.get());
John McCall31168b02011-06-15 23:02:42 +00007547 }
Chris Lattnerea714382008-08-21 18:04:13 +00007548 } else {
7549 // Compound assignment "x += y"
Douglas Gregorc03a1082011-01-28 02:26:04 +00007550 ConvTy = CheckAssignmentConstraints(Loc, LHSType, RHSType);
Chris Lattnerea714382008-08-21 18:04:13 +00007551 }
Chris Lattner9bad62c2008-01-04 18:04:52 +00007552
Chris Lattner326f7572008-11-18 01:30:42 +00007553 if (DiagnoseAssignmentResult(ConvTy, Loc, LHSType, RHSType,
John Wiegley01296292011-04-08 18:41:53 +00007554 RHS.get(), AA_Assigning))
Chris Lattner9bad62c2008-01-04 18:04:52 +00007555 return QualType();
Mike Stump4e1f26a2009-02-19 03:04:26 +00007556
Richard Trieuda4f43a62011-09-07 01:33:52 +00007557 CheckForNullPointerDereference(*this, LHSExpr);
Kaelyn Uhrain2e7aa5a2011-08-05 23:18:04 +00007558
Steve Naroff98cf3e92007-06-06 18:38:38 +00007559 // C99 6.5.16p3: The type of an assignment expression is the type of the
7560 // left operand unless the left operand has qualified type, in which case
Mike Stump4e1f26a2009-02-19 03:04:26 +00007561 // it is the unqualified version of the type of the left operand.
Steve Naroff98cf3e92007-06-06 18:38:38 +00007562 // C99 6.5.16.1p2: In simple assignment, the value of the right operand
7563 // is converted to the type of the assignment expression (above).
Chris Lattnerf17bd422007-08-30 17:45:32 +00007564 // C++ 5.17p1: the type of the assignment expression is that of its left
Douglas Gregord2c2d172009-05-02 00:36:19 +00007565 // operand.
David Blaikiebbafb8a2012-03-11 07:00:24 +00007566 return (getLangOpts().CPlusPlus
John McCall01cbf2d2010-10-12 02:19:57 +00007567 ? LHSType : LHSType.getUnqualifiedType());
Steve Naroffae4143e2007-04-26 20:39:23 +00007568}
7569
Chris Lattner326f7572008-11-18 01:30:42 +00007570// C99 6.5.17
John Wiegley01296292011-04-08 18:41:53 +00007571static QualType CheckCommaOperands(Sema &S, ExprResult &LHS, ExprResult &RHS,
John McCall4bc41ae2010-11-18 19:01:18 +00007572 SourceLocation Loc) {
John McCall3aef3d82011-04-10 19:13:55 +00007573 LHS = S.CheckPlaceholderExpr(LHS.take());
7574 RHS = S.CheckPlaceholderExpr(RHS.take());
John Wiegley01296292011-04-08 18:41:53 +00007575 if (LHS.isInvalid() || RHS.isInvalid())
Douglas Gregor0124e9b2010-11-09 21:07:58 +00007576 return QualType();
7577
John McCall73d36182010-10-12 07:14:40 +00007578 // C's comma performs lvalue conversion (C99 6.3.2.1) on both its
7579 // operands, but not unary promotions.
7580 // C++'s comma does not do any conversions at all (C++ [expr.comma]p1).
Eli Friedmanba961a92009-03-23 00:24:07 +00007581
John McCall34376a62010-12-04 03:47:34 +00007582 // So we treat the LHS as a ignored value, and in C++ we allow the
7583 // containing site to determine what should be done with the RHS.
John Wiegley01296292011-04-08 18:41:53 +00007584 LHS = S.IgnoredValueConversions(LHS.take());
7585 if (LHS.isInvalid())
7586 return QualType();
John McCall34376a62010-12-04 03:47:34 +00007587
Eli Friedmanc11535c2012-05-24 00:47:05 +00007588 S.DiagnoseUnusedExprResult(LHS.get());
7589
David Blaikiebbafb8a2012-03-11 07:00:24 +00007590 if (!S.getLangOpts().CPlusPlus) {
John Wiegley01296292011-04-08 18:41:53 +00007591 RHS = S.DefaultFunctionArrayLvalueConversion(RHS.take());
7592 if (RHS.isInvalid())
7593 return QualType();
7594 if (!RHS.get()->getType()->isVoidType())
Richard Trieucfc491d2011-08-02 04:35:43 +00007595 S.RequireCompleteType(Loc, RHS.get()->getType(),
7596 diag::err_incomplete_type);
John McCall73d36182010-10-12 07:14:40 +00007597 }
Eli Friedmanba961a92009-03-23 00:24:07 +00007598
John Wiegley01296292011-04-08 18:41:53 +00007599 return RHS.get()->getType();
Steve Naroff95af0132007-03-30 23:47:58 +00007600}
7601
Steve Naroff7a5af782007-07-13 16:58:59 +00007602/// CheckIncrementDecrementOperand - unlike most "Check" methods, this routine
7603/// doesn't need to call UsualUnaryConversions or UsualArithmeticConversions.
John McCall4bc41ae2010-11-18 19:01:18 +00007604static QualType CheckIncrementDecrementOperand(Sema &S, Expr *Op,
7605 ExprValueKind &VK,
7606 SourceLocation OpLoc,
Richard Trieuba63ce62011-09-09 01:45:06 +00007607 bool IsInc, bool IsPrefix) {
Sebastian Redl8d2ccae2009-02-26 14:39:58 +00007608 if (Op->isTypeDependent())
John McCall4bc41ae2010-11-18 19:01:18 +00007609 return S.Context.DependentTy;
Sebastian Redl8d2ccae2009-02-26 14:39:58 +00007610
Chris Lattner6b0cf142008-11-21 07:05:48 +00007611 QualType ResType = Op->getType();
David Chisnallfa35df62012-01-16 17:27:18 +00007612 // Atomic types can be used for increment / decrement where the non-atomic
7613 // versions can, so ignore the _Atomic() specifier for the purpose of
7614 // checking.
7615 if (const AtomicType *ResAtomicType = ResType->getAs<AtomicType>())
7616 ResType = ResAtomicType->getValueType();
7617
Chris Lattner6b0cf142008-11-21 07:05:48 +00007618 assert(!ResType.isNull() && "no type for increment/decrement expression");
Steve Naroffd50c88e2007-04-05 21:15:20 +00007619
David Blaikiebbafb8a2012-03-11 07:00:24 +00007620 if (S.getLangOpts().CPlusPlus && ResType->isBooleanType()) {
Sebastian Redle10c2c32008-12-20 09:35:34 +00007621 // Decrement of bool is not allowed.
Richard Trieuba63ce62011-09-09 01:45:06 +00007622 if (!IsInc) {
John McCall4bc41ae2010-11-18 19:01:18 +00007623 S.Diag(OpLoc, diag::err_decrement_bool) << Op->getSourceRange();
Sebastian Redle10c2c32008-12-20 09:35:34 +00007624 return QualType();
7625 }
7626 // Increment of bool sets it to true, but is deprecated.
John McCall4bc41ae2010-11-18 19:01:18 +00007627 S.Diag(OpLoc, diag::warn_increment_bool) << Op->getSourceRange();
Sebastian Redle10c2c32008-12-20 09:35:34 +00007628 } else if (ResType->isRealType()) {
Chris Lattner6b0cf142008-11-21 07:05:48 +00007629 // OK!
Steve Naroff6b712a72009-07-14 18:25:06 +00007630 } else if (ResType->isAnyPointerType()) {
Chris Lattner6b0cf142008-11-21 07:05:48 +00007631 // C99 6.5.2.4p2, 6.5.6p2
Chandler Carruthc9332212011-06-27 08:02:19 +00007632 if (!checkArithmeticOpPointerOperand(S, OpLoc, Op))
Douglas Gregordd430f72009-01-19 19:26:10 +00007633 return QualType();
Chandler Carruthc9332212011-06-27 08:02:19 +00007634
Fariborz Jahanianca75db72009-07-16 17:59:14 +00007635 // Diagnose bad cases where we step over interface counts.
Richard Trieub10c6312011-09-01 22:53:23 +00007636 else if (!checkArithmethicPointerOnNonFragileABI(S, OpLoc, Op))
Fariborz Jahanianca75db72009-07-16 17:59:14 +00007637 return QualType();
Eli Friedman090addd2010-01-03 00:20:48 +00007638 } else if (ResType->isAnyComplexType()) {
Chris Lattner6b0cf142008-11-21 07:05:48 +00007639 // C99 does not support ++/-- on complex types, we allow as an extension.
John McCall4bc41ae2010-11-18 19:01:18 +00007640 S.Diag(OpLoc, diag::ext_integer_increment_complex)
Chris Lattner1e5665e2008-11-24 06:25:27 +00007641 << ResType << Op->getSourceRange();
John McCall36226622010-10-12 02:09:17 +00007642 } else if (ResType->isPlaceholderType()) {
John McCall3aef3d82011-04-10 19:13:55 +00007643 ExprResult PR = S.CheckPlaceholderExpr(Op);
John McCall36226622010-10-12 02:09:17 +00007644 if (PR.isInvalid()) return QualType();
John McCall4bc41ae2010-11-18 19:01:18 +00007645 return CheckIncrementDecrementOperand(S, PR.take(), VK, OpLoc,
Richard Trieuba63ce62011-09-09 01:45:06 +00007646 IsInc, IsPrefix);
David Blaikiebbafb8a2012-03-11 07:00:24 +00007647 } else if (S.getLangOpts().AltiVec && ResType->isVectorType()) {
Anton Yartsev85129b82011-02-07 02:17:30 +00007648 // OK! ( C/C++ Language Extensions for CBEA(Version 2.6) 10.3 )
Chris Lattner6b0cf142008-11-21 07:05:48 +00007649 } else {
John McCall4bc41ae2010-11-18 19:01:18 +00007650 S.Diag(OpLoc, diag::err_typecheck_illegal_increment_decrement)
Richard Trieuba63ce62011-09-09 01:45:06 +00007651 << ResType << int(IsInc) << Op->getSourceRange();
Chris Lattner6b0cf142008-11-21 07:05:48 +00007652 return QualType();
Steve Naroff46ba1eb2007-04-03 23:13:13 +00007653 }
Mike Stump4e1f26a2009-02-19 03:04:26 +00007654 // At this point, we know we have a real, complex or pointer type.
Steve Naroff9e1e5512007-08-23 21:37:33 +00007655 // Now make sure the operand is a modifiable lvalue.
John McCall4bc41ae2010-11-18 19:01:18 +00007656 if (CheckForModifiableLvalue(Op, OpLoc, S))
Steve Naroff35d85152007-05-07 00:24:15 +00007657 return QualType();
Alexis Huntc46382e2010-04-28 23:02:27 +00007658 // In C++, a prefix increment is the same type as the operand. Otherwise
7659 // (in C or with postfix), the increment is the unqualified type of the
7660 // operand.
David Blaikiebbafb8a2012-03-11 07:00:24 +00007661 if (IsPrefix && S.getLangOpts().CPlusPlus) {
John McCall4bc41ae2010-11-18 19:01:18 +00007662 VK = VK_LValue;
7663 return ResType;
7664 } else {
7665 VK = VK_RValue;
7666 return ResType.getUnqualifiedType();
7667 }
Steve Naroff26c8ea52007-03-21 21:08:52 +00007668}
Fariborz Jahanian805b74e2010-09-14 23:02:38 +00007669
7670
Anders Carlsson806700f2008-02-01 07:15:58 +00007671/// getPrimaryDecl - Helper function for CheckAddressOfOperand().
Steve Naroff47500512007-04-19 23:00:49 +00007672/// This routine allows us to typecheck complex/recursive expressions
Daniel Dunbarb692ef42008-08-04 20:02:37 +00007673/// where the declaration is needed for type checking. We only need to
7674/// handle cases when the expression references a function designator
7675/// or is an lvalue. Here are some examples:
7676/// - &(x) => x
7677/// - &*****f => f for f a function designator.
7678/// - &s.xx => s
7679/// - &s.zz[1].yy -> s, if zz is an array
7680/// - *(x + 1) -> x, if x is an array
7681/// - &"123"[2] -> 0
7682/// - & __real__ x -> x
John McCallf3a88602011-02-03 08:15:49 +00007683static ValueDecl *getPrimaryDecl(Expr *E) {
Chris Lattner24d5bfe2008-04-02 04:24:33 +00007684 switch (E->getStmtClass()) {
Steve Naroff47500512007-04-19 23:00:49 +00007685 case Stmt::DeclRefExprClass:
Chris Lattner24d5bfe2008-04-02 04:24:33 +00007686 return cast<DeclRefExpr>(E)->getDecl();
Steve Naroff47500512007-04-19 23:00:49 +00007687 case Stmt::MemberExprClass:
Eli Friedman3a1e6922009-04-20 08:23:18 +00007688 // If this is an arrow operator, the address is an offset from
7689 // the base's value, so the object the base refers to is
7690 // irrelevant.
Chris Lattner24d5bfe2008-04-02 04:24:33 +00007691 if (cast<MemberExpr>(E)->isArrow())
Chris Lattner48d52842007-11-16 17:46:48 +00007692 return 0;
Eli Friedman3a1e6922009-04-20 08:23:18 +00007693 // Otherwise, the expression refers to a part of the base
Chris Lattner24d5bfe2008-04-02 04:24:33 +00007694 return getPrimaryDecl(cast<MemberExpr>(E)->getBase());
Anders Carlsson806700f2008-02-01 07:15:58 +00007695 case Stmt::ArraySubscriptExprClass: {
Mike Stump87c57ac2009-05-16 07:39:55 +00007696 // FIXME: This code shouldn't be necessary! We should catch the implicit
7697 // promotion of register arrays earlier.
Eli Friedman3a1e6922009-04-20 08:23:18 +00007698 Expr* Base = cast<ArraySubscriptExpr>(E)->getBase();
7699 if (ImplicitCastExpr* ICE = dyn_cast<ImplicitCastExpr>(Base)) {
7700 if (ICE->getSubExpr()->getType()->isArrayType())
7701 return getPrimaryDecl(ICE->getSubExpr());
7702 }
7703 return 0;
Anders Carlsson806700f2008-02-01 07:15:58 +00007704 }
Daniel Dunbarb692ef42008-08-04 20:02:37 +00007705 case Stmt::UnaryOperatorClass: {
7706 UnaryOperator *UO = cast<UnaryOperator>(E);
Mike Stump4e1f26a2009-02-19 03:04:26 +00007707
Daniel Dunbarb692ef42008-08-04 20:02:37 +00007708 switch(UO->getOpcode()) {
John McCalle3027922010-08-25 11:45:40 +00007709 case UO_Real:
7710 case UO_Imag:
7711 case UO_Extension:
Daniel Dunbarb692ef42008-08-04 20:02:37 +00007712 return getPrimaryDecl(UO->getSubExpr());
7713 default:
7714 return 0;
7715 }
7716 }
Steve Naroff47500512007-04-19 23:00:49 +00007717 case Stmt::ParenExprClass:
Chris Lattner24d5bfe2008-04-02 04:24:33 +00007718 return getPrimaryDecl(cast<ParenExpr>(E)->getSubExpr());
Chris Lattner48d52842007-11-16 17:46:48 +00007719 case Stmt::ImplicitCastExprClass:
Eli Friedman3a1e6922009-04-20 08:23:18 +00007720 // If the result of an implicit cast is an l-value, we care about
7721 // the sub-expression; otherwise, the result here doesn't matter.
Chris Lattner24d5bfe2008-04-02 04:24:33 +00007722 return getPrimaryDecl(cast<ImplicitCastExpr>(E)->getSubExpr());
Steve Naroff47500512007-04-19 23:00:49 +00007723 default:
7724 return 0;
7725 }
7726}
7727
Richard Trieu5f376f62011-09-07 21:46:33 +00007728namespace {
7729 enum {
7730 AO_Bit_Field = 0,
7731 AO_Vector_Element = 1,
7732 AO_Property_Expansion = 2,
7733 AO_Register_Variable = 3,
7734 AO_No_Error = 4
7735 };
7736}
Richard Trieu3fd7bb82011-09-02 00:47:55 +00007737/// \brief Diagnose invalid operand for address of operations.
7738///
7739/// \param Type The type of operand which cannot have its address taken.
Richard Trieu3fd7bb82011-09-02 00:47:55 +00007740static void diagnoseAddressOfInvalidType(Sema &S, SourceLocation Loc,
7741 Expr *E, unsigned Type) {
7742 S.Diag(Loc, diag::err_typecheck_address_of) << Type << E->getSourceRange();
7743}
7744
Steve Naroff47500512007-04-19 23:00:49 +00007745/// CheckAddressOfOperand - The operand of & must be either a function
Mike Stump4e1f26a2009-02-19 03:04:26 +00007746/// designator or an lvalue designating an object. If it is an lvalue, the
Steve Naroff47500512007-04-19 23:00:49 +00007747/// object cannot be declared with storage class register or be a bit field.
Mike Stump4e1f26a2009-02-19 03:04:26 +00007748/// Note: The usual conversions are *not* applied to the operand of the &
Steve Naroffa78fe7e2007-05-16 19:47:19 +00007749/// operator (C99 6.3.2.1p[2-4]), and its result is never an lvalue.
Mike Stump4e1f26a2009-02-19 03:04:26 +00007750/// In C++, the operand might be an overloaded function name, in which case
Douglas Gregorcd695e52008-11-10 20:40:00 +00007751/// we allow the '&' but retain the overloaded-function type.
John McCall526ab472011-10-25 17:37:35 +00007752static QualType CheckAddressOfOperand(Sema &S, ExprResult &OrigOp,
John McCall4bc41ae2010-11-18 19:01:18 +00007753 SourceLocation OpLoc) {
John McCall526ab472011-10-25 17:37:35 +00007754 if (const BuiltinType *PTy = OrigOp.get()->getType()->getAsPlaceholderType()){
7755 if (PTy->getKind() == BuiltinType::Overload) {
7756 if (!isa<OverloadExpr>(OrigOp.get()->IgnoreParens())) {
7757 S.Diag(OpLoc, diag::err_typecheck_invalid_lvalue_addrof)
7758 << OrigOp.get()->getSourceRange();
7759 return QualType();
7760 }
7761
7762 return S.Context.OverloadTy;
7763 }
7764
7765 if (PTy->getKind() == BuiltinType::UnknownAny)
7766 return S.Context.UnknownAnyTy;
7767
7768 if (PTy->getKind() == BuiltinType::BoundMember) {
7769 S.Diag(OpLoc, diag::err_invalid_form_pointer_member_function)
7770 << OrigOp.get()->getSourceRange();
Douglas Gregor668d3622011-10-09 19:10:41 +00007771 return QualType();
7772 }
John McCall526ab472011-10-25 17:37:35 +00007773
7774 OrigOp = S.CheckPlaceholderExpr(OrigOp.take());
7775 if (OrigOp.isInvalid()) return QualType();
John McCall0009fcc2011-04-26 20:42:42 +00007776 }
John McCall8d08b9b2010-08-27 09:08:28 +00007777
John McCall526ab472011-10-25 17:37:35 +00007778 if (OrigOp.get()->isTypeDependent())
7779 return S.Context.DependentTy;
7780
7781 assert(!OrigOp.get()->getType()->isPlaceholderType());
John McCall36226622010-10-12 02:09:17 +00007782
John McCall8d08b9b2010-08-27 09:08:28 +00007783 // Make sure to ignore parentheses in subsequent checks
John McCall526ab472011-10-25 17:37:35 +00007784 Expr *op = OrigOp.get()->IgnoreParens();
Douglas Gregor19b8c4f2008-12-17 22:52:20 +00007785
David Blaikiebbafb8a2012-03-11 07:00:24 +00007786 if (S.getLangOpts().C99) {
Steve Naroff826e91a2008-01-13 17:10:08 +00007787 // Implement C99-only parts of addressof rules.
7788 if (UnaryOperator* uOp = dyn_cast<UnaryOperator>(op)) {
John McCalle3027922010-08-25 11:45:40 +00007789 if (uOp->getOpcode() == UO_Deref)
Steve Naroff826e91a2008-01-13 17:10:08 +00007790 // Per C99 6.5.3.2, the address of a deref always returns a valid result
7791 // (assuming the deref expression is valid).
7792 return uOp->getSubExpr()->getType();
7793 }
7794 // Technically, there should be a check for array subscript
7795 // expressions here, but the result of one is always an lvalue anyway.
7796 }
John McCallf3a88602011-02-03 08:15:49 +00007797 ValueDecl *dcl = getPrimaryDecl(op);
John McCall086a4642010-11-24 05:12:34 +00007798 Expr::LValueClassification lval = op->ClassifyLValue(S.Context);
Richard Trieu5f376f62011-09-07 21:46:33 +00007799 unsigned AddressOfError = AO_No_Error;
Nuno Lopes17f345f2008-12-16 22:59:47 +00007800
Fariborz Jahanian071caef2011-03-26 19:48:30 +00007801 if (lval == Expr::LV_ClassTemporary) {
John McCall4bc41ae2010-11-18 19:01:18 +00007802 bool sfinae = S.isSFINAEContext();
7803 S.Diag(OpLoc, sfinae ? diag::err_typecheck_addrof_class_temporary
7804 : diag::ext_typecheck_addrof_class_temporary)
Douglas Gregorb154fdc2010-02-16 21:39:57 +00007805 << op->getType() << op->getSourceRange();
John McCall4bc41ae2010-11-18 19:01:18 +00007806 if (sfinae)
Douglas Gregorb154fdc2010-02-16 21:39:57 +00007807 return QualType();
John McCall8d08b9b2010-08-27 09:08:28 +00007808 } else if (isa<ObjCSelectorExpr>(op)) {
John McCall4bc41ae2010-11-18 19:01:18 +00007809 return S.Context.getPointerType(op->getType());
John McCall8d08b9b2010-08-27 09:08:28 +00007810 } else if (lval == Expr::LV_MemberFunction) {
7811 // If it's an instance method, make a member pointer.
7812 // The expression must have exactly the form &A::foo.
7813
7814 // If the underlying expression isn't a decl ref, give up.
7815 if (!isa<DeclRefExpr>(op)) {
John McCall4bc41ae2010-11-18 19:01:18 +00007816 S.Diag(OpLoc, diag::err_invalid_form_pointer_member_function)
John McCall526ab472011-10-25 17:37:35 +00007817 << OrigOp.get()->getSourceRange();
John McCall8d08b9b2010-08-27 09:08:28 +00007818 return QualType();
7819 }
7820 DeclRefExpr *DRE = cast<DeclRefExpr>(op);
7821 CXXMethodDecl *MD = cast<CXXMethodDecl>(DRE->getDecl());
7822
7823 // The id-expression was parenthesized.
John McCall526ab472011-10-25 17:37:35 +00007824 if (OrigOp.get() != DRE) {
John McCall4bc41ae2010-11-18 19:01:18 +00007825 S.Diag(OpLoc, diag::err_parens_pointer_member_function)
John McCall526ab472011-10-25 17:37:35 +00007826 << OrigOp.get()->getSourceRange();
John McCall8d08b9b2010-08-27 09:08:28 +00007827
7828 // The method was named without a qualifier.
7829 } else if (!DRE->getQualifier()) {
John McCall4bc41ae2010-11-18 19:01:18 +00007830 S.Diag(OpLoc, diag::err_unqualified_pointer_member_function)
John McCall8d08b9b2010-08-27 09:08:28 +00007831 << op->getSourceRange();
7832 }
7833
John McCall4bc41ae2010-11-18 19:01:18 +00007834 return S.Context.getMemberPointerType(op->getType(),
7835 S.Context.getTypeDeclType(MD->getParent()).getTypePtr());
John McCall8d08b9b2010-08-27 09:08:28 +00007836 } else if (lval != Expr::LV_Valid && lval != Expr::LV_IncompleteVoidType) {
Eli Friedmance7f9002009-05-16 23:27:50 +00007837 // C99 6.5.3.2p1
Eli Friedman3a1e6922009-04-20 08:23:18 +00007838 // The operand must be either an l-value or a function designator
Eli Friedmance7f9002009-05-16 23:27:50 +00007839 if (!op->getType()->isFunctionType()) {
John McCall526ab472011-10-25 17:37:35 +00007840 // Use a special diagnostic for loads from property references.
John McCallfe96e0b2011-11-06 09:01:30 +00007841 if (isa<PseudoObjectExpr>(op)) {
John McCall526ab472011-10-25 17:37:35 +00007842 AddressOfError = AO_Property_Expansion;
7843 } else {
7844 // FIXME: emit more specific diag...
7845 S.Diag(OpLoc, diag::err_typecheck_invalid_lvalue_addrof)
7846 << op->getSourceRange();
7847 return QualType();
7848 }
Steve Naroff35d85152007-05-07 00:24:15 +00007849 }
John McCall086a4642010-11-24 05:12:34 +00007850 } else if (op->getObjectKind() == OK_BitField) { // C99 6.5.3.2p1
Eli Friedman3a1e6922009-04-20 08:23:18 +00007851 // The operand cannot be a bit-field
Richard Trieu5f376f62011-09-07 21:46:33 +00007852 AddressOfError = AO_Bit_Field;
John McCall086a4642010-11-24 05:12:34 +00007853 } else if (op->getObjectKind() == OK_VectorComponent) {
Eli Friedman3a1e6922009-04-20 08:23:18 +00007854 // The operand cannot be an element of a vector
Richard Trieu5f376f62011-09-07 21:46:33 +00007855 AddressOfError = AO_Vector_Element;
Steve Naroffb96e4ab62008-02-29 23:30:25 +00007856 } else if (dcl) { // C99 6.5.3.2p1
Mike Stump4e1f26a2009-02-19 03:04:26 +00007857 // We have an lvalue with a decl. Make sure the decl is not declared
Steve Naroff47500512007-04-19 23:00:49 +00007858 // with the register storage-class specifier.
7859 if (const VarDecl *vd = dyn_cast<VarDecl>(dcl)) {
Fariborz Jahaniane0fd5a92010-08-24 22:21:48 +00007860 // in C++ it is not error to take address of a register
7861 // variable (c++03 7.1.1P3)
John McCall8e7d6562010-08-26 03:08:43 +00007862 if (vd->getStorageClass() == SC_Register &&
David Blaikiebbafb8a2012-03-11 07:00:24 +00007863 !S.getLangOpts().CPlusPlus) {
Richard Trieu5f376f62011-09-07 21:46:33 +00007864 AddressOfError = AO_Register_Variable;
Steve Naroff35d85152007-05-07 00:24:15 +00007865 }
John McCalld14a8642009-11-21 08:51:07 +00007866 } else if (isa<FunctionTemplateDecl>(dcl)) {
John McCall4bc41ae2010-11-18 19:01:18 +00007867 return S.Context.OverloadTy;
John McCallf3a88602011-02-03 08:15:49 +00007868 } else if (isa<FieldDecl>(dcl) || isa<IndirectFieldDecl>(dcl)) {
Douglas Gregor9aa8b552008-12-10 21:26:49 +00007869 // Okay: we can take the address of a field.
Sebastian Redl3d3f75a2009-02-03 20:19:35 +00007870 // Could be a pointer to member, though, if there is an explicit
7871 // scope qualifier for the class.
Douglas Gregor4bd90e52009-10-23 18:54:35 +00007872 if (isa<DeclRefExpr>(op) && cast<DeclRefExpr>(op)->getQualifier()) {
Sebastian Redl3d3f75a2009-02-03 20:19:35 +00007873 DeclContext *Ctx = dcl->getDeclContext();
Anders Carlsson0b675f52009-07-08 21:45:58 +00007874 if (Ctx && Ctx->isRecord()) {
John McCallf3a88602011-02-03 08:15:49 +00007875 if (dcl->getType()->isReferenceType()) {
John McCall4bc41ae2010-11-18 19:01:18 +00007876 S.Diag(OpLoc,
7877 diag::err_cannot_form_pointer_to_member_of_reference_type)
John McCallf3a88602011-02-03 08:15:49 +00007878 << dcl->getDeclName() << dcl->getType();
Anders Carlsson0b675f52009-07-08 21:45:58 +00007879 return QualType();
7880 }
Mike Stump11289f42009-09-09 15:08:12 +00007881
Argyrios Kyrtzidis8322b422011-01-31 07:04:29 +00007882 while (cast<RecordDecl>(Ctx)->isAnonymousStructOrUnion())
7883 Ctx = Ctx->getParent();
John McCall4bc41ae2010-11-18 19:01:18 +00007884 return S.Context.getMemberPointerType(op->getType(),
7885 S.Context.getTypeDeclType(cast<RecordDecl>(Ctx)).getTypePtr());
Anders Carlsson0b675f52009-07-08 21:45:58 +00007886 }
Sebastian Redl3d3f75a2009-02-03 20:19:35 +00007887 }
Eli Friedman755c0c92011-08-26 20:28:17 +00007888 } else if (!isa<FunctionDecl>(dcl) && !isa<NonTypeTemplateParmDecl>(dcl))
David Blaikie83d382b2011-09-23 05:06:16 +00007889 llvm_unreachable("Unknown/unexpected decl type");
Steve Naroff47500512007-04-19 23:00:49 +00007890 }
Sebastian Redl18f8ff62009-02-04 21:23:32 +00007891
Richard Trieu5f376f62011-09-07 21:46:33 +00007892 if (AddressOfError != AO_No_Error) {
7893 diagnoseAddressOfInvalidType(S, OpLoc, op, AddressOfError);
7894 return QualType();
7895 }
7896
Eli Friedmance7f9002009-05-16 23:27:50 +00007897 if (lval == Expr::LV_IncompleteVoidType) {
7898 // Taking the address of a void variable is technically illegal, but we
7899 // allow it in cases which are otherwise valid.
7900 // Example: "extern void x; void* y = &x;".
John McCall4bc41ae2010-11-18 19:01:18 +00007901 S.Diag(OpLoc, diag::ext_typecheck_addrof_void) << op->getSourceRange();
Eli Friedmance7f9002009-05-16 23:27:50 +00007902 }
7903
Steve Naroff47500512007-04-19 23:00:49 +00007904 // If the operand has type "type", the result has type "pointer to type".
Douglas Gregor0bdcb8a2010-07-29 16:05:45 +00007905 if (op->getType()->isObjCObjectType())
John McCall4bc41ae2010-11-18 19:01:18 +00007906 return S.Context.getObjCObjectPointerType(op->getType());
7907 return S.Context.getPointerType(op->getType());
Steve Naroff47500512007-04-19 23:00:49 +00007908}
7909
Chris Lattner9156f1b2010-07-05 19:17:26 +00007910/// CheckIndirectionOperand - Type check unary indirection (prefix '*').
John McCall4bc41ae2010-11-18 19:01:18 +00007911static QualType CheckIndirectionOperand(Sema &S, Expr *Op, ExprValueKind &VK,
7912 SourceLocation OpLoc) {
Sebastian Redl8d2ccae2009-02-26 14:39:58 +00007913 if (Op->isTypeDependent())
John McCall4bc41ae2010-11-18 19:01:18 +00007914 return S.Context.DependentTy;
Sebastian Redl8d2ccae2009-02-26 14:39:58 +00007915
John Wiegley01296292011-04-08 18:41:53 +00007916 ExprResult ConvResult = S.UsualUnaryConversions(Op);
7917 if (ConvResult.isInvalid())
7918 return QualType();
7919 Op = ConvResult.take();
Chris Lattner9156f1b2010-07-05 19:17:26 +00007920 QualType OpTy = Op->getType();
7921 QualType Result;
Argyrios Kyrtzidis69a2c922011-05-02 18:21:19 +00007922
7923 if (isa<CXXReinterpretCastExpr>(Op)) {
7924 QualType OpOrigType = Op->IgnoreParenCasts()->getType();
7925 S.CheckCompatibleReinterpretCast(OpOrigType, OpTy, /*IsDereference*/true,
7926 Op->getSourceRange());
7927 }
7928
Chris Lattner9156f1b2010-07-05 19:17:26 +00007929 // Note that per both C89 and C99, indirection is always legal, even if OpTy
7930 // is an incomplete type or void. It would be possible to warn about
7931 // dereferencing a void pointer, but it's completely well-defined, and such a
7932 // warning is unlikely to catch any mistakes.
7933 if (const PointerType *PT = OpTy->getAs<PointerType>())
7934 Result = PT->getPointeeType();
7935 else if (const ObjCObjectPointerType *OPT =
7936 OpTy->getAs<ObjCObjectPointerType>())
7937 Result = OPT->getPointeeType();
John McCall36226622010-10-12 02:09:17 +00007938 else {
John McCall3aef3d82011-04-10 19:13:55 +00007939 ExprResult PR = S.CheckPlaceholderExpr(Op);
John McCall36226622010-10-12 02:09:17 +00007940 if (PR.isInvalid()) return QualType();
John McCall4bc41ae2010-11-18 19:01:18 +00007941 if (PR.take() != Op)
7942 return CheckIndirectionOperand(S, PR.take(), VK, OpLoc);
John McCall36226622010-10-12 02:09:17 +00007943 }
Mike Stump4e1f26a2009-02-19 03:04:26 +00007944
Chris Lattner9156f1b2010-07-05 19:17:26 +00007945 if (Result.isNull()) {
John McCall4bc41ae2010-11-18 19:01:18 +00007946 S.Diag(OpLoc, diag::err_typecheck_indirection_requires_pointer)
Chris Lattner9156f1b2010-07-05 19:17:26 +00007947 << OpTy << Op->getSourceRange();
7948 return QualType();
7949 }
John McCall4bc41ae2010-11-18 19:01:18 +00007950
7951 // Dereferences are usually l-values...
7952 VK = VK_LValue;
7953
7954 // ...except that certain expressions are never l-values in C.
David Blaikiebbafb8a2012-03-11 07:00:24 +00007955 if (!S.getLangOpts().CPlusPlus && Result.isCForbiddenLValueType())
John McCall4bc41ae2010-11-18 19:01:18 +00007956 VK = VK_RValue;
Chris Lattner9156f1b2010-07-05 19:17:26 +00007957
7958 return Result;
Steve Naroff1926c832007-04-24 00:23:05 +00007959}
Steve Naroff218bc2b2007-05-04 21:54:46 +00007960
John McCalle3027922010-08-25 11:45:40 +00007961static inline BinaryOperatorKind ConvertTokenKindToBinaryOpcode(
Steve Naroff218bc2b2007-05-04 21:54:46 +00007962 tok::TokenKind Kind) {
John McCalle3027922010-08-25 11:45:40 +00007963 BinaryOperatorKind Opc;
Steve Naroff218bc2b2007-05-04 21:54:46 +00007964 switch (Kind) {
David Blaikie83d382b2011-09-23 05:06:16 +00007965 default: llvm_unreachable("Unknown binop!");
John McCalle3027922010-08-25 11:45:40 +00007966 case tok::periodstar: Opc = BO_PtrMemD; break;
7967 case tok::arrowstar: Opc = BO_PtrMemI; break;
7968 case tok::star: Opc = BO_Mul; break;
7969 case tok::slash: Opc = BO_Div; break;
7970 case tok::percent: Opc = BO_Rem; break;
7971 case tok::plus: Opc = BO_Add; break;
7972 case tok::minus: Opc = BO_Sub; break;
7973 case tok::lessless: Opc = BO_Shl; break;
7974 case tok::greatergreater: Opc = BO_Shr; break;
7975 case tok::lessequal: Opc = BO_LE; break;
7976 case tok::less: Opc = BO_LT; break;
7977 case tok::greaterequal: Opc = BO_GE; break;
7978 case tok::greater: Opc = BO_GT; break;
7979 case tok::exclaimequal: Opc = BO_NE; break;
7980 case tok::equalequal: Opc = BO_EQ; break;
7981 case tok::amp: Opc = BO_And; break;
7982 case tok::caret: Opc = BO_Xor; break;
7983 case tok::pipe: Opc = BO_Or; break;
7984 case tok::ampamp: Opc = BO_LAnd; break;
7985 case tok::pipepipe: Opc = BO_LOr; break;
7986 case tok::equal: Opc = BO_Assign; break;
7987 case tok::starequal: Opc = BO_MulAssign; break;
7988 case tok::slashequal: Opc = BO_DivAssign; break;
7989 case tok::percentequal: Opc = BO_RemAssign; break;
7990 case tok::plusequal: Opc = BO_AddAssign; break;
7991 case tok::minusequal: Opc = BO_SubAssign; break;
7992 case tok::lesslessequal: Opc = BO_ShlAssign; break;
7993 case tok::greatergreaterequal: Opc = BO_ShrAssign; break;
7994 case tok::ampequal: Opc = BO_AndAssign; break;
7995 case tok::caretequal: Opc = BO_XorAssign; break;
7996 case tok::pipeequal: Opc = BO_OrAssign; break;
7997 case tok::comma: Opc = BO_Comma; break;
Steve Naroff218bc2b2007-05-04 21:54:46 +00007998 }
7999 return Opc;
8000}
8001
John McCalle3027922010-08-25 11:45:40 +00008002static inline UnaryOperatorKind ConvertTokenKindToUnaryOpcode(
Steve Naroff35d85152007-05-07 00:24:15 +00008003 tok::TokenKind Kind) {
John McCalle3027922010-08-25 11:45:40 +00008004 UnaryOperatorKind Opc;
Steve Naroff35d85152007-05-07 00:24:15 +00008005 switch (Kind) {
David Blaikie83d382b2011-09-23 05:06:16 +00008006 default: llvm_unreachable("Unknown unary op!");
John McCalle3027922010-08-25 11:45:40 +00008007 case tok::plusplus: Opc = UO_PreInc; break;
8008 case tok::minusminus: Opc = UO_PreDec; break;
8009 case tok::amp: Opc = UO_AddrOf; break;
8010 case tok::star: Opc = UO_Deref; break;
8011 case tok::plus: Opc = UO_Plus; break;
8012 case tok::minus: Opc = UO_Minus; break;
8013 case tok::tilde: Opc = UO_Not; break;
8014 case tok::exclaim: Opc = UO_LNot; break;
8015 case tok::kw___real: Opc = UO_Real; break;
8016 case tok::kw___imag: Opc = UO_Imag; break;
8017 case tok::kw___extension__: Opc = UO_Extension; break;
Steve Naroff35d85152007-05-07 00:24:15 +00008018 }
8019 return Opc;
8020}
8021
Chandler Carruthe0cee6a2011-01-04 06:52:15 +00008022/// DiagnoseSelfAssignment - Emits a warning if a value is assigned to itself.
8023/// This warning is only emitted for builtin assignment operations. It is also
8024/// suppressed in the event of macro expansions.
Richard Trieuda4f43a62011-09-07 01:33:52 +00008025static void DiagnoseSelfAssignment(Sema &S, Expr *LHSExpr, Expr *RHSExpr,
Chandler Carruthe0cee6a2011-01-04 06:52:15 +00008026 SourceLocation OpLoc) {
8027 if (!S.ActiveTemplateInstantiations.empty())
8028 return;
8029 if (OpLoc.isInvalid() || OpLoc.isMacroID())
8030 return;
Richard Trieuda4f43a62011-09-07 01:33:52 +00008031 LHSExpr = LHSExpr->IgnoreParenImpCasts();
8032 RHSExpr = RHSExpr->IgnoreParenImpCasts();
8033 const DeclRefExpr *LHSDeclRef = dyn_cast<DeclRefExpr>(LHSExpr);
8034 const DeclRefExpr *RHSDeclRef = dyn_cast<DeclRefExpr>(RHSExpr);
8035 if (!LHSDeclRef || !RHSDeclRef ||
8036 LHSDeclRef->getLocation().isMacroID() ||
8037 RHSDeclRef->getLocation().isMacroID())
Chandler Carruthe0cee6a2011-01-04 06:52:15 +00008038 return;
Richard Trieuda4f43a62011-09-07 01:33:52 +00008039 const ValueDecl *LHSDecl =
8040 cast<ValueDecl>(LHSDeclRef->getDecl()->getCanonicalDecl());
8041 const ValueDecl *RHSDecl =
8042 cast<ValueDecl>(RHSDeclRef->getDecl()->getCanonicalDecl());
8043 if (LHSDecl != RHSDecl)
Chandler Carruthe0cee6a2011-01-04 06:52:15 +00008044 return;
Richard Trieuda4f43a62011-09-07 01:33:52 +00008045 if (LHSDecl->getType().isVolatileQualified())
Chandler Carruthe0cee6a2011-01-04 06:52:15 +00008046 return;
Richard Trieuda4f43a62011-09-07 01:33:52 +00008047 if (const ReferenceType *RefTy = LHSDecl->getType()->getAs<ReferenceType>())
Chandler Carruthe0cee6a2011-01-04 06:52:15 +00008048 if (RefTy->getPointeeType().isVolatileQualified())
8049 return;
8050
8051 S.Diag(OpLoc, diag::warn_self_assignment)
Richard Trieuda4f43a62011-09-07 01:33:52 +00008052 << LHSDeclRef->getType()
8053 << LHSExpr->getSourceRange() << RHSExpr->getSourceRange();
Chandler Carruthe0cee6a2011-01-04 06:52:15 +00008054}
8055
Douglas Gregor7d5fc7e2008-11-06 23:29:22 +00008056/// CreateBuiltinBinOp - Creates a new built-in binary operation with
8057/// operator @p Opc at location @c TokLoc. This routine only supports
8058/// built-in operations; ActOnBinOp handles overloaded operators.
John McCalldadc5752010-08-24 06:29:42 +00008059ExprResult Sema::CreateBuiltinBinOp(SourceLocation OpLoc,
Argyrios Kyrtzidis7a808c02011-01-05 20:09:36 +00008060 BinaryOperatorKind Opc,
Richard Trieu4a287fb2011-09-07 01:49:20 +00008061 Expr *LHSExpr, Expr *RHSExpr) {
David Blaikiebbafb8a2012-03-11 07:00:24 +00008062 if (getLangOpts().CPlusPlus0x && isa<InitListExpr>(RHSExpr)) {
Sebastian Redl67766732012-02-27 20:34:02 +00008063 // The syntax only allows initializer lists on the RHS of assignment,
8064 // so we don't need to worry about accepting invalid code for
8065 // non-assignment operators.
8066 // C++11 5.17p9:
8067 // The meaning of x = {v} [...] is that of x = T(v) [...]. The meaning
8068 // of x = {} is x = T().
8069 InitializationKind Kind =
8070 InitializationKind::CreateDirectList(RHSExpr->getLocStart());
8071 InitializedEntity Entity =
8072 InitializedEntity::InitializeTemporary(LHSExpr->getType());
8073 InitializationSequence InitSeq(*this, Entity, Kind, &RHSExpr, 1);
8074 ExprResult Init = InitSeq.Perform(*this, Entity, Kind,
8075 MultiExprArg(&RHSExpr, 1));
8076 if (Init.isInvalid())
8077 return Init;
8078 RHSExpr = Init.take();
8079 }
8080
Richard Trieu4a287fb2011-09-07 01:49:20 +00008081 ExprResult LHS = Owned(LHSExpr), RHS = Owned(RHSExpr);
Eli Friedman8b7b1b12009-03-28 01:22:36 +00008082 QualType ResultTy; // Result type of the binary operator.
Eli Friedman8b7b1b12009-03-28 01:22:36 +00008083 // The following two variables are used for compound assignment operators
8084 QualType CompLHSTy; // Type of LHS after promotions for computation
8085 QualType CompResultTy; // Type of computation result
John McCall7decc9e2010-11-18 06:31:45 +00008086 ExprValueKind VK = VK_RValue;
8087 ExprObjectKind OK = OK_Ordinary;
Douglas Gregor7d5fc7e2008-11-06 23:29:22 +00008088
8089 switch (Opc) {
John McCalle3027922010-08-25 11:45:40 +00008090 case BO_Assign:
Richard Trieu4a287fb2011-09-07 01:49:20 +00008091 ResultTy = CheckAssignmentOperands(LHS.get(), RHS, OpLoc, QualType());
David Blaikiebbafb8a2012-03-11 07:00:24 +00008092 if (getLangOpts().CPlusPlus &&
Richard Trieu4a287fb2011-09-07 01:49:20 +00008093 LHS.get()->getObjectKind() != OK_ObjCProperty) {
8094 VK = LHS.get()->getValueKind();
8095 OK = LHS.get()->getObjectKind();
John McCall7decc9e2010-11-18 06:31:45 +00008096 }
Chandler Carruthe0cee6a2011-01-04 06:52:15 +00008097 if (!ResultTy.isNull())
Richard Trieu4a287fb2011-09-07 01:49:20 +00008098 DiagnoseSelfAssignment(*this, LHS.get(), RHS.get(), OpLoc);
Douglas Gregor7d5fc7e2008-11-06 23:29:22 +00008099 break;
John McCalle3027922010-08-25 11:45:40 +00008100 case BO_PtrMemD:
8101 case BO_PtrMemI:
Richard Trieu4a287fb2011-09-07 01:49:20 +00008102 ResultTy = CheckPointerToMemberOperands(LHS, RHS, VK, OpLoc,
John McCalle3027922010-08-25 11:45:40 +00008103 Opc == BO_PtrMemI);
Sebastian Redl112a97662009-02-07 00:15:38 +00008104 break;
John McCalle3027922010-08-25 11:45:40 +00008105 case BO_Mul:
8106 case BO_Div:
Richard Trieu4a287fb2011-09-07 01:49:20 +00008107 ResultTy = CheckMultiplyDivideOperands(LHS, RHS, OpLoc, false,
John McCalle3027922010-08-25 11:45:40 +00008108 Opc == BO_Div);
Douglas Gregor7d5fc7e2008-11-06 23:29:22 +00008109 break;
John McCalle3027922010-08-25 11:45:40 +00008110 case BO_Rem:
Richard Trieu4a287fb2011-09-07 01:49:20 +00008111 ResultTy = CheckRemainderOperands(LHS, RHS, OpLoc);
Douglas Gregor7d5fc7e2008-11-06 23:29:22 +00008112 break;
John McCalle3027922010-08-25 11:45:40 +00008113 case BO_Add:
Nico Weberccec40d2012-03-02 22:01:22 +00008114 ResultTy = CheckAdditionOperands(LHS, RHS, OpLoc, Opc);
Douglas Gregor7d5fc7e2008-11-06 23:29:22 +00008115 break;
John McCalle3027922010-08-25 11:45:40 +00008116 case BO_Sub:
Richard Trieu4a287fb2011-09-07 01:49:20 +00008117 ResultTy = CheckSubtractionOperands(LHS, RHS, OpLoc);
Douglas Gregor7d5fc7e2008-11-06 23:29:22 +00008118 break;
John McCalle3027922010-08-25 11:45:40 +00008119 case BO_Shl:
8120 case BO_Shr:
Richard Trieu4a287fb2011-09-07 01:49:20 +00008121 ResultTy = CheckShiftOperands(LHS, RHS, OpLoc, Opc);
Douglas Gregor7d5fc7e2008-11-06 23:29:22 +00008122 break;
John McCalle3027922010-08-25 11:45:40 +00008123 case BO_LE:
8124 case BO_LT:
8125 case BO_GE:
8126 case BO_GT:
Richard Trieu4a287fb2011-09-07 01:49:20 +00008127 ResultTy = CheckCompareOperands(LHS, RHS, OpLoc, Opc, true);
Douglas Gregor7d5fc7e2008-11-06 23:29:22 +00008128 break;
John McCalle3027922010-08-25 11:45:40 +00008129 case BO_EQ:
8130 case BO_NE:
Jordan Rosed49a33e2012-06-08 21:14:25 +00008131 if (isObjCObjectLiteral(LHS) || isObjCObjectLiteral(RHS)) {
8132 ExprResult IsEqualCall = fixObjCLiteralComparison(*this, OpLoc,
8133 LHS, RHS, Opc);
8134 if (IsEqualCall.isUsable())
8135 return IsEqualCall;
8136 // Otherwise, fall back to the normal diagnostic in CheckCompareOperands.
8137 }
Richard Trieu4a287fb2011-09-07 01:49:20 +00008138 ResultTy = CheckCompareOperands(LHS, RHS, OpLoc, Opc, false);
Douglas Gregor7d5fc7e2008-11-06 23:29:22 +00008139 break;
John McCalle3027922010-08-25 11:45:40 +00008140 case BO_And:
8141 case BO_Xor:
8142 case BO_Or:
Richard Trieu4a287fb2011-09-07 01:49:20 +00008143 ResultTy = CheckBitwiseOperands(LHS, RHS, OpLoc);
Douglas Gregor7d5fc7e2008-11-06 23:29:22 +00008144 break;
John McCalle3027922010-08-25 11:45:40 +00008145 case BO_LAnd:
8146 case BO_LOr:
Richard Trieu4a287fb2011-09-07 01:49:20 +00008147 ResultTy = CheckLogicalOperands(LHS, RHS, OpLoc, Opc);
Douglas Gregor7d5fc7e2008-11-06 23:29:22 +00008148 break;
John McCalle3027922010-08-25 11:45:40 +00008149 case BO_MulAssign:
8150 case BO_DivAssign:
Richard Trieu4a287fb2011-09-07 01:49:20 +00008151 CompResultTy = CheckMultiplyDivideOperands(LHS, RHS, OpLoc, true,
John McCall7decc9e2010-11-18 06:31:45 +00008152 Opc == BO_DivAssign);
Eli Friedman8b7b1b12009-03-28 01:22:36 +00008153 CompLHSTy = CompResultTy;
Richard Trieu4a287fb2011-09-07 01:49:20 +00008154 if (!CompResultTy.isNull() && !LHS.isInvalid() && !RHS.isInvalid())
8155 ResultTy = CheckAssignmentOperands(LHS.get(), RHS, OpLoc, CompResultTy);
Douglas Gregor7d5fc7e2008-11-06 23:29:22 +00008156 break;
John McCalle3027922010-08-25 11:45:40 +00008157 case BO_RemAssign:
Richard Trieu4a287fb2011-09-07 01:49:20 +00008158 CompResultTy = CheckRemainderOperands(LHS, RHS, OpLoc, true);
Eli Friedman8b7b1b12009-03-28 01:22:36 +00008159 CompLHSTy = CompResultTy;
Richard Trieu4a287fb2011-09-07 01:49:20 +00008160 if (!CompResultTy.isNull() && !LHS.isInvalid() && !RHS.isInvalid())
8161 ResultTy = CheckAssignmentOperands(LHS.get(), RHS, OpLoc, CompResultTy);
Douglas Gregor7d5fc7e2008-11-06 23:29:22 +00008162 break;
John McCalle3027922010-08-25 11:45:40 +00008163 case BO_AddAssign:
Nico Weberccec40d2012-03-02 22:01:22 +00008164 CompResultTy = CheckAdditionOperands(LHS, RHS, OpLoc, Opc, &CompLHSTy);
Richard Trieu4a287fb2011-09-07 01:49:20 +00008165 if (!CompResultTy.isNull() && !LHS.isInvalid() && !RHS.isInvalid())
8166 ResultTy = CheckAssignmentOperands(LHS.get(), RHS, OpLoc, CompResultTy);
Douglas Gregor7d5fc7e2008-11-06 23:29:22 +00008167 break;
John McCalle3027922010-08-25 11:45:40 +00008168 case BO_SubAssign:
Richard Trieu4a287fb2011-09-07 01:49:20 +00008169 CompResultTy = CheckSubtractionOperands(LHS, RHS, OpLoc, &CompLHSTy);
8170 if (!CompResultTy.isNull() && !LHS.isInvalid() && !RHS.isInvalid())
8171 ResultTy = CheckAssignmentOperands(LHS.get(), RHS, OpLoc, CompResultTy);
Douglas Gregor7d5fc7e2008-11-06 23:29:22 +00008172 break;
John McCalle3027922010-08-25 11:45:40 +00008173 case BO_ShlAssign:
8174 case BO_ShrAssign:
Richard Trieu4a287fb2011-09-07 01:49:20 +00008175 CompResultTy = CheckShiftOperands(LHS, RHS, OpLoc, Opc, true);
Eli Friedman8b7b1b12009-03-28 01:22:36 +00008176 CompLHSTy = CompResultTy;
Richard Trieu4a287fb2011-09-07 01:49:20 +00008177 if (!CompResultTy.isNull() && !LHS.isInvalid() && !RHS.isInvalid())
8178 ResultTy = CheckAssignmentOperands(LHS.get(), RHS, OpLoc, CompResultTy);
Douglas Gregor7d5fc7e2008-11-06 23:29:22 +00008179 break;
John McCalle3027922010-08-25 11:45:40 +00008180 case BO_AndAssign:
8181 case BO_XorAssign:
8182 case BO_OrAssign:
Richard Trieu4a287fb2011-09-07 01:49:20 +00008183 CompResultTy = CheckBitwiseOperands(LHS, RHS, OpLoc, true);
Eli Friedman8b7b1b12009-03-28 01:22:36 +00008184 CompLHSTy = CompResultTy;
Richard Trieu4a287fb2011-09-07 01:49:20 +00008185 if (!CompResultTy.isNull() && !LHS.isInvalid() && !RHS.isInvalid())
8186 ResultTy = CheckAssignmentOperands(LHS.get(), RHS, OpLoc, CompResultTy);
Douglas Gregor7d5fc7e2008-11-06 23:29:22 +00008187 break;
John McCalle3027922010-08-25 11:45:40 +00008188 case BO_Comma:
Richard Trieu4a287fb2011-09-07 01:49:20 +00008189 ResultTy = CheckCommaOperands(*this, LHS, RHS, OpLoc);
David Blaikiebbafb8a2012-03-11 07:00:24 +00008190 if (getLangOpts().CPlusPlus && !RHS.isInvalid()) {
Richard Trieu4a287fb2011-09-07 01:49:20 +00008191 VK = RHS.get()->getValueKind();
8192 OK = RHS.get()->getObjectKind();
John McCall7decc9e2010-11-18 06:31:45 +00008193 }
Douglas Gregor7d5fc7e2008-11-06 23:29:22 +00008194 break;
8195 }
Richard Trieu4a287fb2011-09-07 01:49:20 +00008196 if (ResultTy.isNull() || LHS.isInvalid() || RHS.isInvalid())
Sebastian Redlb5d49352009-01-19 22:31:54 +00008197 return ExprError();
Kaelyn Uhrain2e7aa5a2011-08-05 23:18:04 +00008198
8199 // Check for array bounds violations for both sides of the BinaryOperator
Richard Trieu4a287fb2011-09-07 01:49:20 +00008200 CheckArrayAccess(LHS.get());
8201 CheckArrayAccess(RHS.get());
Kaelyn Uhrain2e7aa5a2011-08-05 23:18:04 +00008202
Eli Friedman8b7b1b12009-03-28 01:22:36 +00008203 if (CompResultTy.isNull())
Richard Trieu4a287fb2011-09-07 01:49:20 +00008204 return Owned(new (Context) BinaryOperator(LHS.take(), RHS.take(), Opc,
John Wiegley01296292011-04-08 18:41:53 +00008205 ResultTy, VK, OK, OpLoc));
David Blaikiebbafb8a2012-03-11 07:00:24 +00008206 if (getLangOpts().CPlusPlus && LHS.get()->getObjectKind() !=
Richard Trieucfc491d2011-08-02 04:35:43 +00008207 OK_ObjCProperty) {
John McCall7decc9e2010-11-18 06:31:45 +00008208 VK = VK_LValue;
Richard Trieu4a287fb2011-09-07 01:49:20 +00008209 OK = LHS.get()->getObjectKind();
John McCall7decc9e2010-11-18 06:31:45 +00008210 }
Richard Trieu4a287fb2011-09-07 01:49:20 +00008211 return Owned(new (Context) CompoundAssignOperator(LHS.take(), RHS.take(), Opc,
John Wiegley01296292011-04-08 18:41:53 +00008212 ResultTy, VK, OK, CompLHSTy,
John McCall7decc9e2010-11-18 06:31:45 +00008213 CompResultTy, OpLoc));
Douglas Gregor7d5fc7e2008-11-06 23:29:22 +00008214}
8215
Sebastian Redl44615072009-10-27 12:10:02 +00008216/// DiagnoseBitwisePrecedence - Emit a warning when bitwise and comparison
8217/// operators are mixed in a way that suggests that the programmer forgot that
8218/// comparison operators have higher precedence. The most typical example of
8219/// such code is "flags & 0x0020 != 0", which is equivalent to "flags & 1".
John McCalle3027922010-08-25 11:45:40 +00008220static void DiagnoseBitwisePrecedence(Sema &Self, BinaryOperatorKind Opc,
Richard Trieu4a287fb2011-09-07 01:49:20 +00008221 SourceLocation OpLoc, Expr *LHSExpr,
8222 Expr *RHSExpr) {
Sebastian Redl44615072009-10-27 12:10:02 +00008223 typedef BinaryOperator BinOp;
Richard Trieu4a287fb2011-09-07 01:49:20 +00008224 BinOp::Opcode LHSopc = static_cast<BinOp::Opcode>(-1),
8225 RHSopc = static_cast<BinOp::Opcode>(-1);
8226 if (BinOp *BO = dyn_cast<BinOp>(LHSExpr))
8227 LHSopc = BO->getOpcode();
8228 if (BinOp *BO = dyn_cast<BinOp>(RHSExpr))
8229 RHSopc = BO->getOpcode();
Sebastian Redl43028242009-10-26 15:24:15 +00008230
8231 // Subs are not binary operators.
Richard Trieu4a287fb2011-09-07 01:49:20 +00008232 if (LHSopc == -1 && RHSopc == -1)
Sebastian Redl43028242009-10-26 15:24:15 +00008233 return;
8234
8235 // Bitwise operations are sometimes used as eager logical ops.
8236 // Don't diagnose this.
Richard Trieu4a287fb2011-09-07 01:49:20 +00008237 if ((BinOp::isComparisonOp(LHSopc) || BinOp::isBitwiseOp(LHSopc)) &&
8238 (BinOp::isComparisonOp(RHSopc) || BinOp::isBitwiseOp(RHSopc)))
Sebastian Redl43028242009-10-26 15:24:15 +00008239 return;
8240
Richard Trieu4a287fb2011-09-07 01:49:20 +00008241 bool isLeftComp = BinOp::isComparisonOp(LHSopc);
8242 bool isRightComp = BinOp::isComparisonOp(RHSopc);
Richard Trieu73088052011-08-10 22:41:34 +00008243 if (!isLeftComp && !isRightComp) return;
8244
Richard Trieu4a287fb2011-09-07 01:49:20 +00008245 SourceRange DiagRange = isLeftComp ? SourceRange(LHSExpr->getLocStart(),
8246 OpLoc)
8247 : SourceRange(OpLoc, RHSExpr->getLocEnd());
8248 std::string OpStr = isLeftComp ? BinOp::getOpcodeStr(LHSopc)
8249 : BinOp::getOpcodeStr(RHSopc);
Richard Trieu73088052011-08-10 22:41:34 +00008250 SourceRange ParensRange = isLeftComp ?
Richard Trieu4a287fb2011-09-07 01:49:20 +00008251 SourceRange(cast<BinOp>(LHSExpr)->getRHS()->getLocStart(),
8252 RHSExpr->getLocEnd())
8253 : SourceRange(LHSExpr->getLocStart(),
8254 cast<BinOp>(RHSExpr)->getLHS()->getLocStart());
Richard Trieu73088052011-08-10 22:41:34 +00008255
8256 Self.Diag(OpLoc, diag::warn_precedence_bitwise_rel)
8257 << DiagRange << BinOp::getOpcodeStr(Opc) << OpStr;
8258 SuggestParentheses(Self, OpLoc,
8259 Self.PDiag(diag::note_precedence_bitwise_silence) << OpStr,
Nico Webercdfb1ae2012-06-03 07:07:00 +00008260 (isLeftComp ? LHSExpr : RHSExpr)->getSourceRange());
Richard Trieu73088052011-08-10 22:41:34 +00008261 SuggestParentheses(Self, OpLoc,
8262 Self.PDiag(diag::note_precedence_bitwise_first) << BinOp::getOpcodeStr(Opc),
8263 ParensRange);
Sebastian Redl43028242009-10-26 15:24:15 +00008264}
8265
Argyrios Kyrtzidis01bf7772011-06-20 18:41:26 +00008266/// \brief It accepts a '&' expr that is inside a '|' one.
8267/// Emit a diagnostic together with a fixit hint that wraps the '&' expression
8268/// in parentheses.
8269static void
8270EmitDiagnosticForBitwiseAndInBitwiseOr(Sema &Self, SourceLocation OpLoc,
8271 BinaryOperator *Bop) {
8272 assert(Bop->getOpcode() == BO_And);
8273 Self.Diag(Bop->getOperatorLoc(), diag::warn_bitwise_and_in_bitwise_or)
8274 << Bop->getSourceRange() << OpLoc;
8275 SuggestParentheses(Self, Bop->getOperatorLoc(),
8276 Self.PDiag(diag::note_bitwise_and_in_bitwise_or_silence),
8277 Bop->getSourceRange());
8278}
8279
Argyrios Kyrtzidis14a96622010-11-17 18:26:36 +00008280/// \brief It accepts a '&&' expr that is inside a '||' one.
8281/// Emit a diagnostic together with a fixit hint that wraps the '&&' expression
8282/// in parentheses.
8283static void
8284EmitDiagnosticForLogicalAndInLogicalOr(Sema &Self, SourceLocation OpLoc,
Argyrios Kyrtzidisad8b4d42011-04-22 19:16:27 +00008285 BinaryOperator *Bop) {
8286 assert(Bop->getOpcode() == BO_LAnd);
Chandler Carruthb00e8c02011-06-16 01:05:14 +00008287 Self.Diag(Bop->getOperatorLoc(), diag::warn_logical_and_in_logical_or)
8288 << Bop->getSourceRange() << OpLoc;
Argyrios Kyrtzidisad8b4d42011-04-22 19:16:27 +00008289 SuggestParentheses(Self, Bop->getOperatorLoc(),
Argyrios Kyrtzidis14a96622010-11-17 18:26:36 +00008290 Self.PDiag(diag::note_logical_and_in_logical_or_silence),
Chandler Carruthb00e8c02011-06-16 01:05:14 +00008291 Bop->getSourceRange());
Argyrios Kyrtzidis14a96622010-11-17 18:26:36 +00008292}
8293
8294/// \brief Returns true if the given expression can be evaluated as a constant
8295/// 'true'.
8296static bool EvaluatesAsTrue(Sema &S, Expr *E) {
8297 bool Res;
8298 return E->EvaluateAsBooleanCondition(Res, S.getASTContext()) && Res;
8299}
8300
Argyrios Kyrtzidis56e879d2010-11-17 19:18:19 +00008301/// \brief Returns true if the given expression can be evaluated as a constant
8302/// 'false'.
8303static bool EvaluatesAsFalse(Sema &S, Expr *E) {
8304 bool Res;
8305 return E->EvaluateAsBooleanCondition(Res, S.getASTContext()) && !Res;
8306}
8307
Argyrios Kyrtzidis14a96622010-11-17 18:26:36 +00008308/// \brief Look for '&&' in the left hand of a '||' expr.
8309static void DiagnoseLogicalAndInLogicalOrLHS(Sema &S, SourceLocation OpLoc,
Richard Trieuf9bd0f52011-09-07 02:02:10 +00008310 Expr *LHSExpr, Expr *RHSExpr) {
8311 if (BinaryOperator *Bop = dyn_cast<BinaryOperator>(LHSExpr)) {
Argyrios Kyrtzidisf89a56c2010-11-16 21:00:12 +00008312 if (Bop->getOpcode() == BO_LAnd) {
Argyrios Kyrtzidis56e879d2010-11-17 19:18:19 +00008313 // If it's "a && b || 0" don't warn since the precedence doesn't matter.
Richard Trieuf9bd0f52011-09-07 02:02:10 +00008314 if (EvaluatesAsFalse(S, RHSExpr))
Argyrios Kyrtzidis56e879d2010-11-17 19:18:19 +00008315 return;
Argyrios Kyrtzidis14a96622010-11-17 18:26:36 +00008316 // If it's "1 && a || b" don't warn since the precedence doesn't matter.
8317 if (!EvaluatesAsTrue(S, Bop->getLHS()))
8318 return EmitDiagnosticForLogicalAndInLogicalOr(S, OpLoc, Bop);
8319 } else if (Bop->getOpcode() == BO_LOr) {
8320 if (BinaryOperator *RBop = dyn_cast<BinaryOperator>(Bop->getRHS())) {
8321 // If it's "a || b && 1 || c" we didn't warn earlier for
8322 // "a || b && 1", but warn now.
8323 if (RBop->getOpcode() == BO_LAnd && EvaluatesAsTrue(S, RBop->getRHS()))
8324 return EmitDiagnosticForLogicalAndInLogicalOr(S, OpLoc, RBop);
8325 }
8326 }
8327 }
8328}
8329
8330/// \brief Look for '&&' in the right hand of a '||' expr.
8331static void DiagnoseLogicalAndInLogicalOrRHS(Sema &S, SourceLocation OpLoc,
Richard Trieuf9bd0f52011-09-07 02:02:10 +00008332 Expr *LHSExpr, Expr *RHSExpr) {
8333 if (BinaryOperator *Bop = dyn_cast<BinaryOperator>(RHSExpr)) {
Argyrios Kyrtzidis14a96622010-11-17 18:26:36 +00008334 if (Bop->getOpcode() == BO_LAnd) {
Argyrios Kyrtzidis56e879d2010-11-17 19:18:19 +00008335 // If it's "0 || a && b" don't warn since the precedence doesn't matter.
Richard Trieuf9bd0f52011-09-07 02:02:10 +00008336 if (EvaluatesAsFalse(S, LHSExpr))
Argyrios Kyrtzidis56e879d2010-11-17 19:18:19 +00008337 return;
Argyrios Kyrtzidis14a96622010-11-17 18:26:36 +00008338 // If it's "a || b && 1" don't warn since the precedence doesn't matter.
8339 if (!EvaluatesAsTrue(S, Bop->getRHS()))
8340 return EmitDiagnosticForLogicalAndInLogicalOr(S, OpLoc, Bop);
Argyrios Kyrtzidisf89a56c2010-11-16 21:00:12 +00008341 }
8342 }
8343}
8344
Argyrios Kyrtzidis01bf7772011-06-20 18:41:26 +00008345/// \brief Look for '&' in the left or right hand of a '|' expr.
8346static void DiagnoseBitwiseAndInBitwiseOr(Sema &S, SourceLocation OpLoc,
8347 Expr *OrArg) {
8348 if (BinaryOperator *Bop = dyn_cast<BinaryOperator>(OrArg)) {
8349 if (Bop->getOpcode() == BO_And)
8350 return EmitDiagnosticForBitwiseAndInBitwiseOr(S, OpLoc, Bop);
8351 }
8352}
8353
Sebastian Redl43028242009-10-26 15:24:15 +00008354/// DiagnoseBinOpPrecedence - Emit warnings for expressions with tricky
Argyrios Kyrtzidisf89a56c2010-11-16 21:00:12 +00008355/// precedence.
John McCalle3027922010-08-25 11:45:40 +00008356static void DiagnoseBinOpPrecedence(Sema &Self, BinaryOperatorKind Opc,
Richard Trieuf9bd0f52011-09-07 02:02:10 +00008357 SourceLocation OpLoc, Expr *LHSExpr,
8358 Expr *RHSExpr){
Argyrios Kyrtzidisf89a56c2010-11-16 21:00:12 +00008359 // Diagnose "arg1 'bitwise' arg2 'eq' arg3".
Sebastian Redl44615072009-10-27 12:10:02 +00008360 if (BinaryOperator::isBitwiseOp(Opc))
Richard Trieuf9bd0f52011-09-07 02:02:10 +00008361 DiagnoseBitwisePrecedence(Self, Opc, OpLoc, LHSExpr, RHSExpr);
Argyrios Kyrtzidis01bf7772011-06-20 18:41:26 +00008362
8363 // Diagnose "arg1 & arg2 | arg3"
8364 if (Opc == BO_Or && !OpLoc.isMacroID()/* Don't warn in macros. */) {
Richard Trieuf9bd0f52011-09-07 02:02:10 +00008365 DiagnoseBitwiseAndInBitwiseOr(Self, OpLoc, LHSExpr);
8366 DiagnoseBitwiseAndInBitwiseOr(Self, OpLoc, RHSExpr);
Argyrios Kyrtzidis01bf7772011-06-20 18:41:26 +00008367 }
Argyrios Kyrtzidisf89a56c2010-11-16 21:00:12 +00008368
Argyrios Kyrtzidis14a96622010-11-17 18:26:36 +00008369 // Warn about arg1 || arg2 && arg3, as GCC 4.3+ does.
8370 // We don't warn for 'assert(a || b && "bad")' since this is safe.
Argyrios Kyrtzidisb94e5a32010-11-17 18:54:22 +00008371 if (Opc == BO_LOr && !OpLoc.isMacroID()/* Don't warn in macros. */) {
Richard Trieuf9bd0f52011-09-07 02:02:10 +00008372 DiagnoseLogicalAndInLogicalOrLHS(Self, OpLoc, LHSExpr, RHSExpr);
8373 DiagnoseLogicalAndInLogicalOrRHS(Self, OpLoc, LHSExpr, RHSExpr);
Argyrios Kyrtzidisf89a56c2010-11-16 21:00:12 +00008374 }
Sebastian Redl43028242009-10-26 15:24:15 +00008375}
8376
Steve Naroff218bc2b2007-05-04 21:54:46 +00008377// Binary Operators. 'Tok' is the token for the operator.
John McCalldadc5752010-08-24 06:29:42 +00008378ExprResult Sema::ActOnBinOp(Scope *S, SourceLocation TokLoc,
John McCalle3027922010-08-25 11:45:40 +00008379 tok::TokenKind Kind,
Richard Trieuf9bd0f52011-09-07 02:02:10 +00008380 Expr *LHSExpr, Expr *RHSExpr) {
John McCalle3027922010-08-25 11:45:40 +00008381 BinaryOperatorKind Opc = ConvertTokenKindToBinaryOpcode(Kind);
Richard Trieuf9bd0f52011-09-07 02:02:10 +00008382 assert((LHSExpr != 0) && "ActOnBinOp(): missing left expression");
8383 assert((RHSExpr != 0) && "ActOnBinOp(): missing right expression");
Steve Naroff218bc2b2007-05-04 21:54:46 +00008384
Sebastian Redl43028242009-10-26 15:24:15 +00008385 // Emit warnings for tricky precedence issues, e.g. "bitfield & 0x4 == 0"
Richard Trieuf9bd0f52011-09-07 02:02:10 +00008386 DiagnoseBinOpPrecedence(*this, Opc, TokLoc, LHSExpr, RHSExpr);
Sebastian Redl43028242009-10-26 15:24:15 +00008387
Richard Trieuf9bd0f52011-09-07 02:02:10 +00008388 return BuildBinOp(S, TokLoc, Opc, LHSExpr, RHSExpr);
Douglas Gregor5287f092009-11-05 00:51:44 +00008389}
8390
John McCall526ab472011-10-25 17:37:35 +00008391/// Build an overloaded binary operator expression in the given scope.
8392static ExprResult BuildOverloadedBinOp(Sema &S, Scope *Sc, SourceLocation OpLoc,
8393 BinaryOperatorKind Opc,
8394 Expr *LHS, Expr *RHS) {
8395 // Find all of the overloaded operators visible from this
8396 // point. We perform both an operator-name lookup from the local
8397 // scope and an argument-dependent lookup based on the types of
8398 // the arguments.
8399 UnresolvedSet<16> Functions;
8400 OverloadedOperatorKind OverOp
8401 = BinaryOperator::getOverloadedOperator(Opc);
8402 if (Sc && OverOp != OO_None)
8403 S.LookupOverloadedOperatorName(OverOp, Sc, LHS->getType(),
8404 RHS->getType(), Functions);
8405
8406 // Build the (potentially-overloaded, potentially-dependent)
8407 // binary operation.
8408 return S.CreateOverloadedBinOp(OpLoc, Opc, Functions, LHS, RHS);
8409}
8410
John McCalldadc5752010-08-24 06:29:42 +00008411ExprResult Sema::BuildBinOp(Scope *S, SourceLocation OpLoc,
John McCalle3027922010-08-25 11:45:40 +00008412 BinaryOperatorKind Opc,
Richard Trieuf9bd0f52011-09-07 02:02:10 +00008413 Expr *LHSExpr, Expr *RHSExpr) {
John McCall9a43e122011-10-28 01:04:34 +00008414 // We want to end up calling one of checkPseudoObjectAssignment
8415 // (if the LHS is a pseudo-object), BuildOverloadedBinOp (if
8416 // both expressions are overloadable or either is type-dependent),
8417 // or CreateBuiltinBinOp (in any other case). We also want to get
8418 // any placeholder types out of the way.
8419
John McCall526ab472011-10-25 17:37:35 +00008420 // Handle pseudo-objects in the LHS.
8421 if (const BuiltinType *pty = LHSExpr->getType()->getAsPlaceholderType()) {
8422 // Assignments with a pseudo-object l-value need special analysis.
8423 if (pty->getKind() == BuiltinType::PseudoObject &&
8424 BinaryOperator::isAssignmentOp(Opc))
8425 return checkPseudoObjectAssignment(S, OpLoc, Opc, LHSExpr, RHSExpr);
8426
8427 // Don't resolve overloads if the other type is overloadable.
8428 if (pty->getKind() == BuiltinType::Overload) {
8429 // We can't actually test that if we still have a placeholder,
8430 // though. Fortunately, none of the exceptions we see in that
John McCall9a43e122011-10-28 01:04:34 +00008431 // code below are valid when the LHS is an overload set. Note
8432 // that an overload set can be dependently-typed, but it never
8433 // instantiates to having an overloadable type.
John McCall526ab472011-10-25 17:37:35 +00008434 ExprResult resolvedRHS = CheckPlaceholderExpr(RHSExpr);
8435 if (resolvedRHS.isInvalid()) return ExprError();
8436 RHSExpr = resolvedRHS.take();
8437
John McCall9a43e122011-10-28 01:04:34 +00008438 if (RHSExpr->isTypeDependent() ||
8439 RHSExpr->getType()->isOverloadableType())
John McCall526ab472011-10-25 17:37:35 +00008440 return BuildOverloadedBinOp(*this, S, OpLoc, Opc, LHSExpr, RHSExpr);
8441 }
8442
8443 ExprResult LHS = CheckPlaceholderExpr(LHSExpr);
8444 if (LHS.isInvalid()) return ExprError();
8445 LHSExpr = LHS.take();
8446 }
8447
8448 // Handle pseudo-objects in the RHS.
8449 if (const BuiltinType *pty = RHSExpr->getType()->getAsPlaceholderType()) {
8450 // An overload in the RHS can potentially be resolved by the type
8451 // being assigned to.
John McCall9a43e122011-10-28 01:04:34 +00008452 if (Opc == BO_Assign && pty->getKind() == BuiltinType::Overload) {
8453 if (LHSExpr->isTypeDependent() || RHSExpr->isTypeDependent())
8454 return BuildOverloadedBinOp(*this, S, OpLoc, Opc, LHSExpr, RHSExpr);
8455
Eli Friedman419b1ff2012-01-17 21:27:43 +00008456 if (LHSExpr->getType()->isOverloadableType())
8457 return BuildOverloadedBinOp(*this, S, OpLoc, Opc, LHSExpr, RHSExpr);
8458
John McCall526ab472011-10-25 17:37:35 +00008459 return CreateBuiltinBinOp(OpLoc, Opc, LHSExpr, RHSExpr);
John McCall9a43e122011-10-28 01:04:34 +00008460 }
John McCall526ab472011-10-25 17:37:35 +00008461
8462 // Don't resolve overloads if the other type is overloadable.
8463 if (pty->getKind() == BuiltinType::Overload &&
8464 LHSExpr->getType()->isOverloadableType())
8465 return BuildOverloadedBinOp(*this, S, OpLoc, Opc, LHSExpr, RHSExpr);
8466
8467 ExprResult resolvedRHS = CheckPlaceholderExpr(RHSExpr);
8468 if (!resolvedRHS.isUsable()) return ExprError();
8469 RHSExpr = resolvedRHS.take();
8470 }
8471
David Blaikiebbafb8a2012-03-11 07:00:24 +00008472 if (getLangOpts().CPlusPlus) {
John McCall9a43e122011-10-28 01:04:34 +00008473 // If either expression is type-dependent, always build an
8474 // overloaded op.
8475 if (LHSExpr->isTypeDependent() || RHSExpr->isTypeDependent())
8476 return BuildOverloadedBinOp(*this, S, OpLoc, Opc, LHSExpr, RHSExpr);
Kovarththanan Rajaratnamba2c6522010-03-13 10:17:05 +00008477
John McCall9a43e122011-10-28 01:04:34 +00008478 // Otherwise, build an overloaded op if either expression has an
8479 // overloadable type.
8480 if (LHSExpr->getType()->isOverloadableType() ||
8481 RHSExpr->getType()->isOverloadableType())
John McCall526ab472011-10-25 17:37:35 +00008482 return BuildOverloadedBinOp(*this, S, OpLoc, Opc, LHSExpr, RHSExpr);
Sebastian Redlb5d49352009-01-19 22:31:54 +00008483 }
Kovarththanan Rajaratnamba2c6522010-03-13 10:17:05 +00008484
Douglas Gregor7d5fc7e2008-11-06 23:29:22 +00008485 // Build a built-in binary operation.
Richard Trieuf9bd0f52011-09-07 02:02:10 +00008486 return CreateBuiltinBinOp(OpLoc, Opc, LHSExpr, RHSExpr);
Steve Naroff218bc2b2007-05-04 21:54:46 +00008487}
8488
John McCalldadc5752010-08-24 06:29:42 +00008489ExprResult Sema::CreateBuiltinUnaryOp(SourceLocation OpLoc,
Argyrios Kyrtzidis7a808c02011-01-05 20:09:36 +00008490 UnaryOperatorKind Opc,
John Wiegley01296292011-04-08 18:41:53 +00008491 Expr *InputExpr) {
8492 ExprResult Input = Owned(InputExpr);
John McCall7decc9e2010-11-18 06:31:45 +00008493 ExprValueKind VK = VK_RValue;
8494 ExprObjectKind OK = OK_Ordinary;
Steve Naroff35d85152007-05-07 00:24:15 +00008495 QualType resultType;
8496 switch (Opc) {
John McCalle3027922010-08-25 11:45:40 +00008497 case UO_PreInc:
8498 case UO_PreDec:
8499 case UO_PostInc:
8500 case UO_PostDec:
John Wiegley01296292011-04-08 18:41:53 +00008501 resultType = CheckIncrementDecrementOperand(*this, Input.get(), VK, OpLoc,
John McCalle3027922010-08-25 11:45:40 +00008502 Opc == UO_PreInc ||
8503 Opc == UO_PostInc,
8504 Opc == UO_PreInc ||
8505 Opc == UO_PreDec);
Steve Naroff35d85152007-05-07 00:24:15 +00008506 break;
John McCalle3027922010-08-25 11:45:40 +00008507 case UO_AddrOf:
John McCall526ab472011-10-25 17:37:35 +00008508 resultType = CheckAddressOfOperand(*this, Input, OpLoc);
Steve Naroff35d85152007-05-07 00:24:15 +00008509 break;
John McCall31996342011-04-07 08:22:57 +00008510 case UO_Deref: {
John Wiegley01296292011-04-08 18:41:53 +00008511 Input = DefaultFunctionArrayLvalueConversion(Input.take());
8512 resultType = CheckIndirectionOperand(*this, Input.get(), VK, OpLoc);
Steve Naroff35d85152007-05-07 00:24:15 +00008513 break;
John McCall31996342011-04-07 08:22:57 +00008514 }
John McCalle3027922010-08-25 11:45:40 +00008515 case UO_Plus:
8516 case UO_Minus:
John Wiegley01296292011-04-08 18:41:53 +00008517 Input = UsualUnaryConversions(Input.take());
8518 if (Input.isInvalid()) return ExprError();
8519 resultType = Input.get()->getType();
Sebastian Redl8d2ccae2009-02-26 14:39:58 +00008520 if (resultType->isDependentType())
8521 break;
Douglas Gregora3208f92010-06-22 23:41:02 +00008522 if (resultType->isArithmeticType() || // C99 6.5.3.3p1
8523 resultType->isVectorType())
Douglas Gregord08452f2008-11-19 15:42:04 +00008524 break;
David Blaikiebbafb8a2012-03-11 07:00:24 +00008525 else if (getLangOpts().CPlusPlus && // C++ [expr.unary.op]p6-7
Douglas Gregord08452f2008-11-19 15:42:04 +00008526 resultType->isEnumeralType())
8527 break;
David Blaikiebbafb8a2012-03-11 07:00:24 +00008528 else if (getLangOpts().CPlusPlus && // C++ [expr.unary.op]p6
John McCalle3027922010-08-25 11:45:40 +00008529 Opc == UO_Plus &&
Douglas Gregord08452f2008-11-19 15:42:04 +00008530 resultType->isPointerType())
8531 break;
8532
Sebastian Redlc215cfc2009-01-19 00:08:26 +00008533 return ExprError(Diag(OpLoc, diag::err_typecheck_unary_expr)
John Wiegley01296292011-04-08 18:41:53 +00008534 << resultType << Input.get()->getSourceRange());
8535
John McCalle3027922010-08-25 11:45:40 +00008536 case UO_Not: // bitwise complement
John Wiegley01296292011-04-08 18:41:53 +00008537 Input = UsualUnaryConversions(Input.take());
8538 if (Input.isInvalid()) return ExprError();
8539 resultType = Input.get()->getType();
Sebastian Redl8d2ccae2009-02-26 14:39:58 +00008540 if (resultType->isDependentType())
8541 break;
Chris Lattner0d707612008-07-25 23:52:49 +00008542 // C99 6.5.3.3p1. We allow complex int and float as a GCC extension.
8543 if (resultType->isComplexType() || resultType->isComplexIntegerType())
8544 // C99 does not support '~' for complex conjugation.
Chris Lattner29e812b2008-11-20 06:06:08 +00008545 Diag(OpLoc, diag::ext_integer_complement_complex)
John Wiegley01296292011-04-08 18:41:53 +00008546 << resultType << Input.get()->getSourceRange();
John McCall36226622010-10-12 02:09:17 +00008547 else if (resultType->hasIntegerRepresentation())
8548 break;
John McCall526ab472011-10-25 17:37:35 +00008549 else {
Sebastian Redlc215cfc2009-01-19 00:08:26 +00008550 return ExprError(Diag(OpLoc, diag::err_typecheck_unary_expr)
John Wiegley01296292011-04-08 18:41:53 +00008551 << resultType << Input.get()->getSourceRange());
John McCall36226622010-10-12 02:09:17 +00008552 }
Steve Naroff35d85152007-05-07 00:24:15 +00008553 break;
John Wiegley01296292011-04-08 18:41:53 +00008554
John McCalle3027922010-08-25 11:45:40 +00008555 case UO_LNot: // logical negation
Steve Naroff71b59a92007-06-04 22:22:31 +00008556 // Unlike +/-/~, integer promotions aren't done here (C99 6.5.3.3p5).
John Wiegley01296292011-04-08 18:41:53 +00008557 Input = DefaultFunctionArrayLvalueConversion(Input.take());
8558 if (Input.isInvalid()) return ExprError();
8559 resultType = Input.get()->getType();
Anton Korobeynikovf0c267e2011-10-14 23:23:15 +00008560
8561 // Though we still have to promote half FP to float...
8562 if (resultType->isHalfType()) {
8563 Input = ImpCastExprToType(Input.take(), Context.FloatTy, CK_FloatingCast).take();
8564 resultType = Context.FloatTy;
8565 }
8566
Sebastian Redl8d2ccae2009-02-26 14:39:58 +00008567 if (resultType->isDependentType())
8568 break;
Abramo Bagnara7ccce982011-04-07 09:26:19 +00008569 if (resultType->isScalarType()) {
8570 // C99 6.5.3.3p1: ok, fallthrough;
David Blaikiebbafb8a2012-03-11 07:00:24 +00008571 if (Context.getLangOpts().CPlusPlus) {
Abramo Bagnara7ccce982011-04-07 09:26:19 +00008572 // C++03 [expr.unary.op]p8, C++0x [expr.unary.op]p9:
8573 // operand contextually converted to bool.
John Wiegley01296292011-04-08 18:41:53 +00008574 Input = ImpCastExprToType(Input.take(), Context.BoolTy,
8575 ScalarTypeToBooleanCastKind(resultType));
Abramo Bagnara7ccce982011-04-07 09:26:19 +00008576 }
Tanya Lattner3dd33b22012-01-19 01:16:16 +00008577 } else if (resultType->isExtVectorType()) {
Tanya Lattner20248222012-01-16 21:02:28 +00008578 // Vector logical not returns the signed variant of the operand type.
8579 resultType = GetSignedVectorType(resultType);
8580 break;
John McCall36226622010-10-12 02:09:17 +00008581 } else {
Sebastian Redlc215cfc2009-01-19 00:08:26 +00008582 return ExprError(Diag(OpLoc, diag::err_typecheck_unary_expr)
John Wiegley01296292011-04-08 18:41:53 +00008583 << resultType << Input.get()->getSourceRange());
John McCall36226622010-10-12 02:09:17 +00008584 }
Douglas Gregordb8c6fd2010-09-20 17:13:33 +00008585
Chris Lattnerbe31ed82007-06-02 19:11:33 +00008586 // LNot always has type int. C99 6.5.3.3p5.
Sebastian Redlc215cfc2009-01-19 00:08:26 +00008587 // In C++, it's bool. C++ 5.3.1p8
Argyrios Kyrtzidis1bdd6882011-02-18 20:55:15 +00008588 resultType = Context.getLogicalOperationType();
Steve Naroff35d85152007-05-07 00:24:15 +00008589 break;
John McCalle3027922010-08-25 11:45:40 +00008590 case UO_Real:
8591 case UO_Imag:
John McCall4bc41ae2010-11-18 19:01:18 +00008592 resultType = CheckRealImagOperand(*this, Input, OpLoc, Opc == UO_Real);
Richard Smith0b6b8e42012-02-18 20:53:32 +00008593 // _Real maps ordinary l-values into ordinary l-values. _Imag maps ordinary
8594 // complex l-values to ordinary l-values and all other values to r-values.
John Wiegley01296292011-04-08 18:41:53 +00008595 if (Input.isInvalid()) return ExprError();
Richard Smith0b6b8e42012-02-18 20:53:32 +00008596 if (Opc == UO_Real || Input.get()->getType()->isAnyComplexType()) {
8597 if (Input.get()->getValueKind() != VK_RValue &&
8598 Input.get()->getObjectKind() == OK_Ordinary)
8599 VK = Input.get()->getValueKind();
David Blaikiebbafb8a2012-03-11 07:00:24 +00008600 } else if (!getLangOpts().CPlusPlus) {
Richard Smith0b6b8e42012-02-18 20:53:32 +00008601 // In C, a volatile scalar is read by __imag. In C++, it is not.
8602 Input = DefaultLvalueConversion(Input.take());
8603 }
Chris Lattner30b5dd02007-08-24 21:16:53 +00008604 break;
John McCalle3027922010-08-25 11:45:40 +00008605 case UO_Extension:
John Wiegley01296292011-04-08 18:41:53 +00008606 resultType = Input.get()->getType();
8607 VK = Input.get()->getValueKind();
8608 OK = Input.get()->getObjectKind();
Steve Naroff043d45d2007-05-15 02:32:35 +00008609 break;
Steve Naroff35d85152007-05-07 00:24:15 +00008610 }
John Wiegley01296292011-04-08 18:41:53 +00008611 if (resultType.isNull() || Input.isInvalid())
Sebastian Redlc215cfc2009-01-19 00:08:26 +00008612 return ExprError();
Douglas Gregor084d8552009-03-13 23:49:33 +00008613
Kaelyn Uhrain2e7aa5a2011-08-05 23:18:04 +00008614 // Check for array bounds violations in the operand of the UnaryOperator,
8615 // except for the '*' and '&' operators that have to be handled specially
8616 // by CheckArrayAccess (as there are special cases like &array[arraysize]
8617 // that are explicitly defined as valid by the standard).
8618 if (Opc != UO_AddrOf && Opc != UO_Deref)
8619 CheckArrayAccess(Input.get());
8620
John Wiegley01296292011-04-08 18:41:53 +00008621 return Owned(new (Context) UnaryOperator(Input.take(), Opc, resultType,
John McCall7decc9e2010-11-18 06:31:45 +00008622 VK, OK, OpLoc));
Steve Naroff35d85152007-05-07 00:24:15 +00008623}
Chris Lattnereefa10e2007-05-28 06:56:27 +00008624
Douglas Gregor72341032011-12-14 21:23:13 +00008625/// \brief Determine whether the given expression is a qualified member
8626/// access expression, of a form that could be turned into a pointer to member
8627/// with the address-of operator.
8628static bool isQualifiedMemberAccess(Expr *E) {
8629 if (DeclRefExpr *DRE = dyn_cast<DeclRefExpr>(E)) {
8630 if (!DRE->getQualifier())
8631 return false;
8632
8633 ValueDecl *VD = DRE->getDecl();
8634 if (!VD->isCXXClassMember())
8635 return false;
8636
8637 if (isa<FieldDecl>(VD) || isa<IndirectFieldDecl>(VD))
8638 return true;
8639 if (CXXMethodDecl *Method = dyn_cast<CXXMethodDecl>(VD))
8640 return Method->isInstance();
8641
8642 return false;
8643 }
8644
8645 if (UnresolvedLookupExpr *ULE = dyn_cast<UnresolvedLookupExpr>(E)) {
8646 if (!ULE->getQualifier())
8647 return false;
8648
8649 for (UnresolvedLookupExpr::decls_iterator D = ULE->decls_begin(),
8650 DEnd = ULE->decls_end();
8651 D != DEnd; ++D) {
8652 if (CXXMethodDecl *Method = dyn_cast<CXXMethodDecl>(*D)) {
8653 if (Method->isInstance())
8654 return true;
8655 } else {
8656 // Overload set does not contain methods.
8657 break;
8658 }
8659 }
8660
8661 return false;
8662 }
8663
8664 return false;
8665}
8666
John McCalldadc5752010-08-24 06:29:42 +00008667ExprResult Sema::BuildUnaryOp(Scope *S, SourceLocation OpLoc,
Richard Trieuba63ce62011-09-09 01:45:06 +00008668 UnaryOperatorKind Opc, Expr *Input) {
John McCall526ab472011-10-25 17:37:35 +00008669 // First things first: handle placeholders so that the
8670 // overloaded-operator check considers the right type.
8671 if (const BuiltinType *pty = Input->getType()->getAsPlaceholderType()) {
8672 // Increment and decrement of pseudo-object references.
8673 if (pty->getKind() == BuiltinType::PseudoObject &&
8674 UnaryOperator::isIncrementDecrementOp(Opc))
8675 return checkPseudoObjectIncDec(S, OpLoc, Opc, Input);
8676
8677 // extension is always a builtin operator.
8678 if (Opc == UO_Extension)
8679 return CreateBuiltinUnaryOp(OpLoc, Opc, Input);
8680
8681 // & gets special logic for several kinds of placeholder.
8682 // The builtin code knows what to do.
8683 if (Opc == UO_AddrOf &&
8684 (pty->getKind() == BuiltinType::Overload ||
8685 pty->getKind() == BuiltinType::UnknownAny ||
8686 pty->getKind() == BuiltinType::BoundMember))
8687 return CreateBuiltinUnaryOp(OpLoc, Opc, Input);
8688
8689 // Anything else needs to be handled now.
8690 ExprResult Result = CheckPlaceholderExpr(Input);
8691 if (Result.isInvalid()) return ExprError();
8692 Input = Result.take();
8693 }
8694
David Blaikiebbafb8a2012-03-11 07:00:24 +00008695 if (getLangOpts().CPlusPlus && Input->getType()->isOverloadableType() &&
Douglas Gregor72341032011-12-14 21:23:13 +00008696 UnaryOperator::getOverloadedOperator(Opc) != OO_None &&
8697 !(Opc == UO_AddrOf && isQualifiedMemberAccess(Input))) {
Douglas Gregor084d8552009-03-13 23:49:33 +00008698 // Find all of the overloaded operators visible from this
8699 // point. We perform both an operator-name lookup from the local
8700 // scope and an argument-dependent lookup based on the types of
8701 // the arguments.
John McCall4c4c1df2010-01-26 03:27:55 +00008702 UnresolvedSet<16> Functions;
Douglas Gregor084d8552009-03-13 23:49:33 +00008703 OverloadedOperatorKind OverOp = UnaryOperator::getOverloadedOperator(Opc);
John McCall4c4c1df2010-01-26 03:27:55 +00008704 if (S && OverOp != OO_None)
8705 LookupOverloadedOperatorName(OverOp, S, Input->getType(), QualType(),
8706 Functions);
Kovarththanan Rajaratnamba2c6522010-03-13 10:17:05 +00008707
John McCallb268a282010-08-23 23:25:46 +00008708 return CreateOverloadedUnaryOp(OpLoc, Opc, Functions, Input);
Douglas Gregor084d8552009-03-13 23:49:33 +00008709 }
Kovarththanan Rajaratnamba2c6522010-03-13 10:17:05 +00008710
John McCallb268a282010-08-23 23:25:46 +00008711 return CreateBuiltinUnaryOp(OpLoc, Opc, Input);
Douglas Gregor084d8552009-03-13 23:49:33 +00008712}
8713
Douglas Gregor5287f092009-11-05 00:51:44 +00008714// Unary Operators. 'Tok' is the token for the operator.
John McCalldadc5752010-08-24 06:29:42 +00008715ExprResult Sema::ActOnUnaryOp(Scope *S, SourceLocation OpLoc,
John McCall424cec92011-01-19 06:33:43 +00008716 tok::TokenKind Op, Expr *Input) {
John McCallb268a282010-08-23 23:25:46 +00008717 return BuildUnaryOp(S, OpLoc, ConvertTokenKindToUnaryOpcode(Op), Input);
Douglas Gregor5287f092009-11-05 00:51:44 +00008718}
8719
Steve Naroff66356bd2007-09-16 14:56:35 +00008720/// ActOnAddrLabel - Parse the GNU address of label extension: "&&foo".
Chris Lattnerc8e630e2011-02-17 07:39:24 +00008721ExprResult Sema::ActOnAddrLabel(SourceLocation OpLoc, SourceLocation LabLoc,
Chris Lattnercab02a62011-02-17 20:34:02 +00008722 LabelDecl *TheDecl) {
Chris Lattnerc8e630e2011-02-17 07:39:24 +00008723 TheDecl->setUsed();
Chris Lattnereefa10e2007-05-28 06:56:27 +00008724 // Create the AST node. The address of a label always has type 'void*'.
Chris Lattnerc8e630e2011-02-17 07:39:24 +00008725 return Owned(new (Context) AddrLabelExpr(OpLoc, LabLoc, TheDecl,
Sebastian Redl6d4256c2009-03-15 17:47:39 +00008726 Context.getPointerType(Context.VoidTy)));
Chris Lattnereefa10e2007-05-28 06:56:27 +00008727}
8728
John McCall31168b02011-06-15 23:02:42 +00008729/// Given the last statement in a statement-expression, check whether
8730/// the result is a producing expression (like a call to an
8731/// ns_returns_retained function) and, if so, rebuild it to hoist the
8732/// release out of the full-expression. Otherwise, return null.
8733/// Cannot fail.
Richard Trieuba63ce62011-09-09 01:45:06 +00008734static Expr *maybeRebuildARCConsumingStmt(Stmt *Statement) {
John McCall31168b02011-06-15 23:02:42 +00008735 // Should always be wrapped with one of these.
Richard Trieuba63ce62011-09-09 01:45:06 +00008736 ExprWithCleanups *cleanups = dyn_cast<ExprWithCleanups>(Statement);
John McCall31168b02011-06-15 23:02:42 +00008737 if (!cleanups) return 0;
8738
8739 ImplicitCastExpr *cast = dyn_cast<ImplicitCastExpr>(cleanups->getSubExpr());
John McCall2d637d22011-09-10 06:18:15 +00008740 if (!cast || cast->getCastKind() != CK_ARCConsumeObject)
John McCall31168b02011-06-15 23:02:42 +00008741 return 0;
8742
8743 // Splice out the cast. This shouldn't modify any interesting
8744 // features of the statement.
8745 Expr *producer = cast->getSubExpr();
8746 assert(producer->getType() == cast->getType());
8747 assert(producer->getValueKind() == cast->getValueKind());
8748 cleanups->setSubExpr(producer);
8749 return cleanups;
8750}
8751
John McCall3abee492012-04-04 01:27:53 +00008752void Sema::ActOnStartStmtExpr() {
8753 PushExpressionEvaluationContext(ExprEvalContexts.back().Context);
8754}
8755
8756void Sema::ActOnStmtExprError() {
John McCalled7b2782012-04-06 18:20:53 +00008757 // Note that function is also called by TreeTransform when leaving a
8758 // StmtExpr scope without rebuilding anything.
8759
John McCall3abee492012-04-04 01:27:53 +00008760 DiscardCleanupsInEvaluationContext();
8761 PopExpressionEvaluationContext();
8762}
8763
John McCalldadc5752010-08-24 06:29:42 +00008764ExprResult
John McCallb268a282010-08-23 23:25:46 +00008765Sema::ActOnStmtExpr(SourceLocation LPLoc, Stmt *SubStmt,
Sebastian Redl6d4256c2009-03-15 17:47:39 +00008766 SourceLocation RPLoc) { // "({..})"
Chris Lattner366727f2007-07-24 16:58:17 +00008767 assert(SubStmt && isa<CompoundStmt>(SubStmt) && "Invalid action invocation!");
8768 CompoundStmt *Compound = cast<CompoundStmt>(SubStmt);
8769
John McCall3abee492012-04-04 01:27:53 +00008770 if (hasAnyUnrecoverableErrorsInThisFunction())
8771 DiscardCleanupsInEvaluationContext();
8772 assert(!ExprNeedsCleanups && "cleanups within StmtExpr not correctly bound!");
8773 PopExpressionEvaluationContext();
8774
Douglas Gregor6cf3f3c2010-03-10 04:54:39 +00008775 bool isFileScope
8776 = (getCurFunctionOrMethodDecl() == 0) && (getCurBlock() == 0);
Chris Lattnera69b0762009-04-25 19:11:05 +00008777 if (isFileScope)
Sebastian Redl6d4256c2009-03-15 17:47:39 +00008778 return ExprError(Diag(LPLoc, diag::err_stmtexpr_file_scope));
Eli Friedman52cc0162009-01-24 23:09:00 +00008779
Chris Lattner366727f2007-07-24 16:58:17 +00008780 // FIXME: there are a variety of strange constraints to enforce here, for
8781 // example, it is not possible to goto into a stmt expression apparently.
8782 // More semantic analysis is needed.
Mike Stump4e1f26a2009-02-19 03:04:26 +00008783
Chris Lattner366727f2007-07-24 16:58:17 +00008784 // If there are sub stmts in the compound stmt, take the type of the last one
8785 // as the type of the stmtexpr.
8786 QualType Ty = Context.VoidTy;
Fariborz Jahanian56143ae2010-10-25 23:27:26 +00008787 bool StmtExprMayBindToTemp = false;
Chris Lattner944d3062008-07-26 19:51:01 +00008788 if (!Compound->body_empty()) {
8789 Stmt *LastStmt = Compound->body_back();
Fariborz Jahanian56143ae2010-10-25 23:27:26 +00008790 LabelStmt *LastLabelStmt = 0;
Chris Lattner944d3062008-07-26 19:51:01 +00008791 // If LastStmt is a label, skip down through into the body.
Fariborz Jahanian56143ae2010-10-25 23:27:26 +00008792 while (LabelStmt *Label = dyn_cast<LabelStmt>(LastStmt)) {
8793 LastLabelStmt = Label;
Chris Lattner944d3062008-07-26 19:51:01 +00008794 LastStmt = Label->getSubStmt();
Fariborz Jahanian56143ae2010-10-25 23:27:26 +00008795 }
John McCall31168b02011-06-15 23:02:42 +00008796
John Wiegley01296292011-04-08 18:41:53 +00008797 if (Expr *LastE = dyn_cast<Expr>(LastStmt)) {
John McCall34376a62010-12-04 03:47:34 +00008798 // Do function/array conversion on the last expression, but not
8799 // lvalue-to-rvalue. However, initialize an unqualified type.
John Wiegley01296292011-04-08 18:41:53 +00008800 ExprResult LastExpr = DefaultFunctionArrayConversion(LastE);
8801 if (LastExpr.isInvalid())
8802 return ExprError();
8803 Ty = LastExpr.get()->getType().getUnqualifiedType();
John McCall34376a62010-12-04 03:47:34 +00008804
John Wiegley01296292011-04-08 18:41:53 +00008805 if (!Ty->isDependentType() && !LastExpr.get()->isTypeDependent()) {
John McCall31168b02011-06-15 23:02:42 +00008806 // In ARC, if the final expression ends in a consume, splice
8807 // the consume out and bind it later. In the alternate case
8808 // (when dealing with a retainable type), the result
8809 // initialization will create a produce. In both cases the
8810 // result will be +1, and we'll need to balance that out with
8811 // a bind.
8812 if (Expr *rebuiltLastStmt
8813 = maybeRebuildARCConsumingStmt(LastExpr.get())) {
8814 LastExpr = rebuiltLastStmt;
8815 } else {
8816 LastExpr = PerformCopyInitialization(
Fariborz Jahanian56143ae2010-10-25 23:27:26 +00008817 InitializedEntity::InitializeResult(LPLoc,
8818 Ty,
8819 false),
8820 SourceLocation(),
John McCall31168b02011-06-15 23:02:42 +00008821 LastExpr);
8822 }
8823
John Wiegley01296292011-04-08 18:41:53 +00008824 if (LastExpr.isInvalid())
Fariborz Jahanian56143ae2010-10-25 23:27:26 +00008825 return ExprError();
John Wiegley01296292011-04-08 18:41:53 +00008826 if (LastExpr.get() != 0) {
Fariborz Jahanian56143ae2010-10-25 23:27:26 +00008827 if (!LastLabelStmt)
John Wiegley01296292011-04-08 18:41:53 +00008828 Compound->setLastStmt(LastExpr.take());
Fariborz Jahanian56143ae2010-10-25 23:27:26 +00008829 else
John Wiegley01296292011-04-08 18:41:53 +00008830 LastLabelStmt->setSubStmt(LastExpr.take());
Fariborz Jahanian56143ae2010-10-25 23:27:26 +00008831 StmtExprMayBindToTemp = true;
8832 }
8833 }
8834 }
Chris Lattner944d3062008-07-26 19:51:01 +00008835 }
Mike Stump4e1f26a2009-02-19 03:04:26 +00008836
Eli Friedmanba961a92009-03-23 00:24:07 +00008837 // FIXME: Check that expression type is complete/non-abstract; statement
8838 // expressions are not lvalues.
Fariborz Jahanian56143ae2010-10-25 23:27:26 +00008839 Expr *ResStmtExpr = new (Context) StmtExpr(Compound, Ty, LPLoc, RPLoc);
8840 if (StmtExprMayBindToTemp)
8841 return MaybeBindToTemporary(ResStmtExpr);
8842 return Owned(ResStmtExpr);
Chris Lattner366727f2007-07-24 16:58:17 +00008843}
Steve Naroff78864672007-08-01 22:05:33 +00008844
John McCalldadc5752010-08-24 06:29:42 +00008845ExprResult Sema::BuildBuiltinOffsetOf(SourceLocation BuiltinLoc,
John McCall36226622010-10-12 02:09:17 +00008846 TypeSourceInfo *TInfo,
8847 OffsetOfComponent *CompPtr,
8848 unsigned NumComponents,
8849 SourceLocation RParenLoc) {
Douglas Gregor882211c2010-04-28 22:16:22 +00008850 QualType ArgTy = TInfo->getType();
Sebastian Redl8d2ccae2009-02-26 14:39:58 +00008851 bool Dependent = ArgTy->isDependentType();
Abramo Bagnara1108e7b2010-05-20 10:00:11 +00008852 SourceRange TypeRange = TInfo->getTypeLoc().getLocalSourceRange();
Douglas Gregor882211c2010-04-28 22:16:22 +00008853
Chris Lattnerf17bd422007-08-30 17:45:32 +00008854 // We must have at least one component that refers to the type, and the first
8855 // one is known to be a field designator. Verify that the ArgTy represents
8856 // a struct/union/class.
Sebastian Redl8d2ccae2009-02-26 14:39:58 +00008857 if (!Dependent && !ArgTy->isRecordType())
Douglas Gregor882211c2010-04-28 22:16:22 +00008858 return ExprError(Diag(BuiltinLoc, diag::err_offsetof_record_type)
8859 << ArgTy << TypeRange);
8860
8861 // Type must be complete per C99 7.17p3 because a declaring a variable
8862 // with an incomplete type would be ill-formed.
8863 if (!Dependent
8864 && RequireCompleteType(BuiltinLoc, ArgTy,
Douglas Gregor7bfb2d02012-05-04 16:32:21 +00008865 diag::err_offsetof_incomplete_type, TypeRange))
Douglas Gregor882211c2010-04-28 22:16:22 +00008866 return ExprError();
8867
Chris Lattner78502cf2007-08-31 21:49:13 +00008868 // offsetof with non-identifier designators (e.g. "offsetof(x, a.b[c])") are a
8869 // GCC extension, diagnose them.
Eli Friedman988a16b2009-02-27 06:44:11 +00008870 // FIXME: This diagnostic isn't actually visible because the location is in
8871 // a system header!
Chris Lattner78502cf2007-08-31 21:49:13 +00008872 if (NumComponents != 1)
Chris Lattnerf490e152008-11-19 05:27:50 +00008873 Diag(BuiltinLoc, diag::ext_offsetof_extended_field_designator)
8874 << SourceRange(CompPtr[1].LocStart, CompPtr[NumComponents-1].LocEnd);
Douglas Gregor882211c2010-04-28 22:16:22 +00008875
8876 bool DidWarnAboutNonPOD = false;
8877 QualType CurrentType = ArgTy;
8878 typedef OffsetOfExpr::OffsetOfNode OffsetOfNode;
Chris Lattner0e62c1c2011-07-23 10:55:15 +00008879 SmallVector<OffsetOfNode, 4> Comps;
8880 SmallVector<Expr*, 4> Exprs;
Douglas Gregor882211c2010-04-28 22:16:22 +00008881 for (unsigned i = 0; i != NumComponents; ++i) {
8882 const OffsetOfComponent &OC = CompPtr[i];
8883 if (OC.isBrackets) {
8884 // Offset of an array sub-field. TODO: Should we allow vector elements?
8885 if (!CurrentType->isDependentType()) {
8886 const ArrayType *AT = Context.getAsArrayType(CurrentType);
8887 if(!AT)
8888 return ExprError(Diag(OC.LocEnd, diag::err_offsetof_array_type)
8889 << CurrentType);
8890 CurrentType = AT->getElementType();
8891 } else
8892 CurrentType = Context.DependentTy;
8893
Richard Smith9fcc5c32011-10-17 23:29:39 +00008894 ExprResult IdxRval = DefaultLvalueConversion(static_cast<Expr*>(OC.U.E));
8895 if (IdxRval.isInvalid())
8896 return ExprError();
8897 Expr *Idx = IdxRval.take();
8898
Douglas Gregor882211c2010-04-28 22:16:22 +00008899 // The expression must be an integral expression.
8900 // FIXME: An integral constant expression?
Douglas Gregor882211c2010-04-28 22:16:22 +00008901 if (!Idx->isTypeDependent() && !Idx->isValueDependent() &&
8902 !Idx->getType()->isIntegerType())
8903 return ExprError(Diag(Idx->getLocStart(),
8904 diag::err_typecheck_subscript_not_integer)
8905 << Idx->getSourceRange());
Richard Smitheda612882011-10-17 05:48:07 +00008906
Douglas Gregor882211c2010-04-28 22:16:22 +00008907 // Record this array index.
8908 Comps.push_back(OffsetOfNode(OC.LocStart, Exprs.size(), OC.LocEnd));
Richard Smith9fcc5c32011-10-17 23:29:39 +00008909 Exprs.push_back(Idx);
Douglas Gregor882211c2010-04-28 22:16:22 +00008910 continue;
8911 }
8912
8913 // Offset of a field.
8914 if (CurrentType->isDependentType()) {
8915 // We have the offset of a field, but we can't look into the dependent
8916 // type. Just record the identifier of the field.
8917 Comps.push_back(OffsetOfNode(OC.LocStart, OC.U.IdentInfo, OC.LocEnd));
8918 CurrentType = Context.DependentTy;
8919 continue;
8920 }
8921
8922 // We need to have a complete type to look into.
8923 if (RequireCompleteType(OC.LocStart, CurrentType,
8924 diag::err_offsetof_incomplete_type))
8925 return ExprError();
8926
8927 // Look for the designated field.
8928 const RecordType *RC = CurrentType->getAs<RecordType>();
8929 if (!RC)
8930 return ExprError(Diag(OC.LocEnd, diag::err_offsetof_record_type)
8931 << CurrentType);
8932 RecordDecl *RD = RC->getDecl();
8933
8934 // C++ [lib.support.types]p5:
8935 // The macro offsetof accepts a restricted set of type arguments in this
8936 // International Standard. type shall be a POD structure or a POD union
8937 // (clause 9).
Benjamin Kramer9e7876b2012-04-28 11:14:51 +00008938 // C++11 [support.types]p4:
8939 // If type is not a standard-layout class (Clause 9), the results are
8940 // undefined.
Douglas Gregor882211c2010-04-28 22:16:22 +00008941 if (CXXRecordDecl *CRD = dyn_cast<CXXRecordDecl>(RD)) {
Benjamin Kramer9e7876b2012-04-28 11:14:51 +00008942 bool IsSafe = LangOpts.CPlusPlus0x? CRD->isStandardLayout() : CRD->isPOD();
8943 unsigned DiagID =
8944 LangOpts.CPlusPlus0x? diag::warn_offsetof_non_standardlayout_type
8945 : diag::warn_offsetof_non_pod_type;
8946
8947 if (!IsSafe && !DidWarnAboutNonPOD &&
Ted Kremenek55ae3192011-02-23 01:51:43 +00008948 DiagRuntimeBehavior(BuiltinLoc, 0,
Benjamin Kramer9e7876b2012-04-28 11:14:51 +00008949 PDiag(DiagID)
Douglas Gregor882211c2010-04-28 22:16:22 +00008950 << SourceRange(CompPtr[0].LocStart, OC.LocEnd)
8951 << CurrentType))
8952 DidWarnAboutNonPOD = true;
8953 }
8954
8955 // Look for the field.
8956 LookupResult R(*this, OC.U.IdentInfo, OC.LocStart, LookupMemberName);
8957 LookupQualifiedName(R, RD);
8958 FieldDecl *MemberDecl = R.getAsSingle<FieldDecl>();
Francois Pichet783dd6e2010-11-21 06:08:52 +00008959 IndirectFieldDecl *IndirectMemberDecl = 0;
8960 if (!MemberDecl) {
Benjamin Kramer39593702010-11-21 14:11:41 +00008961 if ((IndirectMemberDecl = R.getAsSingle<IndirectFieldDecl>()))
Francois Pichet783dd6e2010-11-21 06:08:52 +00008962 MemberDecl = IndirectMemberDecl->getAnonField();
8963 }
8964
Douglas Gregor882211c2010-04-28 22:16:22 +00008965 if (!MemberDecl)
8966 return ExprError(Diag(BuiltinLoc, diag::err_no_member)
8967 << OC.U.IdentInfo << RD << SourceRange(OC.LocStart,
8968 OC.LocEnd));
8969
Douglas Gregor10982ea2010-04-28 22:36:06 +00008970 // C99 7.17p3:
8971 // (If the specified member is a bit-field, the behavior is undefined.)
8972 //
8973 // We diagnose this as an error.
Richard Smithcaf33902011-10-10 18:28:20 +00008974 if (MemberDecl->isBitField()) {
Douglas Gregor10982ea2010-04-28 22:36:06 +00008975 Diag(OC.LocEnd, diag::err_offsetof_bitfield)
8976 << MemberDecl->getDeclName()
8977 << SourceRange(BuiltinLoc, RParenLoc);
8978 Diag(MemberDecl->getLocation(), diag::note_bitfield_decl);
8979 return ExprError();
8980 }
Eli Friedman74ef7cf2010-08-05 10:11:36 +00008981
8982 RecordDecl *Parent = MemberDecl->getParent();
Francois Pichet783dd6e2010-11-21 06:08:52 +00008983 if (IndirectMemberDecl)
8984 Parent = cast<RecordDecl>(IndirectMemberDecl->getDeclContext());
Eli Friedman74ef7cf2010-08-05 10:11:36 +00008985
Douglas Gregord1702062010-04-29 00:18:15 +00008986 // If the member was found in a base class, introduce OffsetOfNodes for
8987 // the base class indirections.
8988 CXXBasePaths Paths(/*FindAmbiguities=*/true, /*RecordPaths=*/true,
8989 /*DetectVirtual=*/false);
Eli Friedman74ef7cf2010-08-05 10:11:36 +00008990 if (IsDerivedFrom(CurrentType, Context.getTypeDeclType(Parent), Paths)) {
Douglas Gregord1702062010-04-29 00:18:15 +00008991 CXXBasePath &Path = Paths.front();
8992 for (CXXBasePath::iterator B = Path.begin(), BEnd = Path.end();
8993 B != BEnd; ++B)
8994 Comps.push_back(OffsetOfNode(B->Base));
8995 }
Eli Friedman74ef7cf2010-08-05 10:11:36 +00008996
Francois Pichet783dd6e2010-11-21 06:08:52 +00008997 if (IndirectMemberDecl) {
8998 for (IndirectFieldDecl::chain_iterator FI =
8999 IndirectMemberDecl->chain_begin(),
9000 FEnd = IndirectMemberDecl->chain_end(); FI != FEnd; FI++) {
9001 assert(isa<FieldDecl>(*FI));
9002 Comps.push_back(OffsetOfNode(OC.LocStart,
9003 cast<FieldDecl>(*FI), OC.LocEnd));
9004 }
9005 } else
Douglas Gregor882211c2010-04-28 22:16:22 +00009006 Comps.push_back(OffsetOfNode(OC.LocStart, MemberDecl, OC.LocEnd));
Francois Pichet783dd6e2010-11-21 06:08:52 +00009007
Douglas Gregor882211c2010-04-28 22:16:22 +00009008 CurrentType = MemberDecl->getType().getNonReferenceType();
9009 }
9010
9011 return Owned(OffsetOfExpr::Create(Context, Context.getSizeType(), BuiltinLoc,
9012 TInfo, Comps.data(), Comps.size(),
9013 Exprs.data(), Exprs.size(), RParenLoc));
9014}
Mike Stump4e1f26a2009-02-19 03:04:26 +00009015
John McCalldadc5752010-08-24 06:29:42 +00009016ExprResult Sema::ActOnBuiltinOffsetOf(Scope *S,
John McCall36226622010-10-12 02:09:17 +00009017 SourceLocation BuiltinLoc,
9018 SourceLocation TypeLoc,
Richard Trieuba63ce62011-09-09 01:45:06 +00009019 ParsedType ParsedArgTy,
John McCall36226622010-10-12 02:09:17 +00009020 OffsetOfComponent *CompPtr,
9021 unsigned NumComponents,
Richard Trieuba63ce62011-09-09 01:45:06 +00009022 SourceLocation RParenLoc) {
John McCall36226622010-10-12 02:09:17 +00009023
Douglas Gregor882211c2010-04-28 22:16:22 +00009024 TypeSourceInfo *ArgTInfo;
Richard Trieuba63ce62011-09-09 01:45:06 +00009025 QualType ArgTy = GetTypeFromParser(ParsedArgTy, &ArgTInfo);
Douglas Gregor882211c2010-04-28 22:16:22 +00009026 if (ArgTy.isNull())
9027 return ExprError();
9028
Eli Friedman06dcfd92010-08-05 10:15:45 +00009029 if (!ArgTInfo)
9030 ArgTInfo = Context.getTrivialTypeSourceInfo(ArgTy, TypeLoc);
9031
9032 return BuildBuiltinOffsetOf(BuiltinLoc, ArgTInfo, CompPtr, NumComponents,
Richard Trieuba63ce62011-09-09 01:45:06 +00009033 RParenLoc);
Chris Lattnerf17bd422007-08-30 17:45:32 +00009034}
9035
9036
John McCalldadc5752010-08-24 06:29:42 +00009037ExprResult Sema::ActOnChooseExpr(SourceLocation BuiltinLoc,
John McCall36226622010-10-12 02:09:17 +00009038 Expr *CondExpr,
9039 Expr *LHSExpr, Expr *RHSExpr,
9040 SourceLocation RPLoc) {
Steve Naroff9efdabc2007-08-03 21:21:27 +00009041 assert((CondExpr && LHSExpr && RHSExpr) && "Missing type argument(s)");
9042
John McCall7decc9e2010-11-18 06:31:45 +00009043 ExprValueKind VK = VK_RValue;
9044 ExprObjectKind OK = OK_Ordinary;
Sebastian Redl8d2ccae2009-02-26 14:39:58 +00009045 QualType resType;
Douglas Gregor56751b52009-09-25 04:25:58 +00009046 bool ValueDependent = false;
Douglas Gregor0df91122009-05-19 22:43:30 +00009047 if (CondExpr->isTypeDependent() || CondExpr->isValueDependent()) {
Sebastian Redl8d2ccae2009-02-26 14:39:58 +00009048 resType = Context.DependentTy;
Douglas Gregor56751b52009-09-25 04:25:58 +00009049 ValueDependent = true;
Sebastian Redl8d2ccae2009-02-26 14:39:58 +00009050 } else {
9051 // The conditional expression is required to be a constant expression.
9052 llvm::APSInt condEval(32);
Douglas Gregore2b37442012-05-04 22:38:52 +00009053 ExprResult CondICE
9054 = VerifyIntegerConstantExpression(CondExpr, &condEval,
9055 diag::err_typecheck_choose_expr_requires_constant, false);
Richard Smithf4c51d92012-02-04 09:53:13 +00009056 if (CondICE.isInvalid())
9057 return ExprError();
9058 CondExpr = CondICE.take();
Steve Naroff9efdabc2007-08-03 21:21:27 +00009059
Sebastian Redl8d2ccae2009-02-26 14:39:58 +00009060 // If the condition is > zero, then the AST type is the same as the LSHExpr.
John McCall7decc9e2010-11-18 06:31:45 +00009061 Expr *ActiveExpr = condEval.getZExtValue() ? LHSExpr : RHSExpr;
9062
9063 resType = ActiveExpr->getType();
9064 ValueDependent = ActiveExpr->isValueDependent();
9065 VK = ActiveExpr->getValueKind();
9066 OK = ActiveExpr->getObjectKind();
Sebastian Redl8d2ccae2009-02-26 14:39:58 +00009067 }
9068
Sebastian Redl6d4256c2009-03-15 17:47:39 +00009069 return Owned(new (Context) ChooseExpr(BuiltinLoc, CondExpr, LHSExpr, RHSExpr,
John McCall7decc9e2010-11-18 06:31:45 +00009070 resType, VK, OK, RPLoc,
Douglas Gregor56751b52009-09-25 04:25:58 +00009071 resType->isDependentType(),
9072 ValueDependent));
Steve Naroff9efdabc2007-08-03 21:21:27 +00009073}
9074
Steve Naroffc540d662008-09-03 18:15:37 +00009075//===----------------------------------------------------------------------===//
9076// Clang Extensions.
9077//===----------------------------------------------------------------------===//
9078
9079/// ActOnBlockStart - This callback is invoked when a block literal is started.
Richard Trieuba63ce62011-09-09 01:45:06 +00009080void Sema::ActOnBlockStart(SourceLocation CaretLoc, Scope *CurScope) {
Douglas Gregor9a28e842010-03-01 23:15:13 +00009081 BlockDecl *Block = BlockDecl::Create(Context, CurContext, CaretLoc);
Richard Trieuba63ce62011-09-09 01:45:06 +00009082 PushBlockScope(CurScope, Block);
Douglas Gregor9a28e842010-03-01 23:15:13 +00009083 CurContext->addDecl(Block);
Richard Trieuba63ce62011-09-09 01:45:06 +00009084 if (CurScope)
9085 PushDeclContext(CurScope, Block);
Fariborz Jahanian1babe772010-07-09 18:44:02 +00009086 else
9087 CurContext = Block;
John McCallf1a3c2a2011-11-11 03:19:12 +00009088
Eli Friedman34b49062012-01-26 03:00:14 +00009089 getCurBlock()->HasImplicitReturnType = true;
9090
John McCallf1a3c2a2011-11-11 03:19:12 +00009091 // Enter a new evaluation context to insulate the block from any
9092 // cleanups from the enclosing full-expression.
9093 PushExpressionEvaluationContext(PotentiallyEvaluated);
Steve Naroff1d95e5a2008-10-10 01:28:17 +00009094}
9095
Douglas Gregor7efd007c2012-06-15 16:59:29 +00009096void Sema::ActOnBlockArguments(SourceLocation CaretLoc, Declarator &ParamInfo,
9097 Scope *CurScope) {
Mike Stumpf70bcf72009-05-07 18:43:07 +00009098 assert(ParamInfo.getIdentifier()==0 && "block-id should have no identifier!");
John McCall3882ace2011-01-05 12:14:39 +00009099 assert(ParamInfo.getContext() == Declarator::BlockLiteralContext);
Douglas Gregor9a28e842010-03-01 23:15:13 +00009100 BlockScopeInfo *CurBlock = getCurBlock();
Kovarththanan Rajaratnamba2c6522010-03-13 10:17:05 +00009101
John McCall8cb7bdf2010-06-04 23:28:52 +00009102 TypeSourceInfo *Sig = GetTypeForDeclarator(ParamInfo, CurScope);
John McCall8cb7bdf2010-06-04 23:28:52 +00009103 QualType T = Sig->getType();
Mike Stump82f071f2009-02-04 22:31:32 +00009104
Douglas Gregor7efd007c2012-06-15 16:59:29 +00009105 // FIXME: We should allow unexpanded parameter packs here, but that would,
9106 // in turn, make the block expression contain unexpanded parameter packs.
9107 if (DiagnoseUnexpandedParameterPack(CaretLoc, Sig, UPPC_Block)) {
9108 // Drop the parameters.
9109 FunctionProtoType::ExtProtoInfo EPI;
9110 EPI.HasTrailingReturn = false;
9111 EPI.TypeQuals |= DeclSpec::TQ_const;
9112 T = Context.getFunctionType(Context.DependentTy, /*Args=*/0, /*NumArgs=*/0,
9113 EPI);
9114 Sig = Context.getTrivialTypeSourceInfo(T);
9115 }
9116
John McCall3882ace2011-01-05 12:14:39 +00009117 // GetTypeForDeclarator always produces a function type for a block
9118 // literal signature. Furthermore, it is always a FunctionProtoType
9119 // unless the function was written with a typedef.
9120 assert(T->isFunctionType() &&
9121 "GetTypeForDeclarator made a non-function block signature");
9122
9123 // Look for an explicit signature in that function type.
9124 FunctionProtoTypeLoc ExplicitSignature;
9125
9126 TypeLoc tmp = Sig->getTypeLoc().IgnoreParens();
9127 if (isa<FunctionProtoTypeLoc>(tmp)) {
9128 ExplicitSignature = cast<FunctionProtoTypeLoc>(tmp);
9129
9130 // Check whether that explicit signature was synthesized by
9131 // GetTypeForDeclarator. If so, don't save that as part of the
9132 // written signature.
Abramo Bagnaraf2a79d92011-03-12 11:17:06 +00009133 if (ExplicitSignature.getLocalRangeBegin() ==
9134 ExplicitSignature.getLocalRangeEnd()) {
John McCall3882ace2011-01-05 12:14:39 +00009135 // This would be much cheaper if we stored TypeLocs instead of
9136 // TypeSourceInfos.
9137 TypeLoc Result = ExplicitSignature.getResultLoc();
9138 unsigned Size = Result.getFullDataSize();
9139 Sig = Context.CreateTypeSourceInfo(Result.getType(), Size);
9140 Sig->getTypeLoc().initializeFullCopy(Result, Size);
9141
9142 ExplicitSignature = FunctionProtoTypeLoc();
9143 }
John McCalla3ccba02010-06-04 11:21:44 +00009144 }
Mike Stump11289f42009-09-09 15:08:12 +00009145
John McCall3882ace2011-01-05 12:14:39 +00009146 CurBlock->TheDecl->setSignatureAsWritten(Sig);
9147 CurBlock->FunctionType = T;
9148
9149 const FunctionType *Fn = T->getAs<FunctionType>();
9150 QualType RetTy = Fn->getResultType();
9151 bool isVariadic =
9152 (isa<FunctionProtoType>(Fn) && cast<FunctionProtoType>(Fn)->isVariadic());
9153
John McCall8e346702010-06-04 19:02:56 +00009154 CurBlock->TheDecl->setIsVariadic(isVariadic);
Douglas Gregorb92a1562010-02-03 00:27:59 +00009155
John McCalla3ccba02010-06-04 11:21:44 +00009156 // Don't allow returning a objc interface by value.
9157 if (RetTy->isObjCObjectType()) {
Daniel Dunbar62ee6412012-03-09 18:35:03 +00009158 Diag(ParamInfo.getLocStart(),
John McCalla3ccba02010-06-04 11:21:44 +00009159 diag::err_object_cannot_be_passed_returned_by_value) << 0 << RetTy;
9160 return;
9161 }
Mike Stump4e1f26a2009-02-19 03:04:26 +00009162
John McCalla3ccba02010-06-04 11:21:44 +00009163 // Context.DependentTy is used as a placeholder for a missing block
John McCall8e346702010-06-04 19:02:56 +00009164 // return type. TODO: what should we do with declarators like:
9165 // ^ * { ... }
9166 // If the answer is "apply template argument deduction"....
Fariborz Jahaniandd5eb9d2011-12-03 17:47:53 +00009167 if (RetTy != Context.DependentTy) {
John McCalla3ccba02010-06-04 11:21:44 +00009168 CurBlock->ReturnType = RetTy;
Fariborz Jahaniandd5eb9d2011-12-03 17:47:53 +00009169 CurBlock->TheDecl->setBlockMissingReturnType(false);
Eli Friedman34b49062012-01-26 03:00:14 +00009170 CurBlock->HasImplicitReturnType = false;
Fariborz Jahaniandd5eb9d2011-12-03 17:47:53 +00009171 }
Mike Stump4e1f26a2009-02-19 03:04:26 +00009172
John McCalla3ccba02010-06-04 11:21:44 +00009173 // Push block parameters from the declarator if we had them.
Chris Lattner0e62c1c2011-07-23 10:55:15 +00009174 SmallVector<ParmVarDecl*, 8> Params;
John McCall3882ace2011-01-05 12:14:39 +00009175 if (ExplicitSignature) {
9176 for (unsigned I = 0, E = ExplicitSignature.getNumArgs(); I != E; ++I) {
9177 ParmVarDecl *Param = ExplicitSignature.getArg(I);
Fariborz Jahanian5ec502e2010-02-12 21:53:14 +00009178 if (Param->getIdentifier() == 0 &&
9179 !Param->isImplicit() &&
9180 !Param->isInvalidDecl() &&
David Blaikiebbafb8a2012-03-11 07:00:24 +00009181 !getLangOpts().CPlusPlus)
Fariborz Jahanian5ec502e2010-02-12 21:53:14 +00009182 Diag(Param->getLocation(), diag::err_parameter_name_omitted);
John McCall8e346702010-06-04 19:02:56 +00009183 Params.push_back(Param);
Fariborz Jahanian5ec502e2010-02-12 21:53:14 +00009184 }
John McCalla3ccba02010-06-04 11:21:44 +00009185
9186 // Fake up parameter variables if we have a typedef, like
9187 // ^ fntype { ... }
9188 } else if (const FunctionProtoType *Fn = T->getAs<FunctionProtoType>()) {
9189 for (FunctionProtoType::arg_type_iterator
9190 I = Fn->arg_type_begin(), E = Fn->arg_type_end(); I != E; ++I) {
9191 ParmVarDecl *Param =
9192 BuildParmVarDeclForTypedef(CurBlock->TheDecl,
Daniel Dunbar62ee6412012-03-09 18:35:03 +00009193 ParamInfo.getLocStart(),
John McCalla3ccba02010-06-04 11:21:44 +00009194 *I);
John McCall8e346702010-06-04 19:02:56 +00009195 Params.push_back(Param);
John McCalla3ccba02010-06-04 11:21:44 +00009196 }
Steve Naroffc540d662008-09-03 18:15:37 +00009197 }
John McCalla3ccba02010-06-04 11:21:44 +00009198
John McCall8e346702010-06-04 19:02:56 +00009199 // Set the parameters on the block decl.
Douglas Gregorb524d902010-11-01 18:37:59 +00009200 if (!Params.empty()) {
David Blaikie9c70e042011-09-21 18:16:56 +00009201 CurBlock->TheDecl->setParams(Params);
Douglas Gregorb524d902010-11-01 18:37:59 +00009202 CheckParmsForFunctionDef(CurBlock->TheDecl->param_begin(),
9203 CurBlock->TheDecl->param_end(),
9204 /*CheckParameterNames=*/false);
9205 }
9206
John McCalla3ccba02010-06-04 11:21:44 +00009207 // Finally we can process decl attributes.
Douglas Gregor758a8692009-06-17 21:51:59 +00009208 ProcessDeclAttributes(CurScope, CurBlock->TheDecl, ParamInfo);
John McCalldf8b37c2010-03-22 09:20:08 +00009209
John McCalla3ccba02010-06-04 11:21:44 +00009210 // Put the parameter variables in scope. We can bail out immediately
9211 // if we don't have any.
John McCall8e346702010-06-04 19:02:56 +00009212 if (Params.empty())
John McCalla3ccba02010-06-04 11:21:44 +00009213 return;
9214
Steve Naroff1d95e5a2008-10-10 01:28:17 +00009215 for (BlockDecl::param_iterator AI = CurBlock->TheDecl->param_begin(),
John McCallf7b2fb52010-01-22 00:28:27 +00009216 E = CurBlock->TheDecl->param_end(); AI != E; ++AI) {
9217 (*AI)->setOwningFunction(CurBlock->TheDecl);
9218
Steve Naroff1d95e5a2008-10-10 01:28:17 +00009219 // If this has an identifier, add it to the scope stack.
John McCalldf8b37c2010-03-22 09:20:08 +00009220 if ((*AI)->getIdentifier()) {
Argyrios Kyrtzidis1cb0de12010-12-15 18:44:22 +00009221 CheckShadow(CurBlock->TheScope, *AI);
John McCalldf8b37c2010-03-22 09:20:08 +00009222
Steve Naroff1d95e5a2008-10-10 01:28:17 +00009223 PushOnScopeChains(*AI, CurBlock->TheScope);
John McCalldf8b37c2010-03-22 09:20:08 +00009224 }
John McCallf7b2fb52010-01-22 00:28:27 +00009225 }
Steve Naroffc540d662008-09-03 18:15:37 +00009226}
9227
9228/// ActOnBlockError - If there is an error parsing a block, this callback
9229/// is invoked to pop the information about the block from the action impl.
9230void Sema::ActOnBlockError(SourceLocation CaretLoc, Scope *CurScope) {
John McCallf1a3c2a2011-11-11 03:19:12 +00009231 // Leave the expression-evaluation context.
9232 DiscardCleanupsInEvaluationContext();
9233 PopExpressionEvaluationContext();
9234
Steve Naroffc540d662008-09-03 18:15:37 +00009235 // Pop off CurBlock, handle nested blocks.
Chris Lattner41b86942009-04-21 22:38:46 +00009236 PopDeclContext();
Eli Friedman71c80552012-01-05 03:35:19 +00009237 PopFunctionScopeInfo();
Steve Naroffc540d662008-09-03 18:15:37 +00009238}
9239
9240/// ActOnBlockStmtExpr - This is called when the body of a block statement
9241/// literal was successfully completed. ^(int x){...}
John McCalldadc5752010-08-24 06:29:42 +00009242ExprResult Sema::ActOnBlockStmtExpr(SourceLocation CaretLoc,
Chris Lattner60f84492011-02-17 23:58:47 +00009243 Stmt *Body, Scope *CurScope) {
Chris Lattner9eac9312009-03-27 04:18:06 +00009244 // If blocks are disabled, emit an error.
9245 if (!LangOpts.Blocks)
9246 Diag(CaretLoc, diag::err_blocks_disable);
Mike Stump11289f42009-09-09 15:08:12 +00009247
John McCallf1a3c2a2011-11-11 03:19:12 +00009248 // Leave the expression-evaluation context.
John McCall85110b42012-03-08 22:00:17 +00009249 if (hasAnyUnrecoverableErrorsInThisFunction())
9250 DiscardCleanupsInEvaluationContext();
John McCallf1a3c2a2011-11-11 03:19:12 +00009251 assert(!ExprNeedsCleanups && "cleanups within block not correctly bound!");
9252 PopExpressionEvaluationContext();
9253
Douglas Gregor9a28e842010-03-01 23:15:13 +00009254 BlockScopeInfo *BSI = cast<BlockScopeInfo>(FunctionScopes.back());
Fariborz Jahanian1babe772010-07-09 18:44:02 +00009255
Steve Naroff1d95e5a2008-10-10 01:28:17 +00009256 PopDeclContext();
9257
Steve Naroffc540d662008-09-03 18:15:37 +00009258 QualType RetTy = Context.VoidTy;
Fariborz Jahanian3fd73102009-06-19 23:37:08 +00009259 if (!BSI->ReturnType.isNull())
9260 RetTy = BSI->ReturnType;
Mike Stump4e1f26a2009-02-19 03:04:26 +00009261
Mike Stump3bf1ab42009-07-28 22:04:01 +00009262 bool NoReturn = BSI->TheDecl->getAttr<NoReturnAttr>();
Steve Naroffc540d662008-09-03 18:15:37 +00009263 QualType BlockTy;
John McCall8e346702010-06-04 19:02:56 +00009264
John McCallc63de662011-02-02 13:00:07 +00009265 // Set the captured variables on the block.
Eli Friedman20139d32012-01-11 02:36:31 +00009266 // FIXME: Share capture structure between BlockDecl and CapturingScopeInfo!
9267 SmallVector<BlockDecl::Capture, 4> Captures;
9268 for (unsigned i = 0, e = BSI->Captures.size(); i != e; i++) {
9269 CapturingScopeInfo::Capture &Cap = BSI->Captures[i];
9270 if (Cap.isThisCapture())
9271 continue;
Eli Friedman24af8502012-02-03 22:47:37 +00009272 BlockDecl::Capture NewCap(Cap.getVariable(), Cap.isBlockCapture(),
Eli Friedman20139d32012-01-11 02:36:31 +00009273 Cap.isNested(), Cap.getCopyExpr());
9274 Captures.push_back(NewCap);
9275 }
9276 BSI->TheDecl->setCaptures(Context, Captures.begin(), Captures.end(),
9277 BSI->CXXThisCaptureIndex != 0);
John McCallc63de662011-02-02 13:00:07 +00009278
John McCall8e346702010-06-04 19:02:56 +00009279 // If the user wrote a function type in some form, try to use that.
9280 if (!BSI->FunctionType.isNull()) {
9281 const FunctionType *FTy = BSI->FunctionType->getAs<FunctionType>();
9282
9283 FunctionType::ExtInfo Ext = FTy->getExtInfo();
9284 if (NoReturn && !Ext.getNoReturn()) Ext = Ext.withNoReturn(true);
9285
9286 // Turn protoless block types into nullary block types.
9287 if (isa<FunctionNoProtoType>(FTy)) {
John McCalldb40c7f2010-12-14 08:05:40 +00009288 FunctionProtoType::ExtProtoInfo EPI;
9289 EPI.ExtInfo = Ext;
9290 BlockTy = Context.getFunctionType(RetTy, 0, 0, EPI);
John McCall8e346702010-06-04 19:02:56 +00009291
9292 // Otherwise, if we don't need to change anything about the function type,
9293 // preserve its sugar structure.
9294 } else if (FTy->getResultType() == RetTy &&
9295 (!NoReturn || FTy->getNoReturnAttr())) {
9296 BlockTy = BSI->FunctionType;
9297
9298 // Otherwise, make the minimal modifications to the function type.
9299 } else {
9300 const FunctionProtoType *FPT = cast<FunctionProtoType>(FTy);
John McCalldb40c7f2010-12-14 08:05:40 +00009301 FunctionProtoType::ExtProtoInfo EPI = FPT->getExtProtoInfo();
9302 EPI.TypeQuals = 0; // FIXME: silently?
9303 EPI.ExtInfo = Ext;
John McCall8e346702010-06-04 19:02:56 +00009304 BlockTy = Context.getFunctionType(RetTy,
9305 FPT->arg_type_begin(),
9306 FPT->getNumArgs(),
John McCalldb40c7f2010-12-14 08:05:40 +00009307 EPI);
John McCall8e346702010-06-04 19:02:56 +00009308 }
9309
9310 // If we don't have a function type, just build one from nothing.
9311 } else {
John McCalldb40c7f2010-12-14 08:05:40 +00009312 FunctionProtoType::ExtProtoInfo EPI;
John McCall31168b02011-06-15 23:02:42 +00009313 EPI.ExtInfo = FunctionType::ExtInfo().withNoReturn(NoReturn);
John McCalldb40c7f2010-12-14 08:05:40 +00009314 BlockTy = Context.getFunctionType(RetTy, 0, 0, EPI);
John McCall8e346702010-06-04 19:02:56 +00009315 }
Mike Stump4e1f26a2009-02-19 03:04:26 +00009316
John McCall8e346702010-06-04 19:02:56 +00009317 DiagnoseUnusedParameters(BSI->TheDecl->param_begin(),
9318 BSI->TheDecl->param_end());
Steve Naroffc540d662008-09-03 18:15:37 +00009319 BlockTy = Context.getBlockPointerType(BlockTy);
Mike Stump4e1f26a2009-02-19 03:04:26 +00009320
Chris Lattner45542ea2009-04-19 05:28:12 +00009321 // If needed, diagnose invalid gotos and switches in the block.
John McCall31168b02011-06-15 23:02:42 +00009322 if (getCurFunction()->NeedsScopeChecking() &&
9323 !hasAnyUnrecoverableErrorsInThisFunction())
John McCallb268a282010-08-23 23:25:46 +00009324 DiagnoseInvalidJumps(cast<CompoundStmt>(Body));
Mike Stump11289f42009-09-09 15:08:12 +00009325
Chris Lattner60f84492011-02-17 23:58:47 +00009326 BSI->TheDecl->setBody(cast<CompoundStmt>(Body));
Kovarththanan Rajaratnamba2c6522010-03-13 10:17:05 +00009327
Douglas Gregor49695f02011-09-06 20:46:03 +00009328 computeNRVO(Body, getCurBlock());
9329
Benjamin Kramera4fb8362011-07-12 14:11:05 +00009330 BlockExpr *Result = new (Context) BlockExpr(BSI->TheDecl, BlockTy);
9331 const AnalysisBasedWarnings::Policy &WP = AnalysisWarnings.getDefaultPolicy();
Eli Friedman71c80552012-01-05 03:35:19 +00009332 PopFunctionScopeInfo(&WP, Result->getBlockDecl(), Result);
Benjamin Kramera4fb8362011-07-12 14:11:05 +00009333
John McCall28fc7092011-11-10 05:35:25 +00009334 // If the block isn't obviously global, i.e. it captures anything at
John McCalld2393872012-04-13 01:08:17 +00009335 // all, then we need to do a few things in the surrounding context:
John McCall28fc7092011-11-10 05:35:25 +00009336 if (Result->getBlockDecl()->hasCaptures()) {
John McCalld2393872012-04-13 01:08:17 +00009337 // First, this expression has a new cleanup object.
John McCall28fc7092011-11-10 05:35:25 +00009338 ExprCleanupObjects.push_back(Result->getBlockDecl());
9339 ExprNeedsCleanups = true;
John McCalld2393872012-04-13 01:08:17 +00009340
9341 // It also gets a branch-protected scope if any of the captured
9342 // variables needs destruction.
9343 for (BlockDecl::capture_const_iterator
9344 ci = Result->getBlockDecl()->capture_begin(),
9345 ce = Result->getBlockDecl()->capture_end(); ci != ce; ++ci) {
9346 const VarDecl *var = ci->getVariable();
9347 if (var->getType().isDestructedType() != QualType::DK_none) {
9348 getCurFunction()->setHasBranchProtectedScope();
9349 break;
9350 }
9351 }
John McCall28fc7092011-11-10 05:35:25 +00009352 }
Fariborz Jahanian197c68c2012-03-06 18:41:35 +00009353
Douglas Gregor9a28e842010-03-01 23:15:13 +00009354 return Owned(Result);
Steve Naroffc540d662008-09-03 18:15:37 +00009355}
9356
John McCalldadc5752010-08-24 06:29:42 +00009357ExprResult Sema::ActOnVAArg(SourceLocation BuiltinLoc,
Richard Trieuba63ce62011-09-09 01:45:06 +00009358 Expr *E, ParsedType Ty,
Sebastian Redl6d4256c2009-03-15 17:47:39 +00009359 SourceLocation RPLoc) {
Abramo Bagnara27db2392010-08-10 10:06:15 +00009360 TypeSourceInfo *TInfo;
Richard Trieuba63ce62011-09-09 01:45:06 +00009361 GetTypeFromParser(Ty, &TInfo);
9362 return BuildVAArgExpr(BuiltinLoc, E, TInfo, RPLoc);
Abramo Bagnara27db2392010-08-10 10:06:15 +00009363}
9364
John McCalldadc5752010-08-24 06:29:42 +00009365ExprResult Sema::BuildVAArgExpr(SourceLocation BuiltinLoc,
John McCall7decc9e2010-11-18 06:31:45 +00009366 Expr *E, TypeSourceInfo *TInfo,
9367 SourceLocation RPLoc) {
Chris Lattner56382aa2009-04-05 15:49:53 +00009368 Expr *OrigExpr = E;
Mike Stump11289f42009-09-09 15:08:12 +00009369
Eli Friedman121ba0c2008-08-09 23:32:40 +00009370 // Get the va_list type
9371 QualType VaListType = Context.getBuiltinVaListType();
Eli Friedmane2cad652009-05-16 12:46:54 +00009372 if (VaListType->isArrayType()) {
9373 // Deal with implicit array decay; for example, on x86-64,
9374 // va_list is an array, but it's supposed to decay to
9375 // a pointer for va_arg.
Eli Friedman121ba0c2008-08-09 23:32:40 +00009376 VaListType = Context.getArrayDecayedType(VaListType);
Eli Friedmane2cad652009-05-16 12:46:54 +00009377 // Make sure the input expression also decays appropriately.
John Wiegley01296292011-04-08 18:41:53 +00009378 ExprResult Result = UsualUnaryConversions(E);
9379 if (Result.isInvalid())
9380 return ExprError();
9381 E = Result.take();
Eli Friedmane2cad652009-05-16 12:46:54 +00009382 } else {
9383 // Otherwise, the va_list argument must be an l-value because
9384 // it is modified by va_arg.
Mike Stump11289f42009-09-09 15:08:12 +00009385 if (!E->isTypeDependent() &&
Douglas Gregorad3150c2009-05-19 23:10:31 +00009386 CheckForModifiableLvalue(E, BuiltinLoc, *this))
Eli Friedmane2cad652009-05-16 12:46:54 +00009387 return ExprError();
9388 }
Eli Friedman121ba0c2008-08-09 23:32:40 +00009389
Douglas Gregorad3150c2009-05-19 23:10:31 +00009390 if (!E->isTypeDependent() &&
9391 !Context.hasSameType(VaListType, E->getType())) {
Sebastian Redl6d4256c2009-03-15 17:47:39 +00009392 return ExprError(Diag(E->getLocStart(),
9393 diag::err_first_argument_to_va_arg_not_of_type_va_list)
Chris Lattner56382aa2009-04-05 15:49:53 +00009394 << OrigExpr->getType() << E->getSourceRange());
Chris Lattner3f5cd772009-04-05 00:59:53 +00009395 }
Mike Stump4e1f26a2009-02-19 03:04:26 +00009396
David Majnemerc75d1a12011-06-14 05:17:32 +00009397 if (!TInfo->getType()->isDependentType()) {
9398 if (RequireCompleteType(TInfo->getTypeLoc().getBeginLoc(), TInfo->getType(),
Douglas Gregor7bfb2d02012-05-04 16:32:21 +00009399 diag::err_second_parameter_to_va_arg_incomplete,
9400 TInfo->getTypeLoc()))
David Majnemerc75d1a12011-06-14 05:17:32 +00009401 return ExprError();
David Majnemer254a5c02011-06-13 06:37:03 +00009402
David Majnemerc75d1a12011-06-14 05:17:32 +00009403 if (RequireNonAbstractType(TInfo->getTypeLoc().getBeginLoc(),
Douglas Gregorae298422012-05-04 17:09:59 +00009404 TInfo->getType(),
9405 diag::err_second_parameter_to_va_arg_abstract,
9406 TInfo->getTypeLoc()))
David Majnemerc75d1a12011-06-14 05:17:32 +00009407 return ExprError();
9408
Douglas Gregor7e1eb932011-07-30 06:45:27 +00009409 if (!TInfo->getType().isPODType(Context)) {
David Majnemerc75d1a12011-06-14 05:17:32 +00009410 Diag(TInfo->getTypeLoc().getBeginLoc(),
Douglas Gregor7e1eb932011-07-30 06:45:27 +00009411 TInfo->getType()->isObjCLifetimeType()
9412 ? diag::warn_second_parameter_to_va_arg_ownership_qualified
9413 : diag::warn_second_parameter_to_va_arg_not_pod)
David Majnemerc75d1a12011-06-14 05:17:32 +00009414 << TInfo->getType()
9415 << TInfo->getTypeLoc().getSourceRange();
Douglas Gregor7e1eb932011-07-30 06:45:27 +00009416 }
Eli Friedman6290ae42011-07-11 21:45:59 +00009417
9418 // Check for va_arg where arguments of the given type will be promoted
9419 // (i.e. this va_arg is guaranteed to have undefined behavior).
9420 QualType PromoteType;
9421 if (TInfo->getType()->isPromotableIntegerType()) {
9422 PromoteType = Context.getPromotedIntegerType(TInfo->getType());
9423 if (Context.typesAreCompatible(PromoteType, TInfo->getType()))
9424 PromoteType = QualType();
9425 }
9426 if (TInfo->getType()->isSpecificBuiltinType(BuiltinType::Float))
9427 PromoteType = Context.DoubleTy;
9428 if (!PromoteType.isNull())
9429 Diag(TInfo->getTypeLoc().getBeginLoc(),
9430 diag::warn_second_parameter_to_va_arg_never_compatible)
9431 << TInfo->getType()
9432 << PromoteType
9433 << TInfo->getTypeLoc().getSourceRange();
David Majnemerc75d1a12011-06-14 05:17:32 +00009434 }
Mike Stump4e1f26a2009-02-19 03:04:26 +00009435
Abramo Bagnara27db2392010-08-10 10:06:15 +00009436 QualType T = TInfo->getType().getNonLValueExprType(Context);
9437 return Owned(new (Context) VAArgExpr(BuiltinLoc, E, TInfo, RPLoc, T));
Anders Carlsson7e13ab82007-10-15 20:28:48 +00009438}
9439
John McCalldadc5752010-08-24 06:29:42 +00009440ExprResult Sema::ActOnGNUNullExpr(SourceLocation TokenLoc) {
Douglas Gregor3be4b122008-11-29 04:51:27 +00009441 // The type of __null will be int or long, depending on the size of
9442 // pointers on the target.
9443 QualType Ty;
Douglas Gregore8bbc122011-09-02 00:18:52 +00009444 unsigned pw = Context.getTargetInfo().getPointerWidth(0);
9445 if (pw == Context.getTargetInfo().getIntWidth())
Douglas Gregor3be4b122008-11-29 04:51:27 +00009446 Ty = Context.IntTy;
Douglas Gregore8bbc122011-09-02 00:18:52 +00009447 else if (pw == Context.getTargetInfo().getLongWidth())
Douglas Gregor3be4b122008-11-29 04:51:27 +00009448 Ty = Context.LongTy;
Douglas Gregore8bbc122011-09-02 00:18:52 +00009449 else if (pw == Context.getTargetInfo().getLongLongWidth())
NAKAMURA Takumi0d13fd32011-01-19 00:11:41 +00009450 Ty = Context.LongLongTy;
9451 else {
David Blaikie83d382b2011-09-23 05:06:16 +00009452 llvm_unreachable("I don't know size of pointer!");
NAKAMURA Takumi0d13fd32011-01-19 00:11:41 +00009453 }
Douglas Gregor3be4b122008-11-29 04:51:27 +00009454
Sebastian Redl6d4256c2009-03-15 17:47:39 +00009455 return Owned(new (Context) GNUNullExpr(Ty, TokenLoc));
Douglas Gregor3be4b122008-11-29 04:51:27 +00009456}
9457
Alexis Huntc46382e2010-04-28 23:02:27 +00009458static void MakeObjCStringLiteralFixItHint(Sema& SemaRef, QualType DstType,
Douglas Gregora771f462010-03-31 17:46:05 +00009459 Expr *SrcExpr, FixItHint &Hint) {
David Blaikiebbafb8a2012-03-11 07:00:24 +00009460 if (!SemaRef.getLangOpts().ObjC1)
Anders Carlssonace5d072009-11-10 04:46:30 +00009461 return;
Kovarththanan Rajaratnamba2c6522010-03-13 10:17:05 +00009462
Anders Carlssonace5d072009-11-10 04:46:30 +00009463 const ObjCObjectPointerType *PT = DstType->getAs<ObjCObjectPointerType>();
9464 if (!PT)
9465 return;
9466
9467 // Check if the destination is of type 'id'.
9468 if (!PT->isObjCIdType()) {
9469 // Check if the destination is the 'NSString' interface.
9470 const ObjCInterfaceDecl *ID = PT->getInterfaceDecl();
9471 if (!ID || !ID->getIdentifier()->isStr("NSString"))
9472 return;
9473 }
Kovarththanan Rajaratnamba2c6522010-03-13 10:17:05 +00009474
John McCallfe96e0b2011-11-06 09:01:30 +00009475 // Ignore any parens, implicit casts (should only be
9476 // array-to-pointer decays), and not-so-opaque values. The last is
9477 // important for making this trigger for property assignments.
9478 SrcExpr = SrcExpr->IgnoreParenImpCasts();
9479 if (OpaqueValueExpr *OV = dyn_cast<OpaqueValueExpr>(SrcExpr))
9480 if (OV->getSourceExpr())
9481 SrcExpr = OV->getSourceExpr()->IgnoreParenImpCasts();
9482
9483 StringLiteral *SL = dyn_cast<StringLiteral>(SrcExpr);
Douglas Gregorfb65e592011-07-27 05:40:30 +00009484 if (!SL || !SL->isAscii())
Anders Carlssonace5d072009-11-10 04:46:30 +00009485 return;
Kovarththanan Rajaratnamba2c6522010-03-13 10:17:05 +00009486
Douglas Gregora771f462010-03-31 17:46:05 +00009487 Hint = FixItHint::CreateInsertion(SL->getLocStart(), "@");
Anders Carlssonace5d072009-11-10 04:46:30 +00009488}
9489
Chris Lattner9bad62c2008-01-04 18:04:52 +00009490bool Sema::DiagnoseAssignmentResult(AssignConvertType ConvTy,
9491 SourceLocation Loc,
9492 QualType DstType, QualType SrcType,
Douglas Gregor4f4946a2010-04-22 00:20:18 +00009493 Expr *SrcExpr, AssignmentAction Action,
9494 bool *Complained) {
9495 if (Complained)
9496 *Complained = false;
9497
Chris Lattner9bad62c2008-01-04 18:04:52 +00009498 // Decode the result (notice that AST's are still created for extensions).
Douglas Gregor33823722011-06-11 01:09:30 +00009499 bool CheckInferredResultType = false;
Chris Lattner9bad62c2008-01-04 18:04:52 +00009500 bool isInvalid = false;
Eli Friedman381f4312012-02-29 20:59:56 +00009501 unsigned DiagKind = 0;
Douglas Gregora771f462010-03-31 17:46:05 +00009502 FixItHint Hint;
Anna Zaks3b402712011-07-28 19:51:27 +00009503 ConversionFixItGenerator ConvHints;
9504 bool MayHaveConvFixit = false;
Richard Trieucaff2472011-11-23 22:32:32 +00009505 bool MayHaveFunctionDiff = false;
Kovarththanan Rajaratnamba2c6522010-03-13 10:17:05 +00009506
Chris Lattner9bad62c2008-01-04 18:04:52 +00009507 switch (ConvTy) {
Chris Lattner9bad62c2008-01-04 18:04:52 +00009508 case Compatible: return false;
Chris Lattner940cfeb2008-01-04 18:22:42 +00009509 case PointerToInt:
Chris Lattner9bad62c2008-01-04 18:04:52 +00009510 DiagKind = diag::ext_typecheck_convert_pointer_int;
Anna Zaks3b402712011-07-28 19:51:27 +00009511 ConvHints.tryToFixConversion(SrcExpr, SrcType, DstType, *this);
9512 MayHaveConvFixit = true;
Chris Lattner9bad62c2008-01-04 18:04:52 +00009513 break;
Chris Lattner940cfeb2008-01-04 18:22:42 +00009514 case IntToPointer:
9515 DiagKind = diag::ext_typecheck_convert_int_pointer;
Anna Zaks3b402712011-07-28 19:51:27 +00009516 ConvHints.tryToFixConversion(SrcExpr, SrcType, DstType, *this);
9517 MayHaveConvFixit = true;
Chris Lattner940cfeb2008-01-04 18:22:42 +00009518 break;
Chris Lattner9bad62c2008-01-04 18:04:52 +00009519 case IncompatiblePointer:
Douglas Gregora771f462010-03-31 17:46:05 +00009520 MakeObjCStringLiteralFixItHint(*this, DstType, SrcExpr, Hint);
Chris Lattner9bad62c2008-01-04 18:04:52 +00009521 DiagKind = diag::ext_typecheck_convert_incompatible_pointer;
Douglas Gregor33823722011-06-11 01:09:30 +00009522 CheckInferredResultType = DstType->isObjCObjectPointerType() &&
9523 SrcType->isObjCObjectPointerType();
Anna Zaks3b402712011-07-28 19:51:27 +00009524 if (Hint.isNull() && !CheckInferredResultType) {
9525 ConvHints.tryToFixConversion(SrcExpr, SrcType, DstType, *this);
9526 }
9527 MayHaveConvFixit = true;
Chris Lattner9bad62c2008-01-04 18:04:52 +00009528 break;
Eli Friedman80160bd2009-03-22 23:59:44 +00009529 case IncompatiblePointerSign:
9530 DiagKind = diag::ext_typecheck_convert_incompatible_pointer_sign;
9531 break;
Chris Lattner9bad62c2008-01-04 18:04:52 +00009532 case FunctionVoidPointer:
9533 DiagKind = diag::ext_typecheck_convert_pointer_void_func;
9534 break;
John McCall4fff8f62011-02-01 00:10:29 +00009535 case IncompatiblePointerDiscardsQualifiers: {
John McCall71de91c2011-02-01 23:28:01 +00009536 // Perform array-to-pointer decay if necessary.
9537 if (SrcType->isArrayType()) SrcType = Context.getArrayDecayedType(SrcType);
9538
John McCall4fff8f62011-02-01 00:10:29 +00009539 Qualifiers lhq = SrcType->getPointeeType().getQualifiers();
9540 Qualifiers rhq = DstType->getPointeeType().getQualifiers();
9541 if (lhq.getAddressSpace() != rhq.getAddressSpace()) {
9542 DiagKind = diag::err_typecheck_incompatible_address_space;
9543 break;
John McCall31168b02011-06-15 23:02:42 +00009544
9545
9546 } else if (lhq.getObjCLifetime() != rhq.getObjCLifetime()) {
Argyrios Kyrtzidiscff00d92011-06-24 00:08:59 +00009547 DiagKind = diag::err_typecheck_incompatible_ownership;
John McCall31168b02011-06-15 23:02:42 +00009548 break;
John McCall4fff8f62011-02-01 00:10:29 +00009549 }
9550
9551 llvm_unreachable("unknown error case for discarding qualifiers!");
9552 // fallthrough
9553 }
Chris Lattner9bad62c2008-01-04 18:04:52 +00009554 case CompatiblePointerDiscardsQualifiers:
Douglas Gregoraa1e21d2008-09-12 00:47:35 +00009555 // If the qualifiers lost were because we were applying the
9556 // (deprecated) C++ conversion from a string literal to a char*
9557 // (or wchar_t*), then there was no error (C++ 4.2p2). FIXME:
9558 // Ideally, this check would be performed in
John McCallaba90822011-01-31 23:13:11 +00009559 // checkPointerTypesForAssignment. However, that would require a
Douglas Gregoraa1e21d2008-09-12 00:47:35 +00009560 // bit of refactoring (so that the second argument is an
9561 // expression, rather than a type), which should be done as part
John McCallaba90822011-01-31 23:13:11 +00009562 // of a larger effort to fix checkPointerTypesForAssignment for
Douglas Gregoraa1e21d2008-09-12 00:47:35 +00009563 // C++ semantics.
David Blaikiebbafb8a2012-03-11 07:00:24 +00009564 if (getLangOpts().CPlusPlus &&
Douglas Gregoraa1e21d2008-09-12 00:47:35 +00009565 IsStringLiteralToNonConstPointerConversion(SrcExpr, DstType))
9566 return false;
Chris Lattner9bad62c2008-01-04 18:04:52 +00009567 DiagKind = diag::ext_typecheck_convert_discards_qualifiers;
9568 break;
Alexis Hunt6f3de502009-11-08 07:46:34 +00009569 case IncompatibleNestedPointerQualifiers:
Fariborz Jahanianb98dade2009-11-09 22:16:37 +00009570 DiagKind = diag::ext_nested_pointer_qualifier_mismatch;
Fariborz Jahaniand7aa9d82009-11-07 20:20:40 +00009571 break;
Steve Naroff081c7422008-09-04 15:10:53 +00009572 case IntToBlockPointer:
9573 DiagKind = diag::err_int_to_block_pointer;
9574 break;
9575 case IncompatibleBlockPointer:
Mike Stumpd79b5a82009-04-21 22:51:42 +00009576 DiagKind = diag::err_typecheck_convert_incompatible_block_pointer;
Steve Naroff081c7422008-09-04 15:10:53 +00009577 break;
Steve Naroff8afa9892008-10-14 22:18:38 +00009578 case IncompatibleObjCQualifiedId:
Mike Stump4e1f26a2009-02-19 03:04:26 +00009579 // FIXME: Diagnose the problem in ObjCQualifiedIdTypesAreCompatible, since
Steve Naroff8afa9892008-10-14 22:18:38 +00009580 // it can give a more specific diagnostic.
9581 DiagKind = diag::warn_incompatible_qualified_id;
9582 break;
Anders Carlssondb5a9b62009-01-30 23:17:46 +00009583 case IncompatibleVectors:
9584 DiagKind = diag::warn_incompatible_vectors;
9585 break;
Fariborz Jahanian6f472e82011-07-07 18:55:47 +00009586 case IncompatibleObjCWeakRef:
9587 DiagKind = diag::err_arc_weak_unavailable_assign;
9588 break;
Chris Lattner9bad62c2008-01-04 18:04:52 +00009589 case Incompatible:
9590 DiagKind = diag::err_typecheck_convert_incompatible;
Anna Zaks3b402712011-07-28 19:51:27 +00009591 ConvHints.tryToFixConversion(SrcExpr, SrcType, DstType, *this);
9592 MayHaveConvFixit = true;
Chris Lattner9bad62c2008-01-04 18:04:52 +00009593 isInvalid = true;
Richard Trieucaff2472011-11-23 22:32:32 +00009594 MayHaveFunctionDiff = true;
Chris Lattner9bad62c2008-01-04 18:04:52 +00009595 break;
9596 }
Mike Stump4e1f26a2009-02-19 03:04:26 +00009597
Douglas Gregorc68e1402010-04-09 00:35:39 +00009598 QualType FirstType, SecondType;
9599 switch (Action) {
9600 case AA_Assigning:
9601 case AA_Initializing:
9602 // The destination type comes first.
9603 FirstType = DstType;
9604 SecondType = SrcType;
9605 break;
Alexis Huntc46382e2010-04-28 23:02:27 +00009606
Douglas Gregorc68e1402010-04-09 00:35:39 +00009607 case AA_Returning:
9608 case AA_Passing:
9609 case AA_Converting:
9610 case AA_Sending:
9611 case AA_Casting:
9612 // The source type comes first.
9613 FirstType = SrcType;
9614 SecondType = DstType;
9615 break;
9616 }
Alexis Huntc46382e2010-04-28 23:02:27 +00009617
Anna Zaks3b402712011-07-28 19:51:27 +00009618 PartialDiagnostic FDiag = PDiag(DiagKind);
9619 FDiag << FirstType << SecondType << Action << SrcExpr->getSourceRange();
9620
9621 // If we can fix the conversion, suggest the FixIts.
9622 assert(ConvHints.isNull() || Hint.isNull());
9623 if (!ConvHints.isNull()) {
Benjamin Kramer490afa62012-01-14 21:05:10 +00009624 for (std::vector<FixItHint>::iterator HI = ConvHints.Hints.begin(),
9625 HE = ConvHints.Hints.end(); HI != HE; ++HI)
Anna Zaks3b402712011-07-28 19:51:27 +00009626 FDiag << *HI;
9627 } else {
9628 FDiag << Hint;
9629 }
9630 if (MayHaveConvFixit) { FDiag << (unsigned) (ConvHints.Kind); }
9631
Richard Trieucaff2472011-11-23 22:32:32 +00009632 if (MayHaveFunctionDiff)
9633 HandleFunctionTypeMismatch(FDiag, SecondType, FirstType);
9634
Anna Zaks3b402712011-07-28 19:51:27 +00009635 Diag(Loc, FDiag);
9636
Richard Trieucaff2472011-11-23 22:32:32 +00009637 if (SecondType == Context.OverloadTy)
9638 NoteAllOverloadCandidates(OverloadExpr::find(SrcExpr).Expression,
9639 FirstType);
9640
Douglas Gregor33823722011-06-11 01:09:30 +00009641 if (CheckInferredResultType)
9642 EmitRelatedResultTypeNote(SrcExpr);
9643
Douglas Gregor4f4946a2010-04-22 00:20:18 +00009644 if (Complained)
9645 *Complained = true;
Chris Lattner9bad62c2008-01-04 18:04:52 +00009646 return isInvalid;
9647}
Anders Carlssone54e8a12008-11-30 19:50:32 +00009648
Richard Smithf4c51d92012-02-04 09:53:13 +00009649ExprResult Sema::VerifyIntegerConstantExpression(Expr *E,
9650 llvm::APSInt *Result) {
Douglas Gregore2b37442012-05-04 22:38:52 +00009651 class SimpleICEDiagnoser : public VerifyICEDiagnoser {
9652 public:
9653 virtual void diagnoseNotICE(Sema &S, SourceLocation Loc, SourceRange SR) {
9654 S.Diag(Loc, diag::err_expr_not_ice) << S.LangOpts.CPlusPlus << SR;
9655 }
9656 } Diagnoser;
9657
9658 return VerifyIntegerConstantExpression(E, Result, Diagnoser);
9659}
9660
9661ExprResult Sema::VerifyIntegerConstantExpression(Expr *E,
9662 llvm::APSInt *Result,
9663 unsigned DiagID,
9664 bool AllowFold) {
9665 class IDDiagnoser : public VerifyICEDiagnoser {
9666 unsigned DiagID;
9667
9668 public:
9669 IDDiagnoser(unsigned DiagID)
9670 : VerifyICEDiagnoser(DiagID == 0), DiagID(DiagID) { }
9671
9672 virtual void diagnoseNotICE(Sema &S, SourceLocation Loc, SourceRange SR) {
9673 S.Diag(Loc, DiagID) << SR;
9674 }
9675 } Diagnoser(DiagID);
9676
9677 return VerifyIntegerConstantExpression(E, Result, Diagnoser, AllowFold);
9678}
9679
9680void Sema::VerifyICEDiagnoser::diagnoseFold(Sema &S, SourceLocation Loc,
9681 SourceRange SR) {
9682 S.Diag(Loc, diag::ext_expr_not_ice) << SR << S.LangOpts.CPlusPlus;
Richard Smithf4c51d92012-02-04 09:53:13 +00009683}
9684
Benjamin Kramer33adaae2012-04-18 14:22:41 +00009685ExprResult
9686Sema::VerifyIntegerConstantExpression(Expr *E, llvm::APSInt *Result,
Douglas Gregore2b37442012-05-04 22:38:52 +00009687 VerifyICEDiagnoser &Diagnoser,
9688 bool AllowFold) {
Daniel Dunbar62ee6412012-03-09 18:35:03 +00009689 SourceLocation DiagLoc = E->getLocStart();
Richard Smithf4c51d92012-02-04 09:53:13 +00009690
David Blaikiebbafb8a2012-03-11 07:00:24 +00009691 if (getLangOpts().CPlusPlus0x) {
Richard Smithf4c51d92012-02-04 09:53:13 +00009692 // C++11 [expr.const]p5:
9693 // If an expression of literal class type is used in a context where an
9694 // integral constant expression is required, then that class type shall
9695 // have a single non-explicit conversion function to an integral or
9696 // unscoped enumeration type
9697 ExprResult Converted;
Douglas Gregore2b37442012-05-04 22:38:52 +00009698 if (!Diagnoser.Suppress) {
9699 class CXX11ConvertDiagnoser : public ICEConvertDiagnoser {
9700 public:
9701 CXX11ConvertDiagnoser() : ICEConvertDiagnoser(false, true) { }
9702
9703 virtual DiagnosticBuilder diagnoseNotInt(Sema &S, SourceLocation Loc,
9704 QualType T) {
9705 return S.Diag(Loc, diag::err_ice_not_integral) << T;
9706 }
9707
9708 virtual DiagnosticBuilder diagnoseIncomplete(Sema &S,
9709 SourceLocation Loc,
9710 QualType T) {
9711 return S.Diag(Loc, diag::err_ice_incomplete_type) << T;
9712 }
9713
9714 virtual DiagnosticBuilder diagnoseExplicitConv(Sema &S,
9715 SourceLocation Loc,
9716 QualType T,
9717 QualType ConvTy) {
9718 return S.Diag(Loc, diag::err_ice_explicit_conversion) << T << ConvTy;
9719 }
9720
9721 virtual DiagnosticBuilder noteExplicitConv(Sema &S,
9722 CXXConversionDecl *Conv,
9723 QualType ConvTy) {
9724 return S.Diag(Conv->getLocation(), diag::note_ice_conversion_here)
9725 << ConvTy->isEnumeralType() << ConvTy;
9726 }
9727
9728 virtual DiagnosticBuilder diagnoseAmbiguous(Sema &S, SourceLocation Loc,
9729 QualType T) {
9730 return S.Diag(Loc, diag::err_ice_ambiguous_conversion) << T;
9731 }
9732
9733 virtual DiagnosticBuilder noteAmbiguous(Sema &S,
9734 CXXConversionDecl *Conv,
9735 QualType ConvTy) {
9736 return S.Diag(Conv->getLocation(), diag::note_ice_conversion_here)
9737 << ConvTy->isEnumeralType() << ConvTy;
9738 }
9739
9740 virtual DiagnosticBuilder diagnoseConversion(Sema &S,
9741 SourceLocation Loc,
9742 QualType T,
9743 QualType ConvTy) {
9744 return DiagnosticBuilder::getEmpty();
9745 }
9746 } ConvertDiagnoser;
9747
9748 Converted = ConvertToIntegralOrEnumerationType(DiagLoc, E,
9749 ConvertDiagnoser,
9750 /*AllowScopedEnumerations*/ false);
Richard Smithf4c51d92012-02-04 09:53:13 +00009751 } else {
9752 // The caller wants to silently enquire whether this is an ICE. Don't
9753 // produce any diagnostics if it isn't.
Douglas Gregore2b37442012-05-04 22:38:52 +00009754 class SilentICEConvertDiagnoser : public ICEConvertDiagnoser {
9755 public:
9756 SilentICEConvertDiagnoser() : ICEConvertDiagnoser(true, true) { }
9757
9758 virtual DiagnosticBuilder diagnoseNotInt(Sema &S, SourceLocation Loc,
9759 QualType T) {
9760 return DiagnosticBuilder::getEmpty();
9761 }
9762
9763 virtual DiagnosticBuilder diagnoseIncomplete(Sema &S,
9764 SourceLocation Loc,
9765 QualType T) {
9766 return DiagnosticBuilder::getEmpty();
9767 }
9768
9769 virtual DiagnosticBuilder diagnoseExplicitConv(Sema &S,
9770 SourceLocation Loc,
9771 QualType T,
9772 QualType ConvTy) {
9773 return DiagnosticBuilder::getEmpty();
9774 }
9775
9776 virtual DiagnosticBuilder noteExplicitConv(Sema &S,
9777 CXXConversionDecl *Conv,
9778 QualType ConvTy) {
9779 return DiagnosticBuilder::getEmpty();
9780 }
9781
9782 virtual DiagnosticBuilder diagnoseAmbiguous(Sema &S, SourceLocation Loc,
9783 QualType T) {
9784 return DiagnosticBuilder::getEmpty();
9785 }
9786
9787 virtual DiagnosticBuilder noteAmbiguous(Sema &S,
9788 CXXConversionDecl *Conv,
9789 QualType ConvTy) {
9790 return DiagnosticBuilder::getEmpty();
9791 }
9792
9793 virtual DiagnosticBuilder diagnoseConversion(Sema &S,
9794 SourceLocation Loc,
9795 QualType T,
9796 QualType ConvTy) {
9797 return DiagnosticBuilder::getEmpty();
9798 }
9799 } ConvertDiagnoser;
9800
9801 Converted = ConvertToIntegralOrEnumerationType(DiagLoc, E,
9802 ConvertDiagnoser, false);
Richard Smithf4c51d92012-02-04 09:53:13 +00009803 }
9804 if (Converted.isInvalid())
9805 return Converted;
9806 E = Converted.take();
9807 if (!E->getType()->isIntegralOrUnscopedEnumerationType())
9808 return ExprError();
9809 } else if (!E->getType()->isIntegralOrUnscopedEnumerationType()) {
9810 // An ICE must be of integral or unscoped enumeration type.
Douglas Gregore2b37442012-05-04 22:38:52 +00009811 if (!Diagnoser.Suppress)
9812 Diagnoser.diagnoseNotICE(*this, DiagLoc, E->getSourceRange());
Richard Smithf4c51d92012-02-04 09:53:13 +00009813 return ExprError();
9814 }
9815
Richard Smith902ca212011-12-14 23:32:26 +00009816 // Circumvent ICE checking in C++11 to avoid evaluating the expression twice
9817 // in the non-ICE case.
David Blaikiebbafb8a2012-03-11 07:00:24 +00009818 if (!getLangOpts().CPlusPlus0x && E->isIntegerConstantExpr(Context)) {
Richard Smithf4c51d92012-02-04 09:53:13 +00009819 if (Result)
9820 *Result = E->EvaluateKnownConstInt(Context);
9821 return Owned(E);
Eli Friedmanbb967cc2009-04-25 22:26:58 +00009822 }
9823
Anders Carlssone54e8a12008-11-30 19:50:32 +00009824 Expr::EvalResult EvalResult;
Richard Smith92b1ce02011-12-12 09:28:41 +00009825 llvm::SmallVector<PartialDiagnosticAt, 8> Notes;
9826 EvalResult.Diag = &Notes;
Anders Carlssone54e8a12008-11-30 19:50:32 +00009827
Richard Smith902ca212011-12-14 23:32:26 +00009828 // Try to evaluate the expression, and produce diagnostics explaining why it's
9829 // not a constant expression as a side-effect.
9830 bool Folded = E->EvaluateAsRValue(EvalResult, Context) &&
9831 EvalResult.Val.isInt() && !EvalResult.HasSideEffects;
9832
9833 // In C++11, we can rely on diagnostics being produced for any expression
9834 // which is not a constant expression. If no diagnostics were produced, then
9835 // this is a constant expression.
David Blaikiebbafb8a2012-03-11 07:00:24 +00009836 if (Folded && getLangOpts().CPlusPlus0x && Notes.empty()) {
Richard Smith902ca212011-12-14 23:32:26 +00009837 if (Result)
9838 *Result = EvalResult.Val.getInt();
Richard Smithf4c51d92012-02-04 09:53:13 +00009839 return Owned(E);
9840 }
9841
9842 // If our only note is the usual "invalid subexpression" note, just point
9843 // the caret at its location rather than producing an essentially
9844 // redundant note.
9845 if (Notes.size() == 1 && Notes[0].second.getDiagID() ==
9846 diag::note_invalid_subexpr_in_const_expr) {
9847 DiagLoc = Notes[0].first;
9848 Notes.clear();
Richard Smith902ca212011-12-14 23:32:26 +00009849 }
9850
9851 if (!Folded || !AllowFold) {
Douglas Gregore2b37442012-05-04 22:38:52 +00009852 if (!Diagnoser.Suppress) {
9853 Diagnoser.diagnoseNotICE(*this, DiagLoc, E->getSourceRange());
Richard Smith92b1ce02011-12-12 09:28:41 +00009854 for (unsigned I = 0, N = Notes.size(); I != N; ++I)
9855 Diag(Notes[I].first, Notes[I].second);
Anders Carlssone54e8a12008-11-30 19:50:32 +00009856 }
Mike Stump4e1f26a2009-02-19 03:04:26 +00009857
Richard Smithf4c51d92012-02-04 09:53:13 +00009858 return ExprError();
Anders Carlssone54e8a12008-11-30 19:50:32 +00009859 }
9860
Douglas Gregore2b37442012-05-04 22:38:52 +00009861 Diagnoser.diagnoseFold(*this, DiagLoc, E->getSourceRange());
Richard Smith2ec40612012-01-15 03:51:30 +00009862 for (unsigned I = 0, N = Notes.size(); I != N; ++I)
9863 Diag(Notes[I].first, Notes[I].second);
Mike Stump4e1f26a2009-02-19 03:04:26 +00009864
Anders Carlssone54e8a12008-11-30 19:50:32 +00009865 if (Result)
9866 *Result = EvalResult.Val.getInt();
Richard Smithf4c51d92012-02-04 09:53:13 +00009867 return Owned(E);
Anders Carlssone54e8a12008-11-30 19:50:32 +00009868}
Douglas Gregorc9c02ed2009-06-19 23:52:42 +00009869
Eli Friedman456f0182012-01-20 01:26:23 +00009870namespace {
9871 // Handle the case where we conclude a expression which we speculatively
9872 // considered to be unevaluated is actually evaluated.
9873 class TransformToPE : public TreeTransform<TransformToPE> {
9874 typedef TreeTransform<TransformToPE> BaseTransform;
9875
9876 public:
9877 TransformToPE(Sema &SemaRef) : BaseTransform(SemaRef) { }
9878
9879 // Make sure we redo semantic analysis
9880 bool AlwaysRebuild() { return true; }
9881
Eli Friedman5f0ca242012-02-06 23:29:57 +00009882 // Make sure we handle LabelStmts correctly.
9883 // FIXME: This does the right thing, but maybe we need a more general
9884 // fix to TreeTransform?
9885 StmtResult TransformLabelStmt(LabelStmt *S) {
9886 S->getDecl()->setStmt(0);
9887 return BaseTransform::TransformLabelStmt(S);
9888 }
9889
Eli Friedman456f0182012-01-20 01:26:23 +00009890 // We need to special-case DeclRefExprs referring to FieldDecls which
9891 // are not part of a member pointer formation; normal TreeTransforming
9892 // doesn't catch this case because of the way we represent them in the AST.
9893 // FIXME: This is a bit ugly; is it really the best way to handle this
9894 // case?
9895 //
9896 // Error on DeclRefExprs referring to FieldDecls.
9897 ExprResult TransformDeclRefExpr(DeclRefExpr *E) {
9898 if (isa<FieldDecl>(E->getDecl()) &&
9899 SemaRef.ExprEvalContexts.back().Context != Sema::Unevaluated)
9900 return SemaRef.Diag(E->getLocation(),
9901 diag::err_invalid_non_static_member_use)
9902 << E->getDecl() << E->getSourceRange();
9903
9904 return BaseTransform::TransformDeclRefExpr(E);
9905 }
9906
9907 // Exception: filter out member pointer formation
9908 ExprResult TransformUnaryOperator(UnaryOperator *E) {
9909 if (E->getOpcode() == UO_AddrOf && E->getType()->isMemberPointerType())
9910 return E;
9911
9912 return BaseTransform::TransformUnaryOperator(E);
9913 }
9914
Douglas Gregor89625492012-02-09 08:14:43 +00009915 ExprResult TransformLambdaExpr(LambdaExpr *E) {
9916 // Lambdas never need to be transformed.
9917 return E;
9918 }
Eli Friedman456f0182012-01-20 01:26:23 +00009919 };
Eli Friedmanfbc0dff2012-01-18 01:05:54 +00009920}
9921
Eli Friedman456f0182012-01-20 01:26:23 +00009922ExprResult Sema::TranformToPotentiallyEvaluated(Expr *E) {
Eli Friedmane4f22df2012-02-29 04:03:55 +00009923 assert(ExprEvalContexts.back().Context == Unevaluated &&
9924 "Should only transform unevaluated expressions");
Eli Friedman456f0182012-01-20 01:26:23 +00009925 ExprEvalContexts.back().Context =
9926 ExprEvalContexts[ExprEvalContexts.size()-2].Context;
9927 if (ExprEvalContexts.back().Context == Unevaluated)
9928 return E;
9929 return TransformToPE(*this).TransformExpr(E);
Eli Friedmanfbc0dff2012-01-18 01:05:54 +00009930}
9931
Douglas Gregorff790f12009-11-26 00:44:06 +00009932void
Douglas Gregor7fcbd902012-02-21 00:37:24 +00009933Sema::PushExpressionEvaluationContext(ExpressionEvaluationContext NewContext,
Richard Smithfd555f62012-02-22 02:04:18 +00009934 Decl *LambdaContextDecl,
9935 bool IsDecltype) {
Douglas Gregorff790f12009-11-26 00:44:06 +00009936 ExprEvalContexts.push_back(
John McCall31168b02011-06-15 23:02:42 +00009937 ExpressionEvaluationContextRecord(NewContext,
John McCall28fc7092011-11-10 05:35:25 +00009938 ExprCleanupObjects.size(),
Douglas Gregor7fcbd902012-02-21 00:37:24 +00009939 ExprNeedsCleanups,
Richard Smithfd555f62012-02-22 02:04:18 +00009940 LambdaContextDecl,
9941 IsDecltype));
John McCall31168b02011-06-15 23:02:42 +00009942 ExprNeedsCleanups = false;
Eli Friedman3bda6b12012-02-02 23:15:15 +00009943 if (!MaybeODRUseExprs.empty())
9944 std::swap(MaybeODRUseExprs, ExprEvalContexts.back().SavedMaybeODRUseExprs);
Douglas Gregor0b6a6242009-06-22 20:57:11 +00009945}
9946
Richard Trieucfc491d2011-08-02 04:35:43 +00009947void Sema::PopExpressionEvaluationContext() {
Eli Friedmanfa0df832012-02-02 03:46:19 +00009948 ExpressionEvaluationContextRecord& Rec = ExprEvalContexts.back();
Douglas Gregor0b6a6242009-06-22 20:57:11 +00009949
Douglas Gregor89625492012-02-09 08:14:43 +00009950 if (!Rec.Lambdas.empty()) {
9951 if (Rec.Context == Unevaluated) {
9952 // C++11 [expr.prim.lambda]p2:
9953 // A lambda-expression shall not appear in an unevaluated operand
9954 // (Clause 5).
9955 for (unsigned I = 0, N = Rec.Lambdas.size(); I != N; ++I)
9956 Diag(Rec.Lambdas[I]->getLocStart(),
9957 diag::err_lambda_unevaluated_operand);
9958 } else {
9959 // Mark the capture expressions odr-used. This was deferred
9960 // during lambda expression creation.
9961 for (unsigned I = 0, N = Rec.Lambdas.size(); I != N; ++I) {
9962 LambdaExpr *Lambda = Rec.Lambdas[I];
9963 for (LambdaExpr::capture_init_iterator
9964 C = Lambda->capture_init_begin(),
9965 CEnd = Lambda->capture_init_end();
9966 C != CEnd; ++C) {
9967 MarkDeclarationsReferencedInExpr(*C);
9968 }
9969 }
9970 }
9971 }
9972
Douglas Gregorff790f12009-11-26 00:44:06 +00009973 // When are coming out of an unevaluated context, clear out any
9974 // temporaries that we may have created as part of the evaluation of
9975 // the expression in that context: they aren't relevant because they
9976 // will never be constructed.
Richard Smith764d2fe2011-12-20 02:08:33 +00009977 if (Rec.Context == Unevaluated || Rec.Context == ConstantEvaluated) {
John McCall28fc7092011-11-10 05:35:25 +00009978 ExprCleanupObjects.erase(ExprCleanupObjects.begin() + Rec.NumCleanupObjects,
9979 ExprCleanupObjects.end());
John McCall31168b02011-06-15 23:02:42 +00009980 ExprNeedsCleanups = Rec.ParentNeedsCleanups;
Eli Friedman3bda6b12012-02-02 23:15:15 +00009981 CleanupVarDeclMarking();
9982 std::swap(MaybeODRUseExprs, Rec.SavedMaybeODRUseExprs);
John McCall31168b02011-06-15 23:02:42 +00009983 // Otherwise, merge the contexts together.
9984 } else {
9985 ExprNeedsCleanups |= Rec.ParentNeedsCleanups;
Eli Friedman3bda6b12012-02-02 23:15:15 +00009986 MaybeODRUseExprs.insert(Rec.SavedMaybeODRUseExprs.begin(),
9987 Rec.SavedMaybeODRUseExprs.end());
John McCall31168b02011-06-15 23:02:42 +00009988 }
Eli Friedmanfa0df832012-02-02 03:46:19 +00009989
9990 // Pop the current expression evaluation context off the stack.
9991 ExprEvalContexts.pop_back();
Douglas Gregor0b6a6242009-06-22 20:57:11 +00009992}
Douglas Gregorc9c02ed2009-06-19 23:52:42 +00009993
John McCall31168b02011-06-15 23:02:42 +00009994void Sema::DiscardCleanupsInEvaluationContext() {
John McCall28fc7092011-11-10 05:35:25 +00009995 ExprCleanupObjects.erase(
9996 ExprCleanupObjects.begin() + ExprEvalContexts.back().NumCleanupObjects,
9997 ExprCleanupObjects.end());
John McCall31168b02011-06-15 23:02:42 +00009998 ExprNeedsCleanups = false;
Eli Friedman3bda6b12012-02-02 23:15:15 +00009999 MaybeODRUseExprs.clear();
John McCall31168b02011-06-15 23:02:42 +000010000}
10001
Eli Friedmane0afc982012-01-21 01:01:51 +000010002ExprResult Sema::HandleExprEvaluationContextForTypeof(Expr *E) {
10003 if (!E->getType()->isVariablyModifiedType())
10004 return E;
10005 return TranformToPotentiallyEvaluated(E);
10006}
10007
Benjamin Kramerbf8da9d2012-02-06 11:13:08 +000010008static bool IsPotentiallyEvaluatedContext(Sema &SemaRef) {
Douglas Gregorc9c02ed2009-06-19 23:52:42 +000010009 // Do not mark anything as "used" within a dependent context; wait for
10010 // an instantiation.
Eli Friedmanfa0df832012-02-02 03:46:19 +000010011 if (SemaRef.CurContext->isDependentContext())
10012 return false;
Mike Stump11289f42009-09-09 15:08:12 +000010013
Eli Friedmanfa0df832012-02-02 03:46:19 +000010014 switch (SemaRef.ExprEvalContexts.back().Context) {
10015 case Sema::Unevaluated:
Douglas Gregor0b6a6242009-06-22 20:57:11 +000010016 // We are in an expression that is not potentially evaluated; do nothing.
Eli Friedman02b58512012-01-21 04:44:06 +000010017 // (Depending on how you read the standard, we actually do need to do
10018 // something here for null pointer constants, but the standard's
10019 // definition of a null pointer constant is completely crazy.)
Eli Friedmanfa0df832012-02-02 03:46:19 +000010020 return false;
Mike Stump11289f42009-09-09 15:08:12 +000010021
Eli Friedmanfa0df832012-02-02 03:46:19 +000010022 case Sema::ConstantEvaluated:
10023 case Sema::PotentiallyEvaluated:
Eli Friedman02b58512012-01-21 04:44:06 +000010024 // We are in a potentially evaluated expression (or a constant-expression
10025 // in C++03); we need to do implicit template instantiation, implicitly
10026 // define class members, and mark most declarations as used.
Eli Friedmanfa0df832012-02-02 03:46:19 +000010027 return true;
Mike Stump11289f42009-09-09 15:08:12 +000010028
Eli Friedmanfa0df832012-02-02 03:46:19 +000010029 case Sema::PotentiallyEvaluatedIfUsed:
Douglas Gregor8a01b2a2010-09-11 20:24:53 +000010030 // Referenced declarations will only be used if the construct in the
10031 // containing expression is used.
Eli Friedmanfa0df832012-02-02 03:46:19 +000010032 return false;
Douglas Gregor0b6a6242009-06-22 20:57:11 +000010033 }
Matt Beaumont-Gay248bc722012-02-02 18:35:35 +000010034 llvm_unreachable("Invalid context");
Eli Friedmanfa0df832012-02-02 03:46:19 +000010035}
10036
10037/// \brief Mark a function referenced, and check whether it is odr-used
10038/// (C++ [basic.def.odr]p2, C99 6.9p3)
10039void Sema::MarkFunctionReferenced(SourceLocation Loc, FunctionDecl *Func) {
10040 assert(Func && "No function?");
10041
10042 Func->setReferenced();
10043
Richard Smith4a941e22012-02-14 22:25:15 +000010044 // Don't mark this function as used multiple times, unless it's a constexpr
10045 // function which we need to instantiate.
10046 if (Func->isUsed(false) &&
10047 !(Func->isConstexpr() && !Func->getBody() &&
10048 Func->isImplicitlyInstantiable()))
Eli Friedmanfa0df832012-02-02 03:46:19 +000010049 return;
10050
10051 if (!IsPotentiallyEvaluatedContext(*this))
10052 return;
Mike Stump11289f42009-09-09 15:08:12 +000010053
Douglas Gregorc9c02ed2009-06-19 23:52:42 +000010054 // Note that this declaration has been used.
Eli Friedmanfa0df832012-02-02 03:46:19 +000010055 if (CXXConstructorDecl *Constructor = dyn_cast<CXXConstructorDecl>(Func)) {
Richard Smith273c4e92012-02-26 07:51:39 +000010056 if (Constructor->isDefaulted() && !Constructor->isDeleted()) {
Sebastian Redl22653ba2011-08-30 19:58:05 +000010057 if (Constructor->isDefaultConstructor()) {
10058 if (Constructor->isTrivial())
10059 return;
10060 if (!Constructor->isUsed(false))
10061 DefineImplicitDefaultConstructor(Loc, Constructor);
10062 } else if (Constructor->isCopyConstructor()) {
10063 if (!Constructor->isUsed(false))
10064 DefineImplicitCopyConstructor(Loc, Constructor);
10065 } else if (Constructor->isMoveConstructor()) {
10066 if (!Constructor->isUsed(false))
10067 DefineImplicitMoveConstructor(Loc, Constructor);
10068 }
Fariborz Jahanian477d2422009-06-22 23:34:40 +000010069 }
Kovarththanan Rajaratnamba2c6522010-03-13 10:17:05 +000010070
Douglas Gregor88d292c2010-05-13 16:44:06 +000010071 MarkVTableUsed(Loc, Constructor->getParent());
Eli Friedmanfa0df832012-02-02 03:46:19 +000010072 } else if (CXXDestructorDecl *Destructor =
10073 dyn_cast<CXXDestructorDecl>(Func)) {
Richard Smith273c4e92012-02-26 07:51:39 +000010074 if (Destructor->isDefaulted() && !Destructor->isDeleted() &&
10075 !Destructor->isUsed(false))
Fariborz Jahanian24a175b2009-06-26 23:49:16 +000010076 DefineImplicitDestructor(Loc, Destructor);
Douglas Gregor88d292c2010-05-13 16:44:06 +000010077 if (Destructor->isVirtual())
10078 MarkVTableUsed(Loc, Destructor->getParent());
Eli Friedmanfa0df832012-02-02 03:46:19 +000010079 } else if (CXXMethodDecl *MethodDecl = dyn_cast<CXXMethodDecl>(Func)) {
Richard Smith273c4e92012-02-26 07:51:39 +000010080 if (MethodDecl->isDefaulted() && !MethodDecl->isDeleted() &&
10081 MethodDecl->isOverloadedOperator() &&
Fariborz Jahanian41f79272009-06-25 21:45:19 +000010082 MethodDecl->getOverloadedOperator() == OO_Equal) {
Sebastian Redl22653ba2011-08-30 19:58:05 +000010083 if (!MethodDecl->isUsed(false)) {
10084 if (MethodDecl->isCopyAssignmentOperator())
10085 DefineImplicitCopyAssignment(Loc, MethodDecl);
10086 else
10087 DefineImplicitMoveAssignment(Loc, MethodDecl);
10088 }
Douglas Gregord3b672c2012-02-16 01:06:16 +000010089 } else if (isa<CXXConversionDecl>(MethodDecl) &&
10090 MethodDecl->getParent()->isLambda()) {
10091 CXXConversionDecl *Conversion = cast<CXXConversionDecl>(MethodDecl);
10092 if (Conversion->isLambdaToBlockPointerConversion())
10093 DefineImplicitLambdaToBlockPointerConversion(Loc, Conversion);
10094 else
10095 DefineImplicitLambdaToFunctionPointerConversion(Loc, Conversion);
Douglas Gregor88d292c2010-05-13 16:44:06 +000010096 } else if (MethodDecl->isVirtual())
10097 MarkVTableUsed(Loc, MethodDecl->getParent());
Fariborz Jahanian41f79272009-06-25 21:45:19 +000010098 }
John McCall83779672011-02-19 02:53:41 +000010099
Eli Friedmanfa0df832012-02-02 03:46:19 +000010100 // Recursive functions should be marked when used from another function.
10101 // FIXME: Is this really right?
10102 if (CurContext == Func) return;
Kovarththanan Rajaratnamba2c6522010-03-13 10:17:05 +000010103
Richard Smithf623c962012-04-17 00:58:00 +000010104 // Instantiate the exception specification for any function which is
10105 // used: CodeGen will need it.
Richard Smithd3729422012-04-19 00:08:28 +000010106 const FunctionProtoType *FPT = Func->getType()->getAs<FunctionProtoType>();
10107 if (FPT && FPT->getExceptionSpecType() == EST_Uninstantiated)
Richard Smithf623c962012-04-17 00:58:00 +000010108 InstantiateExceptionSpec(Loc, Func);
10109
Eli Friedmanfa0df832012-02-02 03:46:19 +000010110 // Implicit instantiation of function templates and member functions of
10111 // class templates.
10112 if (Func->isImplicitlyInstantiable()) {
10113 bool AlreadyInstantiated = false;
Richard Smith4a941e22012-02-14 22:25:15 +000010114 SourceLocation PointOfInstantiation = Loc;
Eli Friedmanfa0df832012-02-02 03:46:19 +000010115 if (FunctionTemplateSpecializationInfo *SpecInfo
10116 = Func->getTemplateSpecializationInfo()) {
10117 if (SpecInfo->getPointOfInstantiation().isInvalid())
10118 SpecInfo->setPointOfInstantiation(Loc);
10119 else if (SpecInfo->getTemplateSpecializationKind()
Richard Smith4a941e22012-02-14 22:25:15 +000010120 == TSK_ImplicitInstantiation) {
Eli Friedmanfa0df832012-02-02 03:46:19 +000010121 AlreadyInstantiated = true;
Richard Smith4a941e22012-02-14 22:25:15 +000010122 PointOfInstantiation = SpecInfo->getPointOfInstantiation();
10123 }
Eli Friedmanfa0df832012-02-02 03:46:19 +000010124 } else if (MemberSpecializationInfo *MSInfo
10125 = Func->getMemberSpecializationInfo()) {
10126 if (MSInfo->getPointOfInstantiation().isInvalid())
Douglas Gregor06db9f52009-10-12 20:18:28 +000010127 MSInfo->setPointOfInstantiation(Loc);
Eli Friedmanfa0df832012-02-02 03:46:19 +000010128 else if (MSInfo->getTemplateSpecializationKind()
Richard Smith4a941e22012-02-14 22:25:15 +000010129 == TSK_ImplicitInstantiation) {
Eli Friedmanfa0df832012-02-02 03:46:19 +000010130 AlreadyInstantiated = true;
Richard Smith4a941e22012-02-14 22:25:15 +000010131 PointOfInstantiation = MSInfo->getPointOfInstantiation();
10132 }
Douglas Gregor06db9f52009-10-12 20:18:28 +000010133 }
Mike Stump11289f42009-09-09 15:08:12 +000010134
Richard Smith4a941e22012-02-14 22:25:15 +000010135 if (!AlreadyInstantiated || Func->isConstexpr()) {
Eli Friedmanfa0df832012-02-02 03:46:19 +000010136 if (isa<CXXRecordDecl>(Func->getDeclContext()) &&
10137 cast<CXXRecordDecl>(Func->getDeclContext())->isLocalClass())
Richard Smith4a941e22012-02-14 22:25:15 +000010138 PendingLocalImplicitInstantiations.push_back(
10139 std::make_pair(Func, PointOfInstantiation));
10140 else if (Func->isConstexpr())
Eli Friedmanfa0df832012-02-02 03:46:19 +000010141 // Do not defer instantiations of constexpr functions, to avoid the
10142 // expression evaluator needing to call back into Sema if it sees a
10143 // call to such a function.
Richard Smith4a941e22012-02-14 22:25:15 +000010144 InstantiateFunctionDefinition(PointOfInstantiation, Func);
Argyrios Kyrtzidise5dc5b32012-02-10 20:10:44 +000010145 else {
Richard Smith4a941e22012-02-14 22:25:15 +000010146 PendingInstantiations.push_back(std::make_pair(Func,
10147 PointOfInstantiation));
Argyrios Kyrtzidise5dc5b32012-02-10 20:10:44 +000010148 // Notify the consumer that a function was implicitly instantiated.
10149 Consumer.HandleCXXImplicitFunctionInstantiation(Func);
10150 }
John McCall83779672011-02-19 02:53:41 +000010151 }
Eli Friedmanfa0df832012-02-02 03:46:19 +000010152 } else {
10153 // Walk redefinitions, as some of them may be instantiable.
10154 for (FunctionDecl::redecl_iterator i(Func->redecls_begin()),
10155 e(Func->redecls_end()); i != e; ++i) {
10156 if (!i->isUsed(false) && i->isImplicitlyInstantiable())
10157 MarkFunctionReferenced(Loc, *i);
10158 }
Sam Weinigbae69142009-09-11 03:29:30 +000010159 }
Eli Friedmanfa0df832012-02-02 03:46:19 +000010160
10161 // Keep track of used but undefined functions.
10162 if (!Func->isPure() && !Func->hasBody() &&
10163 Func->getLinkage() != ExternalLinkage) {
10164 SourceLocation &old = UndefinedInternals[Func->getCanonicalDecl()];
10165 if (old.isInvalid()) old = Loc;
10166 }
10167
10168 Func->setUsed(true);
10169}
10170
Eli Friedman9bb33f52012-02-03 02:04:35 +000010171static void
10172diagnoseUncapturableValueReference(Sema &S, SourceLocation loc,
10173 VarDecl *var, DeclContext *DC) {
Eli Friedmandd053f62012-02-07 00:15:00 +000010174 DeclContext *VarDC = var->getDeclContext();
10175
Eli Friedman9bb33f52012-02-03 02:04:35 +000010176 // If the parameter still belongs to the translation unit, then
10177 // we're actually just using one parameter in the declaration of
10178 // the next.
10179 if (isa<ParmVarDecl>(var) &&
Eli Friedmandd053f62012-02-07 00:15:00 +000010180 isa<TranslationUnitDecl>(VarDC))
Eli Friedman9bb33f52012-02-03 02:04:35 +000010181 return;
10182
Eli Friedmandd053f62012-02-07 00:15:00 +000010183 // For C code, don't diagnose about capture if we're not actually in code
10184 // right now; it's impossible to write a non-constant expression outside of
10185 // function context, so we'll get other (more useful) diagnostics later.
10186 //
10187 // For C++, things get a bit more nasty... it would be nice to suppress this
10188 // diagnostic for certain cases like using a local variable in an array bound
10189 // for a member of a local class, but the correct predicate is not obvious.
David Blaikiebbafb8a2012-03-11 07:00:24 +000010190 if (!S.getLangOpts().CPlusPlus && !S.CurContext->isFunctionOrMethod())
Eli Friedman9bb33f52012-02-03 02:04:35 +000010191 return;
10192
Eli Friedmandd053f62012-02-07 00:15:00 +000010193 if (isa<CXXMethodDecl>(VarDC) &&
10194 cast<CXXRecordDecl>(VarDC->getParent())->isLambda()) {
10195 S.Diag(loc, diag::err_reference_to_local_var_in_enclosing_lambda)
10196 << var->getIdentifier();
10197 } else if (FunctionDecl *fn = dyn_cast<FunctionDecl>(VarDC)) {
10198 S.Diag(loc, diag::err_reference_to_local_var_in_enclosing_function)
10199 << var->getIdentifier() << fn->getDeclName();
10200 } else if (isa<BlockDecl>(VarDC)) {
10201 S.Diag(loc, diag::err_reference_to_local_var_in_enclosing_block)
10202 << var->getIdentifier();
10203 } else {
10204 // FIXME: Is there any other context where a local variable can be
10205 // declared?
10206 S.Diag(loc, diag::err_reference_to_local_var_in_enclosing_context)
10207 << var->getIdentifier();
10208 }
Eli Friedman9bb33f52012-02-03 02:04:35 +000010209
Eli Friedman9bb33f52012-02-03 02:04:35 +000010210 S.Diag(var->getLocation(), diag::note_local_variable_declared_here)
10211 << var->getIdentifier();
Eli Friedmandd053f62012-02-07 00:15:00 +000010212
10213 // FIXME: Add additional diagnostic info about class etc. which prevents
10214 // capture.
Eli Friedman9bb33f52012-02-03 02:04:35 +000010215}
10216
Douglas Gregor81495f32012-02-12 18:42:33 +000010217/// \brief Capture the given variable in the given lambda expression.
10218static ExprResult captureInLambda(Sema &S, LambdaScopeInfo *LSI,
Douglas Gregorfdf598e2012-02-18 09:37:24 +000010219 VarDecl *Var, QualType FieldType,
10220 QualType DeclRefType,
Douglas Gregora8182f92012-05-16 17:01:33 +000010221 SourceLocation Loc,
10222 bool RefersToEnclosingLocal) {
Douglas Gregor81495f32012-02-12 18:42:33 +000010223 CXXRecordDecl *Lambda = LSI->Lambda;
Douglas Gregor81495f32012-02-12 18:42:33 +000010224
Douglas Gregorabecb9c2012-02-09 01:56:40 +000010225 // Build the non-static data member.
10226 FieldDecl *Field
10227 = FieldDecl::Create(S.Context, Lambda, Loc, Loc, 0, FieldType,
10228 S.Context.getTrivialTypeSourceInfo(FieldType, Loc),
Richard Smith2b013182012-06-10 03:12:00 +000010229 0, false, ICIS_NoInit);
Douglas Gregorabecb9c2012-02-09 01:56:40 +000010230 Field->setImplicit(true);
10231 Field->setAccess(AS_private);
Douglas Gregor3d23f7882012-02-09 02:12:34 +000010232 Lambda->addDecl(Field);
Douglas Gregorabecb9c2012-02-09 01:56:40 +000010233
10234 // C++11 [expr.prim.lambda]p21:
10235 // When the lambda-expression is evaluated, the entities that
10236 // are captured by copy are used to direct-initialize each
10237 // corresponding non-static data member of the resulting closure
10238 // object. (For array members, the array elements are
10239 // direct-initialized in increasing subscript order.) These
10240 // initializations are performed in the (unspecified) order in
10241 // which the non-static data members are declared.
Douglas Gregorabecb9c2012-02-09 01:56:40 +000010242
Douglas Gregor89625492012-02-09 08:14:43 +000010243 // Introduce a new evaluation context for the initialization, so
10244 // that temporaries introduced as part of the capture are retained
10245 // to be re-"exported" from the lambda expression itself.
Douglas Gregorabecb9c2012-02-09 01:56:40 +000010246 S.PushExpressionEvaluationContext(Sema::PotentiallyEvaluated);
10247
Douglas Gregorf02455e2012-02-10 09:26:04 +000010248 // C++ [expr.prim.labda]p12:
10249 // An entity captured by a lambda-expression is odr-used (3.2) in
10250 // the scope containing the lambda-expression.
Douglas Gregora8182f92012-05-16 17:01:33 +000010251 Expr *Ref = new (S.Context) DeclRefExpr(Var, RefersToEnclosingLocal,
10252 DeclRefType, VK_LValue, Loc);
Eli Friedman23b1be92012-03-01 21:32:56 +000010253 Var->setReferenced(true);
Douglas Gregorf02455e2012-02-10 09:26:04 +000010254 Var->setUsed(true);
Douglas Gregor199cec72012-02-09 02:45:47 +000010255
10256 // When the field has array type, create index variables for each
10257 // dimension of the array. We use these index variables to subscript
10258 // the source array, and other clients (e.g., CodeGen) will perform
10259 // the necessary iteration with these index variables.
10260 SmallVector<VarDecl *, 4> IndexVariables;
Douglas Gregor199cec72012-02-09 02:45:47 +000010261 QualType BaseType = FieldType;
10262 QualType SizeType = S.Context.getSizeType();
Douglas Gregor54fcea62012-02-13 16:35:30 +000010263 LSI->ArrayIndexStarts.push_back(LSI->ArrayIndexVars.size());
Douglas Gregor199cec72012-02-09 02:45:47 +000010264 while (const ConstantArrayType *Array
10265 = S.Context.getAsConstantArrayType(BaseType)) {
Douglas Gregor199cec72012-02-09 02:45:47 +000010266 // Create the iteration variable for this array index.
10267 IdentifierInfo *IterationVarName = 0;
10268 {
10269 SmallString<8> Str;
10270 llvm::raw_svector_ostream OS(Str);
10271 OS << "__i" << IndexVariables.size();
10272 IterationVarName = &S.Context.Idents.get(OS.str());
10273 }
10274 VarDecl *IterationVar
10275 = VarDecl::Create(S.Context, S.CurContext, Loc, Loc,
10276 IterationVarName, SizeType,
10277 S.Context.getTrivialTypeSourceInfo(SizeType, Loc),
10278 SC_None, SC_None);
10279 IndexVariables.push_back(IterationVar);
Douglas Gregor54fcea62012-02-13 16:35:30 +000010280 LSI->ArrayIndexVars.push_back(IterationVar);
10281
Douglas Gregor199cec72012-02-09 02:45:47 +000010282 // Create a reference to the iteration variable.
10283 ExprResult IterationVarRef
10284 = S.BuildDeclRefExpr(IterationVar, SizeType, VK_LValue, Loc);
10285 assert(!IterationVarRef.isInvalid() &&
10286 "Reference to invented variable cannot fail!");
10287 IterationVarRef = S.DefaultLvalueConversion(IterationVarRef.take());
10288 assert(!IterationVarRef.isInvalid() &&
10289 "Conversion of invented variable cannot fail!");
10290
10291 // Subscript the array with this iteration variable.
10292 ExprResult Subscript = S.CreateBuiltinArraySubscriptExpr(
10293 Ref, Loc, IterationVarRef.take(), Loc);
10294 if (Subscript.isInvalid()) {
10295 S.CleanupVarDeclMarking();
10296 S.DiscardCleanupsInEvaluationContext();
10297 S.PopExpressionEvaluationContext();
10298 return ExprError();
10299 }
10300
10301 Ref = Subscript.take();
10302 BaseType = Array->getElementType();
10303 }
10304
10305 // Construct the entity that we will be initializing. For an array, this
10306 // will be first element in the array, which may require several levels
10307 // of array-subscript entities.
10308 SmallVector<InitializedEntity, 4> Entities;
10309 Entities.reserve(1 + IndexVariables.size());
Douglas Gregor19666fb2012-02-15 16:57:26 +000010310 Entities.push_back(
10311 InitializedEntity::InitializeLambdaCapture(Var, Field, Loc));
Douglas Gregor199cec72012-02-09 02:45:47 +000010312 for (unsigned I = 0, N = IndexVariables.size(); I != N; ++I)
10313 Entities.push_back(InitializedEntity::InitializeElement(S.Context,
10314 0,
10315 Entities.back()));
10316
Douglas Gregorabecb9c2012-02-09 01:56:40 +000010317 InitializationKind InitKind
10318 = InitializationKind::CreateDirect(Loc, Loc, Loc);
Douglas Gregor199cec72012-02-09 02:45:47 +000010319 InitializationSequence Init(S, Entities.back(), InitKind, &Ref, 1);
Douglas Gregorabecb9c2012-02-09 01:56:40 +000010320 ExprResult Result(true);
Douglas Gregor199cec72012-02-09 02:45:47 +000010321 if (!Init.Diagnose(S, Entities.back(), InitKind, &Ref, 1))
10322 Result = Init.Perform(S, Entities.back(), InitKind,
Douglas Gregorabecb9c2012-02-09 01:56:40 +000010323 MultiExprArg(S, &Ref, 1));
10324
10325 // If this initialization requires any cleanups (e.g., due to a
10326 // default argument to a copy constructor), note that for the
10327 // lambda.
10328 if (S.ExprNeedsCleanups)
10329 LSI->ExprNeedsCleanups = true;
10330
10331 // Exit the expression evaluation context used for the capture.
10332 S.CleanupVarDeclMarking();
10333 S.DiscardCleanupsInEvaluationContext();
10334 S.PopExpressionEvaluationContext();
10335 return Result;
Douglas Gregor199cec72012-02-09 02:45:47 +000010336}
Douglas Gregorabecb9c2012-02-09 01:56:40 +000010337
Douglas Gregorfdf598e2012-02-18 09:37:24 +000010338bool Sema::tryCaptureVariable(VarDecl *Var, SourceLocation Loc,
10339 TryCaptureKind Kind, SourceLocation EllipsisLoc,
10340 bool BuildAndDiagnose,
10341 QualType &CaptureType,
10342 QualType &DeclRefType) {
10343 bool Nested = false;
Douglas Gregor81495f32012-02-12 18:42:33 +000010344
Eli Friedman24af8502012-02-03 22:47:37 +000010345 DeclContext *DC = CurContext;
Douglas Gregorfdf598e2012-02-18 09:37:24 +000010346 if (Var->getDeclContext() == DC) return true;
10347 if (!Var->hasLocalStorage()) return true;
Eli Friedman9bb33f52012-02-03 02:04:35 +000010348
Douglas Gregor81495f32012-02-12 18:42:33 +000010349 bool HasBlocksAttr = Var->hasAttr<BlocksAttr>();
Eli Friedman9bb33f52012-02-03 02:04:35 +000010350
Douglas Gregorfdf598e2012-02-18 09:37:24 +000010351 // Walk up the stack to determine whether we can capture the variable,
10352 // performing the "simple" checks that don't depend on type. We stop when
10353 // we've either hit the declared scope of the variable or find an existing
10354 // capture of that variable.
10355 CaptureType = Var->getType();
10356 DeclRefType = CaptureType.getNonReferenceType();
10357 bool Explicit = (Kind != TryCapture_Implicit);
10358 unsigned FunctionScopesIndex = FunctionScopes.size() - 1;
Eli Friedman9bb33f52012-02-03 02:04:35 +000010359 do {
Eli Friedman24af8502012-02-03 22:47:37 +000010360 // Only block literals and lambda expressions can capture; other
Eli Friedman9bb33f52012-02-03 02:04:35 +000010361 // scopes don't work.
Eli Friedman24af8502012-02-03 22:47:37 +000010362 DeclContext *ParentDC;
10363 if (isa<BlockDecl>(DC))
10364 ParentDC = DC->getParent();
10365 else if (isa<CXXMethodDecl>(DC) &&
Douglas Gregor81495f32012-02-12 18:42:33 +000010366 cast<CXXMethodDecl>(DC)->getOverloadedOperator() == OO_Call &&
Eli Friedman24af8502012-02-03 22:47:37 +000010367 cast<CXXRecordDecl>(DC->getParent())->isLambda())
10368 ParentDC = DC->getParent()->getParent();
Douglas Gregor81495f32012-02-12 18:42:33 +000010369 else {
Douglas Gregorfdf598e2012-02-18 09:37:24 +000010370 if (BuildAndDiagnose)
Douglas Gregor81495f32012-02-12 18:42:33 +000010371 diagnoseUncapturableValueReference(*this, Loc, Var, DC);
Douglas Gregorfdf598e2012-02-18 09:37:24 +000010372 return true;
Douglas Gregor81495f32012-02-12 18:42:33 +000010373 }
Eli Friedman9bb33f52012-02-03 02:04:35 +000010374
Eli Friedman24af8502012-02-03 22:47:37 +000010375 CapturingScopeInfo *CSI =
Douglas Gregor81495f32012-02-12 18:42:33 +000010376 cast<CapturingScopeInfo>(FunctionScopes[FunctionScopesIndex]);
Eli Friedman9bb33f52012-02-03 02:04:35 +000010377
Eli Friedman24af8502012-02-03 22:47:37 +000010378 // Check whether we've already captured it.
Douglas Gregor81495f32012-02-12 18:42:33 +000010379 if (CSI->CaptureMap.count(Var)) {
Douglas Gregorfdf598e2012-02-18 09:37:24 +000010380 // If we found a capture, any subcaptures are nested.
Eli Friedman9bb33f52012-02-03 02:04:35 +000010381 Nested = true;
Douglas Gregorfdf598e2012-02-18 09:37:24 +000010382
10383 // Retrieve the capture type for this variable.
10384 CaptureType = CSI->getCapture(Var).getCaptureType();
10385
10386 // Compute the type of an expression that refers to this variable.
10387 DeclRefType = CaptureType.getNonReferenceType();
10388
10389 const CapturingScopeInfo::Capture &Cap = CSI->getCapture(Var);
10390 if (Cap.isCopyCapture() &&
10391 !(isa<LambdaScopeInfo>(CSI) && cast<LambdaScopeInfo>(CSI)->Mutable))
10392 DeclRefType.addConst();
Eli Friedman9bb33f52012-02-03 02:04:35 +000010393 break;
10394 }
10395
Douglas Gregor81495f32012-02-12 18:42:33 +000010396 bool IsBlock = isa<BlockScopeInfo>(CSI);
Douglas Gregorfdf598e2012-02-18 09:37:24 +000010397 bool IsLambda = !IsBlock;
Eli Friedman24af8502012-02-03 22:47:37 +000010398
10399 // Lambdas are not allowed to capture unnamed variables
10400 // (e.g. anonymous unions).
10401 // FIXME: The C++11 rule don't actually state this explicitly, but I'm
10402 // assuming that's the intent.
Douglas Gregor81495f32012-02-12 18:42:33 +000010403 if (IsLambda && !Var->getDeclName()) {
Douglas Gregorfdf598e2012-02-18 09:37:24 +000010404 if (BuildAndDiagnose) {
Douglas Gregor81495f32012-02-12 18:42:33 +000010405 Diag(Loc, diag::err_lambda_capture_anonymous_var);
10406 Diag(Var->getLocation(), diag::note_declared_at);
10407 }
Douglas Gregorfdf598e2012-02-18 09:37:24 +000010408 return true;
Eli Friedman24af8502012-02-03 22:47:37 +000010409 }
10410
10411 // Prohibit variably-modified types; they're difficult to deal with.
Douglas Gregorfdf598e2012-02-18 09:37:24 +000010412 if (Var->getType()->isVariablyModifiedType()) {
10413 if (BuildAndDiagnose) {
Douglas Gregor81495f32012-02-12 18:42:33 +000010414 if (IsBlock)
10415 Diag(Loc, diag::err_ref_vm_type);
10416 else
10417 Diag(Loc, diag::err_lambda_capture_vm_type) << Var->getDeclName();
10418 Diag(Var->getLocation(), diag::note_previous_decl)
10419 << Var->getDeclName();
10420 }
Douglas Gregorfdf598e2012-02-18 09:37:24 +000010421 return true;
Eli Friedman9bb33f52012-02-03 02:04:35 +000010422 }
10423
Eli Friedman24af8502012-02-03 22:47:37 +000010424 // Lambdas are not allowed to capture __block variables; they don't
10425 // support the expected semantics.
Douglas Gregor81495f32012-02-12 18:42:33 +000010426 if (IsLambda && HasBlocksAttr) {
Douglas Gregorfdf598e2012-02-18 09:37:24 +000010427 if (BuildAndDiagnose) {
Douglas Gregor81495f32012-02-12 18:42:33 +000010428 Diag(Loc, diag::err_lambda_capture_block)
10429 << Var->getDeclName();
10430 Diag(Var->getLocation(), diag::note_previous_decl)
10431 << Var->getDeclName();
10432 }
Douglas Gregorfdf598e2012-02-18 09:37:24 +000010433 return true;
Eli Friedman24af8502012-02-03 22:47:37 +000010434 }
10435
Douglas Gregor81495f32012-02-12 18:42:33 +000010436 if (CSI->ImpCaptureStyle == CapturingScopeInfo::ImpCap_None && !Explicit) {
10437 // No capture-default
Douglas Gregorfdf598e2012-02-18 09:37:24 +000010438 if (BuildAndDiagnose) {
Douglas Gregor81495f32012-02-12 18:42:33 +000010439 Diag(Loc, diag::err_lambda_impcap) << Var->getDeclName();
10440 Diag(Var->getLocation(), diag::note_previous_decl)
10441 << Var->getDeclName();
10442 Diag(cast<LambdaScopeInfo>(CSI)->Lambda->getLocStart(),
10443 diag::note_lambda_decl);
10444 }
Douglas Gregorfdf598e2012-02-18 09:37:24 +000010445 return true;
Douglas Gregor81495f32012-02-12 18:42:33 +000010446 }
10447
10448 FunctionScopesIndex--;
10449 DC = ParentDC;
10450 Explicit = false;
10451 } while (!Var->getDeclContext()->Equals(DC));
10452
Douglas Gregorfdf598e2012-02-18 09:37:24 +000010453 // Walk back down the scope stack, computing the type of the capture at
10454 // each step, checking type-specific requirements, and adding captures if
10455 // requested.
10456 for (unsigned I = ++FunctionScopesIndex, N = FunctionScopes.size(); I != N;
10457 ++I) {
10458 CapturingScopeInfo *CSI = cast<CapturingScopeInfo>(FunctionScopes[I]);
Douglas Gregor812d8f62012-02-18 05:51:20 +000010459
Douglas Gregorfdf598e2012-02-18 09:37:24 +000010460 // Compute the type of the capture and of a reference to the capture within
10461 // this scope.
10462 if (isa<BlockScopeInfo>(CSI)) {
10463 Expr *CopyExpr = 0;
10464 bool ByRef = false;
10465
10466 // Blocks are not allowed to capture arrays.
10467 if (CaptureType->isArrayType()) {
10468 if (BuildAndDiagnose) {
10469 Diag(Loc, diag::err_ref_array_type);
10470 Diag(Var->getLocation(), diag::note_previous_decl)
10471 << Var->getDeclName();
10472 }
10473 return true;
10474 }
10475
John McCall67cd5e02012-03-30 05:23:48 +000010476 // Forbid the block-capture of autoreleasing variables.
10477 if (CaptureType.getObjCLifetime() == Qualifiers::OCL_Autoreleasing) {
10478 if (BuildAndDiagnose) {
10479 Diag(Loc, diag::err_arc_autoreleasing_capture)
10480 << /*block*/ 0;
10481 Diag(Var->getLocation(), diag::note_previous_decl)
10482 << Var->getDeclName();
10483 }
10484 return true;
10485 }
10486
Douglas Gregorfdf598e2012-02-18 09:37:24 +000010487 if (HasBlocksAttr || CaptureType->isReferenceType()) {
10488 // Block capture by reference does not change the capture or
10489 // declaration reference types.
10490 ByRef = true;
10491 } else {
10492 // Block capture by copy introduces 'const'.
10493 CaptureType = CaptureType.getNonReferenceType().withConst();
10494 DeclRefType = CaptureType;
10495
David Blaikiebbafb8a2012-03-11 07:00:24 +000010496 if (getLangOpts().CPlusPlus && BuildAndDiagnose) {
Douglas Gregorfdf598e2012-02-18 09:37:24 +000010497 if (const RecordType *Record = DeclRefType->getAs<RecordType>()) {
10498 // The capture logic needs the destructor, so make sure we mark it.
10499 // Usually this is unnecessary because most local variables have
10500 // their destructors marked at declaration time, but parameters are
10501 // an exception because it's technically only the call site that
10502 // actually requires the destructor.
10503 if (isa<ParmVarDecl>(Var))
10504 FinalizeVarWithDestructor(Var, Record);
10505
10506 // According to the blocks spec, the capture of a variable from
10507 // the stack requires a const copy constructor. This is not true
10508 // of the copy/move done to move a __block variable to the heap.
John McCall113bee02012-03-10 09:33:50 +000010509 Expr *DeclRef = new (Context) DeclRefExpr(Var, false,
Douglas Gregorfdf598e2012-02-18 09:37:24 +000010510 DeclRefType.withConst(),
10511 VK_LValue, Loc);
10512 ExprResult Result
10513 = PerformCopyInitialization(
10514 InitializedEntity::InitializeBlock(Var->getLocation(),
10515 CaptureType, false),
10516 Loc, Owned(DeclRef));
10517
10518 // Build a full-expression copy expression if initialization
10519 // succeeded and used a non-trivial constructor. Recover from
10520 // errors by pretending that the copy isn't necessary.
10521 if (!Result.isInvalid() &&
10522 !cast<CXXConstructExpr>(Result.get())->getConstructor()
10523 ->isTrivial()) {
10524 Result = MaybeCreateExprWithCleanups(Result);
10525 CopyExpr = Result.take();
10526 }
10527 }
10528 }
10529 }
10530
10531 // Actually capture the variable.
10532 if (BuildAndDiagnose)
10533 CSI->addCapture(Var, HasBlocksAttr, ByRef, Nested, Loc,
10534 SourceLocation(), CaptureType, CopyExpr);
10535 Nested = true;
10536 continue;
10537 }
Douglas Gregor812d8f62012-02-18 05:51:20 +000010538
Douglas Gregorfdf598e2012-02-18 09:37:24 +000010539 LambdaScopeInfo *LSI = cast<LambdaScopeInfo>(CSI);
10540
10541 // Determine whether we are capturing by reference or by value.
10542 bool ByRef = false;
10543 if (I == N - 1 && Kind != TryCapture_Implicit) {
10544 ByRef = (Kind == TryCapture_ExplicitByRef);
Eli Friedman24af8502012-02-03 22:47:37 +000010545 } else {
Douglas Gregorfdf598e2012-02-18 09:37:24 +000010546 ByRef = (LSI->ImpCaptureStyle == LambdaScopeInfo::ImpCap_LambdaByref);
Eli Friedman24af8502012-02-03 22:47:37 +000010547 }
Douglas Gregorfdf598e2012-02-18 09:37:24 +000010548
10549 // Compute the type of the field that will capture this variable.
10550 if (ByRef) {
10551 // C++11 [expr.prim.lambda]p15:
10552 // An entity is captured by reference if it is implicitly or
10553 // explicitly captured but not captured by copy. It is
10554 // unspecified whether additional unnamed non-static data
10555 // members are declared in the closure type for entities
10556 // captured by reference.
10557 //
10558 // FIXME: It is not clear whether we want to build an lvalue reference
10559 // to the DeclRefType or to CaptureType.getNonReferenceType(). GCC appears
10560 // to do the former, while EDG does the latter. Core issue 1249 will
10561 // clarify, but for now we follow GCC because it's a more permissive and
10562 // easily defensible position.
10563 CaptureType = Context.getLValueReferenceType(DeclRefType);
10564 } else {
10565 // C++11 [expr.prim.lambda]p14:
10566 // For each entity captured by copy, an unnamed non-static
10567 // data member is declared in the closure type. The
10568 // declaration order of these members is unspecified. The type
10569 // of such a data member is the type of the corresponding
10570 // captured entity if the entity is not a reference to an
10571 // object, or the referenced type otherwise. [Note: If the
10572 // captured entity is a reference to a function, the
10573 // corresponding data member is also a reference to a
10574 // function. - end note ]
10575 if (const ReferenceType *RefType = CaptureType->getAs<ReferenceType>()){
10576 if (!RefType->getPointeeType()->isFunctionType())
10577 CaptureType = RefType->getPointeeType();
Eli Friedman9bb33f52012-02-03 02:04:35 +000010578 }
John McCall67cd5e02012-03-30 05:23:48 +000010579
10580 // Forbid the lambda copy-capture of autoreleasing variables.
10581 if (CaptureType.getObjCLifetime() == Qualifiers::OCL_Autoreleasing) {
10582 if (BuildAndDiagnose) {
10583 Diag(Loc, diag::err_arc_autoreleasing_capture) << /*lambda*/ 1;
10584 Diag(Var->getLocation(), diag::note_previous_decl)
10585 << Var->getDeclName();
10586 }
10587 return true;
10588 }
Eli Friedman9bb33f52012-02-03 02:04:35 +000010589 }
10590
Douglas Gregorfdf598e2012-02-18 09:37:24 +000010591 // Capture this variable in the lambda.
10592 Expr *CopyExpr = 0;
10593 if (BuildAndDiagnose) {
10594 ExprResult Result = captureInLambda(*this, LSI, Var, CaptureType,
Douglas Gregora8182f92012-05-16 17:01:33 +000010595 DeclRefType, Loc,
10596 I == N-1);
Douglas Gregorfdf598e2012-02-18 09:37:24 +000010597 if (!Result.isInvalid())
10598 CopyExpr = Result.take();
10599 }
10600
10601 // Compute the type of a reference to this captured variable.
10602 if (ByRef)
10603 DeclRefType = CaptureType.getNonReferenceType();
10604 else {
10605 // C++ [expr.prim.lambda]p5:
10606 // The closure type for a lambda-expression has a public inline
10607 // function call operator [...]. This function call operator is
10608 // declared const (9.3.1) if and only if the lambda-expression’s
10609 // parameter-declaration-clause is not followed by mutable.
10610 DeclRefType = CaptureType.getNonReferenceType();
10611 if (!LSI->Mutable && !CaptureType->isReferenceType())
10612 DeclRefType.addConst();
10613 }
10614
10615 // Add the capture.
10616 if (BuildAndDiagnose)
10617 CSI->addCapture(Var, /*IsBlock=*/false, ByRef, Nested, Loc,
10618 EllipsisLoc, CaptureType, CopyExpr);
Eli Friedman9bb33f52012-02-03 02:04:35 +000010619 Nested = true;
10620 }
Douglas Gregorfdf598e2012-02-18 09:37:24 +000010621
10622 return false;
10623}
10624
10625bool Sema::tryCaptureVariable(VarDecl *Var, SourceLocation Loc,
10626 TryCaptureKind Kind, SourceLocation EllipsisLoc) {
10627 QualType CaptureType;
10628 QualType DeclRefType;
10629 return tryCaptureVariable(Var, Loc, Kind, EllipsisLoc,
10630 /*BuildAndDiagnose=*/true, CaptureType,
10631 DeclRefType);
10632}
10633
10634QualType Sema::getCapturedDeclRefType(VarDecl *Var, SourceLocation Loc) {
10635 QualType CaptureType;
10636 QualType DeclRefType;
10637
10638 // Determine whether we can capture this variable.
10639 if (tryCaptureVariable(Var, Loc, TryCapture_Implicit, SourceLocation(),
10640 /*BuildAndDiagnose=*/false, CaptureType, DeclRefType))
10641 return QualType();
10642
10643 return DeclRefType;
Eli Friedman9bb33f52012-02-03 02:04:35 +000010644}
10645
Eli Friedman3bda6b12012-02-02 23:15:15 +000010646static void MarkVarDeclODRUsed(Sema &SemaRef, VarDecl *Var,
10647 SourceLocation Loc) {
10648 // Keep track of used but undefined variables.
Eli Friedman130bbd02012-02-04 00:54:05 +000010649 // FIXME: We shouldn't suppress this warning for static data members.
Daniel Dunbar9d355812012-03-09 01:51:51 +000010650 if (Var->hasDefinition(SemaRef.Context) == VarDecl::DeclarationOnly &&
Eli Friedman130bbd02012-02-04 00:54:05 +000010651 Var->getLinkage() != ExternalLinkage &&
10652 !(Var->isStaticDataMember() && Var->hasInit())) {
Eli Friedman3bda6b12012-02-02 23:15:15 +000010653 SourceLocation &old = SemaRef.UndefinedInternals[Var->getCanonicalDecl()];
10654 if (old.isInvalid()) old = Loc;
10655 }
10656
Douglas Gregorfdf598e2012-02-18 09:37:24 +000010657 SemaRef.tryCaptureVariable(Var, Loc);
Eli Friedman9bb33f52012-02-03 02:04:35 +000010658
Eli Friedman3bda6b12012-02-02 23:15:15 +000010659 Var->setUsed(true);
10660}
10661
10662void Sema::UpdateMarkingForLValueToRValue(Expr *E) {
10663 // Per C++11 [basic.def.odr], a variable is odr-used "unless it is
10664 // an object that satisfies the requirements for appearing in a
10665 // constant expression (5.19) and the lvalue-to-rvalue conversion (4.1)
10666 // is immediately applied." This function handles the lvalue-to-rvalue
10667 // conversion part.
10668 MaybeODRUseExprs.erase(E->IgnoreParens());
10669}
10670
Eli Friedmanc6237c62012-02-29 03:16:56 +000010671ExprResult Sema::ActOnConstantExpression(ExprResult Res) {
10672 if (!Res.isUsable())
10673 return Res;
10674
10675 // If a constant-expression is a reference to a variable where we delay
10676 // deciding whether it is an odr-use, just assume we will apply the
10677 // lvalue-to-rvalue conversion. In the one case where this doesn't happen
10678 // (a non-type template argument), we have special handling anyway.
10679 UpdateMarkingForLValueToRValue(Res.get());
10680 return Res;
10681}
10682
Eli Friedman3bda6b12012-02-02 23:15:15 +000010683void Sema::CleanupVarDeclMarking() {
10684 for (llvm::SmallPtrSetIterator<Expr*> i = MaybeODRUseExprs.begin(),
10685 e = MaybeODRUseExprs.end();
10686 i != e; ++i) {
10687 VarDecl *Var;
10688 SourceLocation Loc;
John McCall113bee02012-03-10 09:33:50 +000010689 if (DeclRefExpr *DRE = dyn_cast<DeclRefExpr>(*i)) {
Eli Friedman3bda6b12012-02-02 23:15:15 +000010690 Var = cast<VarDecl>(DRE->getDecl());
10691 Loc = DRE->getLocation();
10692 } else if (MemberExpr *ME = dyn_cast<MemberExpr>(*i)) {
10693 Var = cast<VarDecl>(ME->getMemberDecl());
10694 Loc = ME->getMemberLoc();
10695 } else {
10696 llvm_unreachable("Unexpcted expression");
10697 }
10698
10699 MarkVarDeclODRUsed(*this, Var, Loc);
10700 }
10701
10702 MaybeODRUseExprs.clear();
10703}
10704
10705// Mark a VarDecl referenced, and perform the necessary handling to compute
10706// odr-uses.
10707static void DoMarkVarDeclReferenced(Sema &SemaRef, SourceLocation Loc,
10708 VarDecl *Var, Expr *E) {
Eli Friedmanfa0df832012-02-02 03:46:19 +000010709 Var->setReferenced();
10710
Eli Friedman3bda6b12012-02-02 23:15:15 +000010711 if (!IsPotentiallyEvaluatedContext(SemaRef))
Eli Friedmanfa0df832012-02-02 03:46:19 +000010712 return;
10713
10714 // Implicit instantiation of static data members of class templates.
Richard Smithd3cf2382012-02-15 02:42:50 +000010715 if (Var->isStaticDataMember() && Var->getInstantiatedFromStaticDataMember()) {
Eli Friedmanfa0df832012-02-02 03:46:19 +000010716 MemberSpecializationInfo *MSInfo = Var->getMemberSpecializationInfo();
10717 assert(MSInfo && "Missing member specialization information?");
Richard Smithd3cf2382012-02-15 02:42:50 +000010718 bool AlreadyInstantiated = !MSInfo->getPointOfInstantiation().isInvalid();
10719 if (MSInfo->getTemplateSpecializationKind() == TSK_ImplicitInstantiation &&
Daniel Dunbar9d355812012-03-09 01:51:51 +000010720 (!AlreadyInstantiated ||
10721 Var->isUsableInConstantExpressions(SemaRef.Context))) {
Richard Smithd3cf2382012-02-15 02:42:50 +000010722 if (!AlreadyInstantiated) {
10723 // This is a modification of an existing AST node. Notify listeners.
10724 if (ASTMutationListener *L = SemaRef.getASTMutationListener())
10725 L->StaticDataMemberInstantiated(Var);
10726 MSInfo->setPointOfInstantiation(Loc);
10727 }
10728 SourceLocation PointOfInstantiation = MSInfo->getPointOfInstantiation();
Daniel Dunbar9d355812012-03-09 01:51:51 +000010729 if (Var->isUsableInConstantExpressions(SemaRef.Context))
Eli Friedmanfa0df832012-02-02 03:46:19 +000010730 // Do not defer instantiations of variables which could be used in a
10731 // constant expression.
Richard Smithd3cf2382012-02-15 02:42:50 +000010732 SemaRef.InstantiateStaticDataMemberDefinition(PointOfInstantiation,Var);
Eli Friedmanfa0df832012-02-02 03:46:19 +000010733 else
Richard Smithd3cf2382012-02-15 02:42:50 +000010734 SemaRef.PendingInstantiations.push_back(
10735 std::make_pair(Var, PointOfInstantiation));
Eli Friedmanfa0df832012-02-02 03:46:19 +000010736 }
10737 }
10738
Eli Friedman3bda6b12012-02-02 23:15:15 +000010739 // Per C++11 [basic.def.odr], a variable is odr-used "unless it is
10740 // an object that satisfies the requirements for appearing in a
10741 // constant expression (5.19) and the lvalue-to-rvalue conversion (4.1)
10742 // is immediately applied." We check the first part here, and
10743 // Sema::UpdateMarkingForLValueToRValue deals with the second part.
10744 // Note that we use the C++11 definition everywhere because nothing in
Richard Smith35ecb362012-03-02 04:14:40 +000010745 // C++03 depends on whether we get the C++03 version correct. This does not
10746 // apply to references, since they are not objects.
Eli Friedman3bda6b12012-02-02 23:15:15 +000010747 const VarDecl *DefVD;
Richard Smith35ecb362012-03-02 04:14:40 +000010748 if (E && !isa<ParmVarDecl>(Var) && !Var->getType()->isReferenceType() &&
Daniel Dunbar9d355812012-03-09 01:51:51 +000010749 Var->isUsableInConstantExpressions(SemaRef.Context) &&
Eli Friedman3bda6b12012-02-02 23:15:15 +000010750 Var->getAnyInitializer(DefVD) && DefVD->checkInitIsICE())
10751 SemaRef.MaybeODRUseExprs.insert(E);
10752 else
10753 MarkVarDeclODRUsed(SemaRef, Var, Loc);
10754}
Eli Friedmanfa0df832012-02-02 03:46:19 +000010755
Eli Friedman3bda6b12012-02-02 23:15:15 +000010756/// \brief Mark a variable referenced, and check whether it is odr-used
10757/// (C++ [basic.def.odr]p2, C99 6.9p3). Note that this should not be
10758/// used directly for normal expressions referring to VarDecl.
10759void Sema::MarkVariableReferenced(SourceLocation Loc, VarDecl *Var) {
10760 DoMarkVarDeclReferenced(*this, Loc, Var, 0);
Eli Friedmanfa0df832012-02-02 03:46:19 +000010761}
10762
10763static void MarkExprReferenced(Sema &SemaRef, SourceLocation Loc,
10764 Decl *D, Expr *E) {
Eli Friedman3bda6b12012-02-02 23:15:15 +000010765 if (VarDecl *Var = dyn_cast<VarDecl>(D)) {
10766 DoMarkVarDeclReferenced(SemaRef, Loc, Var, E);
10767 return;
10768 }
10769
Eli Friedmanfa0df832012-02-02 03:46:19 +000010770 SemaRef.MarkAnyDeclReferenced(Loc, D);
Douglas Gregord3b672c2012-02-16 01:06:16 +000010771}
Eli Friedmanfa0df832012-02-02 03:46:19 +000010772
Eli Friedmanfa0df832012-02-02 03:46:19 +000010773/// \brief Perform reference-marking and odr-use handling for a DeclRefExpr.
10774void Sema::MarkDeclRefReferenced(DeclRefExpr *E) {
10775 MarkExprReferenced(*this, E->getLocation(), E->getDecl(), E);
10776}
10777
10778/// \brief Perform reference-marking and odr-use handling for a MemberExpr.
10779void Sema::MarkMemberReferenced(MemberExpr *E) {
10780 MarkExprReferenced(*this, E->getMemberLoc(), E->getMemberDecl(), E);
10781}
10782
Douglas Gregorf02455e2012-02-10 09:26:04 +000010783/// \brief Perform marking for a reference to an arbitrary declaration. It
Eli Friedmanfa0df832012-02-02 03:46:19 +000010784/// marks the declaration referenced, and performs odr-use checking for functions
10785/// and variables. This method should not be used when building an normal
10786/// expression which refers to a variable.
10787void Sema::MarkAnyDeclReferenced(SourceLocation Loc, Decl *D) {
10788 if (VarDecl *VD = dyn_cast<VarDecl>(D))
10789 MarkVariableReferenced(Loc, VD);
10790 else if (FunctionDecl *FD = dyn_cast<FunctionDecl>(D))
10791 MarkFunctionReferenced(Loc, FD);
10792 else
10793 D->setReferenced();
Douglas Gregorc9c02ed2009-06-19 23:52:42 +000010794}
Anders Carlsson7f84ed92009-10-09 23:51:55 +000010795
Douglas Gregor5597ab42010-05-07 23:12:07 +000010796namespace {
Chandler Carruthaf80f662010-06-09 08:17:30 +000010797 // Mark all of the declarations referenced
Douglas Gregor5597ab42010-05-07 23:12:07 +000010798 // FIXME: Not fully implemented yet! We need to have a better understanding
Chandler Carruthaf80f662010-06-09 08:17:30 +000010799 // of when we're entering
Douglas Gregor5597ab42010-05-07 23:12:07 +000010800 class MarkReferencedDecls : public RecursiveASTVisitor<MarkReferencedDecls> {
10801 Sema &S;
10802 SourceLocation Loc;
Chandler Carruthaf80f662010-06-09 08:17:30 +000010803
Douglas Gregor5597ab42010-05-07 23:12:07 +000010804 public:
10805 typedef RecursiveASTVisitor<MarkReferencedDecls> Inherited;
Chandler Carruthaf80f662010-06-09 08:17:30 +000010806
Douglas Gregor5597ab42010-05-07 23:12:07 +000010807 MarkReferencedDecls(Sema &S, SourceLocation Loc) : S(S), Loc(Loc) { }
Chandler Carruthaf80f662010-06-09 08:17:30 +000010808
10809 bool TraverseTemplateArgument(const TemplateArgument &Arg);
10810 bool TraverseRecordType(RecordType *T);
Douglas Gregor5597ab42010-05-07 23:12:07 +000010811 };
10812}
10813
Chandler Carruthaf80f662010-06-09 08:17:30 +000010814bool MarkReferencedDecls::TraverseTemplateArgument(
10815 const TemplateArgument &Arg) {
Douglas Gregor5597ab42010-05-07 23:12:07 +000010816 if (Arg.getKind() == TemplateArgument::Declaration) {
Douglas Gregor31f55dc2012-04-06 22:40:38 +000010817 if (Decl *D = Arg.getAsDecl())
10818 S.MarkAnyDeclReferenced(Loc, D);
Douglas Gregor5597ab42010-05-07 23:12:07 +000010819 }
Chandler Carruthaf80f662010-06-09 08:17:30 +000010820
10821 return Inherited::TraverseTemplateArgument(Arg);
Douglas Gregor5597ab42010-05-07 23:12:07 +000010822}
10823
Chandler Carruthaf80f662010-06-09 08:17:30 +000010824bool MarkReferencedDecls::TraverseRecordType(RecordType *T) {
Douglas Gregor5597ab42010-05-07 23:12:07 +000010825 if (ClassTemplateSpecializationDecl *Spec
10826 = dyn_cast<ClassTemplateSpecializationDecl>(T->getDecl())) {
10827 const TemplateArgumentList &Args = Spec->getTemplateArgs();
Douglas Gregor1ccc8412010-11-07 23:05:16 +000010828 return TraverseTemplateArguments(Args.data(), Args.size());
Douglas Gregor5597ab42010-05-07 23:12:07 +000010829 }
10830
Chandler Carruthc65667c2010-06-10 10:31:57 +000010831 return true;
Douglas Gregor5597ab42010-05-07 23:12:07 +000010832}
10833
10834void Sema::MarkDeclarationsReferencedInType(SourceLocation Loc, QualType T) {
10835 MarkReferencedDecls Marker(*this, Loc);
Chandler Carruthaf80f662010-06-09 08:17:30 +000010836 Marker.TraverseType(Context.getCanonicalType(T));
Douglas Gregor5597ab42010-05-07 23:12:07 +000010837}
10838
Douglas Gregor8a01b2a2010-09-11 20:24:53 +000010839namespace {
10840 /// \brief Helper class that marks all of the declarations referenced by
10841 /// potentially-evaluated subexpressions as "referenced".
10842 class EvaluatedExprMarker : public EvaluatedExprVisitor<EvaluatedExprMarker> {
10843 Sema &S;
Douglas Gregor680e9e02012-02-21 19:11:17 +000010844 bool SkipLocalVariables;
Douglas Gregor8a01b2a2010-09-11 20:24:53 +000010845
10846 public:
10847 typedef EvaluatedExprVisitor<EvaluatedExprMarker> Inherited;
10848
Douglas Gregor680e9e02012-02-21 19:11:17 +000010849 EvaluatedExprMarker(Sema &S, bool SkipLocalVariables)
10850 : Inherited(S.Context), S(S), SkipLocalVariables(SkipLocalVariables) { }
Douglas Gregor8a01b2a2010-09-11 20:24:53 +000010851
10852 void VisitDeclRefExpr(DeclRefExpr *E) {
Douglas Gregor680e9e02012-02-21 19:11:17 +000010853 // If we were asked not to visit local variables, don't.
10854 if (SkipLocalVariables) {
10855 if (VarDecl *VD = dyn_cast<VarDecl>(E->getDecl()))
10856 if (VD->hasLocalStorage())
10857 return;
10858 }
10859
Eli Friedmanfa0df832012-02-02 03:46:19 +000010860 S.MarkDeclRefReferenced(E);
Douglas Gregor8a01b2a2010-09-11 20:24:53 +000010861 }
10862
10863 void VisitMemberExpr(MemberExpr *E) {
Eli Friedmanfa0df832012-02-02 03:46:19 +000010864 S.MarkMemberReferenced(E);
Douglas Gregor32b3de52010-09-11 23:32:50 +000010865 Inherited::VisitMemberExpr(E);
Douglas Gregor8a01b2a2010-09-11 20:24:53 +000010866 }
10867
John McCall28fc7092011-11-10 05:35:25 +000010868 void VisitCXXBindTemporaryExpr(CXXBindTemporaryExpr *E) {
Eli Friedmanfa0df832012-02-02 03:46:19 +000010869 S.MarkFunctionReferenced(E->getLocStart(),
John McCall28fc7092011-11-10 05:35:25 +000010870 const_cast<CXXDestructorDecl*>(E->getTemporary()->getDestructor()));
10871 Visit(E->getSubExpr());
10872 }
10873
Douglas Gregor8a01b2a2010-09-11 20:24:53 +000010874 void VisitCXXNewExpr(CXXNewExpr *E) {
Douglas Gregor8a01b2a2010-09-11 20:24:53 +000010875 if (E->getOperatorNew())
Eli Friedmanfa0df832012-02-02 03:46:19 +000010876 S.MarkFunctionReferenced(E->getLocStart(), E->getOperatorNew());
Douglas Gregor8a01b2a2010-09-11 20:24:53 +000010877 if (E->getOperatorDelete())
Eli Friedmanfa0df832012-02-02 03:46:19 +000010878 S.MarkFunctionReferenced(E->getLocStart(), E->getOperatorDelete());
Douglas Gregor32b3de52010-09-11 23:32:50 +000010879 Inherited::VisitCXXNewExpr(E);
Douglas Gregor8a01b2a2010-09-11 20:24:53 +000010880 }
Sebastian Redl6047f072012-02-16 12:22:20 +000010881
Douglas Gregor8a01b2a2010-09-11 20:24:53 +000010882 void VisitCXXDeleteExpr(CXXDeleteExpr *E) {
10883 if (E->getOperatorDelete())
Eli Friedmanfa0df832012-02-02 03:46:19 +000010884 S.MarkFunctionReferenced(E->getLocStart(), E->getOperatorDelete());
Douglas Gregor6ed2fee2010-09-14 22:55:20 +000010885 QualType Destroyed = S.Context.getBaseElementType(E->getDestroyedType());
10886 if (const RecordType *DestroyedRec = Destroyed->getAs<RecordType>()) {
10887 CXXRecordDecl *Record = cast<CXXRecordDecl>(DestroyedRec->getDecl());
Eli Friedmanfa0df832012-02-02 03:46:19 +000010888 S.MarkFunctionReferenced(E->getLocStart(),
Douglas Gregor6ed2fee2010-09-14 22:55:20 +000010889 S.LookupDestructor(Record));
10890 }
10891
Douglas Gregor32b3de52010-09-11 23:32:50 +000010892 Inherited::VisitCXXDeleteExpr(E);
Douglas Gregor8a01b2a2010-09-11 20:24:53 +000010893 }
10894
10895 void VisitCXXConstructExpr(CXXConstructExpr *E) {
Eli Friedmanfa0df832012-02-02 03:46:19 +000010896 S.MarkFunctionReferenced(E->getLocStart(), E->getConstructor());
Douglas Gregor32b3de52010-09-11 23:32:50 +000010897 Inherited::VisitCXXConstructExpr(E);
Douglas Gregor8a01b2a2010-09-11 20:24:53 +000010898 }
10899
Douglas Gregorf0873f42010-10-19 17:17:35 +000010900 void VisitCXXDefaultArgExpr(CXXDefaultArgExpr *E) {
10901 Visit(E->getExpr());
10902 }
Eli Friedman3bda6b12012-02-02 23:15:15 +000010903
10904 void VisitImplicitCastExpr(ImplicitCastExpr *E) {
10905 Inherited::VisitImplicitCastExpr(E);
10906
10907 if (E->getCastKind() == CK_LValueToRValue)
10908 S.UpdateMarkingForLValueToRValue(E->getSubExpr());
10909 }
Douglas Gregor8a01b2a2010-09-11 20:24:53 +000010910 };
10911}
10912
10913/// \brief Mark any declarations that appear within this expression or any
10914/// potentially-evaluated subexpressions as "referenced".
Douglas Gregor680e9e02012-02-21 19:11:17 +000010915///
10916/// \param SkipLocalVariables If true, don't mark local variables as
10917/// 'referenced'.
10918void Sema::MarkDeclarationsReferencedInExpr(Expr *E,
10919 bool SkipLocalVariables) {
10920 EvaluatedExprMarker(*this, SkipLocalVariables).Visit(E);
Douglas Gregor8a01b2a2010-09-11 20:24:53 +000010921}
10922
Douglas Gregorda8cdbc2009-12-22 01:01:55 +000010923/// \brief Emit a diagnostic that describes an effect on the run-time behavior
10924/// of the program being compiled.
10925///
10926/// This routine emits the given diagnostic when the code currently being
Kovarththanan Rajaratnamba2c6522010-03-13 10:17:05 +000010927/// type-checked is "potentially evaluated", meaning that there is a
Douglas Gregorda8cdbc2009-12-22 01:01:55 +000010928/// possibility that the code will actually be executable. Code in sizeof()
10929/// expressions, code used only during overload resolution, etc., are not
10930/// potentially evaluated. This routine will suppress such diagnostics or,
10931/// in the absolutely nutty case of potentially potentially evaluated
Kovarththanan Rajaratnamba2c6522010-03-13 10:17:05 +000010932/// expressions (C++ typeid), queue the diagnostic to potentially emit it
Douglas Gregorda8cdbc2009-12-22 01:01:55 +000010933/// later.
Kovarththanan Rajaratnamba2c6522010-03-13 10:17:05 +000010934///
Douglas Gregorda8cdbc2009-12-22 01:01:55 +000010935/// This routine should be used for all diagnostics that describe the run-time
10936/// behavior of a program, such as passing a non-POD value through an ellipsis.
10937/// Failure to do so will likely result in spurious diagnostics or failures
10938/// during overload resolution or within sizeof/alignof/typeof/typeid.
Richard Trieuba63ce62011-09-09 01:45:06 +000010939bool Sema::DiagRuntimeBehavior(SourceLocation Loc, const Stmt *Statement,
Douglas Gregorda8cdbc2009-12-22 01:01:55 +000010940 const PartialDiagnostic &PD) {
John McCall31168b02011-06-15 23:02:42 +000010941 switch (ExprEvalContexts.back().Context) {
Douglas Gregorda8cdbc2009-12-22 01:01:55 +000010942 case Unevaluated:
10943 // The argument will never be evaluated, so don't complain.
10944 break;
Kovarththanan Rajaratnamba2c6522010-03-13 10:17:05 +000010945
Richard Smith764d2fe2011-12-20 02:08:33 +000010946 case ConstantEvaluated:
10947 // Relevant diagnostics should be produced by constant evaluation.
10948 break;
10949
Douglas Gregorda8cdbc2009-12-22 01:01:55 +000010950 case PotentiallyEvaluated:
Douglas Gregor8a01b2a2010-09-11 20:24:53 +000010951 case PotentiallyEvaluatedIfUsed:
Richard Trieuba63ce62011-09-09 01:45:06 +000010952 if (Statement && getCurFunctionOrMethodDecl()) {
Ted Kremenek3427fac2011-02-23 01:52:04 +000010953 FunctionScopes.back()->PossiblyUnreachableDiags.
Richard Trieuba63ce62011-09-09 01:45:06 +000010954 push_back(sema::PossiblyUnreachableDiag(PD, Loc, Statement));
Ted Kremenek3427fac2011-02-23 01:52:04 +000010955 }
10956 else
10957 Diag(Loc, PD);
10958
Douglas Gregorda8cdbc2009-12-22 01:01:55 +000010959 return true;
Douglas Gregorda8cdbc2009-12-22 01:01:55 +000010960 }
10961
10962 return false;
10963}
10964
Anders Carlsson7f84ed92009-10-09 23:51:55 +000010965bool Sema::CheckCallReturnType(QualType ReturnType, SourceLocation Loc,
10966 CallExpr *CE, FunctionDecl *FD) {
10967 if (ReturnType->isVoidType() || !ReturnType->isIncompleteType())
10968 return false;
10969
Richard Smithfd555f62012-02-22 02:04:18 +000010970 // If we're inside a decltype's expression, don't check for a valid return
10971 // type or construct temporaries until we know whether this is the last call.
10972 if (ExprEvalContexts.back().IsDecltype) {
10973 ExprEvalContexts.back().DelayedDecltypeCalls.push_back(CE);
10974 return false;
10975 }
10976
Douglas Gregora6c5abb2012-05-04 16:48:41 +000010977 class CallReturnIncompleteDiagnoser : public TypeDiagnoser {
Douglas Gregor7bfb2d02012-05-04 16:32:21 +000010978 FunctionDecl *FD;
10979 CallExpr *CE;
10980
10981 public:
10982 CallReturnIncompleteDiagnoser(FunctionDecl *FD, CallExpr *CE)
10983 : FD(FD), CE(CE) { }
10984
10985 virtual void diagnose(Sema &S, SourceLocation Loc, QualType T) {
10986 if (!FD) {
10987 S.Diag(Loc, diag::err_call_incomplete_return)
10988 << T << CE->getSourceRange();
10989 return;
10990 }
10991
10992 S.Diag(Loc, diag::err_call_function_incomplete_return)
10993 << CE->getSourceRange() << FD->getDeclName() << T;
10994 S.Diag(FD->getLocation(),
10995 diag::note_function_with_incomplete_return_type_declared_here)
10996 << FD->getDeclName();
10997 }
10998 } Diagnoser(FD, CE);
10999
11000 if (RequireCompleteType(Loc, ReturnType, Diagnoser))
Anders Carlsson7f84ed92009-10-09 23:51:55 +000011001 return true;
11002
11003 return false;
11004}
11005
Douglas Gregor2d4f64f2011-01-19 16:50:08 +000011006// Diagnose the s/=/==/ and s/\|=/!=/ typos. Note that adding parentheses
John McCalld5707ab2009-10-12 21:59:07 +000011007// will prevent this condition from triggering, which is what we want.
11008void Sema::DiagnoseAssignmentAsCondition(Expr *E) {
11009 SourceLocation Loc;
11010
John McCall0506e4a2009-11-11 02:41:58 +000011011 unsigned diagnostic = diag::warn_condition_is_assignment;
Douglas Gregor2d4f64f2011-01-19 16:50:08 +000011012 bool IsOrAssign = false;
John McCall0506e4a2009-11-11 02:41:58 +000011013
Chandler Carruthf87d6c02011-08-16 22:30:10 +000011014 if (BinaryOperator *Op = dyn_cast<BinaryOperator>(E)) {
Douglas Gregor2d4f64f2011-01-19 16:50:08 +000011015 if (Op->getOpcode() != BO_Assign && Op->getOpcode() != BO_OrAssign)
John McCalld5707ab2009-10-12 21:59:07 +000011016 return;
11017
Douglas Gregor2d4f64f2011-01-19 16:50:08 +000011018 IsOrAssign = Op->getOpcode() == BO_OrAssign;
11019
John McCallb0e419e2009-11-12 00:06:05 +000011020 // Greylist some idioms by putting them into a warning subcategory.
11021 if (ObjCMessageExpr *ME
11022 = dyn_cast<ObjCMessageExpr>(Op->getRHS()->IgnoreParenCasts())) {
11023 Selector Sel = ME->getSelector();
11024
John McCallb0e419e2009-11-12 00:06:05 +000011025 // self = [<foo> init...]
Douglas Gregor486b74e2011-09-27 16:10:05 +000011026 if (isSelfExpr(Op->getLHS()) && Sel.getNameForSlot(0).startswith("init"))
John McCallb0e419e2009-11-12 00:06:05 +000011027 diagnostic = diag::warn_condition_is_idiomatic_assignment;
11028
11029 // <foo> = [<bar> nextObject]
Douglas Gregoraf2a6ae2011-02-18 22:29:55 +000011030 else if (Sel.isUnarySelector() && Sel.getNameForSlot(0) == "nextObject")
John McCallb0e419e2009-11-12 00:06:05 +000011031 diagnostic = diag::warn_condition_is_idiomatic_assignment;
11032 }
John McCall0506e4a2009-11-11 02:41:58 +000011033
John McCalld5707ab2009-10-12 21:59:07 +000011034 Loc = Op->getOperatorLoc();
Chandler Carruthf87d6c02011-08-16 22:30:10 +000011035 } else if (CXXOperatorCallExpr *Op = dyn_cast<CXXOperatorCallExpr>(E)) {
Douglas Gregor2d4f64f2011-01-19 16:50:08 +000011036 if (Op->getOperator() != OO_Equal && Op->getOperator() != OO_PipeEqual)
John McCalld5707ab2009-10-12 21:59:07 +000011037 return;
11038
Douglas Gregor2d4f64f2011-01-19 16:50:08 +000011039 IsOrAssign = Op->getOperator() == OO_PipeEqual;
John McCalld5707ab2009-10-12 21:59:07 +000011040 Loc = Op->getOperatorLoc();
11041 } else {
11042 // Not an assignment.
11043 return;
11044 }
11045
Douglas Gregor2bf2d3d2010-04-14 16:09:52 +000011046 Diag(Loc, diagnostic) << E->getSourceRange();
Douglas Gregor2d4f64f2011-01-19 16:50:08 +000011047
Daniel Dunbar62ee6412012-03-09 18:35:03 +000011048 SourceLocation Open = E->getLocStart();
Argyrios Kyrtzidise1b97c42011-04-25 23:01:29 +000011049 SourceLocation Close = PP.getLocForEndOfToken(E->getSourceRange().getEnd());
11050 Diag(Loc, diag::note_condition_assign_silence)
11051 << FixItHint::CreateInsertion(Open, "(")
11052 << FixItHint::CreateInsertion(Close, ")");
11053
Douglas Gregor2d4f64f2011-01-19 16:50:08 +000011054 if (IsOrAssign)
11055 Diag(Loc, diag::note_condition_or_assign_to_comparison)
11056 << FixItHint::CreateReplacement(Loc, "!=");
11057 else
11058 Diag(Loc, diag::note_condition_assign_to_comparison)
11059 << FixItHint::CreateReplacement(Loc, "==");
John McCalld5707ab2009-10-12 21:59:07 +000011060}
11061
Argyrios Kyrtzidis8b6ec682011-02-01 18:24:22 +000011062/// \brief Redundant parentheses over an equality comparison can indicate
11063/// that the user intended an assignment used as condition.
Richard Trieuba63ce62011-09-09 01:45:06 +000011064void Sema::DiagnoseEqualityWithExtraParens(ParenExpr *ParenE) {
Argyrios Kyrtzidisf4f82782011-02-01 22:23:56 +000011065 // Don't warn if the parens came from a macro.
Richard Trieuba63ce62011-09-09 01:45:06 +000011066 SourceLocation parenLoc = ParenE->getLocStart();
Argyrios Kyrtzidisf4f82782011-02-01 22:23:56 +000011067 if (parenLoc.isInvalid() || parenLoc.isMacroID())
11068 return;
Argyrios Kyrtzidisba699d62011-03-28 23:52:04 +000011069 // Don't warn for dependent expressions.
Richard Trieuba63ce62011-09-09 01:45:06 +000011070 if (ParenE->isTypeDependent())
Argyrios Kyrtzidisba699d62011-03-28 23:52:04 +000011071 return;
Argyrios Kyrtzidisf4f82782011-02-01 22:23:56 +000011072
Richard Trieuba63ce62011-09-09 01:45:06 +000011073 Expr *E = ParenE->IgnoreParens();
Argyrios Kyrtzidis8b6ec682011-02-01 18:24:22 +000011074
11075 if (BinaryOperator *opE = dyn_cast<BinaryOperator>(E))
Argyrios Kyrtzidis582dd682011-02-01 19:32:59 +000011076 if (opE->getOpcode() == BO_EQ &&
11077 opE->getLHS()->IgnoreParenImpCasts()->isModifiableLvalue(Context)
11078 == Expr::MLV_Valid) {
Argyrios Kyrtzidis8b6ec682011-02-01 18:24:22 +000011079 SourceLocation Loc = opE->getOperatorLoc();
Ted Kremenekc358d9f2011-02-01 22:36:09 +000011080
Ted Kremenekae022092011-02-02 02:20:30 +000011081 Diag(Loc, diag::warn_equality_with_extra_parens) << E->getSourceRange();
Daniel Dunbar62ee6412012-03-09 18:35:03 +000011082 SourceRange ParenERange = ParenE->getSourceRange();
Ted Kremenekae022092011-02-02 02:20:30 +000011083 Diag(Loc, diag::note_equality_comparison_silence)
Daniel Dunbar62ee6412012-03-09 18:35:03 +000011084 << FixItHint::CreateRemoval(ParenERange.getBegin())
11085 << FixItHint::CreateRemoval(ParenERange.getEnd());
Argyrios Kyrtzidise1b97c42011-04-25 23:01:29 +000011086 Diag(Loc, diag::note_equality_comparison_to_assign)
11087 << FixItHint::CreateReplacement(Loc, "=");
Argyrios Kyrtzidis8b6ec682011-02-01 18:24:22 +000011088 }
11089}
11090
John Wiegley01296292011-04-08 18:41:53 +000011091ExprResult Sema::CheckBooleanCondition(Expr *E, SourceLocation Loc) {
John McCalld5707ab2009-10-12 21:59:07 +000011092 DiagnoseAssignmentAsCondition(E);
Argyrios Kyrtzidis8b6ec682011-02-01 18:24:22 +000011093 if (ParenExpr *parenE = dyn_cast<ParenExpr>(E))
11094 DiagnoseEqualityWithExtraParens(parenE);
John McCalld5707ab2009-10-12 21:59:07 +000011095
John McCall0009fcc2011-04-26 20:42:42 +000011096 ExprResult result = CheckPlaceholderExpr(E);
11097 if (result.isInvalid()) return ExprError();
11098 E = result.take();
Argyrios Kyrtzidisca766292010-11-01 18:49:26 +000011099
John McCall0009fcc2011-04-26 20:42:42 +000011100 if (!E->isTypeDependent()) {
David Blaikiebbafb8a2012-03-11 07:00:24 +000011101 if (getLangOpts().CPlusPlus)
John McCall34376a62010-12-04 03:47:34 +000011102 return CheckCXXBooleanCondition(E); // C++ 6.4p4
11103
John Wiegley01296292011-04-08 18:41:53 +000011104 ExprResult ERes = DefaultFunctionArrayLvalueConversion(E);
11105 if (ERes.isInvalid())
11106 return ExprError();
11107 E = ERes.take();
John McCall29cb2fd2010-12-04 06:09:13 +000011108
11109 QualType T = E->getType();
John Wiegley01296292011-04-08 18:41:53 +000011110 if (!T->isScalarType()) { // C99 6.8.4.1p1
11111 Diag(Loc, diag::err_typecheck_statement_requires_scalar)
11112 << T << E->getSourceRange();
11113 return ExprError();
11114 }
John McCalld5707ab2009-10-12 21:59:07 +000011115 }
11116
John Wiegley01296292011-04-08 18:41:53 +000011117 return Owned(E);
John McCalld5707ab2009-10-12 21:59:07 +000011118}
Douglas Gregore60e41a2010-05-06 17:25:47 +000011119
John McCalldadc5752010-08-24 06:29:42 +000011120ExprResult Sema::ActOnBooleanCondition(Scope *S, SourceLocation Loc,
Richard Trieuba63ce62011-09-09 01:45:06 +000011121 Expr *SubExpr) {
11122 if (!SubExpr)
Douglas Gregore60e41a2010-05-06 17:25:47 +000011123 return ExprError();
John Wiegley01296292011-04-08 18:41:53 +000011124
Richard Trieuba63ce62011-09-09 01:45:06 +000011125 return CheckBooleanCondition(SubExpr, Loc);
Douglas Gregore60e41a2010-05-06 17:25:47 +000011126}
John McCall36e7fe32010-10-12 00:20:44 +000011127
John McCall31996342011-04-07 08:22:57 +000011128namespace {
John McCall2979fe02011-04-12 00:42:48 +000011129 /// A visitor for rebuilding a call to an __unknown_any expression
11130 /// to have an appropriate type.
11131 struct RebuildUnknownAnyFunction
11132 : StmtVisitor<RebuildUnknownAnyFunction, ExprResult> {
11133
11134 Sema &S;
11135
11136 RebuildUnknownAnyFunction(Sema &S) : S(S) {}
11137
11138 ExprResult VisitStmt(Stmt *S) {
11139 llvm_unreachable("unexpected statement!");
John McCall2979fe02011-04-12 00:42:48 +000011140 }
11141
Richard Trieu10162ab2011-09-09 03:59:41 +000011142 ExprResult VisitExpr(Expr *E) {
11143 S.Diag(E->getExprLoc(), diag::err_unsupported_unknown_any_call)
11144 << E->getSourceRange();
John McCall2979fe02011-04-12 00:42:48 +000011145 return ExprError();
11146 }
11147
11148 /// Rebuild an expression which simply semantically wraps another
11149 /// expression which it shares the type and value kind of.
Richard Trieu10162ab2011-09-09 03:59:41 +000011150 template <class T> ExprResult rebuildSugarExpr(T *E) {
11151 ExprResult SubResult = Visit(E->getSubExpr());
11152 if (SubResult.isInvalid()) return ExprError();
John McCall2979fe02011-04-12 00:42:48 +000011153
Richard Trieu10162ab2011-09-09 03:59:41 +000011154 Expr *SubExpr = SubResult.take();
11155 E->setSubExpr(SubExpr);
11156 E->setType(SubExpr->getType());
11157 E->setValueKind(SubExpr->getValueKind());
11158 assert(E->getObjectKind() == OK_Ordinary);
11159 return E;
John McCall2979fe02011-04-12 00:42:48 +000011160 }
11161
Richard Trieu10162ab2011-09-09 03:59:41 +000011162 ExprResult VisitParenExpr(ParenExpr *E) {
11163 return rebuildSugarExpr(E);
John McCall2979fe02011-04-12 00:42:48 +000011164 }
11165
Richard Trieu10162ab2011-09-09 03:59:41 +000011166 ExprResult VisitUnaryExtension(UnaryOperator *E) {
11167 return rebuildSugarExpr(E);
John McCall2979fe02011-04-12 00:42:48 +000011168 }
11169
Richard Trieu10162ab2011-09-09 03:59:41 +000011170 ExprResult VisitUnaryAddrOf(UnaryOperator *E) {
11171 ExprResult SubResult = Visit(E->getSubExpr());
11172 if (SubResult.isInvalid()) return ExprError();
John McCall2979fe02011-04-12 00:42:48 +000011173
Richard Trieu10162ab2011-09-09 03:59:41 +000011174 Expr *SubExpr = SubResult.take();
11175 E->setSubExpr(SubExpr);
11176 E->setType(S.Context.getPointerType(SubExpr->getType()));
11177 assert(E->getValueKind() == VK_RValue);
11178 assert(E->getObjectKind() == OK_Ordinary);
11179 return E;
John McCall2979fe02011-04-12 00:42:48 +000011180 }
11181
Richard Trieu10162ab2011-09-09 03:59:41 +000011182 ExprResult resolveDecl(Expr *E, ValueDecl *VD) {
11183 if (!isa<FunctionDecl>(VD)) return VisitExpr(E);
John McCall2979fe02011-04-12 00:42:48 +000011184
Richard Trieu10162ab2011-09-09 03:59:41 +000011185 E->setType(VD->getType());
John McCall2979fe02011-04-12 00:42:48 +000011186
Richard Trieu10162ab2011-09-09 03:59:41 +000011187 assert(E->getValueKind() == VK_RValue);
David Blaikiebbafb8a2012-03-11 07:00:24 +000011188 if (S.getLangOpts().CPlusPlus &&
Richard Trieu10162ab2011-09-09 03:59:41 +000011189 !(isa<CXXMethodDecl>(VD) &&
11190 cast<CXXMethodDecl>(VD)->isInstance()))
11191 E->setValueKind(VK_LValue);
John McCall2979fe02011-04-12 00:42:48 +000011192
Richard Trieu10162ab2011-09-09 03:59:41 +000011193 return E;
John McCall2979fe02011-04-12 00:42:48 +000011194 }
11195
Richard Trieu10162ab2011-09-09 03:59:41 +000011196 ExprResult VisitMemberExpr(MemberExpr *E) {
11197 return resolveDecl(E, E->getMemberDecl());
John McCall2979fe02011-04-12 00:42:48 +000011198 }
11199
Richard Trieu10162ab2011-09-09 03:59:41 +000011200 ExprResult VisitDeclRefExpr(DeclRefExpr *E) {
11201 return resolveDecl(E, E->getDecl());
John McCall2979fe02011-04-12 00:42:48 +000011202 }
11203 };
11204}
11205
11206/// Given a function expression of unknown-any type, try to rebuild it
11207/// to have a function type.
Richard Trieu10162ab2011-09-09 03:59:41 +000011208static ExprResult rebuildUnknownAnyFunction(Sema &S, Expr *FunctionExpr) {
11209 ExprResult Result = RebuildUnknownAnyFunction(S).Visit(FunctionExpr);
11210 if (Result.isInvalid()) return ExprError();
11211 return S.DefaultFunctionArrayConversion(Result.take());
John McCall2979fe02011-04-12 00:42:48 +000011212}
11213
11214namespace {
John McCall2d2e8702011-04-11 07:02:50 +000011215 /// A visitor for rebuilding an expression of type __unknown_anytype
11216 /// into one which resolves the type directly on the referring
11217 /// expression. Strict preservation of the original source
11218 /// structure is not a goal.
John McCall31996342011-04-07 08:22:57 +000011219 struct RebuildUnknownAnyExpr
John McCall39439732011-04-09 22:50:59 +000011220 : StmtVisitor<RebuildUnknownAnyExpr, ExprResult> {
John McCall31996342011-04-07 08:22:57 +000011221
11222 Sema &S;
11223
11224 /// The current destination type.
11225 QualType DestType;
11226
Richard Trieu10162ab2011-09-09 03:59:41 +000011227 RebuildUnknownAnyExpr(Sema &S, QualType CastType)
11228 : S(S), DestType(CastType) {}
John McCall31996342011-04-07 08:22:57 +000011229
John McCall39439732011-04-09 22:50:59 +000011230 ExprResult VisitStmt(Stmt *S) {
John McCall2d2e8702011-04-11 07:02:50 +000011231 llvm_unreachable("unexpected statement!");
John McCall31996342011-04-07 08:22:57 +000011232 }
11233
Richard Trieu10162ab2011-09-09 03:59:41 +000011234 ExprResult VisitExpr(Expr *E) {
11235 S.Diag(E->getExprLoc(), diag::err_unsupported_unknown_any_expr)
11236 << E->getSourceRange();
John McCall2d2e8702011-04-11 07:02:50 +000011237 return ExprError();
John McCall31996342011-04-07 08:22:57 +000011238 }
11239
Richard Trieu10162ab2011-09-09 03:59:41 +000011240 ExprResult VisitCallExpr(CallExpr *E);
11241 ExprResult VisitObjCMessageExpr(ObjCMessageExpr *E);
John McCall2d2e8702011-04-11 07:02:50 +000011242
John McCall39439732011-04-09 22:50:59 +000011243 /// Rebuild an expression which simply semantically wraps another
11244 /// expression which it shares the type and value kind of.
Richard Trieu10162ab2011-09-09 03:59:41 +000011245 template <class T> ExprResult rebuildSugarExpr(T *E) {
11246 ExprResult SubResult = Visit(E->getSubExpr());
11247 if (SubResult.isInvalid()) return ExprError();
11248 Expr *SubExpr = SubResult.take();
11249 E->setSubExpr(SubExpr);
11250 E->setType(SubExpr->getType());
11251 E->setValueKind(SubExpr->getValueKind());
11252 assert(E->getObjectKind() == OK_Ordinary);
11253 return E;
John McCall39439732011-04-09 22:50:59 +000011254 }
John McCall31996342011-04-07 08:22:57 +000011255
Richard Trieu10162ab2011-09-09 03:59:41 +000011256 ExprResult VisitParenExpr(ParenExpr *E) {
11257 return rebuildSugarExpr(E);
John McCall39439732011-04-09 22:50:59 +000011258 }
11259
Richard Trieu10162ab2011-09-09 03:59:41 +000011260 ExprResult VisitUnaryExtension(UnaryOperator *E) {
11261 return rebuildSugarExpr(E);
John McCall39439732011-04-09 22:50:59 +000011262 }
11263
Richard Trieu10162ab2011-09-09 03:59:41 +000011264 ExprResult VisitUnaryAddrOf(UnaryOperator *E) {
11265 const PointerType *Ptr = DestType->getAs<PointerType>();
11266 if (!Ptr) {
11267 S.Diag(E->getOperatorLoc(), diag::err_unknown_any_addrof)
11268 << E->getSourceRange();
John McCall2979fe02011-04-12 00:42:48 +000011269 return ExprError();
11270 }
Richard Trieu10162ab2011-09-09 03:59:41 +000011271 assert(E->getValueKind() == VK_RValue);
11272 assert(E->getObjectKind() == OK_Ordinary);
11273 E->setType(DestType);
John McCall2979fe02011-04-12 00:42:48 +000011274
11275 // Build the sub-expression as if it were an object of the pointee type.
Richard Trieu10162ab2011-09-09 03:59:41 +000011276 DestType = Ptr->getPointeeType();
11277 ExprResult SubResult = Visit(E->getSubExpr());
11278 if (SubResult.isInvalid()) return ExprError();
11279 E->setSubExpr(SubResult.take());
11280 return E;
John McCall2979fe02011-04-12 00:42:48 +000011281 }
11282
Richard Trieu10162ab2011-09-09 03:59:41 +000011283 ExprResult VisitImplicitCastExpr(ImplicitCastExpr *E);
John McCall39439732011-04-09 22:50:59 +000011284
Richard Trieu10162ab2011-09-09 03:59:41 +000011285 ExprResult resolveDecl(Expr *E, ValueDecl *VD);
John McCall39439732011-04-09 22:50:59 +000011286
Richard Trieu10162ab2011-09-09 03:59:41 +000011287 ExprResult VisitMemberExpr(MemberExpr *E) {
11288 return resolveDecl(E, E->getMemberDecl());
John McCall2979fe02011-04-12 00:42:48 +000011289 }
John McCall39439732011-04-09 22:50:59 +000011290
Richard Trieu10162ab2011-09-09 03:59:41 +000011291 ExprResult VisitDeclRefExpr(DeclRefExpr *E) {
11292 return resolveDecl(E, E->getDecl());
John McCall31996342011-04-07 08:22:57 +000011293 }
11294 };
11295}
11296
John McCall2d2e8702011-04-11 07:02:50 +000011297/// Rebuilds a call expression which yielded __unknown_anytype.
Richard Trieu10162ab2011-09-09 03:59:41 +000011298ExprResult RebuildUnknownAnyExpr::VisitCallExpr(CallExpr *E) {
11299 Expr *CalleeExpr = E->getCallee();
John McCall2d2e8702011-04-11 07:02:50 +000011300
11301 enum FnKind {
John McCall4adb38c2011-04-27 00:36:17 +000011302 FK_MemberFunction,
John McCall2d2e8702011-04-11 07:02:50 +000011303 FK_FunctionPointer,
11304 FK_BlockPointer
11305 };
11306
Richard Trieu10162ab2011-09-09 03:59:41 +000011307 FnKind Kind;
11308 QualType CalleeType = CalleeExpr->getType();
11309 if (CalleeType == S.Context.BoundMemberTy) {
11310 assert(isa<CXXMemberCallExpr>(E) || isa<CXXOperatorCallExpr>(E));
11311 Kind = FK_MemberFunction;
11312 CalleeType = Expr::findBoundMemberType(CalleeExpr);
11313 } else if (const PointerType *Ptr = CalleeType->getAs<PointerType>()) {
11314 CalleeType = Ptr->getPointeeType();
11315 Kind = FK_FunctionPointer;
John McCall2d2e8702011-04-11 07:02:50 +000011316 } else {
Richard Trieu10162ab2011-09-09 03:59:41 +000011317 CalleeType = CalleeType->castAs<BlockPointerType>()->getPointeeType();
11318 Kind = FK_BlockPointer;
John McCall2d2e8702011-04-11 07:02:50 +000011319 }
Richard Trieu10162ab2011-09-09 03:59:41 +000011320 const FunctionType *FnType = CalleeType->castAs<FunctionType>();
John McCall2d2e8702011-04-11 07:02:50 +000011321
11322 // Verify that this is a legal result type of a function.
11323 if (DestType->isArrayType() || DestType->isFunctionType()) {
11324 unsigned diagID = diag::err_func_returning_array_function;
Richard Trieu10162ab2011-09-09 03:59:41 +000011325 if (Kind == FK_BlockPointer)
John McCall2d2e8702011-04-11 07:02:50 +000011326 diagID = diag::err_block_returning_array_function;
11327
Richard Trieu10162ab2011-09-09 03:59:41 +000011328 S.Diag(E->getExprLoc(), diagID)
John McCall2d2e8702011-04-11 07:02:50 +000011329 << DestType->isFunctionType() << DestType;
11330 return ExprError();
11331 }
11332
11333 // Otherwise, go ahead and set DestType as the call's result.
Richard Trieu10162ab2011-09-09 03:59:41 +000011334 E->setType(DestType.getNonLValueExprType(S.Context));
11335 E->setValueKind(Expr::getValueKindForType(DestType));
11336 assert(E->getObjectKind() == OK_Ordinary);
John McCall2d2e8702011-04-11 07:02:50 +000011337
11338 // Rebuild the function type, replacing the result type with DestType.
Richard Trieu10162ab2011-09-09 03:59:41 +000011339 if (const FunctionProtoType *Proto = dyn_cast<FunctionProtoType>(FnType))
John McCall2d2e8702011-04-11 07:02:50 +000011340 DestType = S.Context.getFunctionType(DestType,
Richard Trieu10162ab2011-09-09 03:59:41 +000011341 Proto->arg_type_begin(),
11342 Proto->getNumArgs(),
11343 Proto->getExtProtoInfo());
John McCall2d2e8702011-04-11 07:02:50 +000011344 else
11345 DestType = S.Context.getFunctionNoProtoType(DestType,
Richard Trieu10162ab2011-09-09 03:59:41 +000011346 FnType->getExtInfo());
John McCall2d2e8702011-04-11 07:02:50 +000011347
11348 // Rebuild the appropriate pointer-to-function type.
Richard Trieu10162ab2011-09-09 03:59:41 +000011349 switch (Kind) {
John McCall4adb38c2011-04-27 00:36:17 +000011350 case FK_MemberFunction:
John McCall2d2e8702011-04-11 07:02:50 +000011351 // Nothing to do.
11352 break;
11353
11354 case FK_FunctionPointer:
11355 DestType = S.Context.getPointerType(DestType);
11356 break;
11357
11358 case FK_BlockPointer:
11359 DestType = S.Context.getBlockPointerType(DestType);
11360 break;
11361 }
11362
11363 // Finally, we can recurse.
Richard Trieu10162ab2011-09-09 03:59:41 +000011364 ExprResult CalleeResult = Visit(CalleeExpr);
11365 if (!CalleeResult.isUsable()) return ExprError();
11366 E->setCallee(CalleeResult.take());
John McCall2d2e8702011-04-11 07:02:50 +000011367
11368 // Bind a temporary if necessary.
Richard Trieu10162ab2011-09-09 03:59:41 +000011369 return S.MaybeBindToTemporary(E);
John McCall2d2e8702011-04-11 07:02:50 +000011370}
11371
Richard Trieu10162ab2011-09-09 03:59:41 +000011372ExprResult RebuildUnknownAnyExpr::VisitObjCMessageExpr(ObjCMessageExpr *E) {
John McCall2979fe02011-04-12 00:42:48 +000011373 // Verify that this is a legal result type of a call.
11374 if (DestType->isArrayType() || DestType->isFunctionType()) {
Richard Trieu10162ab2011-09-09 03:59:41 +000011375 S.Diag(E->getExprLoc(), diag::err_func_returning_array_function)
John McCall2979fe02011-04-12 00:42:48 +000011376 << DestType->isFunctionType() << DestType;
11377 return ExprError();
John McCall2d2e8702011-04-11 07:02:50 +000011378 }
11379
John McCall3f4138c2011-07-13 17:56:40 +000011380 // Rewrite the method result type if available.
Richard Trieu10162ab2011-09-09 03:59:41 +000011381 if (ObjCMethodDecl *Method = E->getMethodDecl()) {
11382 assert(Method->getResultType() == S.Context.UnknownAnyTy);
11383 Method->setResultType(DestType);
John McCall3f4138c2011-07-13 17:56:40 +000011384 }
John McCall2979fe02011-04-12 00:42:48 +000011385
John McCall2d2e8702011-04-11 07:02:50 +000011386 // Change the type of the message.
Richard Trieu10162ab2011-09-09 03:59:41 +000011387 E->setType(DestType.getNonReferenceType());
11388 E->setValueKind(Expr::getValueKindForType(DestType));
John McCall2d2e8702011-04-11 07:02:50 +000011389
Richard Trieu10162ab2011-09-09 03:59:41 +000011390 return S.MaybeBindToTemporary(E);
John McCall2d2e8702011-04-11 07:02:50 +000011391}
11392
Richard Trieu10162ab2011-09-09 03:59:41 +000011393ExprResult RebuildUnknownAnyExpr::VisitImplicitCastExpr(ImplicitCastExpr *E) {
John McCall2979fe02011-04-12 00:42:48 +000011394 // The only case we should ever see here is a function-to-pointer decay.
Sean Callanan2db103c2012-03-06 23:12:57 +000011395 if (E->getCastKind() == CK_FunctionToPointerDecay) {
Sean Callanan12495112012-03-06 21:34:12 +000011396 assert(E->getValueKind() == VK_RValue);
11397 assert(E->getObjectKind() == OK_Ordinary);
11398
11399 E->setType(DestType);
11400
11401 // Rebuild the sub-expression as the pointee (function) type.
11402 DestType = DestType->castAs<PointerType>()->getPointeeType();
11403
11404 ExprResult Result = Visit(E->getSubExpr());
11405 if (!Result.isUsable()) return ExprError();
11406
11407 E->setSubExpr(Result.take());
11408 return S.Owned(E);
Sean Callanan2db103c2012-03-06 23:12:57 +000011409 } else if (E->getCastKind() == CK_LValueToRValue) {
Sean Callanan12495112012-03-06 21:34:12 +000011410 assert(E->getValueKind() == VK_RValue);
11411 assert(E->getObjectKind() == OK_Ordinary);
John McCall2d2e8702011-04-11 07:02:50 +000011412
Sean Callanan12495112012-03-06 21:34:12 +000011413 assert(isa<BlockPointerType>(E->getType()));
John McCall2979fe02011-04-12 00:42:48 +000011414
Sean Callanan12495112012-03-06 21:34:12 +000011415 E->setType(DestType);
John McCall2d2e8702011-04-11 07:02:50 +000011416
Sean Callanan12495112012-03-06 21:34:12 +000011417 // The sub-expression has to be a lvalue reference, so rebuild it as such.
11418 DestType = S.Context.getLValueReferenceType(DestType);
John McCall2d2e8702011-04-11 07:02:50 +000011419
Sean Callanan12495112012-03-06 21:34:12 +000011420 ExprResult Result = Visit(E->getSubExpr());
11421 if (!Result.isUsable()) return ExprError();
11422
11423 E->setSubExpr(Result.take());
11424 return S.Owned(E);
Sean Callanan2db103c2012-03-06 23:12:57 +000011425 } else {
Sean Callanan12495112012-03-06 21:34:12 +000011426 llvm_unreachable("Unhandled cast type!");
11427 }
John McCall2d2e8702011-04-11 07:02:50 +000011428}
11429
Richard Trieu10162ab2011-09-09 03:59:41 +000011430ExprResult RebuildUnknownAnyExpr::resolveDecl(Expr *E, ValueDecl *VD) {
11431 ExprValueKind ValueKind = VK_LValue;
11432 QualType Type = DestType;
John McCall2d2e8702011-04-11 07:02:50 +000011433
11434 // We know how to make this work for certain kinds of decls:
11435
11436 // - functions
Richard Trieu10162ab2011-09-09 03:59:41 +000011437 if (FunctionDecl *FD = dyn_cast<FunctionDecl>(VD)) {
11438 if (const PointerType *Ptr = Type->getAs<PointerType>()) {
11439 DestType = Ptr->getPointeeType();
11440 ExprResult Result = resolveDecl(E, VD);
11441 if (Result.isInvalid()) return ExprError();
11442 return S.ImpCastExprToType(Result.take(), Type,
John McCall9a877fe2011-08-10 04:12:23 +000011443 CK_FunctionToPointerDecay, VK_RValue);
11444 }
11445
Richard Trieu10162ab2011-09-09 03:59:41 +000011446 if (!Type->isFunctionType()) {
11447 S.Diag(E->getExprLoc(), diag::err_unknown_any_function)
11448 << VD << E->getSourceRange();
John McCall9a877fe2011-08-10 04:12:23 +000011449 return ExprError();
11450 }
John McCall2d2e8702011-04-11 07:02:50 +000011451
Richard Trieu10162ab2011-09-09 03:59:41 +000011452 if (CXXMethodDecl *MD = dyn_cast<CXXMethodDecl>(FD))
11453 if (MD->isInstance()) {
11454 ValueKind = VK_RValue;
11455 Type = S.Context.BoundMemberTy;
John McCall4adb38c2011-04-27 00:36:17 +000011456 }
11457
John McCall2d2e8702011-04-11 07:02:50 +000011458 // Function references aren't l-values in C.
David Blaikiebbafb8a2012-03-11 07:00:24 +000011459 if (!S.getLangOpts().CPlusPlus)
Richard Trieu10162ab2011-09-09 03:59:41 +000011460 ValueKind = VK_RValue;
John McCall2d2e8702011-04-11 07:02:50 +000011461
11462 // - variables
Richard Trieu10162ab2011-09-09 03:59:41 +000011463 } else if (isa<VarDecl>(VD)) {
11464 if (const ReferenceType *RefTy = Type->getAs<ReferenceType>()) {
11465 Type = RefTy->getPointeeType();
11466 } else if (Type->isFunctionType()) {
11467 S.Diag(E->getExprLoc(), diag::err_unknown_any_var_function_type)
11468 << VD << E->getSourceRange();
John McCall2979fe02011-04-12 00:42:48 +000011469 return ExprError();
John McCall2d2e8702011-04-11 07:02:50 +000011470 }
11471
11472 // - nothing else
11473 } else {
Richard Trieu10162ab2011-09-09 03:59:41 +000011474 S.Diag(E->getExprLoc(), diag::err_unsupported_unknown_any_decl)
11475 << VD << E->getSourceRange();
John McCall2d2e8702011-04-11 07:02:50 +000011476 return ExprError();
11477 }
11478
Richard Trieu10162ab2011-09-09 03:59:41 +000011479 VD->setType(DestType);
11480 E->setType(Type);
11481 E->setValueKind(ValueKind);
11482 return S.Owned(E);
John McCall2d2e8702011-04-11 07:02:50 +000011483}
11484
John McCall31996342011-04-07 08:22:57 +000011485/// Check a cast of an unknown-any type. We intentionally only
11486/// trigger this for C-style casts.
Richard Trieuba63ce62011-09-09 01:45:06 +000011487ExprResult Sema::checkUnknownAnyCast(SourceRange TypeRange, QualType CastType,
11488 Expr *CastExpr, CastKind &CastKind,
11489 ExprValueKind &VK, CXXCastPath &Path) {
John McCall31996342011-04-07 08:22:57 +000011490 // Rewrite the casted expression from scratch.
Richard Trieuba63ce62011-09-09 01:45:06 +000011491 ExprResult result = RebuildUnknownAnyExpr(*this, CastType).Visit(CastExpr);
John McCall39439732011-04-09 22:50:59 +000011492 if (!result.isUsable()) return ExprError();
John McCall31996342011-04-07 08:22:57 +000011493
Richard Trieuba63ce62011-09-09 01:45:06 +000011494 CastExpr = result.take();
11495 VK = CastExpr->getValueKind();
11496 CastKind = CK_NoOp;
John McCall39439732011-04-09 22:50:59 +000011497
Richard Trieuba63ce62011-09-09 01:45:06 +000011498 return CastExpr;
John McCall31996342011-04-07 08:22:57 +000011499}
11500
Douglas Gregord8fb1e32011-12-01 01:37:36 +000011501ExprResult Sema::forceUnknownAnyToType(Expr *E, QualType ToType) {
11502 return RebuildUnknownAnyExpr(*this, ToType).Visit(E);
11503}
11504
Richard Trieuba63ce62011-09-09 01:45:06 +000011505static ExprResult diagnoseUnknownAnyExpr(Sema &S, Expr *E) {
11506 Expr *orig = E;
John McCall2d2e8702011-04-11 07:02:50 +000011507 unsigned diagID = diag::err_uncasted_use_of_unknown_any;
John McCall31996342011-04-07 08:22:57 +000011508 while (true) {
Richard Trieuba63ce62011-09-09 01:45:06 +000011509 E = E->IgnoreParenImpCasts();
11510 if (CallExpr *call = dyn_cast<CallExpr>(E)) {
11511 E = call->getCallee();
John McCall2d2e8702011-04-11 07:02:50 +000011512 diagID = diag::err_uncasted_call_of_unknown_any;
11513 } else {
John McCall31996342011-04-07 08:22:57 +000011514 break;
John McCall2d2e8702011-04-11 07:02:50 +000011515 }
John McCall31996342011-04-07 08:22:57 +000011516 }
11517
John McCall2d2e8702011-04-11 07:02:50 +000011518 SourceLocation loc;
11519 NamedDecl *d;
Richard Trieuba63ce62011-09-09 01:45:06 +000011520 if (DeclRefExpr *ref = dyn_cast<DeclRefExpr>(E)) {
John McCall2d2e8702011-04-11 07:02:50 +000011521 loc = ref->getLocation();
11522 d = ref->getDecl();
Richard Trieuba63ce62011-09-09 01:45:06 +000011523 } else if (MemberExpr *mem = dyn_cast<MemberExpr>(E)) {
John McCall2d2e8702011-04-11 07:02:50 +000011524 loc = mem->getMemberLoc();
11525 d = mem->getMemberDecl();
Richard Trieuba63ce62011-09-09 01:45:06 +000011526 } else if (ObjCMessageExpr *msg = dyn_cast<ObjCMessageExpr>(E)) {
John McCall2d2e8702011-04-11 07:02:50 +000011527 diagID = diag::err_uncasted_call_of_unknown_any;
Argyrios Kyrtzidisa6011e22011-10-03 06:36:51 +000011528 loc = msg->getSelectorStartLoc();
John McCall2d2e8702011-04-11 07:02:50 +000011529 d = msg->getMethodDecl();
John McCallfa6f5d62011-08-31 20:57:36 +000011530 if (!d) {
11531 S.Diag(loc, diag::err_uncasted_send_to_unknown_any_method)
11532 << static_cast<unsigned>(msg->isClassMessage()) << msg->getSelector()
11533 << orig->getSourceRange();
11534 return ExprError();
11535 }
John McCall2d2e8702011-04-11 07:02:50 +000011536 } else {
Richard Trieuba63ce62011-09-09 01:45:06 +000011537 S.Diag(E->getExprLoc(), diag::err_unsupported_unknown_any_expr)
11538 << E->getSourceRange();
John McCall2d2e8702011-04-11 07:02:50 +000011539 return ExprError();
11540 }
11541
11542 S.Diag(loc, diagID) << d << orig->getSourceRange();
John McCall31996342011-04-07 08:22:57 +000011543
11544 // Never recoverable.
11545 return ExprError();
11546}
11547
John McCall36e7fe32010-10-12 00:20:44 +000011548/// Check for operands with placeholder types and complain if found.
11549/// Returns true if there was an error and no recovery was possible.
John McCall3aef3d82011-04-10 19:13:55 +000011550ExprResult Sema::CheckPlaceholderExpr(Expr *E) {
John McCall4124c492011-10-17 18:40:02 +000011551 const BuiltinType *placeholderType = E->getType()->getAsPlaceholderType();
11552 if (!placeholderType) return Owned(E);
11553
11554 switch (placeholderType->getKind()) {
John McCall36e7fe32010-10-12 00:20:44 +000011555
John McCall31996342011-04-07 08:22:57 +000011556 // Overloaded expressions.
John McCall4124c492011-10-17 18:40:02 +000011557 case BuiltinType::Overload: {
John McCall50a2c2c2011-10-11 23:14:30 +000011558 // Try to resolve a single function template specialization.
11559 // This is obligatory.
11560 ExprResult result = Owned(E);
11561 if (ResolveAndFixSingleFunctionTemplateSpecialization(result, false)) {
11562 return result;
11563
11564 // If that failed, try to recover with a call.
11565 } else {
11566 tryToRecoverWithCall(result, PDiag(diag::err_ovl_unresolvable),
11567 /*complain*/ true);
11568 return result;
11569 }
11570 }
John McCall31996342011-04-07 08:22:57 +000011571
John McCall0009fcc2011-04-26 20:42:42 +000011572 // Bound member functions.
John McCall4124c492011-10-17 18:40:02 +000011573 case BuiltinType::BoundMember: {
John McCall50a2c2c2011-10-11 23:14:30 +000011574 ExprResult result = Owned(E);
11575 tryToRecoverWithCall(result, PDiag(diag::err_bound_member_function),
11576 /*complain*/ true);
11577 return result;
John McCall4124c492011-10-17 18:40:02 +000011578 }
11579
11580 // ARC unbridged casts.
11581 case BuiltinType::ARCUnbridgedCast: {
11582 Expr *realCast = stripARCUnbridgedCast(E);
11583 diagnoseARCUnbridgedCast(realCast);
11584 return Owned(realCast);
11585 }
John McCall0009fcc2011-04-26 20:42:42 +000011586
John McCall31996342011-04-07 08:22:57 +000011587 // Expressions of unknown type.
John McCall4124c492011-10-17 18:40:02 +000011588 case BuiltinType::UnknownAny:
John McCall31996342011-04-07 08:22:57 +000011589 return diagnoseUnknownAnyExpr(*this, E);
11590
John McCall526ab472011-10-25 17:37:35 +000011591 // Pseudo-objects.
11592 case BuiltinType::PseudoObject:
11593 return checkPseudoObjectRValue(E);
11594
John McCalle314e272011-10-18 21:02:43 +000011595 // Everything else should be impossible.
11596#define BUILTIN_TYPE(Id, SingletonId) \
11597 case BuiltinType::Id:
11598#define PLACEHOLDER_TYPE(Id, SingletonId)
11599#include "clang/AST/BuiltinTypes.def"
John McCall4124c492011-10-17 18:40:02 +000011600 break;
11601 }
11602
11603 llvm_unreachable("invalid placeholder type!");
John McCall36e7fe32010-10-12 00:20:44 +000011604}
Richard Trieu2c850c02011-04-21 21:44:26 +000011605
Richard Trieuba63ce62011-09-09 01:45:06 +000011606bool Sema::CheckCaseExpression(Expr *E) {
11607 if (E->isTypeDependent())
Richard Trieu2c850c02011-04-21 21:44:26 +000011608 return true;
Richard Trieuba63ce62011-09-09 01:45:06 +000011609 if (E->isValueDependent() || E->isIntegerConstantExpr(Context))
11610 return E->getType()->isIntegralOrEnumerationType();
Richard Trieu2c850c02011-04-21 21:44:26 +000011611 return false;
11612}
Ted Kremeneke65b0862012-03-06 20:05:56 +000011613
11614/// ActOnObjCBoolLiteral - Parse {__objc_yes,__objc_no} literals.
11615ExprResult
11616Sema::ActOnObjCBoolLiteral(SourceLocation OpLoc, tok::TokenKind Kind) {
11617 assert((Kind == tok::kw___objc_yes || Kind == tok::kw___objc_no) &&
11618 "Unknown Objective-C Boolean value!");
11619 return Owned(new (Context) ObjCBoolLiteralExpr(Kind == tok::kw___objc_yes,
Fariborz Jahanian29898f42012-04-16 21:03:30 +000011620 Context.ObjCBuiltinBoolTy, OpLoc));
Ted Kremeneke65b0862012-03-06 20:05:56 +000011621}