blob: a67d5c6bd09a63e27d67bb35da4fcd43803daeae [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
Fariborz Jahanian66c93f42012-09-06 16:43:18 +000069static void DiagnoseUnusedOfDecl(Sema &S, NamedDecl *D, SourceLocation Loc) {
70 // Warn if this is used but marked unused.
71 if (D->hasAttr<UnusedAttr>()) {
72 const Decl *DC = cast<Decl>(S.getCurLexicalContext());
73 // A category implicitly has the availability of the interface.
74 if (const ObjCCategoryDecl *CatD = dyn_cast<ObjCCategoryDecl>(DC))
75 DC = CatD->getClassInterface();
76 if (!DC->hasAttr<UnusedAttr>())
77 S.Diag(Loc, diag::warn_used_but_marked_unused) << D->getDeclName();
78 }
79}
80
Ted Kremenek6eb25622012-02-10 02:45:47 +000081static AvailabilityResult DiagnoseAvailabilityOfDecl(Sema &S,
Fariborz Jahanian6b854c52011-09-29 22:45:21 +000082 NamedDecl *D, SourceLocation Loc,
83 const ObjCInterfaceDecl *UnknownObjCClass) {
84 // See if this declaration is unavailable or deprecated.
85 std::string Message;
86 AvailabilityResult Result = D->getAvailability(&Message);
Fariborz Jahanian25d09c22011-11-28 19:45:58 +000087 if (const EnumConstantDecl *ECD = dyn_cast<EnumConstantDecl>(D))
88 if (Result == AR_Available) {
89 const DeclContext *DC = ECD->getDeclContext();
90 if (const EnumDecl *TheEnumDecl = dyn_cast<EnumDecl>(DC))
91 Result = TheEnumDecl->getAvailability(&Message);
92 }
93
Fariborz Jahanian6b854c52011-09-29 22:45:21 +000094 switch (Result) {
95 case AR_Available:
96 case AR_NotYetIntroduced:
97 break;
98
99 case AR_Deprecated:
Ted Kremenek6eb25622012-02-10 02:45:47 +0000100 S.EmitDeprecationWarning(D, Message, Loc, UnknownObjCClass);
Fariborz Jahanian6b854c52011-09-29 22:45:21 +0000101 break;
102
103 case AR_Unavailable:
Ted Kremenek6eb25622012-02-10 02:45:47 +0000104 if (S.getCurContextAvailability() != AR_Unavailable) {
Fariborz Jahanian6b854c52011-09-29 22:45:21 +0000105 if (Message.empty()) {
106 if (!UnknownObjCClass)
Ted Kremenek6eb25622012-02-10 02:45:47 +0000107 S.Diag(Loc, diag::err_unavailable) << D->getDeclName();
Fariborz Jahanian6b854c52011-09-29 22:45:21 +0000108 else
Ted Kremenek6eb25622012-02-10 02:45:47 +0000109 S.Diag(Loc, diag::warn_unavailable_fwdclass_message)
Fariborz Jahanian6b854c52011-09-29 22:45:21 +0000110 << D->getDeclName();
111 }
112 else
Ted Kremenek6eb25622012-02-10 02:45:47 +0000113 S.Diag(Loc, diag::err_unavailable_message)
Fariborz Jahanian6b854c52011-09-29 22:45:21 +0000114 << D->getDeclName() << Message;
Ted Kremenek6eb25622012-02-10 02:45:47 +0000115 S.Diag(D->getLocation(), diag::note_unavailable_here)
Fariborz Jahanian6b854c52011-09-29 22:45:21 +0000116 << isa<FunctionDecl>(D) << false;
117 }
118 break;
119 }
120 return Result;
121}
122
Richard Smith852265f2012-03-30 20:53:28 +0000123/// \brief Emit a note explaining that this function is deleted or unavailable.
124void Sema::NoteDeletedFunction(FunctionDecl *Decl) {
125 CXXMethodDecl *Method = dyn_cast<CXXMethodDecl>(Decl);
126
Richard Smith6f1e2c62012-04-02 20:59:25 +0000127 if (Method && Method->isDeleted() && !Method->isDeletedAsWritten()) {
128 // If the method was explicitly defaulted, point at that declaration.
129 if (!Method->isImplicit())
130 Diag(Decl->getLocation(), diag::note_implicitly_deleted);
131
132 // Try to diagnose why this special member function was implicitly
133 // deleted. This might fail, if that reason no longer applies.
Richard Smith852265f2012-03-30 20:53:28 +0000134 CXXSpecialMember CSM = getSpecialMember(Method);
Richard Smith6f1e2c62012-04-02 20:59:25 +0000135 if (CSM != CXXInvalid)
136 ShouldDeleteSpecialMember(Method, CSM, /*Diagnose=*/true);
137
138 return;
Richard Smith852265f2012-03-30 20:53:28 +0000139 }
140
141 Diag(Decl->getLocation(), diag::note_unavailable_here)
142 << 1 << Decl->isDeleted();
143}
144
Jordan Rose28cd12f2012-06-18 22:09:19 +0000145/// \brief Determine whether a FunctionDecl was ever declared with an
146/// explicit storage class.
147static bool hasAnyExplicitStorageClass(const FunctionDecl *D) {
148 for (FunctionDecl::redecl_iterator I = D->redecls_begin(),
149 E = D->redecls_end();
150 I != E; ++I) {
151 if (I->getStorageClassAsWritten() != SC_None)
152 return true;
153 }
154 return false;
155}
156
157/// \brief Check whether we're in an extern inline function and referring to a
Jordan Rosede9e9762012-06-20 18:50:06 +0000158/// variable or function with internal linkage (C11 6.7.4p3).
Jordan Rose28cd12f2012-06-18 22:09:19 +0000159///
Jordan Rose28cd12f2012-06-18 22:09:19 +0000160/// This is only a warning because we used to silently accept this code, but
Jordan Rosede9e9762012-06-20 18:50:06 +0000161/// in many cases it will not behave correctly. This is not enabled in C++ mode
162/// because the restriction language is a bit weaker (C++11 [basic.def.odr]p6)
163/// and so while there may still be user mistakes, most of the time we can't
164/// prove that there are errors.
Jordan Rose28cd12f2012-06-18 22:09:19 +0000165static void diagnoseUseOfInternalDeclInInlineFunction(Sema &S,
166 const NamedDecl *D,
167 SourceLocation Loc) {
Jordan Rosede9e9762012-06-20 18:50:06 +0000168 // This is disabled under C++; there are too many ways for this to fire in
169 // contexts where the warning is a false positive, or where it is technically
170 // correct but benign.
171 if (S.getLangOpts().CPlusPlus)
172 return;
Jordan Rose28cd12f2012-06-18 22:09:19 +0000173
174 // Check if this is an inlined function or method.
175 FunctionDecl *Current = S.getCurFunctionDecl();
176 if (!Current)
177 return;
178 if (!Current->isInlined())
179 return;
180 if (Current->getLinkage() != ExternalLinkage)
181 return;
182
183 // Check if the decl has internal linkage.
Jordan Rosede9e9762012-06-20 18:50:06 +0000184 if (D->getLinkage() != InternalLinkage)
Jordan Rose28cd12f2012-06-18 22:09:19 +0000185 return;
Jordan Rose28cd12f2012-06-18 22:09:19 +0000186
Jordan Rose815fe262012-06-21 05:54:50 +0000187 // Downgrade from ExtWarn to Extension if
188 // (1) the supposedly external inline function is in the main file,
189 // and probably won't be included anywhere else.
190 // (2) the thing we're referencing is a pure function.
191 // (3) the thing we're referencing is another inline function.
192 // This last can give us false negatives, but it's better than warning on
193 // wrappers for simple C library functions.
194 const FunctionDecl *UsedFn = dyn_cast<FunctionDecl>(D);
195 bool DowngradeWarning = S.getSourceManager().isFromMainFile(Loc);
196 if (!DowngradeWarning && UsedFn)
197 DowngradeWarning = UsedFn->isInlined() || UsedFn->hasAttr<ConstAttr>();
198
199 S.Diag(Loc, DowngradeWarning ? diag::ext_internal_in_extern_inline
200 : diag::warn_internal_in_extern_inline)
201 << /*IsVar=*/!UsedFn << D;
Jordan Rose28cd12f2012-06-18 22:09:19 +0000202
203 // Suggest "static" on the inline function, if possible.
Jordan Rosede9e9762012-06-20 18:50:06 +0000204 if (!hasAnyExplicitStorageClass(Current)) {
Jordan Rose28cd12f2012-06-18 22:09:19 +0000205 const FunctionDecl *FirstDecl = Current->getCanonicalDecl();
206 SourceLocation DeclBegin = FirstDecl->getSourceRange().getBegin();
207 S.Diag(DeclBegin, diag::note_convert_inline_to_static)
208 << Current << FixItHint::CreateInsertion(DeclBegin, "static ");
209 }
210
211 S.Diag(D->getCanonicalDecl()->getLocation(),
212 diag::note_internal_decl_declared_here)
213 << D;
214}
215
Douglas Gregor171c45a2009-02-18 21:56:37 +0000216/// \brief Determine whether the use of this declaration is valid, and
217/// emit any corresponding diagnostics.
218///
219/// This routine diagnoses various problems with referencing
220/// declarations that can occur when using a declaration. For example,
221/// it might warn if a deprecated or unavailable declaration is being
222/// used, or produce an error (and return true) if a C++0x deleted
223/// function is being used.
224///
225/// \returns true if there was an error (this declaration cannot be
226/// referenced), false otherwise.
Chris Lattnerb7df3c62009-10-25 22:31:57 +0000227///
Fariborz Jahanian7d6e11a2010-12-21 00:44:01 +0000228bool Sema::DiagnoseUseOfDecl(NamedDecl *D, SourceLocation Loc,
Fariborz Jahanian6b854c52011-09-29 22:45:21 +0000229 const ObjCInterfaceDecl *UnknownObjCClass) {
David Blaikiebbafb8a2012-03-11 07:00:24 +0000230 if (getLangOpts().CPlusPlus && isa<FunctionDecl>(D)) {
Douglas Gregor5bb5e4a2010-10-12 23:32:35 +0000231 // If there were any diagnostics suppressed by template argument deduction,
232 // emit them now.
Chris Lattner0e62c1c2011-07-23 10:55:15 +0000233 llvm::DenseMap<Decl *, SmallVector<PartialDiagnosticAt, 1> >::iterator
Douglas Gregor5bb5e4a2010-10-12 23:32:35 +0000234 Pos = SuppressedDiagnostics.find(D->getCanonicalDecl());
235 if (Pos != SuppressedDiagnostics.end()) {
Chris Lattner0e62c1c2011-07-23 10:55:15 +0000236 SmallVectorImpl<PartialDiagnosticAt> &Suppressed = Pos->second;
Douglas Gregor5bb5e4a2010-10-12 23:32:35 +0000237 for (unsigned I = 0, N = Suppressed.size(); I != N; ++I)
238 Diag(Suppressed[I].first, Suppressed[I].second);
239
240 // Clear out the list of suppressed diagnostics, so that we don't emit
Douglas Gregor20b2ebd2011-03-23 00:50:03 +0000241 // them again for this specialization. However, we don't obsolete this
Douglas Gregor5bb5e4a2010-10-12 23:32:35 +0000242 // entry from the table, because we want to avoid ever emitting these
243 // diagnostics again.
244 Suppressed.clear();
245 }
246 }
247
Richard Smith30482bc2011-02-20 03:19:35 +0000248 // See if this is an auto-typed variable whose initializer we are parsing.
Richard Smithb2bc2e62011-02-21 20:05:19 +0000249 if (ParsingInitForAutoVars.count(D)) {
250 Diag(Loc, diag::err_auto_variable_cannot_appear_in_own_initializer)
251 << D->getDeclName();
252 return true;
Richard Smith30482bc2011-02-20 03:19:35 +0000253 }
254
Douglas Gregor171c45a2009-02-18 21:56:37 +0000255 // See if this is a deleted function.
Douglas Gregorde681d42009-02-24 04:26:15 +0000256 if (FunctionDecl *FD = dyn_cast<FunctionDecl>(D)) {
Douglas Gregor171c45a2009-02-18 21:56:37 +0000257 if (FD->isDeleted()) {
258 Diag(Loc, diag::err_deleted_function_use);
Richard Smith852265f2012-03-30 20:53:28 +0000259 NoteDeletedFunction(FD);
Douglas Gregor171c45a2009-02-18 21:56:37 +0000260 return true;
261 }
Douglas Gregorde681d42009-02-24 04:26:15 +0000262 }
Ted Kremenek6eb25622012-02-10 02:45:47 +0000263 DiagnoseAvailabilityOfDecl(*this, D, Loc, UnknownObjCClass);
Douglas Gregor20b2ebd2011-03-23 00:50:03 +0000264
Fariborz Jahanian66c93f42012-09-06 16:43:18 +0000265 DiagnoseUnusedOfDecl(*this, D, Loc);
Jordan Rose2684c682012-06-15 18:19:48 +0000266
Jordan Rose28cd12f2012-06-18 22:09:19 +0000267 diagnoseUseOfInternalDeclInInlineFunction(*this, D, Loc);
Jordan Rose2684c682012-06-15 18:19:48 +0000268
Douglas Gregor171c45a2009-02-18 21:56:37 +0000269 return false;
Chris Lattner4bf74fd2009-02-15 22:43:40 +0000270}
271
Douglas Gregor20b2ebd2011-03-23 00:50:03 +0000272/// \brief Retrieve the message suffix that should be added to a
273/// diagnostic complaining about the given function being deleted or
274/// unavailable.
275std::string Sema::getDeletedOrUnavailableSuffix(const FunctionDecl *FD) {
276 // FIXME: C++0x implicitly-deleted special member functions could be
277 // detected here so that we could improve diagnostics to say, e.g.,
278 // "base class 'A' had a deleted copy constructor".
279 if (FD->isDeleted())
280 return std::string();
281
282 std::string Message;
283 if (FD->getAvailability(&Message))
284 return ": " + Message;
285
286 return std::string();
287}
288
John McCallb46f2872011-09-09 07:56:05 +0000289/// DiagnoseSentinelCalls - This routine checks whether a call or
290/// message-send is to a declaration with the sentinel attribute, and
291/// if so, it checks that the requirements of the sentinel are
292/// satisfied.
Fariborz Jahanian027b8862009-05-13 18:09:35 +0000293void Sema::DiagnoseSentinelCalls(NamedDecl *D, SourceLocation Loc,
John McCallb46f2872011-09-09 07:56:05 +0000294 Expr **args, unsigned numArgs) {
Argyrios Kyrtzidisb4b64ca2009-06-30 02:34:44 +0000295 const SentinelAttr *attr = D->getAttr<SentinelAttr>();
Mike Stump11289f42009-09-09 15:08:12 +0000296 if (!attr)
Fariborz Jahanian9e877212009-05-13 23:20:50 +0000297 return;
Douglas Gregorc298ffc2010-04-22 16:44:27 +0000298
John McCallb46f2872011-09-09 07:56:05 +0000299 // The number of formal parameters of the declaration.
300 unsigned numFormalParams;
Mike Stump11289f42009-09-09 15:08:12 +0000301
John McCallb46f2872011-09-09 07:56:05 +0000302 // The kind of declaration. This is also an index into a %select in
303 // the diagnostic.
304 enum CalleeType { CT_Function, CT_Method, CT_Block } calleeType;
305
Fariborz Jahanian4a528032009-05-14 18:00:00 +0000306 if (ObjCMethodDecl *MD = dyn_cast<ObjCMethodDecl>(D)) {
John McCallb46f2872011-09-09 07:56:05 +0000307 numFormalParams = MD->param_size();
308 calleeType = CT_Method;
Mike Stump12b8ce12009-08-04 21:02:39 +0000309 } else if (FunctionDecl *FD = dyn_cast<FunctionDecl>(D)) {
John McCallb46f2872011-09-09 07:56:05 +0000310 numFormalParams = FD->param_size();
311 calleeType = CT_Function;
312 } else if (isa<VarDecl>(D)) {
313 QualType type = cast<ValueDecl>(D)->getType();
314 const FunctionType *fn = 0;
315 if (const PointerType *ptr = type->getAs<PointerType>()) {
316 fn = ptr->getPointeeType()->getAs<FunctionType>();
317 if (!fn) return;
318 calleeType = CT_Function;
319 } else if (const BlockPointerType *ptr = type->getAs<BlockPointerType>()) {
320 fn = ptr->getPointeeType()->castAs<FunctionType>();
321 calleeType = CT_Block;
322 } else {
Fariborz Jahanian0aa5c452009-05-15 20:33:25 +0000323 return;
John McCallb46f2872011-09-09 07:56:05 +0000324 }
Fariborz Jahanian4a528032009-05-14 18:00:00 +0000325
John McCallb46f2872011-09-09 07:56:05 +0000326 if (const FunctionProtoType *proto = dyn_cast<FunctionProtoType>(fn)) {
327 numFormalParams = proto->getNumArgs();
328 } else {
329 numFormalParams = 0;
330 }
331 } else {
Fariborz Jahanian9e877212009-05-13 23:20:50 +0000332 return;
333 }
John McCallb46f2872011-09-09 07:56:05 +0000334
335 // "nullPos" is the number of formal parameters at the end which
336 // effectively count as part of the variadic arguments. This is
337 // useful if you would prefer to not have *any* formal parameters,
338 // but the language forces you to have at least one.
339 unsigned nullPos = attr->getNullPos();
340 assert((nullPos == 0 || nullPos == 1) && "invalid null position on sentinel");
341 numFormalParams = (nullPos > numFormalParams ? 0 : numFormalParams - nullPos);
342
343 // The number of arguments which should follow the sentinel.
344 unsigned numArgsAfterSentinel = attr->getSentinel();
345
346 // If there aren't enough arguments for all the formal parameters,
347 // the sentinel, and the args after the sentinel, complain.
348 if (numArgs < numFormalParams + numArgsAfterSentinel + 1) {
Fariborz Jahanian9e877212009-05-13 23:20:50 +0000349 Diag(Loc, diag::warn_not_enough_argument) << D->getDeclName();
John McCallb46f2872011-09-09 07:56:05 +0000350 Diag(D->getLocation(), diag::note_sentinel_here) << calleeType;
Fariborz Jahanian9e877212009-05-13 23:20:50 +0000351 return;
352 }
John McCallb46f2872011-09-09 07:56:05 +0000353
354 // Otherwise, find the sentinel expression.
355 Expr *sentinelExpr = args[numArgs - numArgsAfterSentinel - 1];
John McCall7ddbcf42010-05-06 23:53:00 +0000356 if (!sentinelExpr) return;
John McCall7ddbcf42010-05-06 23:53:00 +0000357 if (sentinelExpr->isValueDependent()) return;
Argyrios Kyrtzidis2e809ce2012-02-03 05:58:16 +0000358 if (Context.isSentinelNullExpr(sentinelExpr)) return;
John McCall7ddbcf42010-05-06 23:53:00 +0000359
John McCallb46f2872011-09-09 07:56:05 +0000360 // Pick a reasonable string to insert. Optimistically use 'nil' or
361 // 'NULL' if those are actually defined in the context. Only use
362 // 'nil' for ObjC methods, where it's much more likely that the
363 // variadic arguments form a list of object pointers.
364 SourceLocation MissingNilLoc
Douglas Gregor5ff4e982011-07-30 08:57:03 +0000365 = PP.getLocForEndOfToken(sentinelExpr->getLocEnd());
366 std::string NullValue;
John McCallb46f2872011-09-09 07:56:05 +0000367 if (calleeType == CT_Method &&
368 PP.getIdentifierInfo("nil")->hasMacroDefinition())
Douglas Gregor5ff4e982011-07-30 08:57:03 +0000369 NullValue = "nil";
370 else if (PP.getIdentifierInfo("NULL")->hasMacroDefinition())
371 NullValue = "NULL";
Douglas Gregor5ff4e982011-07-30 08:57:03 +0000372 else
John McCallb46f2872011-09-09 07:56:05 +0000373 NullValue = "(void*) 0";
Eli Friedman9ab36372011-09-27 23:46:37 +0000374
375 if (MissingNilLoc.isInvalid())
376 Diag(Loc, diag::warn_missing_sentinel) << calleeType;
377 else
378 Diag(MissingNilLoc, diag::warn_missing_sentinel)
379 << calleeType
380 << FixItHint::CreateInsertion(MissingNilLoc, ", " + NullValue);
John McCallb46f2872011-09-09 07:56:05 +0000381 Diag(D->getLocation(), diag::note_sentinel_here) << calleeType;
Fariborz Jahanian027b8862009-05-13 18:09:35 +0000382}
383
Richard Trieuba63ce62011-09-09 01:45:06 +0000384SourceRange Sema::getExprRange(Expr *E) const {
385 return E ? E->getSourceRange() : SourceRange();
Douglas Gregor87f95b02009-02-26 21:00:50 +0000386}
387
Chris Lattner513165e2008-07-25 21:10:04 +0000388//===----------------------------------------------------------------------===//
389// Standard Promotions and Conversions
390//===----------------------------------------------------------------------===//
391
Chris Lattner513165e2008-07-25 21:10:04 +0000392/// DefaultFunctionArrayConversion (C99 6.3.2.1p3, C99 6.3.2.1p4).
John Wiegley01296292011-04-08 18:41:53 +0000393ExprResult Sema::DefaultFunctionArrayConversion(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
Chris Lattner513165e2008-07-25 21:10:04 +0000401 QualType Ty = E->getType();
402 assert(!Ty.isNull() && "DefaultFunctionArrayConversion - missing type");
403
Chris Lattner513165e2008-07-25 21:10:04 +0000404 if (Ty->isFunctionType())
John Wiegley01296292011-04-08 18:41:53 +0000405 E = ImpCastExprToType(E, Context.getPointerType(Ty),
406 CK_FunctionToPointerDecay).take();
Chris Lattner61f60a02008-07-25 21:33:13 +0000407 else if (Ty->isArrayType()) {
408 // In C90 mode, arrays only promote to pointers if the array expression is
409 // an lvalue. The relevant legalese is C90 6.2.2.1p3: "an lvalue that has
410 // type 'array of type' is converted to an expression that has type 'pointer
411 // to type'...". In C99 this was changed to: C99 6.3.2.1p3: "an expression
412 // that has type 'array of type' ...". The relevant change is "an lvalue"
413 // (C90) to "an expression" (C99).
Argyrios Kyrtzidis9321c742008-09-11 04:25:59 +0000414 //
415 // C++ 4.2p1:
416 // An lvalue or rvalue of type "array of N T" or "array of unknown bound of
417 // T" can be converted to an rvalue of type "pointer to T".
418 //
David Blaikiebbafb8a2012-03-11 07:00:24 +0000419 if (getLangOpts().C99 || getLangOpts().CPlusPlus || E->isLValue())
John Wiegley01296292011-04-08 18:41:53 +0000420 E = ImpCastExprToType(E, Context.getArrayDecayedType(Ty),
421 CK_ArrayToPointerDecay).take();
Chris Lattner61f60a02008-07-25 21:33:13 +0000422 }
John Wiegley01296292011-04-08 18:41:53 +0000423 return Owned(E);
Chris Lattner513165e2008-07-25 21:10:04 +0000424}
425
Argyrios Kyrtzidisa9b630e2011-04-26 17:41:22 +0000426static void CheckForNullPointerDereference(Sema &S, Expr *E) {
427 // Check to see if we are dereferencing a null pointer. If so,
428 // and if not volatile-qualified, this is undefined behavior that the
429 // optimizer will delete, so warn about it. People sometimes try to use this
430 // to get a deterministic trap and are surprised by clang's behavior. This
431 // only handles the pattern "*null", which is a very syntactic check.
432 if (UnaryOperator *UO = dyn_cast<UnaryOperator>(E->IgnoreParenCasts()))
433 if (UO->getOpcode() == UO_Deref &&
434 UO->getSubExpr()->IgnoreParenCasts()->
435 isNullPointerConstant(S.Context, Expr::NPC_ValueDependentIsNotNull) &&
436 !UO->getType().isVolatileQualified()) {
437 S.DiagRuntimeBehavior(UO->getOperatorLoc(), UO,
438 S.PDiag(diag::warn_indirection_through_null)
439 << UO->getSubExpr()->getSourceRange());
440 S.DiagRuntimeBehavior(UO->getOperatorLoc(), UO,
441 S.PDiag(diag::note_indirection_through_null));
442 }
443}
444
John Wiegley01296292011-04-08 18:41:53 +0000445ExprResult Sema::DefaultLvalueConversion(Expr *E) {
John McCall50a2c2c2011-10-11 23:14:30 +0000446 // Handle any placeholder expressions which made it here.
447 if (E->getType()->isPlaceholderType()) {
448 ExprResult result = CheckPlaceholderExpr(E);
449 if (result.isInvalid()) return ExprError();
450 E = result.take();
451 }
452
John McCallf3735e02010-12-01 04:43:34 +0000453 // C++ [conv.lval]p1:
454 // A glvalue of a non-function, non-array type T can be
455 // converted to a prvalue.
John Wiegley01296292011-04-08 18:41:53 +0000456 if (!E->isGLValue()) return Owned(E);
Kaelyn Uhrain2e7aa5a2011-08-05 23:18:04 +0000457
John McCall27584242010-12-06 20:48:59 +0000458 QualType T = E->getType();
459 assert(!T.isNull() && "r-value conversion on typeless expression?");
John McCall34376a62010-12-04 03:47:34 +0000460
John McCall27584242010-12-06 20:48:59 +0000461 // We don't want to throw lvalue-to-rvalue casts on top of
462 // expressions of certain types in C++.
David Blaikiebbafb8a2012-03-11 07:00:24 +0000463 if (getLangOpts().CPlusPlus &&
John McCall27584242010-12-06 20:48:59 +0000464 (E->getType() == Context.OverloadTy ||
465 T->isDependentType() ||
466 T->isRecordType()))
John Wiegley01296292011-04-08 18:41:53 +0000467 return Owned(E);
John McCall27584242010-12-06 20:48:59 +0000468
469 // The C standard is actually really unclear on this point, and
470 // DR106 tells us what the result should be but not why. It's
471 // generally best to say that void types just doesn't undergo
472 // lvalue-to-rvalue at all. Note that expressions of unqualified
473 // 'void' type are never l-values, but qualified void can be.
474 if (T->isVoidType())
John Wiegley01296292011-04-08 18:41:53 +0000475 return Owned(E);
John McCall27584242010-12-06 20:48:59 +0000476
Argyrios Kyrtzidisa9b630e2011-04-26 17:41:22 +0000477 CheckForNullPointerDereference(*this, E);
478
John McCall27584242010-12-06 20:48:59 +0000479 // C++ [conv.lval]p1:
480 // [...] If T is a non-class type, the type of the prvalue is the
481 // cv-unqualified version of T. Otherwise, the type of the
482 // rvalue is T.
483 //
484 // C99 6.3.2.1p2:
485 // If the lvalue has qualified type, the value has the unqualified
486 // version of the type of the lvalue; otherwise, the value has the
Anton Korobeynikovf0c267e2011-10-14 23:23:15 +0000487 // type of the lvalue.
John McCall27584242010-12-06 20:48:59 +0000488 if (T.hasQualifiers())
489 T = T.getUnqualifiedType();
Anton Korobeynikovf0c267e2011-10-14 23:23:15 +0000490
Eli Friedman3bda6b12012-02-02 23:15:15 +0000491 UpdateMarkingForLValueToRValue(E);
492
Anton Korobeynikovf0c267e2011-10-14 23:23:15 +0000493 ExprResult Res = Owned(ImplicitCastExpr::Create(Context, T, CK_LValueToRValue,
494 E, 0, VK_RValue));
495
Douglas Gregorc79862f2012-04-12 17:51:55 +0000496 // C11 6.3.2.1p2:
497 // ... if the lvalue has atomic type, the value has the non-atomic version
498 // of the type of the lvalue ...
499 if (const AtomicType *Atomic = T->getAs<AtomicType>()) {
500 T = Atomic->getValueType().getUnqualifiedType();
501 Res = Owned(ImplicitCastExpr::Create(Context, T, CK_AtomicToNonAtomic,
502 Res.get(), 0, VK_RValue));
503 }
504
Anton Korobeynikovf0c267e2011-10-14 23:23:15 +0000505 return Res;
John McCall27584242010-12-06 20:48:59 +0000506}
507
John Wiegley01296292011-04-08 18:41:53 +0000508ExprResult Sema::DefaultFunctionArrayLvalueConversion(Expr *E) {
509 ExprResult Res = DefaultFunctionArrayConversion(E);
510 if (Res.isInvalid())
511 return ExprError();
512 Res = DefaultLvalueConversion(Res.take());
513 if (Res.isInvalid())
514 return ExprError();
Benjamin Kramer62b95d82012-08-23 21:35:17 +0000515 return Res;
Douglas Gregorb92a1562010-02-03 00:27:59 +0000516}
517
518
Chris Lattner513165e2008-07-25 21:10:04 +0000519/// UsualUnaryConversions - Performs various conversions that are common to most
Mike Stump11289f42009-09-09 15:08:12 +0000520/// operators (C99 6.3). The conversions of array and function types are
Chris Lattner57540c52011-04-15 05:22:18 +0000521/// sometimes suppressed. For example, the array->pointer conversion doesn't
Chris Lattner513165e2008-07-25 21:10:04 +0000522/// apply if the array is an argument to the sizeof or address (&) operators.
523/// In these instances, this routine should *not* be called.
John Wiegley01296292011-04-08 18:41:53 +0000524ExprResult Sema::UsualUnaryConversions(Expr *E) {
John McCallf3735e02010-12-01 04:43:34 +0000525 // First, convert to an r-value.
John Wiegley01296292011-04-08 18:41:53 +0000526 ExprResult Res = DefaultFunctionArrayLvalueConversion(E);
527 if (Res.isInvalid())
528 return Owned(E);
529 E = Res.take();
Anton Korobeynikovf0c267e2011-10-14 23:23:15 +0000530
John McCallf3735e02010-12-01 04:43:34 +0000531 QualType Ty = E->getType();
Chris Lattner513165e2008-07-25 21:10:04 +0000532 assert(!Ty.isNull() && "UsualUnaryConversions - missing type");
Anton Korobeynikovf0c267e2011-10-14 23:23:15 +0000533
534 // Half FP is a bit different: it's a storage-only type, meaning that any
535 // "use" of it should be promoted to float.
536 if (Ty->isHalfType())
537 return ImpCastExprToType(Res.take(), Context.FloatTy, CK_FloatingCast);
538
John McCallf3735e02010-12-01 04:43:34 +0000539 // Try to perform integral promotions if the object has a theoretically
540 // promotable type.
541 if (Ty->isIntegralOrUnscopedEnumerationType()) {
542 // C99 6.3.1.1p2:
543 //
544 // The following may be used in an expression wherever an int or
545 // unsigned int may be used:
546 // - an object or expression with an integer type whose integer
547 // conversion rank is less than or equal to the rank of int
548 // and unsigned int.
549 // - A bit-field of type _Bool, int, signed int, or unsigned int.
550 //
551 // If an int can represent all values of the original type, the
552 // value is converted to an int; otherwise, it is converted to an
553 // unsigned int. These are called the integer promotions. All
554 // other types are unchanged by the integer promotions.
Anton Korobeynikovf0c267e2011-10-14 23:23:15 +0000555
John McCallf3735e02010-12-01 04:43:34 +0000556 QualType PTy = Context.isPromotableBitField(E);
557 if (!PTy.isNull()) {
John Wiegley01296292011-04-08 18:41:53 +0000558 E = ImpCastExprToType(E, PTy, CK_IntegralCast).take();
559 return Owned(E);
John McCallf3735e02010-12-01 04:43:34 +0000560 }
561 if (Ty->isPromotableIntegerType()) {
562 QualType PT = Context.getPromotedIntegerType(Ty);
John Wiegley01296292011-04-08 18:41:53 +0000563 E = ImpCastExprToType(E, PT, CK_IntegralCast).take();
564 return Owned(E);
John McCallf3735e02010-12-01 04:43:34 +0000565 }
Eli Friedman629ffb92009-08-20 04:21:42 +0000566 }
John Wiegley01296292011-04-08 18:41:53 +0000567 return Owned(E);
Chris Lattner513165e2008-07-25 21:10:04 +0000568}
569
Chris Lattner2ce500f2008-07-25 22:25:12 +0000570/// DefaultArgumentPromotion (C99 6.5.2.2p6). Used for function calls that
Mike Stump11289f42009-09-09 15:08:12 +0000571/// do not have a prototype. Arguments that have type float are promoted to
Chris Lattner2ce500f2008-07-25 22:25:12 +0000572/// double. All other argument types are converted by UsualUnaryConversions().
John Wiegley01296292011-04-08 18:41:53 +0000573ExprResult Sema::DefaultArgumentPromotion(Expr *E) {
574 QualType Ty = E->getType();
Chris Lattner2ce500f2008-07-25 22:25:12 +0000575 assert(!Ty.isNull() && "DefaultArgumentPromotion - missing type");
Mike Stump11289f42009-09-09 15:08:12 +0000576
John Wiegley01296292011-04-08 18:41:53 +0000577 ExprResult Res = UsualUnaryConversions(E);
578 if (Res.isInvalid())
579 return Owned(E);
580 E = Res.take();
John McCall9bc26772010-12-06 18:36:11 +0000581
Chris Lattner2ce500f2008-07-25 22:25:12 +0000582 // If this is a 'float' (CVR qualified or typedef) promote to double.
Chris Lattnerbb53efb2010-05-16 04:01:30 +0000583 if (Ty->isSpecificBuiltinType(BuiltinType::Float))
John Wiegley01296292011-04-08 18:41:53 +0000584 E = ImpCastExprToType(E, Context.DoubleTy, CK_FloatingCast).take();
585
John McCall4bb057d2011-08-27 22:06:17 +0000586 // C++ performs lvalue-to-rvalue conversion as a default argument
John McCall0562caa2011-08-29 23:55:37 +0000587 // promotion, even on class types, but note:
588 // C++11 [conv.lval]p2:
589 // When an lvalue-to-rvalue conversion occurs in an unevaluated
590 // operand or a subexpression thereof the value contained in the
591 // referenced object is not accessed. Otherwise, if the glvalue
592 // has a class type, the conversion copy-initializes a temporary
593 // of type T from the glvalue and the result of the conversion
594 // is a prvalue for the temporary.
Eli Friedman05e28012012-01-17 02:13:45 +0000595 // FIXME: add some way to gate this entire thing for correctness in
596 // potentially potentially evaluated contexts.
David Blaikie131fcb42012-08-06 22:47:24 +0000597 if (getLangOpts().CPlusPlus && E->isGLValue() && !isUnevaluatedContext()) {
Eli Friedman05e28012012-01-17 02:13:45 +0000598 ExprResult Temp = PerformCopyInitialization(
599 InitializedEntity::InitializeTemporary(E->getType()),
600 E->getExprLoc(),
601 Owned(E));
602 if (Temp.isInvalid())
603 return ExprError();
604 E = Temp.get();
John McCall29ad95b2011-08-27 01:09:30 +0000605 }
606
John Wiegley01296292011-04-08 18:41:53 +0000607 return Owned(E);
Chris Lattner2ce500f2008-07-25 22:25:12 +0000608}
609
Richard Smith55ce3522012-06-25 20:30:08 +0000610/// Determine the degree of POD-ness for an expression.
611/// Incomplete types are considered POD, since this check can be performed
612/// when we're in an unevaluated context.
613Sema::VarArgKind Sema::isValidVarArgType(const QualType &Ty) {
Jordan Rose3e0ec582012-07-19 18:10:23 +0000614 if (Ty->isIncompleteType()) {
615 if (Ty->isObjCObjectType())
616 return VAK_Invalid;
Richard Smith55ce3522012-06-25 20:30:08 +0000617 return VAK_Valid;
Jordan Rose3e0ec582012-07-19 18:10:23 +0000618 }
619
620 if (Ty.isCXX98PODType(Context))
621 return VAK_Valid;
622
Richard Smith55ce3522012-06-25 20:30:08 +0000623 // C++0x [expr.call]p7:
624 // Passing a potentially-evaluated argument of class type (Clause 9)
625 // having a non-trivial copy constructor, a non-trivial move constructor,
626 // or a non-trivial destructor, with no corresponding parameter,
627 // is conditionally-supported with implementation-defined semantics.
Richard Smith55ce3522012-06-25 20:30:08 +0000628 if (getLangOpts().CPlusPlus0x && !Ty->isDependentType())
629 if (CXXRecordDecl *Record = Ty->getAsCXXRecordDecl())
630 if (Record->hasTrivialCopyConstructor() &&
631 Record->hasTrivialMoveConstructor() &&
632 Record->hasTrivialDestructor())
633 return VAK_ValidInCXX11;
634
635 if (getLangOpts().ObjCAutoRefCount && Ty->isObjCLifetimeType())
636 return VAK_Valid;
637 return VAK_Invalid;
638}
639
640bool Sema::variadicArgumentPODCheck(const Expr *E, VariadicCallType CT) {
641 // Don't allow one to pass an Objective-C interface to a vararg.
642 const QualType & Ty = E->getType();
643
644 // Complain about passing non-POD types through varargs.
645 switch (isValidVarArgType(Ty)) {
646 case VAK_Valid:
647 break;
648 case VAK_ValidInCXX11:
649 DiagRuntimeBehavior(E->getLocStart(), 0,
650 PDiag(diag::warn_cxx98_compat_pass_non_pod_arg_to_vararg)
651 << E->getType() << CT);
652 break;
Jordan Rose3e0ec582012-07-19 18:10:23 +0000653 case VAK_Invalid: {
654 if (Ty->isObjCObjectType())
655 return DiagRuntimeBehavior(E->getLocStart(), 0,
656 PDiag(diag::err_cannot_pass_objc_interface_to_vararg)
657 << Ty << CT);
658
Richard Smith55ce3522012-06-25 20:30:08 +0000659 return DiagRuntimeBehavior(E->getLocStart(), 0,
660 PDiag(diag::warn_cannot_pass_non_pod_arg_to_vararg)
661 << getLangOpts().CPlusPlus0x << Ty << CT);
662 }
Jordan Rose3e0ec582012-07-19 18:10:23 +0000663 }
Richard Smith55ce3522012-06-25 20:30:08 +0000664 // c++ rules are enforced elsewhere.
665 return false;
666}
667
Chris Lattnera8a7d0f2009-04-12 08:11:20 +0000668/// DefaultVariadicArgumentPromotion - Like DefaultArgumentPromotion, but
Jordan Rose3e0ec582012-07-19 18:10:23 +0000669/// will create a trap if the resulting type is not a POD type.
John Wiegley01296292011-04-08 18:41:53 +0000670ExprResult Sema::DefaultVariadicArgumentPromotion(Expr *E, VariadicCallType CT,
John McCall31168b02011-06-15 23:02:42 +0000671 FunctionDecl *FDecl) {
Richard Smith7659b122012-06-27 20:29:39 +0000672 if (const BuiltinType *PlaceholderTy = E->getType()->getAsPlaceholderType()) {
John McCall4124c492011-10-17 18:40:02 +0000673 // Strip the unbridged-cast placeholder expression off, if applicable.
674 if (PlaceholderTy->getKind() == BuiltinType::ARCUnbridgedCast &&
675 (CT == VariadicMethod ||
676 (FDecl && FDecl->hasAttr<CFAuditedTransferAttr>()))) {
677 E = stripARCUnbridgedCast(E);
678
679 // Otherwise, do normal placeholder checking.
680 } else {
681 ExprResult ExprRes = CheckPlaceholderExpr(E);
682 if (ExprRes.isInvalid())
683 return ExprError();
684 E = ExprRes.take();
685 }
686 }
Douglas Gregorcbd446d2011-06-17 00:15:10 +0000687
John McCall4124c492011-10-17 18:40:02 +0000688 ExprResult ExprRes = DefaultArgumentPromotion(E);
John Wiegley01296292011-04-08 18:41:53 +0000689 if (ExprRes.isInvalid())
690 return ExprError();
691 E = ExprRes.take();
Mike Stump11289f42009-09-09 15:08:12 +0000692
Richard Smith55ce3522012-06-25 20:30:08 +0000693 // Diagnostics regarding non-POD argument types are
694 // emitted along with format string checking in Sema::CheckFunctionCall().
Richard Smith56471fd2012-06-27 20:23:58 +0000695 if (isValidVarArgType(E->getType()) == VAK_Invalid) {
Richard Smith55ce3522012-06-25 20:30:08 +0000696 // Turn this into a trap.
697 CXXScopeSpec SS;
698 SourceLocation TemplateKWLoc;
699 UnqualifiedId Name;
700 Name.setIdentifier(PP.getIdentifierInfo("__builtin_trap"),
701 E->getLocStart());
702 ExprResult TrapFn = ActOnIdExpression(TUScope, SS, TemplateKWLoc,
703 Name, true, false);
704 if (TrapFn.isInvalid())
705 return ExprError();
John McCall31168b02011-06-15 23:02:42 +0000706
Richard Smith55ce3522012-06-25 20:30:08 +0000707 ExprResult Call = ActOnCallExpr(TUScope, TrapFn.get(),
708 E->getLocStart(), MultiExprArg(),
709 E->getLocEnd());
710 if (Call.isInvalid())
711 return ExprError();
Douglas Gregor347e0f22011-05-21 19:26:31 +0000712
Richard Smith55ce3522012-06-25 20:30:08 +0000713 ExprResult Comma = ActOnBinOp(TUScope, E->getLocStart(), tok::comma,
714 Call.get(), E);
715 if (Comma.isInvalid())
716 return ExprError();
717 return Comma.get();
Douglas Gregor253cadf2011-05-21 16:27:21 +0000718 }
Richard Smith55ce3522012-06-25 20:30:08 +0000719
David Blaikiebbafb8a2012-03-11 07:00:24 +0000720 if (!getLangOpts().CPlusPlus &&
Fariborz Jahanian3854a552012-03-01 23:42:00 +0000721 RequireCompleteType(E->getExprLoc(), E->getType(),
Fariborz Jahanianbf482812012-03-02 17:05:03 +0000722 diag::err_call_incomplete_argument))
Fariborz Jahanian3854a552012-03-01 23:42:00 +0000723 return ExprError();
Richard Smith55ce3522012-06-25 20:30:08 +0000724
John Wiegley01296292011-04-08 18:41:53 +0000725 return Owned(E);
Anders Carlssona7d069d2009-01-16 16:48:51 +0000726}
727
Richard Trieu7aa58f12011-09-02 20:58:51 +0000728/// \brief Converts an integer to complex float type. Helper function of
729/// UsualArithmeticConversions()
730///
731/// \return false if the integer expression is an integer type and is
732/// successfully converted to the complex type.
Richard Trieuba63ce62011-09-09 01:45:06 +0000733static bool handleIntegerToComplexFloatConversion(Sema &S, ExprResult &IntExpr,
734 ExprResult &ComplexExpr,
735 QualType IntTy,
736 QualType ComplexTy,
737 bool SkipCast) {
738 if (IntTy->isComplexType() || IntTy->isRealFloatingType()) return true;
739 if (SkipCast) return false;
740 if (IntTy->isIntegerType()) {
741 QualType fpTy = cast<ComplexType>(ComplexTy)->getElementType();
742 IntExpr = S.ImpCastExprToType(IntExpr.take(), fpTy, CK_IntegralToFloating);
743 IntExpr = S.ImpCastExprToType(IntExpr.take(), ComplexTy,
Richard Trieu7aa58f12011-09-02 20:58:51 +0000744 CK_FloatingRealToComplex);
745 } else {
Richard Trieuba63ce62011-09-09 01:45:06 +0000746 assert(IntTy->isComplexIntegerType());
747 IntExpr = S.ImpCastExprToType(IntExpr.take(), ComplexTy,
Richard Trieu7aa58f12011-09-02 20:58:51 +0000748 CK_IntegralComplexToFloatingComplex);
749 }
750 return false;
751}
752
753/// \brief Takes two complex float types and converts them to the same type.
754/// Helper function of UsualArithmeticConversions()
755static QualType
Richard Trieu5065cdd2011-09-06 18:25:09 +0000756handleComplexFloatToComplexFloatConverstion(Sema &S, ExprResult &LHS,
757 ExprResult &RHS, QualType LHSType,
758 QualType RHSType,
Richard Trieuba63ce62011-09-09 01:45:06 +0000759 bool IsCompAssign) {
Richard Trieu5065cdd2011-09-06 18:25:09 +0000760 int order = S.Context.getFloatingTypeOrder(LHSType, RHSType);
Richard Trieu7aa58f12011-09-02 20:58:51 +0000761
762 if (order < 0) {
763 // _Complex float -> _Complex double
Richard Trieuba63ce62011-09-09 01:45:06 +0000764 if (!IsCompAssign)
Richard Trieu5065cdd2011-09-06 18:25:09 +0000765 LHS = S.ImpCastExprToType(LHS.take(), RHSType, CK_FloatingComplexCast);
766 return RHSType;
Richard Trieu7aa58f12011-09-02 20:58:51 +0000767 }
768 if (order > 0)
769 // _Complex float -> _Complex double
Richard Trieu5065cdd2011-09-06 18:25:09 +0000770 RHS = S.ImpCastExprToType(RHS.take(), LHSType, CK_FloatingComplexCast);
771 return LHSType;
Richard Trieu7aa58f12011-09-02 20:58:51 +0000772}
773
774/// \brief Converts otherExpr to complex float and promotes complexExpr if
775/// necessary. Helper function of UsualArithmeticConversions()
776static QualType handleOtherComplexFloatConversion(Sema &S,
Richard Trieuba63ce62011-09-09 01:45:06 +0000777 ExprResult &ComplexExpr,
778 ExprResult &OtherExpr,
779 QualType ComplexTy,
780 QualType OtherTy,
781 bool ConvertComplexExpr,
782 bool ConvertOtherExpr) {
783 int order = S.Context.getFloatingTypeOrder(ComplexTy, OtherTy);
Richard Trieu7aa58f12011-09-02 20:58:51 +0000784
785 // If just the complexExpr is complex, the otherExpr needs to be converted,
786 // and the complexExpr might need to be promoted.
787 if (order > 0) { // complexExpr is wider
788 // float -> _Complex double
Richard Trieuba63ce62011-09-09 01:45:06 +0000789 if (ConvertOtherExpr) {
790 QualType fp = cast<ComplexType>(ComplexTy)->getElementType();
791 OtherExpr = S.ImpCastExprToType(OtherExpr.take(), fp, CK_FloatingCast);
792 OtherExpr = S.ImpCastExprToType(OtherExpr.take(), ComplexTy,
Richard Trieu7aa58f12011-09-02 20:58:51 +0000793 CK_FloatingRealToComplex);
794 }
Richard Trieuba63ce62011-09-09 01:45:06 +0000795 return ComplexTy;
Richard Trieu7aa58f12011-09-02 20:58:51 +0000796 }
797
798 // otherTy is at least as wide. Find its corresponding complex type.
Richard Trieuba63ce62011-09-09 01:45:06 +0000799 QualType result = (order == 0 ? ComplexTy :
800 S.Context.getComplexType(OtherTy));
Richard Trieu7aa58f12011-09-02 20:58:51 +0000801
802 // double -> _Complex double
Richard Trieuba63ce62011-09-09 01:45:06 +0000803 if (ConvertOtherExpr)
804 OtherExpr = S.ImpCastExprToType(OtherExpr.take(), result,
Richard Trieu7aa58f12011-09-02 20:58:51 +0000805 CK_FloatingRealToComplex);
806
807 // _Complex float -> _Complex double
Richard Trieuba63ce62011-09-09 01:45:06 +0000808 if (ConvertComplexExpr && order < 0)
809 ComplexExpr = S.ImpCastExprToType(ComplexExpr.take(), result,
Richard Trieu7aa58f12011-09-02 20:58:51 +0000810 CK_FloatingComplexCast);
811
812 return result;
813}
814
815/// \brief Handle arithmetic conversion with complex types. Helper function of
816/// UsualArithmeticConversions()
Richard Trieu5065cdd2011-09-06 18:25:09 +0000817static QualType handleComplexFloatConversion(Sema &S, ExprResult &LHS,
818 ExprResult &RHS, QualType LHSType,
819 QualType RHSType,
Richard Trieuba63ce62011-09-09 01:45:06 +0000820 bool IsCompAssign) {
Richard Trieu7aa58f12011-09-02 20:58:51 +0000821 // if we have an integer operand, the result is the complex type.
Richard Trieu5065cdd2011-09-06 18:25:09 +0000822 if (!handleIntegerToComplexFloatConversion(S, RHS, LHS, RHSType, LHSType,
Richard Trieu7aa58f12011-09-02 20:58:51 +0000823 /*skipCast*/false))
Richard Trieu5065cdd2011-09-06 18:25:09 +0000824 return LHSType;
825 if (!handleIntegerToComplexFloatConversion(S, LHS, RHS, LHSType, RHSType,
Richard Trieuba63ce62011-09-09 01:45:06 +0000826 /*skipCast*/IsCompAssign))
Richard Trieu5065cdd2011-09-06 18:25:09 +0000827 return RHSType;
Richard Trieu7aa58f12011-09-02 20:58:51 +0000828
829 // This handles complex/complex, complex/float, or float/complex.
830 // When both operands are complex, the shorter operand is converted to the
831 // type of the longer, and that is the type of the result. This corresponds
832 // to what is done when combining two real floating-point operands.
833 // The fun begins when size promotion occur across type domains.
834 // From H&S 6.3.4: When one operand is complex and the other is a real
835 // floating-point type, the less precise type is converted, within it's
836 // real or complex domain, to the precision of the other type. For example,
837 // when combining a "long double" with a "double _Complex", the
838 // "double _Complex" is promoted to "long double _Complex".
839
Richard Trieu5065cdd2011-09-06 18:25:09 +0000840 bool LHSComplexFloat = LHSType->isComplexType();
841 bool RHSComplexFloat = RHSType->isComplexType();
Richard Trieu7aa58f12011-09-02 20:58:51 +0000842
843 // If both are complex, just cast to the more precise type.
844 if (LHSComplexFloat && RHSComplexFloat)
Richard Trieu5065cdd2011-09-06 18:25:09 +0000845 return handleComplexFloatToComplexFloatConverstion(S, LHS, RHS,
846 LHSType, RHSType,
Richard Trieuba63ce62011-09-09 01:45:06 +0000847 IsCompAssign);
Richard Trieu7aa58f12011-09-02 20:58:51 +0000848
849 // If only one operand is complex, promote it if necessary and convert the
850 // other operand to complex.
851 if (LHSComplexFloat)
852 return handleOtherComplexFloatConversion(
Richard Trieuba63ce62011-09-09 01:45:06 +0000853 S, LHS, RHS, LHSType, RHSType, /*convertComplexExpr*/!IsCompAssign,
Richard Trieu7aa58f12011-09-02 20:58:51 +0000854 /*convertOtherExpr*/ true);
855
856 assert(RHSComplexFloat);
857 return handleOtherComplexFloatConversion(
Richard Trieu5065cdd2011-09-06 18:25:09 +0000858 S, RHS, LHS, RHSType, LHSType, /*convertComplexExpr*/true,
Richard Trieuba63ce62011-09-09 01:45:06 +0000859 /*convertOtherExpr*/ !IsCompAssign);
Richard Trieu7aa58f12011-09-02 20:58:51 +0000860}
861
862/// \brief Hande arithmetic conversion from integer to float. Helper function
863/// of UsualArithmeticConversions()
Richard Trieuba63ce62011-09-09 01:45:06 +0000864static QualType handleIntToFloatConversion(Sema &S, ExprResult &FloatExpr,
865 ExprResult &IntExpr,
866 QualType FloatTy, QualType IntTy,
867 bool ConvertFloat, bool ConvertInt) {
868 if (IntTy->isIntegerType()) {
869 if (ConvertInt)
Richard Trieu7aa58f12011-09-02 20:58:51 +0000870 // Convert intExpr to the lhs floating point type.
Richard Trieuba63ce62011-09-09 01:45:06 +0000871 IntExpr = S.ImpCastExprToType(IntExpr.take(), FloatTy,
Richard Trieu7aa58f12011-09-02 20:58:51 +0000872 CK_IntegralToFloating);
Richard Trieuba63ce62011-09-09 01:45:06 +0000873 return FloatTy;
Richard Trieu7aa58f12011-09-02 20:58:51 +0000874 }
875
876 // Convert both sides to the appropriate complex float.
Richard Trieuba63ce62011-09-09 01:45:06 +0000877 assert(IntTy->isComplexIntegerType());
878 QualType result = S.Context.getComplexType(FloatTy);
Richard Trieu7aa58f12011-09-02 20:58:51 +0000879
880 // _Complex int -> _Complex float
Richard Trieuba63ce62011-09-09 01:45:06 +0000881 if (ConvertInt)
882 IntExpr = S.ImpCastExprToType(IntExpr.take(), result,
Richard Trieu7aa58f12011-09-02 20:58:51 +0000883 CK_IntegralComplexToFloatingComplex);
884
885 // float -> _Complex float
Richard Trieuba63ce62011-09-09 01:45:06 +0000886 if (ConvertFloat)
887 FloatExpr = S.ImpCastExprToType(FloatExpr.take(), result,
Richard Trieu7aa58f12011-09-02 20:58:51 +0000888 CK_FloatingRealToComplex);
889
890 return result;
891}
892
893/// \brief Handle arithmethic conversion with floating point types. Helper
894/// function of UsualArithmeticConversions()
Richard Trieucfe3f212011-09-06 18:38:41 +0000895static QualType handleFloatConversion(Sema &S, ExprResult &LHS,
896 ExprResult &RHS, QualType LHSType,
Richard Trieuba63ce62011-09-09 01:45:06 +0000897 QualType RHSType, bool IsCompAssign) {
Richard Trieucfe3f212011-09-06 18:38:41 +0000898 bool LHSFloat = LHSType->isRealFloatingType();
899 bool RHSFloat = RHSType->isRealFloatingType();
Richard Trieu7aa58f12011-09-02 20:58:51 +0000900
901 // If we have two real floating types, convert the smaller operand
902 // to the bigger result.
903 if (LHSFloat && RHSFloat) {
Richard Trieucfe3f212011-09-06 18:38:41 +0000904 int order = S.Context.getFloatingTypeOrder(LHSType, RHSType);
Richard Trieu7aa58f12011-09-02 20:58:51 +0000905 if (order > 0) {
Richard Trieucfe3f212011-09-06 18:38:41 +0000906 RHS = S.ImpCastExprToType(RHS.take(), LHSType, CK_FloatingCast);
907 return LHSType;
Richard Trieu7aa58f12011-09-02 20:58:51 +0000908 }
909
910 assert(order < 0 && "illegal float comparison");
Richard Trieuba63ce62011-09-09 01:45:06 +0000911 if (!IsCompAssign)
Richard Trieucfe3f212011-09-06 18:38:41 +0000912 LHS = S.ImpCastExprToType(LHS.take(), RHSType, CK_FloatingCast);
913 return RHSType;
Richard Trieu7aa58f12011-09-02 20:58:51 +0000914 }
915
916 if (LHSFloat)
Richard Trieucfe3f212011-09-06 18:38:41 +0000917 return handleIntToFloatConversion(S, LHS, RHS, LHSType, RHSType,
Richard Trieuba63ce62011-09-09 01:45:06 +0000918 /*convertFloat=*/!IsCompAssign,
Richard Trieu7aa58f12011-09-02 20:58:51 +0000919 /*convertInt=*/ true);
920 assert(RHSFloat);
Richard Trieucfe3f212011-09-06 18:38:41 +0000921 return handleIntToFloatConversion(S, RHS, LHS, RHSType, LHSType,
Richard Trieu7aa58f12011-09-02 20:58:51 +0000922 /*convertInt=*/ true,
Richard Trieuba63ce62011-09-09 01:45:06 +0000923 /*convertFloat=*/!IsCompAssign);
Richard Trieu7aa58f12011-09-02 20:58:51 +0000924}
925
926/// \brief Handle conversions with GCC complex int extension. Helper function
Benjamin Kramer499c68b2011-09-06 19:57:14 +0000927/// of UsualArithmeticConversions()
Richard Trieu7aa58f12011-09-02 20:58:51 +0000928// FIXME: if the operands are (int, _Complex long), we currently
929// don't promote the complex. Also, signedness?
Benjamin Kramer499c68b2011-09-06 19:57:14 +0000930static QualType handleComplexIntConversion(Sema &S, ExprResult &LHS,
931 ExprResult &RHS, QualType LHSType,
932 QualType RHSType,
Richard Trieuba63ce62011-09-09 01:45:06 +0000933 bool IsCompAssign) {
Richard Trieucfe3f212011-09-06 18:38:41 +0000934 const ComplexType *LHSComplexInt = LHSType->getAsComplexIntegerType();
935 const ComplexType *RHSComplexInt = RHSType->getAsComplexIntegerType();
Richard Trieu7aa58f12011-09-02 20:58:51 +0000936
Richard Trieucfe3f212011-09-06 18:38:41 +0000937 if (LHSComplexInt && RHSComplexInt) {
938 int order = S.Context.getIntegerTypeOrder(LHSComplexInt->getElementType(),
939 RHSComplexInt->getElementType());
Richard Trieu7aa58f12011-09-02 20:58:51 +0000940 assert(order && "inequal types with equal element ordering");
941 if (order > 0) {
942 // _Complex int -> _Complex long
Richard Trieucfe3f212011-09-06 18:38:41 +0000943 RHS = S.ImpCastExprToType(RHS.take(), LHSType, CK_IntegralComplexCast);
944 return LHSType;
Richard Trieu7aa58f12011-09-02 20:58:51 +0000945 }
946
Richard Trieuba63ce62011-09-09 01:45:06 +0000947 if (!IsCompAssign)
Richard Trieucfe3f212011-09-06 18:38:41 +0000948 LHS = S.ImpCastExprToType(LHS.take(), RHSType, CK_IntegralComplexCast);
949 return RHSType;
Richard Trieu7aa58f12011-09-02 20:58:51 +0000950 }
951
Richard Trieucfe3f212011-09-06 18:38:41 +0000952 if (LHSComplexInt) {
Richard Trieu7aa58f12011-09-02 20:58:51 +0000953 // int -> _Complex int
Eli Friedman47133be2011-11-12 03:56:23 +0000954 // FIXME: This needs to take integer ranks into account
955 RHS = S.ImpCastExprToType(RHS.take(), LHSComplexInt->getElementType(),
956 CK_IntegralCast);
Richard Trieucfe3f212011-09-06 18:38:41 +0000957 RHS = S.ImpCastExprToType(RHS.take(), LHSType, CK_IntegralRealToComplex);
958 return LHSType;
Richard Trieu7aa58f12011-09-02 20:58:51 +0000959 }
960
Richard Trieucfe3f212011-09-06 18:38:41 +0000961 assert(RHSComplexInt);
Richard Trieu7aa58f12011-09-02 20:58:51 +0000962 // int -> _Complex int
Eli Friedman47133be2011-11-12 03:56:23 +0000963 // FIXME: This needs to take integer ranks into account
964 if (!IsCompAssign) {
965 LHS = S.ImpCastExprToType(LHS.take(), RHSComplexInt->getElementType(),
966 CK_IntegralCast);
Richard Trieucfe3f212011-09-06 18:38:41 +0000967 LHS = S.ImpCastExprToType(LHS.take(), RHSType, CK_IntegralRealToComplex);
Eli Friedman47133be2011-11-12 03:56:23 +0000968 }
Richard Trieucfe3f212011-09-06 18:38:41 +0000969 return RHSType;
Richard Trieu7aa58f12011-09-02 20:58:51 +0000970}
971
972/// \brief Handle integer arithmetic conversions. Helper function of
973/// UsualArithmeticConversions()
Richard Trieu9a52fbb2011-09-06 19:52:52 +0000974static QualType handleIntegerConversion(Sema &S, ExprResult &LHS,
975 ExprResult &RHS, QualType LHSType,
Richard Trieuba63ce62011-09-09 01:45:06 +0000976 QualType RHSType, bool IsCompAssign) {
Richard Trieu7aa58f12011-09-02 20:58:51 +0000977 // The rules for this case are in C99 6.3.1.8
Richard Trieu9a52fbb2011-09-06 19:52:52 +0000978 int order = S.Context.getIntegerTypeOrder(LHSType, RHSType);
979 bool LHSSigned = LHSType->hasSignedIntegerRepresentation();
980 bool RHSSigned = RHSType->hasSignedIntegerRepresentation();
981 if (LHSSigned == RHSSigned) {
Richard Trieu7aa58f12011-09-02 20:58:51 +0000982 // Same signedness; use the higher-ranked type
983 if (order >= 0) {
Richard Trieu9a52fbb2011-09-06 19:52:52 +0000984 RHS = S.ImpCastExprToType(RHS.take(), LHSType, CK_IntegralCast);
985 return LHSType;
Richard Trieuba63ce62011-09-09 01:45:06 +0000986 } else if (!IsCompAssign)
Richard Trieu9a52fbb2011-09-06 19:52:52 +0000987 LHS = S.ImpCastExprToType(LHS.take(), RHSType, CK_IntegralCast);
988 return RHSType;
989 } else if (order != (LHSSigned ? 1 : -1)) {
Richard Trieu7aa58f12011-09-02 20:58:51 +0000990 // The unsigned type has greater than or equal rank to the
991 // signed type, so use the unsigned type
Richard Trieu9a52fbb2011-09-06 19:52:52 +0000992 if (RHSSigned) {
993 RHS = S.ImpCastExprToType(RHS.take(), LHSType, CK_IntegralCast);
994 return LHSType;
Richard Trieuba63ce62011-09-09 01:45:06 +0000995 } else if (!IsCompAssign)
Richard Trieu9a52fbb2011-09-06 19:52:52 +0000996 LHS = S.ImpCastExprToType(LHS.take(), RHSType, CK_IntegralCast);
997 return RHSType;
998 } else if (S.Context.getIntWidth(LHSType) != S.Context.getIntWidth(RHSType)) {
Richard Trieu7aa58f12011-09-02 20:58:51 +0000999 // The two types are different widths; if we are here, that
1000 // means the signed type is larger than the unsigned type, so
1001 // use the signed type.
Richard Trieu9a52fbb2011-09-06 19:52:52 +00001002 if (LHSSigned) {
1003 RHS = S.ImpCastExprToType(RHS.take(), LHSType, CK_IntegralCast);
1004 return LHSType;
Richard Trieuba63ce62011-09-09 01:45:06 +00001005 } else if (!IsCompAssign)
Richard Trieu9a52fbb2011-09-06 19:52:52 +00001006 LHS = S.ImpCastExprToType(LHS.take(), RHSType, CK_IntegralCast);
1007 return RHSType;
Richard Trieu7aa58f12011-09-02 20:58:51 +00001008 } else {
1009 // The signed type is higher-ranked than the unsigned type,
1010 // but isn't actually any bigger (like unsigned int and long
1011 // on most 32-bit systems). Use the unsigned type corresponding
1012 // to the signed type.
1013 QualType result =
Richard Trieu9a52fbb2011-09-06 19:52:52 +00001014 S.Context.getCorrespondingUnsignedType(LHSSigned ? LHSType : RHSType);
1015 RHS = S.ImpCastExprToType(RHS.take(), result, CK_IntegralCast);
Richard Trieuba63ce62011-09-09 01:45:06 +00001016 if (!IsCompAssign)
Richard Trieu9a52fbb2011-09-06 19:52:52 +00001017 LHS = S.ImpCastExprToType(LHS.take(), result, CK_IntegralCast);
Richard Trieu7aa58f12011-09-02 20:58:51 +00001018 return result;
1019 }
1020}
1021
Chris Lattner513165e2008-07-25 21:10:04 +00001022/// UsualArithmeticConversions - Performs various conversions that are common to
1023/// binary operators (C99 6.3.1.8). If both operands aren't arithmetic, this
Mike Stump11289f42009-09-09 15:08:12 +00001024/// routine returns the first non-arithmetic type found. The client is
Chris Lattner513165e2008-07-25 21:10:04 +00001025/// responsible for emitting appropriate error diagnostics.
1026/// FIXME: verify the conversion rules for "complex int" are consistent with
1027/// GCC.
Richard Trieu9a52fbb2011-09-06 19:52:52 +00001028QualType Sema::UsualArithmeticConversions(ExprResult &LHS, ExprResult &RHS,
Richard Trieuba63ce62011-09-09 01:45:06 +00001029 bool IsCompAssign) {
1030 if (!IsCompAssign) {
Richard Trieu9a52fbb2011-09-06 19:52:52 +00001031 LHS = UsualUnaryConversions(LHS.take());
1032 if (LHS.isInvalid())
John Wiegley01296292011-04-08 18:41:53 +00001033 return QualType();
1034 }
Eli Friedman8b7b1b12009-03-28 01:22:36 +00001035
Richard Trieu9a52fbb2011-09-06 19:52:52 +00001036 RHS = UsualUnaryConversions(RHS.take());
1037 if (RHS.isInvalid())
John Wiegley01296292011-04-08 18:41:53 +00001038 return QualType();
Douglas Gregora11693b2008-11-12 17:17:38 +00001039
Mike Stump11289f42009-09-09 15:08:12 +00001040 // For conversion purposes, we ignore any qualifiers.
Chris Lattner513165e2008-07-25 21:10:04 +00001041 // For example, "const float" and "float" are equivalent.
Richard Trieu9a52fbb2011-09-06 19:52:52 +00001042 QualType LHSType =
1043 Context.getCanonicalType(LHS.get()->getType()).getUnqualifiedType();
1044 QualType RHSType =
1045 Context.getCanonicalType(RHS.get()->getType()).getUnqualifiedType();
Douglas Gregora11693b2008-11-12 17:17:38 +00001046
Eli Friedman93ee5ca2012-06-16 02:19:17 +00001047 // For conversion purposes, we ignore any atomic qualifier on the LHS.
1048 if (const AtomicType *AtomicLHS = LHSType->getAs<AtomicType>())
1049 LHSType = AtomicLHS->getValueType();
1050
Douglas Gregora11693b2008-11-12 17:17:38 +00001051 // If both types are identical, no conversion is needed.
Richard Trieu9a52fbb2011-09-06 19:52:52 +00001052 if (LHSType == RHSType)
1053 return LHSType;
Douglas Gregora11693b2008-11-12 17:17:38 +00001054
1055 // If either side is a non-arithmetic type (e.g. a pointer), we are done.
1056 // The caller can deal with this (e.g. pointer + int).
Richard Trieu9a52fbb2011-09-06 19:52:52 +00001057 if (!LHSType->isArithmeticType() || !RHSType->isArithmeticType())
Eli Friedman93ee5ca2012-06-16 02:19:17 +00001058 return QualType();
Douglas Gregora11693b2008-11-12 17:17:38 +00001059
John McCalld005ac92010-11-13 08:17:45 +00001060 // Apply unary and bitfield promotions to the LHS's type.
Richard Trieu9a52fbb2011-09-06 19:52:52 +00001061 QualType LHSUnpromotedType = LHSType;
1062 if (LHSType->isPromotableIntegerType())
1063 LHSType = Context.getPromotedIntegerType(LHSType);
1064 QualType LHSBitfieldPromoteTy = Context.isPromotableBitField(LHS.get());
Douglas Gregord2c2d172009-05-02 00:36:19 +00001065 if (!LHSBitfieldPromoteTy.isNull())
Richard Trieu9a52fbb2011-09-06 19:52:52 +00001066 LHSType = LHSBitfieldPromoteTy;
Richard Trieuba63ce62011-09-09 01:45:06 +00001067 if (LHSType != LHSUnpromotedType && !IsCompAssign)
Richard Trieu9a52fbb2011-09-06 19:52:52 +00001068 LHS = ImpCastExprToType(LHS.take(), LHSType, CK_IntegralCast);
Douglas Gregord2c2d172009-05-02 00:36:19 +00001069
John McCalld005ac92010-11-13 08:17:45 +00001070 // If both types are identical, no conversion is needed.
Richard Trieu9a52fbb2011-09-06 19:52:52 +00001071 if (LHSType == RHSType)
1072 return LHSType;
John McCalld005ac92010-11-13 08:17:45 +00001073
1074 // At this point, we have two different arithmetic types.
1075
1076 // Handle complex types first (C99 6.3.1.8p1).
Richard Trieu9a52fbb2011-09-06 19:52:52 +00001077 if (LHSType->isComplexType() || RHSType->isComplexType())
1078 return handleComplexFloatConversion(*this, LHS, RHS, LHSType, RHSType,
Richard Trieuba63ce62011-09-09 01:45:06 +00001079 IsCompAssign);
John McCalld005ac92010-11-13 08:17:45 +00001080
1081 // Now handle "real" floating types (i.e. float, double, long double).
Richard Trieu9a52fbb2011-09-06 19:52:52 +00001082 if (LHSType->isRealFloatingType() || RHSType->isRealFloatingType())
1083 return handleFloatConversion(*this, LHS, RHS, LHSType, RHSType,
Richard Trieuba63ce62011-09-09 01:45:06 +00001084 IsCompAssign);
John McCalld005ac92010-11-13 08:17:45 +00001085
1086 // Handle GCC complex int extension.
Richard Trieu9a52fbb2011-09-06 19:52:52 +00001087 if (LHSType->isComplexIntegerType() || RHSType->isComplexIntegerType())
Benjamin Kramer499c68b2011-09-06 19:57:14 +00001088 return handleComplexIntConversion(*this, LHS, RHS, LHSType, RHSType,
Richard Trieuba63ce62011-09-09 01:45:06 +00001089 IsCompAssign);
John McCalld005ac92010-11-13 08:17:45 +00001090
1091 // Finally, we have two differing integer types.
Richard Trieu9a52fbb2011-09-06 19:52:52 +00001092 return handleIntegerConversion(*this, LHS, RHS, LHSType, RHSType,
Richard Trieuba63ce62011-09-09 01:45:06 +00001093 IsCompAssign);
Douglas Gregora11693b2008-11-12 17:17:38 +00001094}
1095
Chris Lattner513165e2008-07-25 21:10:04 +00001096//===----------------------------------------------------------------------===//
1097// Semantic Analysis for various Expression Types
1098//===----------------------------------------------------------------------===//
1099
1100
Peter Collingbourne91147592011-04-15 00:35:48 +00001101ExprResult
1102Sema::ActOnGenericSelectionExpr(SourceLocation KeyLoc,
1103 SourceLocation DefaultLoc,
1104 SourceLocation RParenLoc,
1105 Expr *ControllingExpr,
Richard Trieuba63ce62011-09-09 01:45:06 +00001106 MultiTypeArg ArgTypes,
1107 MultiExprArg ArgExprs) {
1108 unsigned NumAssocs = ArgTypes.size();
1109 assert(NumAssocs == ArgExprs.size());
Peter Collingbourne91147592011-04-15 00:35:48 +00001110
Benjamin Kramercc4c49d2012-08-23 23:38:35 +00001111 ParsedType *ParsedTypes = ArgTypes.data();
1112 Expr **Exprs = ArgExprs.data();
Peter Collingbourne91147592011-04-15 00:35:48 +00001113
1114 TypeSourceInfo **Types = new TypeSourceInfo*[NumAssocs];
1115 for (unsigned i = 0; i < NumAssocs; ++i) {
1116 if (ParsedTypes[i])
1117 (void) GetTypeFromParser(ParsedTypes[i], &Types[i]);
1118 else
1119 Types[i] = 0;
1120 }
1121
1122 ExprResult ER = CreateGenericSelectionExpr(KeyLoc, DefaultLoc, RParenLoc,
1123 ControllingExpr, Types, Exprs,
1124 NumAssocs);
Benjamin Kramer34623762011-04-15 11:21:57 +00001125 delete [] Types;
Peter Collingbourne91147592011-04-15 00:35:48 +00001126 return ER;
1127}
1128
1129ExprResult
1130Sema::CreateGenericSelectionExpr(SourceLocation KeyLoc,
1131 SourceLocation DefaultLoc,
1132 SourceLocation RParenLoc,
1133 Expr *ControllingExpr,
1134 TypeSourceInfo **Types,
1135 Expr **Exprs,
1136 unsigned NumAssocs) {
1137 bool TypeErrorFound = false,
1138 IsResultDependent = ControllingExpr->isTypeDependent(),
1139 ContainsUnexpandedParameterPack
1140 = ControllingExpr->containsUnexpandedParameterPack();
1141
1142 for (unsigned i = 0; i < NumAssocs; ++i) {
1143 if (Exprs[i]->containsUnexpandedParameterPack())
1144 ContainsUnexpandedParameterPack = true;
1145
1146 if (Types[i]) {
1147 if (Types[i]->getType()->containsUnexpandedParameterPack())
1148 ContainsUnexpandedParameterPack = true;
1149
1150 if (Types[i]->getType()->isDependentType()) {
1151 IsResultDependent = true;
1152 } else {
Benjamin Kramere56f3932011-12-23 17:00:35 +00001153 // C11 6.5.1.1p2 "The type name in a generic association shall specify a
Peter Collingbourne91147592011-04-15 00:35:48 +00001154 // complete object type other than a variably modified type."
1155 unsigned D = 0;
1156 if (Types[i]->getType()->isIncompleteType())
1157 D = diag::err_assoc_type_incomplete;
1158 else if (!Types[i]->getType()->isObjectType())
1159 D = diag::err_assoc_type_nonobject;
1160 else if (Types[i]->getType()->isVariablyModifiedType())
1161 D = diag::err_assoc_type_variably_modified;
1162
1163 if (D != 0) {
1164 Diag(Types[i]->getTypeLoc().getBeginLoc(), D)
1165 << Types[i]->getTypeLoc().getSourceRange()
1166 << Types[i]->getType();
1167 TypeErrorFound = true;
1168 }
1169
Benjamin Kramere56f3932011-12-23 17:00:35 +00001170 // C11 6.5.1.1p2 "No two generic associations in the same generic
Peter Collingbourne91147592011-04-15 00:35:48 +00001171 // selection shall specify compatible types."
1172 for (unsigned j = i+1; j < NumAssocs; ++j)
1173 if (Types[j] && !Types[j]->getType()->isDependentType() &&
1174 Context.typesAreCompatible(Types[i]->getType(),
1175 Types[j]->getType())) {
1176 Diag(Types[j]->getTypeLoc().getBeginLoc(),
1177 diag::err_assoc_compatible_types)
1178 << Types[j]->getTypeLoc().getSourceRange()
1179 << Types[j]->getType()
1180 << Types[i]->getType();
1181 Diag(Types[i]->getTypeLoc().getBeginLoc(),
1182 diag::note_compat_assoc)
1183 << Types[i]->getTypeLoc().getSourceRange()
1184 << Types[i]->getType();
1185 TypeErrorFound = true;
1186 }
1187 }
1188 }
1189 }
1190 if (TypeErrorFound)
1191 return ExprError();
1192
1193 // If we determined that the generic selection is result-dependent, don't
1194 // try to compute the result expression.
1195 if (IsResultDependent)
1196 return Owned(new (Context) GenericSelectionExpr(
1197 Context, KeyLoc, ControllingExpr,
Benjamin Kramerc215e762012-08-24 11:54:20 +00001198 llvm::makeArrayRef(Types, NumAssocs),
1199 llvm::makeArrayRef(Exprs, NumAssocs),
1200 DefaultLoc, RParenLoc, ContainsUnexpandedParameterPack));
Peter Collingbourne91147592011-04-15 00:35:48 +00001201
Chris Lattner0e62c1c2011-07-23 10:55:15 +00001202 SmallVector<unsigned, 1> CompatIndices;
Peter Collingbourne91147592011-04-15 00:35:48 +00001203 unsigned DefaultIndex = -1U;
1204 for (unsigned i = 0; i < NumAssocs; ++i) {
1205 if (!Types[i])
1206 DefaultIndex = i;
1207 else if (Context.typesAreCompatible(ControllingExpr->getType(),
1208 Types[i]->getType()))
1209 CompatIndices.push_back(i);
1210 }
1211
Benjamin Kramere56f3932011-12-23 17:00:35 +00001212 // C11 6.5.1.1p2 "The controlling expression of a generic selection shall have
Peter Collingbourne91147592011-04-15 00:35:48 +00001213 // type compatible with at most one of the types named in its generic
1214 // association list."
1215 if (CompatIndices.size() > 1) {
1216 // We strip parens here because the controlling expression is typically
1217 // parenthesized in macro definitions.
1218 ControllingExpr = ControllingExpr->IgnoreParens();
1219 Diag(ControllingExpr->getLocStart(), diag::err_generic_sel_multi_match)
1220 << ControllingExpr->getSourceRange() << ControllingExpr->getType()
1221 << (unsigned) CompatIndices.size();
Chris Lattner0e62c1c2011-07-23 10:55:15 +00001222 for (SmallVector<unsigned, 1>::iterator I = CompatIndices.begin(),
Peter Collingbourne91147592011-04-15 00:35:48 +00001223 E = CompatIndices.end(); I != E; ++I) {
1224 Diag(Types[*I]->getTypeLoc().getBeginLoc(),
1225 diag::note_compat_assoc)
1226 << Types[*I]->getTypeLoc().getSourceRange()
1227 << Types[*I]->getType();
1228 }
1229 return ExprError();
1230 }
1231
Benjamin Kramere56f3932011-12-23 17:00:35 +00001232 // C11 6.5.1.1p2 "If a generic selection has no default generic association,
Peter Collingbourne91147592011-04-15 00:35:48 +00001233 // its controlling expression shall have type compatible with exactly one of
1234 // the types named in its generic association list."
1235 if (DefaultIndex == -1U && CompatIndices.size() == 0) {
1236 // We strip parens here because the controlling expression is typically
1237 // parenthesized in macro definitions.
1238 ControllingExpr = ControllingExpr->IgnoreParens();
1239 Diag(ControllingExpr->getLocStart(), diag::err_generic_sel_no_match)
1240 << ControllingExpr->getSourceRange() << ControllingExpr->getType();
1241 return ExprError();
1242 }
1243
Benjamin Kramere56f3932011-12-23 17:00:35 +00001244 // C11 6.5.1.1p3 "If a generic selection has a generic association with a
Peter Collingbourne91147592011-04-15 00:35:48 +00001245 // type name that is compatible with the type of the controlling expression,
1246 // then the result expression of the generic selection is the expression
1247 // in that generic association. Otherwise, the result expression of the
1248 // generic selection is the expression in the default generic association."
1249 unsigned ResultIndex =
1250 CompatIndices.size() ? CompatIndices[0] : DefaultIndex;
1251
1252 return Owned(new (Context) GenericSelectionExpr(
1253 Context, KeyLoc, ControllingExpr,
Benjamin Kramerc215e762012-08-24 11:54:20 +00001254 llvm::makeArrayRef(Types, NumAssocs),
1255 llvm::makeArrayRef(Exprs, NumAssocs),
1256 DefaultLoc, RParenLoc, ContainsUnexpandedParameterPack,
Peter Collingbourne91147592011-04-15 00:35:48 +00001257 ResultIndex));
1258}
1259
Richard Smith75b67d62012-03-08 01:34:56 +00001260/// getUDSuffixLoc - Create a SourceLocation for a ud-suffix, given the
1261/// location of the token and the offset of the ud-suffix within it.
1262static SourceLocation getUDSuffixLoc(Sema &S, SourceLocation TokLoc,
1263 unsigned Offset) {
1264 return Lexer::AdvanceToTokenCharacter(TokLoc, Offset, S.getSourceManager(),
David Blaikiebbafb8a2012-03-11 07:00:24 +00001265 S.getLangOpts());
Richard Smith75b67d62012-03-08 01:34:56 +00001266}
1267
Richard Smithbcc22fc2012-03-09 08:00:36 +00001268/// BuildCookedLiteralOperatorCall - A user-defined literal was found. Look up
1269/// the corresponding cooked (non-raw) literal operator, and build a call to it.
1270static ExprResult BuildCookedLiteralOperatorCall(Sema &S, Scope *Scope,
1271 IdentifierInfo *UDSuffix,
1272 SourceLocation UDSuffixLoc,
1273 ArrayRef<Expr*> Args,
1274 SourceLocation LitEndLoc) {
1275 assert(Args.size() <= 2 && "too many arguments for literal operator");
1276
1277 QualType ArgTy[2];
1278 for (unsigned ArgIdx = 0; ArgIdx != Args.size(); ++ArgIdx) {
1279 ArgTy[ArgIdx] = Args[ArgIdx]->getType();
1280 if (ArgTy[ArgIdx]->isArrayType())
1281 ArgTy[ArgIdx] = S.Context.getArrayDecayedType(ArgTy[ArgIdx]);
1282 }
1283
1284 DeclarationName OpName =
1285 S.Context.DeclarationNames.getCXXLiteralOperatorName(UDSuffix);
1286 DeclarationNameInfo OpNameInfo(OpName, UDSuffixLoc);
1287 OpNameInfo.setCXXLiteralOperatorNameLoc(UDSuffixLoc);
1288
1289 LookupResult R(S, OpName, UDSuffixLoc, Sema::LookupOrdinaryName);
1290 if (S.LookupLiteralOperator(Scope, R, llvm::makeArrayRef(ArgTy, Args.size()),
1291 /*AllowRawAndTemplate*/false) == Sema::LOLR_Error)
1292 return ExprError();
1293
1294 return S.BuildLiteralOperatorCall(R, OpNameInfo, Args, LitEndLoc);
1295}
1296
Steve Naroff83895f72007-09-16 03:34:24 +00001297/// ActOnStringLiteral - The specified tokens were lexed as pasted string
Chris Lattner5b183d82006-11-10 05:03:26 +00001298/// fragments (e.g. "foo" "bar" L"baz"). The result string has to handle string
1299/// concatenation ([C99 5.1.1.2, translation phase #6]), so it may come from
1300/// multiple tokens. However, the common case is that StringToks points to one
1301/// string.
Sebastian Redlffbcf962009-01-18 18:53:16 +00001302///
John McCalldadc5752010-08-24 06:29:42 +00001303ExprResult
Richard Smithbcc22fc2012-03-09 08:00:36 +00001304Sema::ActOnStringLiteral(const Token *StringToks, unsigned NumStringToks,
1305 Scope *UDLScope) {
Chris Lattner5b183d82006-11-10 05:03:26 +00001306 assert(NumStringToks && "Must have at least one string!");
1307
Chris Lattner8a24e582009-01-16 18:51:42 +00001308 StringLiteralParser Literal(StringToks, NumStringToks, PP);
Steve Naroff4f88b312007-03-13 22:37:02 +00001309 if (Literal.hadError)
Sebastian Redlffbcf962009-01-18 18:53:16 +00001310 return ExprError();
Chris Lattner5b183d82006-11-10 05:03:26 +00001311
Chris Lattner0e62c1c2011-07-23 10:55:15 +00001312 SmallVector<SourceLocation, 4> StringTokLocs;
Chris Lattner5b183d82006-11-10 05:03:26 +00001313 for (unsigned i = 0; i != NumStringToks; ++i)
1314 StringTokLocs.push_back(StringToks[i].getLocation());
Chris Lattner36fc8792008-02-11 00:02:17 +00001315
Chris Lattner36fc8792008-02-11 00:02:17 +00001316 QualType StrTy = Context.CharTy;
Douglas Gregorfb65e592011-07-27 05:40:30 +00001317 if (Literal.isWide())
Anders Carlsson6b06e182011-04-06 18:42:48 +00001318 StrTy = Context.getWCharType();
Douglas Gregorfb65e592011-07-27 05:40:30 +00001319 else if (Literal.isUTF16())
1320 StrTy = Context.Char16Ty;
1321 else if (Literal.isUTF32())
1322 StrTy = Context.Char32Ty;
Eli Friedmanfcec6302011-11-01 02:23:42 +00001323 else if (Literal.isPascal())
Anders Carlsson6b06e182011-04-06 18:42:48 +00001324 StrTy = Context.UnsignedCharTy;
Douglas Gregoraa1e21d2008-09-12 00:47:35 +00001325
Douglas Gregorfb65e592011-07-27 05:40:30 +00001326 StringLiteral::StringKind Kind = StringLiteral::Ascii;
1327 if (Literal.isWide())
1328 Kind = StringLiteral::Wide;
1329 else if (Literal.isUTF8())
1330 Kind = StringLiteral::UTF8;
1331 else if (Literal.isUTF16())
1332 Kind = StringLiteral::UTF16;
1333 else if (Literal.isUTF32())
1334 Kind = StringLiteral::UTF32;
1335
Douglas Gregoraa1e21d2008-09-12 00:47:35 +00001336 // A C++ string literal has a const-qualified element type (C++ 2.13.4p1).
David Blaikiebbafb8a2012-03-11 07:00:24 +00001337 if (getLangOpts().CPlusPlus || getLangOpts().ConstStrings)
Douglas Gregoraa1e21d2008-09-12 00:47:35 +00001338 StrTy.addConst();
Sebastian Redlffbcf962009-01-18 18:53:16 +00001339
Chris Lattner36fc8792008-02-11 00:02:17 +00001340 // Get an array type for the string, according to C99 6.4.5. This includes
1341 // the nul terminator character as well as the string length for pascal
1342 // strings.
1343 StrTy = Context.getConstantArrayType(StrTy,
Chris Lattnerd42c29f2009-02-26 23:01:51 +00001344 llvm::APInt(32, Literal.GetNumStringChars()+1),
Chris Lattner36fc8792008-02-11 00:02:17 +00001345 ArrayType::Normal, 0);
Mike Stump11289f42009-09-09 15:08:12 +00001346
Chris Lattner5b183d82006-11-10 05:03:26 +00001347 // Pass &StringTokLocs[0], StringTokLocs.size() to factory!
Richard Smithc67fdd42012-03-07 08:35:16 +00001348 StringLiteral *Lit = StringLiteral::Create(Context, Literal.GetString(),
1349 Kind, Literal.Pascal, StrTy,
1350 &StringTokLocs[0],
1351 StringTokLocs.size());
1352 if (Literal.getUDSuffix().empty())
1353 return Owned(Lit);
1354
1355 // We're building a user-defined literal.
1356 IdentifierInfo *UDSuffix = &Context.Idents.get(Literal.getUDSuffix());
Richard Smith75b67d62012-03-08 01:34:56 +00001357 SourceLocation UDSuffixLoc =
1358 getUDSuffixLoc(*this, StringTokLocs[Literal.getUDSuffixToken()],
1359 Literal.getUDSuffixOffset());
Richard Smithc67fdd42012-03-07 08:35:16 +00001360
Richard Smithbcc22fc2012-03-09 08:00:36 +00001361 // Make sure we're allowed user-defined literals here.
1362 if (!UDLScope)
1363 return ExprError(Diag(UDSuffixLoc, diag::err_invalid_string_udl));
1364
Richard Smithc67fdd42012-03-07 08:35:16 +00001365 // C++11 [lex.ext]p5: The literal L is treated as a call of the form
1366 // operator "" X (str, len)
1367 QualType SizeType = Context.getSizeType();
1368 llvm::APInt Len(Context.getIntWidth(SizeType), Literal.GetNumStringChars());
1369 IntegerLiteral *LenArg = IntegerLiteral::Create(Context, Len, SizeType,
1370 StringTokLocs[0]);
1371 Expr *Args[] = { Lit, LenArg };
Richard Smithbcc22fc2012-03-09 08:00:36 +00001372 return BuildCookedLiteralOperatorCall(*this, UDLScope, UDSuffix, UDSuffixLoc,
1373 Args, StringTokLocs.back());
Chris Lattner5b183d82006-11-10 05:03:26 +00001374}
1375
John McCalldadc5752010-08-24 06:29:42 +00001376ExprResult
John McCall7decc9e2010-11-18 06:31:45 +00001377Sema::BuildDeclRefExpr(ValueDecl *D, QualType Ty, ExprValueKind VK,
John McCallf4cd4f92011-02-09 01:13:10 +00001378 SourceLocation Loc,
1379 const CXXScopeSpec *SS) {
Abramo Bagnarad6d2f182010-08-11 22:01:17 +00001380 DeclarationNameInfo NameInfo(D->getDeclName(), Loc);
John McCall7decc9e2010-11-18 06:31:45 +00001381 return BuildDeclRefExpr(D, Ty, VK, NameInfo, SS);
Abramo Bagnarad6d2f182010-08-11 22:01:17 +00001382}
1383
John McCallf4cd4f92011-02-09 01:13:10 +00001384/// BuildDeclRefExpr - Build an expression that references a
1385/// declaration that does not require a closure capture.
John McCalldadc5752010-08-24 06:29:42 +00001386ExprResult
John McCallf4cd4f92011-02-09 01:13:10 +00001387Sema::BuildDeclRefExpr(ValueDecl *D, QualType Ty, ExprValueKind VK,
Abramo Bagnarad6d2f182010-08-11 22:01:17 +00001388 const DeclarationNameInfo &NameInfo,
1389 const CXXScopeSpec *SS) {
David Blaikiebbafb8a2012-03-11 07:00:24 +00001390 if (getLangOpts().CUDA)
Peter Collingbourne7277fe82011-10-02 23:49:40 +00001391 if (const FunctionDecl *Caller = dyn_cast<FunctionDecl>(CurContext))
1392 if (const FunctionDecl *Callee = dyn_cast<FunctionDecl>(D)) {
1393 CUDAFunctionTarget CallerTarget = IdentifyCUDATarget(Caller),
1394 CalleeTarget = IdentifyCUDATarget(Callee);
1395 if (CheckCUDATarget(CallerTarget, CalleeTarget)) {
1396 Diag(NameInfo.getLoc(), diag::err_ref_bad_target)
1397 << CalleeTarget << D->getIdentifier() << CallerTarget;
1398 Diag(D->getLocation(), diag::note_previous_decl)
1399 << D->getIdentifier();
1400 return ExprError();
1401 }
1402 }
1403
John McCall113bee02012-03-10 09:33:50 +00001404 bool refersToEnclosingScope =
1405 (CurContext != D->getDeclContext() &&
1406 D->getDeclContext()->isFunctionOrMethod());
1407
Eli Friedmanfa0df832012-02-02 03:46:19 +00001408 DeclRefExpr *E = DeclRefExpr::Create(Context,
1409 SS ? SS->getWithLocInContext(Context)
1410 : NestedNameSpecifierLoc(),
John McCall113bee02012-03-10 09:33:50 +00001411 SourceLocation(),
1412 D, refersToEnclosingScope,
1413 NameInfo, Ty, VK);
Mike Stump11289f42009-09-09 15:08:12 +00001414
Eli Friedmanfa0df832012-02-02 03:46:19 +00001415 MarkDeclRefReferenced(E);
John McCall086a4642010-11-24 05:12:34 +00001416
1417 // Just in case we're building an illegal pointer-to-member.
Richard Smithcaf33902011-10-10 18:28:20 +00001418 FieldDecl *FD = dyn_cast<FieldDecl>(D);
1419 if (FD && FD->isBitField())
John McCall086a4642010-11-24 05:12:34 +00001420 E->setObjectKind(OK_BitField);
1421
1422 return Owned(E);
Douglas Gregorc7acfdf2009-01-06 05:10:23 +00001423}
1424
Abramo Bagnarad6d2f182010-08-11 22:01:17 +00001425/// Decomposes the given name into a DeclarationNameInfo, its location, and
John McCall10eae182009-11-30 22:42:35 +00001426/// possibly a list of template arguments.
1427///
1428/// If this produces template arguments, it is permitted to call
1429/// DecomposeTemplateName.
1430///
1431/// This actually loses a lot of source location information for
1432/// non-standard name kinds; we should consider preserving that in
1433/// some way.
Richard Trieucfc491d2011-08-02 04:35:43 +00001434void
1435Sema::DecomposeUnqualifiedId(const UnqualifiedId &Id,
1436 TemplateArgumentListInfo &Buffer,
1437 DeclarationNameInfo &NameInfo,
1438 const TemplateArgumentListInfo *&TemplateArgs) {
John McCall10eae182009-11-30 22:42:35 +00001439 if (Id.getKind() == UnqualifiedId::IK_TemplateId) {
1440 Buffer.setLAngleLoc(Id.TemplateId->LAngleLoc);
1441 Buffer.setRAngleLoc(Id.TemplateId->RAngleLoc);
1442
Benjamin Kramercc4c49d2012-08-23 23:38:35 +00001443 ASTTemplateArgsPtr TemplateArgsPtr(Id.TemplateId->getTemplateArgs(),
John McCall10eae182009-11-30 22:42:35 +00001444 Id.TemplateId->NumArgs);
Douglas Gregor5476205b2011-06-23 00:49:38 +00001445 translateTemplateArguments(TemplateArgsPtr, Buffer);
John McCall10eae182009-11-30 22:42:35 +00001446
John McCall3e56fd42010-08-23 07:28:44 +00001447 TemplateName TName = Id.TemplateId->Template.get();
Abramo Bagnarad6d2f182010-08-11 22:01:17 +00001448 SourceLocation TNameLoc = Id.TemplateId->TemplateNameLoc;
Douglas Gregor5476205b2011-06-23 00:49:38 +00001449 NameInfo = Context.getNameForTemplate(TName, TNameLoc);
John McCall10eae182009-11-30 22:42:35 +00001450 TemplateArgs = &Buffer;
1451 } else {
Douglas Gregor5476205b2011-06-23 00:49:38 +00001452 NameInfo = GetNameFromUnqualifiedId(Id);
John McCall10eae182009-11-30 22:42:35 +00001453 TemplateArgs = 0;
1454 }
1455}
1456
John McCalld681c392009-12-16 08:11:27 +00001457/// Diagnose an empty lookup.
1458///
1459/// \return false if new lookup candidates were found
Nick Lewyckyc96c37f2010-07-06 19:51:49 +00001460bool Sema::DiagnoseEmptyLookup(Scope *S, CXXScopeSpec &SS, LookupResult &R,
Kaelyn Uhrain79d01c12012-01-18 05:58:54 +00001461 CorrectionCandidateCallback &CCC,
Kaelyn Uhrain42830922011-08-05 00:09:52 +00001462 TemplateArgumentListInfo *ExplicitTemplateArgs,
Ahmed Charlesb24b9aa2012-02-25 11:00:22 +00001463 llvm::ArrayRef<Expr *> Args) {
John McCalld681c392009-12-16 08:11:27 +00001464 DeclarationName Name = R.getLookupName();
1465
John McCalld681c392009-12-16 08:11:27 +00001466 unsigned diagnostic = diag::err_undeclared_var_use;
Douglas Gregor598b08f2009-12-31 05:20:13 +00001467 unsigned diagnostic_suggest = diag::err_undeclared_var_use_suggest;
John McCalld681c392009-12-16 08:11:27 +00001468 if (Name.getNameKind() == DeclarationName::CXXOperatorName ||
1469 Name.getNameKind() == DeclarationName::CXXLiteralOperatorName ||
Douglas Gregor598b08f2009-12-31 05:20:13 +00001470 Name.getNameKind() == DeclarationName::CXXConversionFunctionName) {
John McCalld681c392009-12-16 08:11:27 +00001471 diagnostic = diag::err_undeclared_use;
Douglas Gregor598b08f2009-12-31 05:20:13 +00001472 diagnostic_suggest = diag::err_undeclared_use_suggest;
1473 }
John McCalld681c392009-12-16 08:11:27 +00001474
Douglas Gregor598b08f2009-12-31 05:20:13 +00001475 // If the original lookup was an unqualified lookup, fake an
1476 // unqualified lookup. This is useful when (for example) the
1477 // original lookup would not have found something because it was a
1478 // dependent name.
David Blaikiec4c0e8a2012-05-28 01:26:45 +00001479 DeclContext *DC = (SS.isEmpty() && !CallsUndergoingInstantiation.empty())
1480 ? CurContext : 0;
Francois Pichetde232cb2011-11-25 01:10:54 +00001481 while (DC) {
John McCalld681c392009-12-16 08:11:27 +00001482 if (isa<CXXRecordDecl>(DC)) {
1483 LookupQualifiedName(R, DC);
1484
1485 if (!R.empty()) {
1486 // Don't give errors about ambiguities in this lookup.
1487 R.suppressDiagnostics();
1488
Francois Pichet857f9d62011-11-17 03:44:24 +00001489 // During a default argument instantiation the CurContext points
1490 // to a CXXMethodDecl; but we can't apply a this-> fixit inside a
1491 // function parameter list, hence add an explicit check.
1492 bool isDefaultArgument = !ActiveTemplateInstantiations.empty() &&
1493 ActiveTemplateInstantiations.back().Kind ==
1494 ActiveTemplateInstantiation::DefaultFunctionArgumentInstantiation;
John McCalld681c392009-12-16 08:11:27 +00001495 CXXMethodDecl *CurMethod = dyn_cast<CXXMethodDecl>(CurContext);
1496 bool isInstance = CurMethod &&
1497 CurMethod->isInstance() &&
Francois Pichet857f9d62011-11-17 03:44:24 +00001498 DC == CurMethod->getParent() && !isDefaultArgument;
1499
John McCalld681c392009-12-16 08:11:27 +00001500
1501 // Give a code modification hint to insert 'this->'.
1502 // TODO: fixit for inserting 'Base<T>::' in the other cases.
1503 // Actually quite difficult!
Nico Weberdf7dffb2012-06-20 20:21:42 +00001504 if (getLangOpts().MicrosoftMode)
1505 diagnostic = diag::warn_found_via_dependent_bases_lookup;
Nick Lewyckyc96c37f2010-07-06 19:51:49 +00001506 if (isInstance) {
Nico Weber3c10fb12012-06-22 16:39:39 +00001507 Diag(R.getNameLoc(), diagnostic) << Name
1508 << FixItHint::CreateInsertion(R.getNameLoc(), "this->");
Nick Lewyckyc96c37f2010-07-06 19:51:49 +00001509 UnresolvedLookupExpr *ULE = cast<UnresolvedLookupExpr>(
1510 CallsUndergoingInstantiation.back()->getCallee());
Nico Weber3c10fb12012-06-22 16:39:39 +00001511
1512
1513 CXXMethodDecl *DepMethod;
1514 if (CurMethod->getTemplatedKind() ==
1515 FunctionDecl::TK_FunctionTemplateSpecialization)
1516 DepMethod = cast<CXXMethodDecl>(CurMethod->getPrimaryTemplate()->
1517 getInstantiatedFromMemberTemplate()->getTemplatedDecl());
1518 else
1519 DepMethod = cast<CXXMethodDecl>(
1520 CurMethod->getInstantiatedFromMemberFunction());
1521 assert(DepMethod && "No template pattern found");
1522
1523 QualType DepThisType = DepMethod->getThisType(Context);
1524 CheckCXXThisCapture(R.getNameLoc());
1525 CXXThisExpr *DepThis = new (Context) CXXThisExpr(
1526 R.getNameLoc(), DepThisType, false);
1527 TemplateArgumentListInfo TList;
1528 if (ULE->hasExplicitTemplateArgs())
1529 ULE->copyTemplateArgumentsInto(TList);
1530
1531 CXXScopeSpec SS;
1532 SS.Adopt(ULE->getQualifierLoc());
1533 CXXDependentScopeMemberExpr *DepExpr =
1534 CXXDependentScopeMemberExpr::Create(
1535 Context, DepThis, DepThisType, true, SourceLocation(),
1536 SS.getWithLocInContext(Context),
1537 ULE->getTemplateKeywordLoc(), 0,
1538 R.getLookupNameInfo(),
1539 ULE->hasExplicitTemplateArgs() ? &TList : 0);
1540 CallsUndergoingInstantiation.back()->setCallee(DepExpr);
Nick Lewyckyc96c37f2010-07-06 19:51:49 +00001541 } else {
John McCalld681c392009-12-16 08:11:27 +00001542 Diag(R.getNameLoc(), diagnostic) << Name;
Nick Lewyckyc96c37f2010-07-06 19:51:49 +00001543 }
John McCalld681c392009-12-16 08:11:27 +00001544
1545 // Do we really want to note all of these?
1546 for (LookupResult::iterator I = R.begin(), E = R.end(); I != E; ++I)
1547 Diag((*I)->getLocation(), diag::note_dependent_var_use);
1548
Francois Pichet857f9d62011-11-17 03:44:24 +00001549 // Return true if we are inside a default argument instantiation
1550 // and the found name refers to an instance member function, otherwise
1551 // the function calling DiagnoseEmptyLookup will try to create an
1552 // implicit member call and this is wrong for default argument.
1553 if (isDefaultArgument && ((*R.begin())->isCXXInstanceMember())) {
1554 Diag(R.getNameLoc(), diag::err_member_call_without_object);
1555 return true;
1556 }
1557
John McCalld681c392009-12-16 08:11:27 +00001558 // Tell the callee to try to recover.
1559 return false;
1560 }
Douglas Gregor86b8d9f2010-08-09 22:38:14 +00001561
1562 R.clear();
John McCalld681c392009-12-16 08:11:27 +00001563 }
Francois Pichetde232cb2011-11-25 01:10:54 +00001564
1565 // In Microsoft mode, if we are performing lookup from within a friend
1566 // function definition declared at class scope then we must set
1567 // DC to the lexical parent to be able to search into the parent
1568 // class.
David Blaikiebbafb8a2012-03-11 07:00:24 +00001569 if (getLangOpts().MicrosoftMode && isa<FunctionDecl>(DC) &&
Francois Pichetde232cb2011-11-25 01:10:54 +00001570 cast<FunctionDecl>(DC)->getFriendObjectKind() &&
1571 DC->getLexicalParent()->isRecord())
1572 DC = DC->getLexicalParent();
1573 else
1574 DC = DC->getParent();
John McCalld681c392009-12-16 08:11:27 +00001575 }
1576
Douglas Gregor598b08f2009-12-31 05:20:13 +00001577 // We didn't find anything, so try to correct for a typo.
Douglas Gregorc2fa1692011-06-28 16:20:02 +00001578 TypoCorrection Corrected;
1579 if (S && (Corrected = CorrectTypo(R.getLookupNameInfo(), R.getLookupKind(),
Kaelyn Uhrain4e8942c2012-01-31 23:49:25 +00001580 S, &SS, CCC))) {
David Blaikiebbafb8a2012-03-11 07:00:24 +00001581 std::string CorrectedStr(Corrected.getAsString(getLangOpts()));
1582 std::string CorrectedQuotedStr(Corrected.getQuoted(getLangOpts()));
Douglas Gregorc2fa1692011-06-28 16:20:02 +00001583 R.setLookupName(Corrected.getCorrection());
1584
Hans Wennborg38198de2011-07-12 08:45:31 +00001585 if (NamedDecl *ND = Corrected.getCorrectionDecl()) {
Kaelyn Uhrainacbdc572011-08-03 20:36:05 +00001586 if (Corrected.isOverloaded()) {
1587 OverloadCandidateSet OCS(R.getNameLoc());
1588 OverloadCandidateSet::iterator Best;
1589 for (TypoCorrection::decl_iterator CD = Corrected.begin(),
1590 CDEnd = Corrected.end();
1591 CD != CDEnd; ++CD) {
Kaelyn Uhrain62422202011-08-08 17:35:31 +00001592 if (FunctionTemplateDecl *FTD =
Kaelyn Uhrain42830922011-08-05 00:09:52 +00001593 dyn_cast<FunctionTemplateDecl>(*CD))
1594 AddTemplateOverloadCandidate(
1595 FTD, DeclAccessPair::make(FTD, AS_none), ExplicitTemplateArgs,
Ahmed Charlesb24b9aa2012-02-25 11:00:22 +00001596 Args, OCS);
Kaelyn Uhrain62422202011-08-08 17:35:31 +00001597 else if (FunctionDecl *FD = dyn_cast<FunctionDecl>(*CD))
1598 if (!ExplicitTemplateArgs || ExplicitTemplateArgs->size() == 0)
1599 AddOverloadCandidate(FD, DeclAccessPair::make(FD, AS_none),
Ahmed Charlesb24b9aa2012-02-25 11:00:22 +00001600 Args, OCS);
Kaelyn Uhrainacbdc572011-08-03 20:36:05 +00001601 }
1602 switch (OCS.BestViableFunction(*this, R.getNameLoc(), Best)) {
1603 case OR_Success:
1604 ND = Best->Function;
1605 break;
1606 default:
Kaelyn Uhrainea350182011-08-04 23:30:54 +00001607 break;
Kaelyn Uhrainacbdc572011-08-03 20:36:05 +00001608 }
1609 }
Douglas Gregorc2fa1692011-06-28 16:20:02 +00001610 R.addDecl(ND);
1611 if (isa<ValueDecl>(ND) || isa<FunctionTemplateDecl>(ND)) {
Douglas Gregor280e1ee2010-04-14 20:04:41 +00001612 if (SS.isEmpty())
Douglas Gregorc2fa1692011-06-28 16:20:02 +00001613 Diag(R.getNameLoc(), diagnostic_suggest) << Name << CorrectedQuotedStr
1614 << FixItHint::CreateReplacement(R.getNameLoc(), CorrectedStr);
Douglas Gregor280e1ee2010-04-14 20:04:41 +00001615 else
1616 Diag(R.getNameLoc(), diag::err_no_member_suggest)
Douglas Gregorc2fa1692011-06-28 16:20:02 +00001617 << Name << computeDeclContext(SS, false) << CorrectedQuotedStr
Douglas Gregor280e1ee2010-04-14 20:04:41 +00001618 << SS.getRange()
Douglas Gregorc2fa1692011-06-28 16:20:02 +00001619 << FixItHint::CreateReplacement(R.getNameLoc(), CorrectedStr);
1620 if (ND)
Douglas Gregor280e1ee2010-04-14 20:04:41 +00001621 Diag(ND->getLocation(), diag::note_previous_decl)
Douglas Gregorc2fa1692011-06-28 16:20:02 +00001622 << CorrectedQuotedStr;
Douglas Gregor280e1ee2010-04-14 20:04:41 +00001623
1624 // Tell the callee to try to recover.
1625 return false;
1626 }
Alexis Huntc46382e2010-04-28 23:02:27 +00001627
Douglas Gregorc2fa1692011-06-28 16:20:02 +00001628 if (isa<TypeDecl>(ND) || isa<ObjCInterfaceDecl>(ND)) {
Douglas Gregor280e1ee2010-04-14 20:04:41 +00001629 // FIXME: If we ended up with a typo for a type name or
1630 // Objective-C class name, we're in trouble because the parser
1631 // is in the wrong place to recover. Suggest the typo
1632 // correction, but don't make it a fix-it since we're not going
1633 // to recover well anyway.
1634 if (SS.isEmpty())
Richard Trieucfc491d2011-08-02 04:35:43 +00001635 Diag(R.getNameLoc(), diagnostic_suggest)
1636 << Name << CorrectedQuotedStr;
Douglas Gregor280e1ee2010-04-14 20:04:41 +00001637 else
1638 Diag(R.getNameLoc(), diag::err_no_member_suggest)
Douglas Gregorc2fa1692011-06-28 16:20:02 +00001639 << Name << computeDeclContext(SS, false) << CorrectedQuotedStr
Douglas Gregor280e1ee2010-04-14 20:04:41 +00001640 << SS.getRange();
1641
1642 // Don't try to recover; it won't work.
1643 return true;
1644 }
1645 } else {
Alexis Huntc46382e2010-04-28 23:02:27 +00001646 // FIXME: We found a keyword. Suggest it, but don't provide a fix-it
Douglas Gregor280e1ee2010-04-14 20:04:41 +00001647 // because we aren't able to recover.
Douglas Gregor25363982010-01-01 00:15:04 +00001648 if (SS.isEmpty())
Douglas Gregorc2fa1692011-06-28 16:20:02 +00001649 Diag(R.getNameLoc(), diagnostic_suggest) << Name << CorrectedQuotedStr;
Kovarththanan Rajaratnamba2c6522010-03-13 10:17:05 +00001650 else
Douglas Gregor25363982010-01-01 00:15:04 +00001651 Diag(R.getNameLoc(), diag::err_no_member_suggest)
Douglas Gregorc2fa1692011-06-28 16:20:02 +00001652 << Name << computeDeclContext(SS, false) << CorrectedQuotedStr
Douglas Gregor280e1ee2010-04-14 20:04:41 +00001653 << SS.getRange();
Douglas Gregor25363982010-01-01 00:15:04 +00001654 return true;
1655 }
Douglas Gregor598b08f2009-12-31 05:20:13 +00001656 }
Douglas Gregorc2fa1692011-06-28 16:20:02 +00001657 R.clear();
Douglas Gregor598b08f2009-12-31 05:20:13 +00001658
1659 // Emit a special diagnostic for failed member lookups.
1660 // FIXME: computing the declaration context might fail here (?)
1661 if (!SS.isEmpty()) {
1662 Diag(R.getNameLoc(), diag::err_no_member)
1663 << Name << computeDeclContext(SS, false)
1664 << SS.getRange();
1665 return true;
1666 }
1667
John McCalld681c392009-12-16 08:11:27 +00001668 // Give up, we can't recover.
1669 Diag(R.getNameLoc(), diagnostic) << Name;
1670 return true;
1671}
1672
John McCalldadc5752010-08-24 06:29:42 +00001673ExprResult Sema::ActOnIdExpression(Scope *S,
John McCall24d18942010-08-24 22:52:39 +00001674 CXXScopeSpec &SS,
Abramo Bagnara7945c982012-01-27 09:46:47 +00001675 SourceLocation TemplateKWLoc,
John McCall24d18942010-08-24 22:52:39 +00001676 UnqualifiedId &Id,
1677 bool HasTrailingLParen,
Kaelyn Uhrain77e21fc2012-01-25 20:49:08 +00001678 bool IsAddressOfOperand,
1679 CorrectionCandidateCallback *CCC) {
Richard Trieuba63ce62011-09-09 01:45:06 +00001680 assert(!(IsAddressOfOperand && HasTrailingLParen) &&
John McCalle66edc12009-11-24 19:00:30 +00001681 "cannot be direct & operand and have a trailing lparen");
1682
1683 if (SS.isInvalid())
Douglas Gregored8f2882009-01-30 01:04:22 +00001684 return ExprError();
Douglas Gregor90a1a652009-03-19 17:26:29 +00001685
John McCall10eae182009-11-30 22:42:35 +00001686 TemplateArgumentListInfo TemplateArgsBuffer;
John McCalle66edc12009-11-24 19:00:30 +00001687
1688 // Decompose the UnqualifiedId into the following data.
Abramo Bagnarad6d2f182010-08-11 22:01:17 +00001689 DeclarationNameInfo NameInfo;
John McCalle66edc12009-11-24 19:00:30 +00001690 const TemplateArgumentListInfo *TemplateArgs;
Douglas Gregor5476205b2011-06-23 00:49:38 +00001691 DecomposeUnqualifiedId(Id, TemplateArgsBuffer, NameInfo, TemplateArgs);
Douglas Gregor90a1a652009-03-19 17:26:29 +00001692
Abramo Bagnarad6d2f182010-08-11 22:01:17 +00001693 DeclarationName Name = NameInfo.getName();
Douglas Gregor4ea80432008-11-18 15:03:34 +00001694 IdentifierInfo *II = Name.getAsIdentifierInfo();
Abramo Bagnarad6d2f182010-08-11 22:01:17 +00001695 SourceLocation NameLoc = NameInfo.getLoc();
John McCalld14a8642009-11-21 08:51:07 +00001696
John McCalle66edc12009-11-24 19:00:30 +00001697 // C++ [temp.dep.expr]p3:
1698 // An id-expression is type-dependent if it contains:
Douglas Gregorea0a0a92010-01-11 18:40:55 +00001699 // -- an identifier that was declared with a dependent type,
1700 // (note: handled after lookup)
1701 // -- a template-id that is dependent,
1702 // (note: handled in BuildTemplateIdExpr)
1703 // -- a conversion-function-id that specifies a dependent type,
John McCalle66edc12009-11-24 19:00:30 +00001704 // -- a nested-name-specifier that contains a class-name that
1705 // names a dependent type.
1706 // Determine whether this is a member of an unknown specialization;
1707 // we need to handle these differently.
Eli Friedman964dbda2010-08-06 23:41:47 +00001708 bool DependentID = false;
1709 if (Name.getNameKind() == DeclarationName::CXXConversionFunctionName &&
1710 Name.getCXXNameType()->isDependentType()) {
1711 DependentID = true;
1712 } else if (SS.isSet()) {
Chris Lattnerebb5c6c2011-02-18 01:27:55 +00001713 if (DeclContext *DC = computeDeclContext(SS, false)) {
Eli Friedman964dbda2010-08-06 23:41:47 +00001714 if (RequireCompleteDeclContext(SS, DC))
1715 return ExprError();
Eli Friedman964dbda2010-08-06 23:41:47 +00001716 } else {
1717 DependentID = true;
1718 }
1719 }
1720
Chris Lattnerebb5c6c2011-02-18 01:27:55 +00001721 if (DependentID)
Abramo Bagnara7945c982012-01-27 09:46:47 +00001722 return ActOnDependentIdExpression(SS, TemplateKWLoc, NameInfo,
1723 IsAddressOfOperand, TemplateArgs);
Chris Lattnerebb5c6c2011-02-18 01:27:55 +00001724
John McCalle66edc12009-11-24 19:00:30 +00001725 // Perform the required lookup.
Fariborz Jahanian7f4427f2011-07-12 17:16:56 +00001726 LookupResult R(*this, NameInfo,
1727 (Id.getKind() == UnqualifiedId::IK_ImplicitSelfParam)
1728 ? LookupObjCImplicitSelfParam : LookupOrdinaryName);
John McCalle66edc12009-11-24 19:00:30 +00001729 if (TemplateArgs) {
Douglas Gregor3e51e172010-05-20 20:58:56 +00001730 // Lookup the template name again to correctly establish the context in
1731 // which it was found. This is really unfortunate as we already did the
1732 // lookup to determine that it was a template name in the first place. If
1733 // this becomes a performance hit, we can work harder to preserve those
1734 // results until we get here but it's likely not worth it.
Douglas Gregor786123d2010-05-21 23:18:07 +00001735 bool MemberOfUnknownSpecialization;
1736 LookupTemplateName(R, S, SS, QualType(), /*EnteringContext=*/false,
1737 MemberOfUnknownSpecialization);
Douglas Gregora5226932011-02-04 13:35:07 +00001738
1739 if (MemberOfUnknownSpecialization ||
1740 (R.getResultKind() == LookupResult::NotFoundInCurrentInstantiation))
Abramo Bagnara7945c982012-01-27 09:46:47 +00001741 return ActOnDependentIdExpression(SS, TemplateKWLoc, NameInfo,
1742 IsAddressOfOperand, TemplateArgs);
John McCalle66edc12009-11-24 19:00:30 +00001743 } else {
Benjamin Kramer46921442012-01-20 14:57:34 +00001744 bool IvarLookupFollowUp = II && !SS.isSet() && getCurMethodDecl();
Fariborz Jahanian6fada5b2010-01-12 23:58:59 +00001745 LookupParsedName(R, S, &SS, !IvarLookupFollowUp);
Mike Stump11289f42009-09-09 15:08:12 +00001746
Douglas Gregora5226932011-02-04 13:35:07 +00001747 // If the result might be in a dependent base class, this is a dependent
1748 // id-expression.
1749 if (R.getResultKind() == LookupResult::NotFoundInCurrentInstantiation)
Abramo Bagnara7945c982012-01-27 09:46:47 +00001750 return ActOnDependentIdExpression(SS, TemplateKWLoc, NameInfo,
1751 IsAddressOfOperand, TemplateArgs);
1752
John McCalle66edc12009-11-24 19:00:30 +00001753 // If this reference is in an Objective-C method, then we need to do
1754 // some special Objective-C lookup, too.
Fariborz Jahanian6fada5b2010-01-12 23:58:59 +00001755 if (IvarLookupFollowUp) {
John McCalldadc5752010-08-24 06:29:42 +00001756 ExprResult E(LookupInObjCMethod(R, S, II, true));
John McCalle66edc12009-11-24 19:00:30 +00001757 if (E.isInvalid())
1758 return ExprError();
Mike Stump11289f42009-09-09 15:08:12 +00001759
Chris Lattnerebb5c6c2011-02-18 01:27:55 +00001760 if (Expr *Ex = E.takeAs<Expr>())
1761 return Owned(Ex);
Steve Naroffebf4cb42008-06-02 23:03:37 +00001762 }
Chris Lattner59a25942008-03-31 00:36:02 +00001763 }
Douglas Gregorf15f5d32009-02-16 19:28:42 +00001764
John McCalle66edc12009-11-24 19:00:30 +00001765 if (R.isAmbiguous())
1766 return ExprError();
1767
Douglas Gregor171c45a2009-02-18 21:56:37 +00001768 // Determine whether this name might be a candidate for
1769 // argument-dependent lookup.
John McCalle66edc12009-11-24 19:00:30 +00001770 bool ADL = UseArgumentDependentLookup(SS, R, HasTrailingLParen);
Douglas Gregor171c45a2009-02-18 21:56:37 +00001771
John McCalle66edc12009-11-24 19:00:30 +00001772 if (R.empty() && !ADL) {
Bill Wendling4073ed52007-02-13 01:51:42 +00001773 // Otherwise, this could be an implicitly declared function reference (legal
John McCalle66edc12009-11-24 19:00:30 +00001774 // in C90, extension in C99, forbidden in C++).
David Blaikiebbafb8a2012-03-11 07:00:24 +00001775 if (HasTrailingLParen && II && !getLangOpts().CPlusPlus) {
John McCalle66edc12009-11-24 19:00:30 +00001776 NamedDecl *D = ImplicitlyDefineFunction(NameLoc, *II, S);
1777 if (D) R.addDecl(D);
1778 }
1779
1780 // If this name wasn't predeclared and if this is not a function
1781 // call, diagnose the problem.
1782 if (R.empty()) {
Francois Pichetd8e4e412011-09-24 10:38:05 +00001783
1784 // In Microsoft mode, if we are inside a template class member function
1785 // and we can't resolve an identifier then assume the identifier is type
1786 // dependent. The goal is to postpone name lookup to instantiation time
1787 // to be able to search into type dependent base classes.
David Blaikiebbafb8a2012-03-11 07:00:24 +00001788 if (getLangOpts().MicrosoftMode && CurContext->isDependentContext() &&
Francois Pichetd8e4e412011-09-24 10:38:05 +00001789 isa<CXXMethodDecl>(CurContext))
Abramo Bagnara7945c982012-01-27 09:46:47 +00001790 return ActOnDependentIdExpression(SS, TemplateKWLoc, NameInfo,
1791 IsAddressOfOperand, TemplateArgs);
Francois Pichetd8e4e412011-09-24 10:38:05 +00001792
Kaelyn Uhrain79d01c12012-01-18 05:58:54 +00001793 CorrectionCandidateCallback DefaultValidator;
Kaelyn Uhrain77e21fc2012-01-25 20:49:08 +00001794 if (DiagnoseEmptyLookup(S, SS, R, CCC ? *CCC : DefaultValidator))
John McCalld681c392009-12-16 08:11:27 +00001795 return ExprError();
1796
1797 assert(!R.empty() &&
1798 "DiagnoseEmptyLookup returned false but added no results");
Douglas Gregor35b0bac2010-01-03 18:01:57 +00001799
1800 // If we found an Objective-C instance variable, let
1801 // LookupInObjCMethod build the appropriate expression to
Kovarththanan Rajaratnamba2c6522010-03-13 10:17:05 +00001802 // reference the ivar.
Douglas Gregor35b0bac2010-01-03 18:01:57 +00001803 if (ObjCIvarDecl *Ivar = R.getAsSingle<ObjCIvarDecl>()) {
1804 R.clear();
John McCalldadc5752010-08-24 06:29:42 +00001805 ExprResult E(LookupInObjCMethod(R, S, Ivar->getIdentifier()));
Fariborz Jahanian44653702011-09-23 23:11:38 +00001806 // In a hopelessly buggy code, Objective-C instance variable
1807 // lookup fails and no expression will be built to reference it.
1808 if (!E.isInvalid() && !E.get())
1809 return ExprError();
Benjamin Kramer62b95d82012-08-23 21:35:17 +00001810 return E;
Douglas Gregor35b0bac2010-01-03 18:01:57 +00001811 }
Steve Naroff92e30f82007-04-02 22:35:25 +00001812 }
Chris Lattner17ed4872006-11-20 04:58:19 +00001813 }
Mike Stump11289f42009-09-09 15:08:12 +00001814
John McCalle66edc12009-11-24 19:00:30 +00001815 // This is guaranteed from this point on.
1816 assert(!R.empty() || ADL);
1817
John McCall2d74de92009-12-01 22:10:20 +00001818 // Check whether this might be a C++ implicit instance member access.
John McCall24d18942010-08-24 22:52:39 +00001819 // C++ [class.mfct.non-static]p3:
1820 // When an id-expression that is not part of a class member access
1821 // syntax and not used to form a pointer to member is used in the
1822 // body of a non-static member function of class X, if name lookup
1823 // resolves the name in the id-expression to a non-static non-type
1824 // member of some class C, the id-expression is transformed into a
1825 // class member access expression using (*this) as the
1826 // postfix-expression to the left of the . operator.
John McCall8d08b9b2010-08-27 09:08:28 +00001827 //
1828 // But we don't actually need to do this for '&' operands if R
1829 // resolved to a function or overloaded function set, because the
1830 // expression is ill-formed if it actually works out to be a
1831 // non-static member function:
1832 //
1833 // C++ [expr.ref]p4:
1834 // Otherwise, if E1.E2 refers to a non-static member function. . .
1835 // [t]he expression can be used only as the left-hand operand of a
1836 // member function call.
1837 //
1838 // There are other safeguards against such uses, but it's important
1839 // to get this right here so that we don't end up making a
1840 // spuriously dependent expression if we're inside a dependent
1841 // instance method.
John McCall57500772009-12-16 12:17:52 +00001842 if (!R.empty() && (*R.begin())->isCXXClassMember()) {
John McCall8d08b9b2010-08-27 09:08:28 +00001843 bool MightBeImplicitMember;
Richard Trieuba63ce62011-09-09 01:45:06 +00001844 if (!IsAddressOfOperand)
John McCall8d08b9b2010-08-27 09:08:28 +00001845 MightBeImplicitMember = true;
1846 else if (!SS.isEmpty())
1847 MightBeImplicitMember = false;
1848 else if (R.isOverloadedResult())
1849 MightBeImplicitMember = false;
Douglas Gregor1262b062010-08-30 16:00:47 +00001850 else if (R.isUnresolvableResult())
1851 MightBeImplicitMember = true;
John McCall8d08b9b2010-08-27 09:08:28 +00001852 else
Francois Pichet783dd6e2010-11-21 06:08:52 +00001853 MightBeImplicitMember = isa<FieldDecl>(R.getFoundDecl()) ||
1854 isa<IndirectFieldDecl>(R.getFoundDecl());
John McCall8d08b9b2010-08-27 09:08:28 +00001855
1856 if (MightBeImplicitMember)
Abramo Bagnara7945c982012-01-27 09:46:47 +00001857 return BuildPossibleImplicitMemberExpr(SS, TemplateKWLoc,
1858 R, TemplateArgs);
John McCallb53bbd42009-11-22 01:44:31 +00001859 }
1860
Abramo Bagnara65f7c3d2012-02-06 14:31:00 +00001861 if (TemplateArgs || TemplateKWLoc.isValid())
1862 return BuildTemplateIdExpr(SS, TemplateKWLoc, R, ADL, TemplateArgs);
John McCallb53bbd42009-11-22 01:44:31 +00001863
John McCalle66edc12009-11-24 19:00:30 +00001864 return BuildDeclarationNameExpr(SS, R, ADL);
1865}
1866
John McCall10eae182009-11-30 22:42:35 +00001867/// BuildQualifiedDeclarationNameExpr - Build a C++ qualified
1868/// declaration name, generally during template instantiation.
1869/// There's a large number of things which don't need to be done along
1870/// this path.
John McCalldadc5752010-08-24 06:29:42 +00001871ExprResult
Jeffrey Yasskinc76498d2010-04-08 16:38:48 +00001872Sema::BuildQualifiedDeclarationNameExpr(CXXScopeSpec &SS,
Abramo Bagnarad6d2f182010-08-11 22:01:17 +00001873 const DeclarationNameInfo &NameInfo) {
John McCalle66edc12009-11-24 19:00:30 +00001874 DeclContext *DC;
Douglas Gregora02bb342010-04-28 07:04:26 +00001875 if (!(DC = computeDeclContext(SS, false)) || DC->isDependentContext())
Abramo Bagnara65f7c3d2012-02-06 14:31:00 +00001876 return BuildDependentDeclRefExpr(SS, /*TemplateKWLoc=*/SourceLocation(),
1877 NameInfo, /*TemplateArgs=*/0);
John McCalle66edc12009-11-24 19:00:30 +00001878
John McCall0b66eb32010-05-01 00:40:08 +00001879 if (RequireCompleteDeclContext(SS, DC))
Douglas Gregora02bb342010-04-28 07:04:26 +00001880 return ExprError();
1881
Abramo Bagnarad6d2f182010-08-11 22:01:17 +00001882 LookupResult R(*this, NameInfo, LookupOrdinaryName);
John McCalle66edc12009-11-24 19:00:30 +00001883 LookupQualifiedName(R, DC);
1884
1885 if (R.isAmbiguous())
1886 return ExprError();
1887
1888 if (R.empty()) {
Abramo Bagnarad6d2f182010-08-11 22:01:17 +00001889 Diag(NameInfo.getLoc(), diag::err_no_member)
1890 << NameInfo.getName() << DC << SS.getRange();
John McCalle66edc12009-11-24 19:00:30 +00001891 return ExprError();
1892 }
1893
1894 return BuildDeclarationNameExpr(SS, R, /*ADL*/ false);
1895}
1896
1897/// LookupInObjCMethod - The parser has read a name in, and Sema has
1898/// detected that we're currently inside an ObjC method. Perform some
1899/// additional lookup.
1900///
1901/// Ideally, most of this would be done by lookup, but there's
1902/// actually quite a lot of extra work involved.
1903///
1904/// Returns a null sentinel to indicate trivial success.
John McCalldadc5752010-08-24 06:29:42 +00001905ExprResult
John McCalle66edc12009-11-24 19:00:30 +00001906Sema::LookupInObjCMethod(LookupResult &Lookup, Scope *S,
Chris Lattnera36ec422010-04-11 08:28:14 +00001907 IdentifierInfo *II, bool AllowBuiltinCreation) {
John McCalle66edc12009-11-24 19:00:30 +00001908 SourceLocation Loc = Lookup.getNameLoc();
Chris Lattner87313662010-04-12 05:10:17 +00001909 ObjCMethodDecl *CurMethod = getCurMethodDecl();
Alexis Huntc46382e2010-04-28 23:02:27 +00001910
John McCalle66edc12009-11-24 19:00:30 +00001911 // There are two cases to handle here. 1) scoped lookup could have failed,
1912 // in which case we should look for an ivar. 2) scoped lookup could have
1913 // found a decl, but that decl is outside the current instance method (i.e.
1914 // a global variable). In these two cases, we do a lookup for an ivar with
1915 // this name, if the lookup sucedes, we replace it our current decl.
1916
1917 // If we're in a class method, we don't normally want to look for
1918 // ivars. But if we don't find anything else, and there's an
1919 // ivar, that's an error.
Chris Lattner87313662010-04-12 05:10:17 +00001920 bool IsClassMethod = CurMethod->isClassMethod();
John McCalle66edc12009-11-24 19:00:30 +00001921
1922 bool LookForIvars;
1923 if (Lookup.empty())
1924 LookForIvars = true;
1925 else if (IsClassMethod)
1926 LookForIvars = false;
1927 else
1928 LookForIvars = (Lookup.isSingleResult() &&
1929 Lookup.getFoundDecl()->isDefinedOutsideFunctionOrMethod());
Fariborz Jahanian45878032010-02-09 19:31:38 +00001930 ObjCInterfaceDecl *IFace = 0;
John McCalle66edc12009-11-24 19:00:30 +00001931 if (LookForIvars) {
Chris Lattner87313662010-04-12 05:10:17 +00001932 IFace = CurMethod->getClassInterface();
John McCalle66edc12009-11-24 19:00:30 +00001933 ObjCInterfaceDecl *ClassDeclared;
Argyrios Kyrtzidis4e8b1362011-10-19 02:25:16 +00001934 ObjCIvarDecl *IV = 0;
1935 if (IFace && (IV = IFace->lookupInstanceVariable(II, ClassDeclared))) {
John McCalle66edc12009-11-24 19:00:30 +00001936 // Diagnose using an ivar in a class method.
1937 if (IsClassMethod)
1938 return ExprError(Diag(Loc, diag::error_ivar_use_in_class_method)
1939 << IV->getDeclName());
1940
1941 // If we're referencing an invalid decl, just return this as a silent
1942 // error node. The error diagnostic was already emitted on the decl.
1943 if (IV->isInvalidDecl())
1944 return ExprError();
1945
1946 // Check if referencing a field with __attribute__((deprecated)).
1947 if (DiagnoseUseOfDecl(IV, Loc))
1948 return ExprError();
1949
1950 // Diagnose the use of an ivar outside of the declaring class.
1951 if (IV->getAccessControl() == ObjCIvarDecl::Private &&
Fariborz Jahaniand6cb4a82012-03-07 00:58:41 +00001952 !declaresSameEntity(ClassDeclared, IFace) &&
David Blaikiebbafb8a2012-03-11 07:00:24 +00001953 !getLangOpts().DebuggerSupport)
John McCalle66edc12009-11-24 19:00:30 +00001954 Diag(Loc, diag::error_private_ivar_access) << IV->getDeclName();
1955
1956 // FIXME: This should use a new expr for a direct reference, don't
1957 // turn this into Self->ivar, just return a BareIVarExpr or something.
1958 IdentifierInfo &II = Context.Idents.get("self");
1959 UnqualifiedId SelfName;
Kovarththanan Rajaratnamba2c6522010-03-13 10:17:05 +00001960 SelfName.setIdentifier(&II, SourceLocation());
Fariborz Jahanian7f4427f2011-07-12 17:16:56 +00001961 SelfName.setKind(UnqualifiedId::IK_ImplicitSelfParam);
John McCalle66edc12009-11-24 19:00:30 +00001962 CXXScopeSpec SelfScopeSpec;
Abramo Bagnara7945c982012-01-27 09:46:47 +00001963 SourceLocation TemplateKWLoc;
1964 ExprResult SelfExpr = ActOnIdExpression(S, SelfScopeSpec, TemplateKWLoc,
Douglas Gregora1ed39b2010-09-22 16:33:13 +00001965 SelfName, false, false);
1966 if (SelfExpr.isInvalid())
1967 return ExprError();
1968
John Wiegley01296292011-04-08 18:41:53 +00001969 SelfExpr = DefaultLvalueConversion(SelfExpr.take());
1970 if (SelfExpr.isInvalid())
1971 return ExprError();
John McCall27584242010-12-06 20:48:59 +00001972
Eli Friedmanfa0df832012-02-02 03:46:19 +00001973 MarkAnyDeclReferenced(Loc, IV);
Fariborz Jahaniana5063a62012-08-08 16:41:04 +00001974
1975 ObjCMethodFamily MF = CurMethod->getMethodFamily();
1976 if (MF != OMF_init && MF != OMF_dealloc && MF != OMF_finalize)
1977 Diag(Loc, diag::warn_direct_ivar_access) << IV->getDeclName();
John McCalle66edc12009-11-24 19:00:30 +00001978 return Owned(new (Context)
1979 ObjCIvarRefExpr(IV, IV->getType(), Loc,
John Wiegley01296292011-04-08 18:41:53 +00001980 SelfExpr.take(), true, true));
John McCalle66edc12009-11-24 19:00:30 +00001981 }
Chris Lattner87313662010-04-12 05:10:17 +00001982 } else if (CurMethod->isInstanceMethod()) {
John McCalle66edc12009-11-24 19:00:30 +00001983 // We should warn if a local variable hides an ivar.
Fariborz Jahanian557fc9a2011-11-08 22:51:27 +00001984 if (ObjCInterfaceDecl *IFace = CurMethod->getClassInterface()) {
1985 ObjCInterfaceDecl *ClassDeclared;
1986 if (ObjCIvarDecl *IV = IFace->lookupInstanceVariable(II, ClassDeclared)) {
1987 if (IV->getAccessControl() != ObjCIvarDecl::Private ||
Douglas Gregor0b144e12011-12-15 00:29:59 +00001988 declaresSameEntity(IFace, ClassDeclared))
Fariborz Jahanian557fc9a2011-11-08 22:51:27 +00001989 Diag(Loc, diag::warn_ivar_use_hidden) << IV->getDeclName();
1990 }
John McCalle66edc12009-11-24 19:00:30 +00001991 }
Fariborz Jahanian028b9e12011-12-20 22:21:08 +00001992 } else if (Lookup.isSingleResult() &&
1993 Lookup.getFoundDecl()->isDefinedOutsideFunctionOrMethod()) {
1994 // If accessing a stand-alone ivar in a class method, this is an error.
1995 if (const ObjCIvarDecl *IV = dyn_cast<ObjCIvarDecl>(Lookup.getFoundDecl()))
1996 return ExprError(Diag(Loc, diag::error_ivar_use_in_class_method)
1997 << IV->getDeclName());
John McCalle66edc12009-11-24 19:00:30 +00001998 }
1999
Fariborz Jahanian6fada5b2010-01-12 23:58:59 +00002000 if (Lookup.empty() && II && AllowBuiltinCreation) {
2001 // FIXME. Consolidate this with similar code in LookupName.
2002 if (unsigned BuiltinID = II->getBuiltinID()) {
David Blaikiebbafb8a2012-03-11 07:00:24 +00002003 if (!(getLangOpts().CPlusPlus &&
Fariborz Jahanian6fada5b2010-01-12 23:58:59 +00002004 Context.BuiltinInfo.isPredefinedLibFunction(BuiltinID))) {
2005 NamedDecl *D = LazilyCreateBuiltin((IdentifierInfo *)II, BuiltinID,
2006 S, Lookup.isForRedeclaration(),
2007 Lookup.getNameLoc());
2008 if (D) Lookup.addDecl(D);
2009 }
2010 }
2011 }
John McCalle66edc12009-11-24 19:00:30 +00002012 // Sentinel value saying that we didn't do anything special.
2013 return Owned((Expr*) 0);
Douglas Gregor3256d042009-06-30 15:47:41 +00002014}
John McCalld14a8642009-11-21 08:51:07 +00002015
John McCall16df1e52010-03-30 21:47:33 +00002016/// \brief Cast a base object to a member's actual type.
2017///
2018/// Logically this happens in three phases:
2019///
2020/// * First we cast from the base type to the naming class.
2021/// The naming class is the class into which we were looking
2022/// when we found the member; it's the qualifier type if a
2023/// qualifier was provided, and otherwise it's the base type.
2024///
2025/// * Next we cast from the naming class to the declaring class.
2026/// If the member we found was brought into a class's scope by
2027/// a using declaration, this is that class; otherwise it's
2028/// the class declaring the member.
2029///
2030/// * Finally we cast from the declaring class to the "true"
2031/// declaring class of the member. This conversion does not
2032/// obey access control.
John Wiegley01296292011-04-08 18:41:53 +00002033ExprResult
2034Sema::PerformObjectMemberConversion(Expr *From,
Douglas Gregorcc3f3252010-03-03 23:55:11 +00002035 NestedNameSpecifier *Qualifier,
John McCall16df1e52010-03-30 21:47:33 +00002036 NamedDecl *FoundDecl,
Douglas Gregorcc3f3252010-03-03 23:55:11 +00002037 NamedDecl *Member) {
2038 CXXRecordDecl *RD = dyn_cast<CXXRecordDecl>(Member->getDeclContext());
2039 if (!RD)
John Wiegley01296292011-04-08 18:41:53 +00002040 return Owned(From);
Kovarththanan Rajaratnamba2c6522010-03-13 10:17:05 +00002041
Douglas Gregorcc3f3252010-03-03 23:55:11 +00002042 QualType DestRecordType;
2043 QualType DestType;
2044 QualType FromRecordType;
2045 QualType FromType = From->getType();
2046 bool PointerConversions = false;
2047 if (isa<FieldDecl>(Member)) {
2048 DestRecordType = Context.getCanonicalType(Context.getTypeDeclType(RD));
Kovarththanan Rajaratnamba2c6522010-03-13 10:17:05 +00002049
Douglas Gregorcc3f3252010-03-03 23:55:11 +00002050 if (FromType->getAs<PointerType>()) {
2051 DestType = Context.getPointerType(DestRecordType);
2052 FromRecordType = FromType->getPointeeType();
2053 PointerConversions = true;
2054 } else {
2055 DestType = DestRecordType;
2056 FromRecordType = FromType;
Fariborz Jahanianbb67b822009-07-29 18:40:24 +00002057 }
Douglas Gregorcc3f3252010-03-03 23:55:11 +00002058 } else if (CXXMethodDecl *Method = dyn_cast<CXXMethodDecl>(Member)) {
2059 if (Method->isStatic())
John Wiegley01296292011-04-08 18:41:53 +00002060 return Owned(From);
Kovarththanan Rajaratnamba2c6522010-03-13 10:17:05 +00002061
Douglas Gregorcc3f3252010-03-03 23:55:11 +00002062 DestType = Method->getThisType(Context);
2063 DestRecordType = DestType->getPointeeType();
Kovarththanan Rajaratnamba2c6522010-03-13 10:17:05 +00002064
Douglas Gregorcc3f3252010-03-03 23:55:11 +00002065 if (FromType->getAs<PointerType>()) {
2066 FromRecordType = FromType->getPointeeType();
2067 PointerConversions = true;
2068 } else {
2069 FromRecordType = FromType;
2070 DestType = DestRecordType;
2071 }
2072 } else {
2073 // No conversion necessary.
John Wiegley01296292011-04-08 18:41:53 +00002074 return Owned(From);
Douglas Gregorcc3f3252010-03-03 23:55:11 +00002075 }
Kovarththanan Rajaratnamba2c6522010-03-13 10:17:05 +00002076
Douglas Gregorcc3f3252010-03-03 23:55:11 +00002077 if (DestType->isDependentType() || FromType->isDependentType())
John Wiegley01296292011-04-08 18:41:53 +00002078 return Owned(From);
Kovarththanan Rajaratnamba2c6522010-03-13 10:17:05 +00002079
Douglas Gregorcc3f3252010-03-03 23:55:11 +00002080 // If the unqualified types are the same, no conversion is necessary.
2081 if (Context.hasSameUnqualifiedType(FromRecordType, DestRecordType))
John Wiegley01296292011-04-08 18:41:53 +00002082 return Owned(From);
Kovarththanan Rajaratnamba2c6522010-03-13 10:17:05 +00002083
John McCall16df1e52010-03-30 21:47:33 +00002084 SourceRange FromRange = From->getSourceRange();
2085 SourceLocation FromLoc = FromRange.getBegin();
2086
Eli Friedmanbe4b3632011-09-27 21:58:52 +00002087 ExprValueKind VK = From->getValueKind();
Sebastian Redlc57d34b2010-07-20 04:20:21 +00002088
Douglas Gregorcc3f3252010-03-03 23:55:11 +00002089 // C++ [class.member.lookup]p8:
Kovarththanan Rajaratnamba2c6522010-03-13 10:17:05 +00002090 // [...] Ambiguities can often be resolved by qualifying a name with its
Douglas Gregorcc3f3252010-03-03 23:55:11 +00002091 // class name.
2092 //
2093 // If the member was a qualified name and the qualified referred to a
2094 // specific base subobject type, we'll cast to that intermediate type
2095 // first and then to the object in which the member is declared. That allows
2096 // one to resolve ambiguities in, e.g., a diamond-shaped hierarchy such as:
2097 //
2098 // class Base { public: int x; };
2099 // class Derived1 : public Base { };
2100 // class Derived2 : public Base { };
2101 // class VeryDerived : public Derived1, public Derived2 { void f(); };
2102 //
2103 // void VeryDerived::f() {
2104 // x = 17; // error: ambiguous base subobjects
2105 // Derived1::x = 17; // okay, pick the Base subobject of Derived1
2106 // }
Douglas Gregorcc3f3252010-03-03 23:55:11 +00002107 if (Qualifier) {
John McCall16df1e52010-03-30 21:47:33 +00002108 QualType QType = QualType(Qualifier->getAsType(), 0);
2109 assert(!QType.isNull() && "lookup done with dependent qualifier?");
2110 assert(QType->isRecordType() && "lookup done with non-record type");
2111
2112 QualType QRecordType = QualType(QType->getAs<RecordType>(), 0);
2113
2114 // In C++98, the qualifier type doesn't actually have to be a base
2115 // type of the object type, in which case we just ignore it.
2116 // Otherwise build the appropriate casts.
2117 if (IsDerivedFrom(FromRecordType, QRecordType)) {
John McCallcf142162010-08-07 06:22:56 +00002118 CXXCastPath BasePath;
John McCall16df1e52010-03-30 21:47:33 +00002119 if (CheckDerivedToBaseConversion(FromRecordType, QRecordType,
Anders Carlssonb78feca2010-04-24 19:22:20 +00002120 FromLoc, FromRange, &BasePath))
John Wiegley01296292011-04-08 18:41:53 +00002121 return ExprError();
John McCall16df1e52010-03-30 21:47:33 +00002122
Douglas Gregorcc3f3252010-03-03 23:55:11 +00002123 if (PointerConversions)
John McCall16df1e52010-03-30 21:47:33 +00002124 QType = Context.getPointerType(QType);
John Wiegley01296292011-04-08 18:41:53 +00002125 From = ImpCastExprToType(From, QType, CK_UncheckedDerivedToBase,
2126 VK, &BasePath).take();
John McCall16df1e52010-03-30 21:47:33 +00002127
2128 FromType = QType;
2129 FromRecordType = QRecordType;
2130
2131 // If the qualifier type was the same as the destination type,
2132 // we're done.
2133 if (Context.hasSameUnqualifiedType(FromRecordType, DestRecordType))
John Wiegley01296292011-04-08 18:41:53 +00002134 return Owned(From);
Douglas Gregorcc3f3252010-03-03 23:55:11 +00002135 }
2136 }
Kovarththanan Rajaratnamba2c6522010-03-13 10:17:05 +00002137
John McCall16df1e52010-03-30 21:47:33 +00002138 bool IgnoreAccess = false;
Douglas Gregorcc3f3252010-03-03 23:55:11 +00002139
John McCall16df1e52010-03-30 21:47:33 +00002140 // If we actually found the member through a using declaration, cast
2141 // down to the using declaration's type.
2142 //
2143 // Pointer equality is fine here because only one declaration of a
2144 // class ever has member declarations.
2145 if (FoundDecl->getDeclContext() != Member->getDeclContext()) {
2146 assert(isa<UsingShadowDecl>(FoundDecl));
2147 QualType URecordType = Context.getTypeDeclType(
2148 cast<CXXRecordDecl>(FoundDecl->getDeclContext()));
2149
2150 // We only need to do this if the naming-class to declaring-class
2151 // conversion is non-trivial.
2152 if (!Context.hasSameUnqualifiedType(FromRecordType, URecordType)) {
2153 assert(IsDerivedFrom(FromRecordType, URecordType));
John McCallcf142162010-08-07 06:22:56 +00002154 CXXCastPath BasePath;
John McCall16df1e52010-03-30 21:47:33 +00002155 if (CheckDerivedToBaseConversion(FromRecordType, URecordType,
Anders Carlssonb78feca2010-04-24 19:22:20 +00002156 FromLoc, FromRange, &BasePath))
John Wiegley01296292011-04-08 18:41:53 +00002157 return ExprError();
Alexis Huntc46382e2010-04-28 23:02:27 +00002158
John McCall16df1e52010-03-30 21:47:33 +00002159 QualType UType = URecordType;
2160 if (PointerConversions)
2161 UType = Context.getPointerType(UType);
John Wiegley01296292011-04-08 18:41:53 +00002162 From = ImpCastExprToType(From, UType, CK_UncheckedDerivedToBase,
2163 VK, &BasePath).take();
John McCall16df1e52010-03-30 21:47:33 +00002164 FromType = UType;
2165 FromRecordType = URecordType;
2166 }
2167
2168 // We don't do access control for the conversion from the
2169 // declaring class to the true declaring class.
2170 IgnoreAccess = true;
Douglas Gregorcc3f3252010-03-03 23:55:11 +00002171 }
Kovarththanan Rajaratnamba2c6522010-03-13 10:17:05 +00002172
John McCallcf142162010-08-07 06:22:56 +00002173 CXXCastPath BasePath;
Anders Carlssonb78feca2010-04-24 19:22:20 +00002174 if (CheckDerivedToBaseConversion(FromRecordType, DestRecordType,
2175 FromLoc, FromRange, &BasePath,
John McCall16df1e52010-03-30 21:47:33 +00002176 IgnoreAccess))
John Wiegley01296292011-04-08 18:41:53 +00002177 return ExprError();
Kovarththanan Rajaratnamba2c6522010-03-13 10:17:05 +00002178
John Wiegley01296292011-04-08 18:41:53 +00002179 return ImpCastExprToType(From, DestType, CK_UncheckedDerivedToBase,
2180 VK, &BasePath);
Fariborz Jahanianbb67b822009-07-29 18:40:24 +00002181}
Douglas Gregor3256d042009-06-30 15:47:41 +00002182
John McCalle66edc12009-11-24 19:00:30 +00002183bool Sema::UseArgumentDependentLookup(const CXXScopeSpec &SS,
John McCallb53bbd42009-11-22 01:44:31 +00002184 const LookupResult &R,
2185 bool HasTrailingLParen) {
John McCalld14a8642009-11-21 08:51:07 +00002186 // Only when used directly as the postfix-expression of a call.
2187 if (!HasTrailingLParen)
2188 return false;
2189
2190 // Never if a scope specifier was provided.
John McCalle66edc12009-11-24 19:00:30 +00002191 if (SS.isSet())
John McCalld14a8642009-11-21 08:51:07 +00002192 return false;
2193
2194 // Only in C++ or ObjC++.
David Blaikiebbafb8a2012-03-11 07:00:24 +00002195 if (!getLangOpts().CPlusPlus)
John McCalld14a8642009-11-21 08:51:07 +00002196 return false;
2197
2198 // Turn off ADL when we find certain kinds of declarations during
2199 // normal lookup:
2200 for (LookupResult::iterator I = R.begin(), E = R.end(); I != E; ++I) {
2201 NamedDecl *D = *I;
2202
2203 // C++0x [basic.lookup.argdep]p3:
2204 // -- a declaration of a class member
2205 // Since using decls preserve this property, we check this on the
2206 // original decl.
John McCall57500772009-12-16 12:17:52 +00002207 if (D->isCXXClassMember())
John McCalld14a8642009-11-21 08:51:07 +00002208 return false;
2209
2210 // C++0x [basic.lookup.argdep]p3:
2211 // -- a block-scope function declaration that is not a
2212 // using-declaration
2213 // NOTE: we also trigger this for function templates (in fact, we
2214 // don't check the decl type at all, since all other decl types
2215 // turn off ADL anyway).
2216 if (isa<UsingShadowDecl>(D))
2217 D = cast<UsingShadowDecl>(D)->getTargetDecl();
2218 else if (D->getDeclContext()->isFunctionOrMethod())
2219 return false;
2220
2221 // C++0x [basic.lookup.argdep]p3:
2222 // -- a declaration that is neither a function or a function
2223 // template
2224 // And also for builtin functions.
2225 if (isa<FunctionDecl>(D)) {
2226 FunctionDecl *FDecl = cast<FunctionDecl>(D);
2227
2228 // But also builtin functions.
2229 if (FDecl->getBuiltinID() && FDecl->isImplicit())
2230 return false;
2231 } else if (!isa<FunctionTemplateDecl>(D))
2232 return false;
2233 }
2234
2235 return true;
2236}
2237
2238
John McCalld14a8642009-11-21 08:51:07 +00002239/// Diagnoses obvious problems with the use of the given declaration
2240/// as an expression. This is only actually called for lookups that
2241/// were not overloaded, and it doesn't promise that the declaration
2242/// will in fact be used.
2243static bool CheckDeclInExpr(Sema &S, SourceLocation Loc, NamedDecl *D) {
Richard Smithdda56e42011-04-15 14:24:37 +00002244 if (isa<TypedefNameDecl>(D)) {
John McCalld14a8642009-11-21 08:51:07 +00002245 S.Diag(Loc, diag::err_unexpected_typedef) << D->getDeclName();
2246 return true;
2247 }
2248
2249 if (isa<ObjCInterfaceDecl>(D)) {
2250 S.Diag(Loc, diag::err_unexpected_interface) << D->getDeclName();
2251 return true;
2252 }
2253
2254 if (isa<NamespaceDecl>(D)) {
2255 S.Diag(Loc, diag::err_unexpected_namespace) << D->getDeclName();
2256 return true;
2257 }
2258
2259 return false;
2260}
2261
John McCalldadc5752010-08-24 06:29:42 +00002262ExprResult
John McCalle66edc12009-11-24 19:00:30 +00002263Sema::BuildDeclarationNameExpr(const CXXScopeSpec &SS,
John McCallb53bbd42009-11-22 01:44:31 +00002264 LookupResult &R,
2265 bool NeedsADL) {
John McCall3a60c872009-12-08 22:45:53 +00002266 // If this is a single, fully-resolved result and we don't need ADL,
2267 // just build an ordinary singleton decl ref.
Douglas Gregor4b4844f2010-01-29 17:15:43 +00002268 if (!NeedsADL && R.isSingleResult() && !R.getAsSingle<FunctionTemplateDecl>())
Abramo Bagnarad6d2f182010-08-11 22:01:17 +00002269 return BuildDeclarationNameExpr(SS, R.getLookupNameInfo(),
2270 R.getFoundDecl());
John McCalld14a8642009-11-21 08:51:07 +00002271
2272 // We only need to check the declaration if there's exactly one
2273 // result, because in the overloaded case the results can only be
2274 // functions and function templates.
John McCallb53bbd42009-11-22 01:44:31 +00002275 if (R.isSingleResult() &&
2276 CheckDeclInExpr(*this, R.getNameLoc(), R.getFoundDecl()))
John McCalld14a8642009-11-21 08:51:07 +00002277 return ExprError();
2278
John McCall58cc69d2010-01-27 01:50:18 +00002279 // Otherwise, just build an unresolved lookup expression. Suppress
2280 // any lookup-related diagnostics; we'll hash these out later, when
2281 // we've picked a target.
2282 R.suppressDiagnostics();
2283
John McCalld14a8642009-11-21 08:51:07 +00002284 UnresolvedLookupExpr *ULE
Douglas Gregora6e053e2010-12-15 01:34:56 +00002285 = UnresolvedLookupExpr::Create(Context, R.getNamingClass(),
Douglas Gregor0da1d432011-02-28 20:01:57 +00002286 SS.getWithLocInContext(Context),
2287 R.getLookupNameInfo(),
Douglas Gregor30a4f4c2010-05-23 18:57:34 +00002288 NeedsADL, R.isOverloadedResult(),
2289 R.begin(), R.end());
John McCalld14a8642009-11-21 08:51:07 +00002290
2291 return Owned(ULE);
2292}
Kovarththanan Rajaratnamba2c6522010-03-13 10:17:05 +00002293
John McCalld14a8642009-11-21 08:51:07 +00002294/// \brief Complete semantic analysis for a reference to the given declaration.
John McCalldadc5752010-08-24 06:29:42 +00002295ExprResult
John McCalle66edc12009-11-24 19:00:30 +00002296Sema::BuildDeclarationNameExpr(const CXXScopeSpec &SS,
Abramo Bagnarad6d2f182010-08-11 22:01:17 +00002297 const DeclarationNameInfo &NameInfo,
2298 NamedDecl *D) {
John McCalld14a8642009-11-21 08:51:07 +00002299 assert(D && "Cannot refer to a NULL declaration");
John McCall283b9012009-11-22 00:44:51 +00002300 assert(!isa<FunctionTemplateDecl>(D) &&
2301 "Cannot refer unambiguously to a function template");
John McCalld14a8642009-11-21 08:51:07 +00002302
Abramo Bagnarad6d2f182010-08-11 22:01:17 +00002303 SourceLocation Loc = NameInfo.getLoc();
John McCalld14a8642009-11-21 08:51:07 +00002304 if (CheckDeclInExpr(*this, Loc, D))
2305 return ExprError();
Steve Narofff1e53692007-03-23 22:27:02 +00002306
Douglas Gregore7488b92009-12-01 16:58:18 +00002307 if (TemplateDecl *Template = dyn_cast<TemplateDecl>(D)) {
2308 // Specifically diagnose references to class templates that are missing
2309 // a template argument list.
2310 Diag(Loc, diag::err_template_decl_ref)
2311 << Template << SS.getRange();
2312 Diag(Template->getLocation(), diag::note_template_decl_here);
2313 return ExprError();
2314 }
2315
2316 // Make sure that we're referring to a value.
2317 ValueDecl *VD = dyn_cast<ValueDecl>(D);
2318 if (!VD) {
Kovarththanan Rajaratnamba2c6522010-03-13 10:17:05 +00002319 Diag(Loc, diag::err_ref_non_value)
Douglas Gregore7488b92009-12-01 16:58:18 +00002320 << D << SS.getRange();
John McCallb48971d2009-12-18 18:35:10 +00002321 Diag(D->getLocation(), diag::note_declared_at);
Douglas Gregore7488b92009-12-01 16:58:18 +00002322 return ExprError();
2323 }
Sebastian Redlffbcf962009-01-18 18:53:16 +00002324
Douglas Gregor171c45a2009-02-18 21:56:37 +00002325 // Check whether this declaration can be used. Note that we suppress
2326 // this check when we're going to perform argument-dependent lookup
2327 // on this function name, because this might not be the function
2328 // that overload resolution actually selects.
John McCalld14a8642009-11-21 08:51:07 +00002329 if (DiagnoseUseOfDecl(VD, Loc))
Douglas Gregor171c45a2009-02-18 21:56:37 +00002330 return ExprError();
2331
Steve Naroff8de9c3a2008-09-05 22:11:13 +00002332 // Only create DeclRefExpr's for valid Decl's.
2333 if (VD->isInvalidDecl())
Sebastian Redlffbcf962009-01-18 18:53:16 +00002334 return ExprError();
2335
John McCallf3a88602011-02-03 08:15:49 +00002336 // Handle members of anonymous structs and unions. If we got here,
2337 // and the reference is to a class member indirect field, then this
2338 // must be the subject of a pointer-to-member expression.
2339 if (IndirectFieldDecl *indirectField = dyn_cast<IndirectFieldDecl>(VD))
2340 if (!indirectField->isCXXClassMember())
2341 return BuildAnonymousStructUnionMemberReference(SS, NameInfo.getLoc(),
2342 indirectField);
Francois Pichet783dd6e2010-11-21 06:08:52 +00002343
Eli Friedman9bb33f52012-02-03 02:04:35 +00002344 {
John McCallf4cd4f92011-02-09 01:13:10 +00002345 QualType type = VD->getType();
Daniel Dunbar7c2dc362011-02-10 18:29:28 +00002346 ExprValueKind valueKind = VK_RValue;
John McCallf4cd4f92011-02-09 01:13:10 +00002347
2348 switch (D->getKind()) {
2349 // Ignore all the non-ValueDecl kinds.
2350#define ABSTRACT_DECL(kind)
2351#define VALUE(type, base)
2352#define DECL(type, base) \
2353 case Decl::type:
2354#include "clang/AST/DeclNodes.inc"
2355 llvm_unreachable("invalid value decl kind");
John McCallf4cd4f92011-02-09 01:13:10 +00002356
2357 // These shouldn't make it here.
2358 case Decl::ObjCAtDefsField:
2359 case Decl::ObjCIvar:
2360 llvm_unreachable("forming non-member reference to ivar?");
John McCallf4cd4f92011-02-09 01:13:10 +00002361
2362 // Enum constants are always r-values and never references.
2363 // Unresolved using declarations are dependent.
2364 case Decl::EnumConstant:
2365 case Decl::UnresolvedUsingValue:
2366 valueKind = VK_RValue;
2367 break;
2368
2369 // Fields and indirect fields that got here must be for
2370 // pointer-to-member expressions; we just call them l-values for
2371 // internal consistency, because this subexpression doesn't really
2372 // exist in the high-level semantics.
2373 case Decl::Field:
2374 case Decl::IndirectField:
David Blaikiebbafb8a2012-03-11 07:00:24 +00002375 assert(getLangOpts().CPlusPlus &&
John McCallf4cd4f92011-02-09 01:13:10 +00002376 "building reference to field in C?");
2377
2378 // These can't have reference type in well-formed programs, but
2379 // for internal consistency we do this anyway.
2380 type = type.getNonReferenceType();
2381 valueKind = VK_LValue;
2382 break;
2383
2384 // Non-type template parameters are either l-values or r-values
2385 // depending on the type.
2386 case Decl::NonTypeTemplateParm: {
2387 if (const ReferenceType *reftype = type->getAs<ReferenceType>()) {
2388 type = reftype->getPointeeType();
2389 valueKind = VK_LValue; // even if the parameter is an r-value reference
2390 break;
2391 }
2392
2393 // For non-references, we need to strip qualifiers just in case
2394 // the template parameter was declared as 'const int' or whatever.
2395 valueKind = VK_RValue;
2396 type = type.getUnqualifiedType();
2397 break;
2398 }
2399
2400 case Decl::Var:
2401 // In C, "extern void blah;" is valid and is an r-value.
David Blaikiebbafb8a2012-03-11 07:00:24 +00002402 if (!getLangOpts().CPlusPlus &&
John McCallf4cd4f92011-02-09 01:13:10 +00002403 !type.hasQualifiers() &&
2404 type->isVoidType()) {
2405 valueKind = VK_RValue;
2406 break;
2407 }
2408 // fallthrough
2409
2410 case Decl::ImplicitParam:
Douglas Gregor812d8f62012-02-18 05:51:20 +00002411 case Decl::ParmVar: {
John McCallf4cd4f92011-02-09 01:13:10 +00002412 // These are always l-values.
2413 valueKind = VK_LValue;
2414 type = type.getNonReferenceType();
Eli Friedman9bb33f52012-02-03 02:04:35 +00002415
Douglas Gregor812d8f62012-02-18 05:51:20 +00002416 // FIXME: Does the addition of const really only apply in
2417 // potentially-evaluated contexts? Since the variable isn't actually
2418 // captured in an unevaluated context, it seems that the answer is no.
David Blaikie131fcb42012-08-06 22:47:24 +00002419 if (!isUnevaluatedContext()) {
Douglas Gregor812d8f62012-02-18 05:51:20 +00002420 QualType CapturedType = getCapturedDeclRefType(cast<VarDecl>(VD), Loc);
2421 if (!CapturedType.isNull())
2422 type = CapturedType;
2423 }
2424
John McCallf4cd4f92011-02-09 01:13:10 +00002425 break;
Douglas Gregor812d8f62012-02-18 05:51:20 +00002426 }
2427
John McCallf4cd4f92011-02-09 01:13:10 +00002428 case Decl::Function: {
Eli Friedman34866c72012-08-31 00:14:07 +00002429 if (unsigned BID = cast<FunctionDecl>(VD)->getBuiltinID()) {
2430 if (!Context.BuiltinInfo.isPredefinedLibFunction(BID)) {
2431 type = Context.BuiltinFnTy;
2432 valueKind = VK_RValue;
2433 break;
2434 }
2435 }
2436
John McCall2979fe02011-04-12 00:42:48 +00002437 const FunctionType *fty = type->castAs<FunctionType>();
2438
2439 // If we're referring to a function with an __unknown_anytype
2440 // result type, make the entire expression __unknown_anytype.
2441 if (fty->getResultType() == Context.UnknownAnyTy) {
2442 type = Context.UnknownAnyTy;
2443 valueKind = VK_RValue;
2444 break;
2445 }
2446
John McCallf4cd4f92011-02-09 01:13:10 +00002447 // Functions are l-values in C++.
David Blaikiebbafb8a2012-03-11 07:00:24 +00002448 if (getLangOpts().CPlusPlus) {
John McCallf4cd4f92011-02-09 01:13:10 +00002449 valueKind = VK_LValue;
2450 break;
2451 }
2452
2453 // C99 DR 316 says that, if a function type comes from a
2454 // function definition (without a prototype), that type is only
2455 // used for checking compatibility. Therefore, when referencing
2456 // the function, we pretend that we don't have the full function
2457 // type.
John McCall2979fe02011-04-12 00:42:48 +00002458 if (!cast<FunctionDecl>(VD)->hasPrototype() &&
2459 isa<FunctionProtoType>(fty))
2460 type = Context.getFunctionNoProtoType(fty->getResultType(),
2461 fty->getExtInfo());
John McCallf4cd4f92011-02-09 01:13:10 +00002462
2463 // Functions are r-values in C.
2464 valueKind = VK_RValue;
2465 break;
2466 }
2467
2468 case Decl::CXXMethod:
John McCall2979fe02011-04-12 00:42:48 +00002469 // If we're referring to a method with an __unknown_anytype
2470 // result type, make the entire expression __unknown_anytype.
2471 // This should only be possible with a type written directly.
Richard Trieucfc491d2011-08-02 04:35:43 +00002472 if (const FunctionProtoType *proto
2473 = dyn_cast<FunctionProtoType>(VD->getType()))
John McCall2979fe02011-04-12 00:42:48 +00002474 if (proto->getResultType() == Context.UnknownAnyTy) {
2475 type = Context.UnknownAnyTy;
2476 valueKind = VK_RValue;
2477 break;
2478 }
2479
John McCallf4cd4f92011-02-09 01:13:10 +00002480 // C++ methods are l-values if static, r-values if non-static.
2481 if (cast<CXXMethodDecl>(VD)->isStatic()) {
2482 valueKind = VK_LValue;
2483 break;
2484 }
2485 // fallthrough
2486
2487 case Decl::CXXConversion:
2488 case Decl::CXXDestructor:
2489 case Decl::CXXConstructor:
2490 valueKind = VK_RValue;
2491 break;
2492 }
2493
2494 return BuildDeclRefExpr(VD, type, valueKind, NameInfo, &SS);
2495 }
Chris Lattner17ed4872006-11-20 04:58:19 +00002496}
Chris Lattnere168f762006-11-10 05:29:30 +00002497
John McCall2979fe02011-04-12 00:42:48 +00002498ExprResult Sema::ActOnPredefinedExpr(SourceLocation Loc, tok::TokenKind Kind) {
Chris Lattner6307f192008-08-10 01:53:14 +00002499 PredefinedExpr::IdentType IT;
Sebastian Redlffbcf962009-01-18 18:53:16 +00002500
Chris Lattnere168f762006-11-10 05:29:30 +00002501 switch (Kind) {
David Blaikie83d382b2011-09-23 05:06:16 +00002502 default: llvm_unreachable("Unknown simple primary expr!");
Chris Lattner6307f192008-08-10 01:53:14 +00002503 case tok::kw___func__: IT = PredefinedExpr::Func; break; // [C99 6.4.2.2]
2504 case tok::kw___FUNCTION__: IT = PredefinedExpr::Function; break;
Nico Weber3a691a32012-06-23 02:07:59 +00002505 case tok::kw_L__FUNCTION__: IT = PredefinedExpr::LFunction; break;
Chris Lattner6307f192008-08-10 01:53:14 +00002506 case tok::kw___PRETTY_FUNCTION__: IT = PredefinedExpr::PrettyFunction; break;
Chris Lattnere168f762006-11-10 05:29:30 +00002507 }
Chris Lattner317e6ba2008-01-12 18:39:25 +00002508
Chris Lattnera81a0272008-01-12 08:14:25 +00002509 // Pre-defined identifiers are of type char[x], where x is the length of the
2510 // string.
Mike Stump11289f42009-09-09 15:08:12 +00002511
Anders Carlsson2fb08242009-09-08 18:24:21 +00002512 Decl *currentDecl = getCurFunctionOrMethodDecl();
Fariborz Jahanian94627442010-07-23 21:53:24 +00002513 if (!currentDecl && getCurBlock())
2514 currentDecl = getCurBlock()->TheDecl;
Anders Carlsson2fb08242009-09-08 18:24:21 +00002515 if (!currentDecl) {
Chris Lattnerf45c5ec2008-12-12 05:05:20 +00002516 Diag(Loc, diag::ext_predef_outside_function);
Anders Carlsson2fb08242009-09-08 18:24:21 +00002517 currentDecl = Context.getTranslationUnitDecl();
Chris Lattnerf45c5ec2008-12-12 05:05:20 +00002518 }
Sebastian Redlffbcf962009-01-18 18:53:16 +00002519
Anders Carlsson0b209a82009-09-11 01:22:35 +00002520 QualType ResTy;
2521 if (cast<DeclContext>(currentDecl)->isDependentContext()) {
2522 ResTy = Context.DependentTy;
2523 } else {
Anders Carlsson5bd8d192010-02-11 18:20:28 +00002524 unsigned Length = PredefinedExpr::ComputeName(IT, currentDecl).length();
Sebastian Redlffbcf962009-01-18 18:53:16 +00002525
Anders Carlsson0b209a82009-09-11 01:22:35 +00002526 llvm::APInt LengthI(32, Length + 1);
Nico Weber3052abd2012-06-29 16:39:58 +00002527 if (IT == PredefinedExpr::LFunction)
Nico Weber3a691a32012-06-23 02:07:59 +00002528 ResTy = Context.WCharTy.withConst();
2529 else
2530 ResTy = Context.CharTy.withConst();
Anders Carlsson0b209a82009-09-11 01:22:35 +00002531 ResTy = Context.getConstantArrayType(ResTy, LengthI, ArrayType::Normal, 0);
2532 }
Steve Narofff6009ed2009-01-21 00:14:39 +00002533 return Owned(new (Context) PredefinedExpr(Loc, ResTy, IT));
Chris Lattnere168f762006-11-10 05:29:30 +00002534}
2535
Richard Smithbcc22fc2012-03-09 08:00:36 +00002536ExprResult Sema::ActOnCharacterConstant(const Token &Tok, Scope *UDLScope) {
Dylan Noblesmith2c1dd272012-02-05 02:13:05 +00002537 SmallString<16> CharBuffer;
Douglas Gregordc970f02010-03-16 22:30:13 +00002538 bool Invalid = false;
Chris Lattner0e62c1c2011-07-23 10:55:15 +00002539 StringRef ThisTok = PP.getSpelling(Tok, CharBuffer, &Invalid);
Douglas Gregordc970f02010-03-16 22:30:13 +00002540 if (Invalid)
2541 return ExprError();
Sebastian Redlffbcf962009-01-18 18:53:16 +00002542
Benjamin Kramer0a1abd42010-02-27 13:44:12 +00002543 CharLiteralParser Literal(ThisTok.begin(), ThisTok.end(), Tok.getLocation(),
Douglas Gregorfb65e592011-07-27 05:40:30 +00002544 PP, Tok.getKind());
Steve Naroffae4143e2007-04-26 20:39:23 +00002545 if (Literal.hadError())
Sebastian Redlffbcf962009-01-18 18:53:16 +00002546 return ExprError();
Chris Lattneref24b382008-03-01 08:32:21 +00002547
Chris Lattnerc3847ba2009-12-30 21:19:39 +00002548 QualType Ty;
Seth Cantrell02f86052012-01-18 12:27:06 +00002549 if (Literal.isWide())
2550 Ty = Context.WCharTy; // L'x' -> wchar_t in C and C++.
Douglas Gregorfb65e592011-07-27 05:40:30 +00002551 else if (Literal.isUTF16())
Seth Cantrell02f86052012-01-18 12:27:06 +00002552 Ty = Context.Char16Ty; // u'x' -> char16_t in C11 and C++11.
Douglas Gregorfb65e592011-07-27 05:40:30 +00002553 else if (Literal.isUTF32())
Seth Cantrell02f86052012-01-18 12:27:06 +00002554 Ty = Context.Char32Ty; // U'x' -> char32_t in C11 and C++11.
David Blaikiebbafb8a2012-03-11 07:00:24 +00002555 else if (!getLangOpts().CPlusPlus || Literal.isMultiChar())
Seth Cantrell02f86052012-01-18 12:27:06 +00002556 Ty = Context.IntTy; // 'x' -> int in C, 'wxyz' -> int in C++.
Chris Lattnerc3847ba2009-12-30 21:19:39 +00002557 else
2558 Ty = Context.CharTy; // 'x' -> char in C++
Chris Lattneref24b382008-03-01 08:32:21 +00002559
Douglas Gregorfb65e592011-07-27 05:40:30 +00002560 CharacterLiteral::CharacterKind Kind = CharacterLiteral::Ascii;
2561 if (Literal.isWide())
2562 Kind = CharacterLiteral::Wide;
2563 else if (Literal.isUTF16())
2564 Kind = CharacterLiteral::UTF16;
2565 else if (Literal.isUTF32())
2566 Kind = CharacterLiteral::UTF32;
2567
Richard Smith75b67d62012-03-08 01:34:56 +00002568 Expr *Lit = new (Context) CharacterLiteral(Literal.getValue(), Kind, Ty,
2569 Tok.getLocation());
2570
2571 if (Literal.getUDSuffix().empty())
2572 return Owned(Lit);
2573
2574 // We're building a user-defined literal.
2575 IdentifierInfo *UDSuffix = &Context.Idents.get(Literal.getUDSuffix());
2576 SourceLocation UDSuffixLoc =
2577 getUDSuffixLoc(*this, Tok.getLocation(), Literal.getUDSuffixOffset());
2578
Richard Smithbcc22fc2012-03-09 08:00:36 +00002579 // Make sure we're allowed user-defined literals here.
2580 if (!UDLScope)
2581 return ExprError(Diag(UDSuffixLoc, diag::err_invalid_character_udl));
2582
Richard Smith75b67d62012-03-08 01:34:56 +00002583 // C++11 [lex.ext]p6: The literal L is treated as a call of the form
2584 // operator "" X (ch)
Richard Smithbcc22fc2012-03-09 08:00:36 +00002585 return BuildCookedLiteralOperatorCall(*this, UDLScope, UDSuffix, UDSuffixLoc,
2586 llvm::makeArrayRef(&Lit, 1),
2587 Tok.getLocation());
Steve Naroffae4143e2007-04-26 20:39:23 +00002588}
2589
Ted Kremeneke65b0862012-03-06 20:05:56 +00002590ExprResult Sema::ActOnIntegerConstant(SourceLocation Loc, uint64_t Val) {
2591 unsigned IntSize = Context.getTargetInfo().getIntWidth();
2592 return Owned(IntegerLiteral::Create(Context, llvm::APInt(IntSize, Val),
2593 Context.IntTy, Loc));
2594}
2595
Richard Smith39570d002012-03-08 08:45:32 +00002596static Expr *BuildFloatingLiteral(Sema &S, NumericLiteralParser &Literal,
2597 QualType Ty, SourceLocation Loc) {
2598 const llvm::fltSemantics &Format = S.Context.getFloatTypeSemantics(Ty);
2599
2600 using llvm::APFloat;
2601 APFloat Val(Format);
2602
2603 APFloat::opStatus result = Literal.GetFloatValue(Val);
2604
2605 // Overflow is always an error, but underflow is only an error if
2606 // we underflowed to zero (APFloat reports denormals as underflow).
2607 if ((result & APFloat::opOverflow) ||
2608 ((result & APFloat::opUnderflow) && Val.isZero())) {
2609 unsigned diagnostic;
2610 SmallString<20> buffer;
2611 if (result & APFloat::opOverflow) {
2612 diagnostic = diag::warn_float_overflow;
2613 APFloat::getLargest(Format).toString(buffer);
2614 } else {
2615 diagnostic = diag::warn_float_underflow;
2616 APFloat::getSmallest(Format).toString(buffer);
2617 }
2618
2619 S.Diag(Loc, diagnostic)
2620 << Ty
2621 << StringRef(buffer.data(), buffer.size());
2622 }
2623
2624 bool isExact = (result == APFloat::opOK);
2625 return FloatingLiteral::Create(S.Context, Val, isExact, Ty, Loc);
2626}
2627
Richard Smithbcc22fc2012-03-09 08:00:36 +00002628ExprResult Sema::ActOnNumericConstant(const Token &Tok, Scope *UDLScope) {
Sebastian Redlffbcf962009-01-18 18:53:16 +00002629 // Fast path for a single digit (which is quite common). A single digit
Richard Smithbcc22fc2012-03-09 08:00:36 +00002630 // cannot have a trigraph, escaped newline, radix prefix, or suffix.
Steve Narofff2fb89e2007-03-13 20:29:44 +00002631 if (Tok.getLength() == 1) {
Chris Lattner9240b3e2009-01-26 22:36:52 +00002632 const char Val = PP.getSpellingOfSingleCharacterNumericConstant(Tok);
Ted Kremeneke65b0862012-03-06 20:05:56 +00002633 return ActOnIntegerConstant(Tok.getLocation(), Val-'0');
Steve Narofff2fb89e2007-03-13 20:29:44 +00002634 }
Ted Kremeneke9814182009-01-13 23:19:12 +00002635
Dylan Noblesmith2c1dd272012-02-05 02:13:05 +00002636 SmallString<512> IntegerBuffer;
Chris Lattnera1cf5f92008-09-30 20:53:45 +00002637 // Add padding so that NumericLiteralParser can overread by one character.
2638 IntegerBuffer.resize(Tok.getLength()+1);
Steve Naroff8160ea22007-03-06 01:09:46 +00002639 const char *ThisTokBegin = &IntegerBuffer[0];
Sebastian Redlffbcf962009-01-18 18:53:16 +00002640
Chris Lattner67ca9252007-05-21 01:08:44 +00002641 // Get the spelling of the token, which eliminates trigraphs, etc.
Douglas Gregordc970f02010-03-16 22:30:13 +00002642 bool Invalid = false;
2643 unsigned ActualLength = PP.getSpelling(Tok, ThisTokBegin, &Invalid);
2644 if (Invalid)
2645 return ExprError();
Sebastian Redlffbcf962009-01-18 18:53:16 +00002646
Mike Stump11289f42009-09-09 15:08:12 +00002647 NumericLiteralParser Literal(ThisTokBegin, ThisTokBegin+ActualLength,
Steve Naroff451d8f162007-03-12 23:22:38 +00002648 Tok.getLocation(), PP);
Steve Narofff2fb89e2007-03-13 20:29:44 +00002649 if (Literal.hadError)
Sebastian Redlffbcf962009-01-18 18:53:16 +00002650 return ExprError();
2651
Richard Smith39570d002012-03-08 08:45:32 +00002652 if (Literal.hasUDSuffix()) {
2653 // We're building a user-defined literal.
2654 IdentifierInfo *UDSuffix = &Context.Idents.get(Literal.getUDSuffix());
2655 SourceLocation UDSuffixLoc =
2656 getUDSuffixLoc(*this, Tok.getLocation(), Literal.getUDSuffixOffset());
2657
Richard Smithbcc22fc2012-03-09 08:00:36 +00002658 // Make sure we're allowed user-defined literals here.
2659 if (!UDLScope)
2660 return ExprError(Diag(UDSuffixLoc, diag::err_invalid_numeric_udl));
Richard Smith39570d002012-03-08 08:45:32 +00002661
Richard Smithbcc22fc2012-03-09 08:00:36 +00002662 QualType CookedTy;
Richard Smith39570d002012-03-08 08:45:32 +00002663 if (Literal.isFloatingLiteral()) {
2664 // C++11 [lex.ext]p4: If S contains a literal operator with parameter type
2665 // long double, the literal is treated as a call of the form
2666 // operator "" X (f L)
Richard Smithbcc22fc2012-03-09 08:00:36 +00002667 CookedTy = Context.LongDoubleTy;
Richard Smith39570d002012-03-08 08:45:32 +00002668 } else {
2669 // C++11 [lex.ext]p3: If S contains a literal operator with parameter type
2670 // unsigned long long, the literal is treated as a call of the form
2671 // operator "" X (n ULL)
Richard Smithbcc22fc2012-03-09 08:00:36 +00002672 CookedTy = Context.UnsignedLongLongTy;
Richard Smith39570d002012-03-08 08:45:32 +00002673 }
2674
Richard Smithbcc22fc2012-03-09 08:00:36 +00002675 DeclarationName OpName =
2676 Context.DeclarationNames.getCXXLiteralOperatorName(UDSuffix);
2677 DeclarationNameInfo OpNameInfo(OpName, UDSuffixLoc);
2678 OpNameInfo.setCXXLiteralOperatorNameLoc(UDSuffixLoc);
2679
2680 // Perform literal operator lookup to determine if we're building a raw
2681 // literal or a cooked one.
2682 LookupResult R(*this, OpName, UDSuffixLoc, LookupOrdinaryName);
2683 switch (LookupLiteralOperator(UDLScope, R, llvm::makeArrayRef(&CookedTy, 1),
2684 /*AllowRawAndTemplate*/true)) {
2685 case LOLR_Error:
2686 return ExprError();
2687
2688 case LOLR_Cooked: {
2689 Expr *Lit;
2690 if (Literal.isFloatingLiteral()) {
2691 Lit = BuildFloatingLiteral(*this, Literal, CookedTy, Tok.getLocation());
2692 } else {
2693 llvm::APInt ResultVal(Context.getTargetInfo().getLongLongWidth(), 0);
2694 if (Literal.GetIntegerValue(ResultVal))
2695 Diag(Tok.getLocation(), diag::warn_integer_too_large);
2696 Lit = IntegerLiteral::Create(Context, ResultVal, CookedTy,
2697 Tok.getLocation());
2698 }
2699 return BuildLiteralOperatorCall(R, OpNameInfo,
2700 llvm::makeArrayRef(&Lit, 1),
2701 Tok.getLocation());
2702 }
2703
2704 case LOLR_Raw: {
2705 // C++11 [lit.ext]p3, p4: If S contains a raw literal operator, the
2706 // literal is treated as a call of the form
2707 // operator "" X ("n")
2708 SourceLocation TokLoc = Tok.getLocation();
2709 unsigned Length = Literal.getUDSuffixOffset();
2710 QualType StrTy = Context.getConstantArrayType(
2711 Context.CharTy, llvm::APInt(32, Length + 1),
2712 ArrayType::Normal, 0);
2713 Expr *Lit = StringLiteral::Create(
2714 Context, StringRef(ThisTokBegin, Length), StringLiteral::Ascii,
2715 /*Pascal*/false, StrTy, &TokLoc, 1);
2716 return BuildLiteralOperatorCall(R, OpNameInfo,
2717 llvm::makeArrayRef(&Lit, 1), TokLoc);
2718 }
2719
2720 case LOLR_Template:
2721 // C++11 [lit.ext]p3, p4: Otherwise (S contains a literal operator
2722 // template), L is treated as a call fo the form
2723 // operator "" X <'c1', 'c2', ... 'ck'>()
2724 // where n is the source character sequence c1 c2 ... ck.
2725 TemplateArgumentListInfo ExplicitArgs;
2726 unsigned CharBits = Context.getIntWidth(Context.CharTy);
2727 bool CharIsUnsigned = Context.CharTy->isUnsignedIntegerType();
2728 llvm::APSInt Value(CharBits, CharIsUnsigned);
2729 for (unsigned I = 0, N = Literal.getUDSuffixOffset(); I != N; ++I) {
2730 Value = ThisTokBegin[I];
Benjamin Kramer6003ad52012-06-07 15:09:51 +00002731 TemplateArgument Arg(Context, Value, Context.CharTy);
Richard Smithbcc22fc2012-03-09 08:00:36 +00002732 TemplateArgumentLocInfo ArgInfo;
2733 ExplicitArgs.addArgument(TemplateArgumentLoc(Arg, ArgInfo));
2734 }
2735 return BuildLiteralOperatorCall(R, OpNameInfo, ArrayRef<Expr*>(),
2736 Tok.getLocation(), &ExplicitArgs);
2737 }
2738
2739 llvm_unreachable("unexpected literal operator lookup result");
Richard Smith39570d002012-03-08 08:45:32 +00002740 }
2741
Chris Lattner1c20a172007-08-26 03:42:43 +00002742 Expr *Res;
Sebastian Redlffbcf962009-01-18 18:53:16 +00002743
Chris Lattner1c20a172007-08-26 03:42:43 +00002744 if (Literal.isFloatingLiteral()) {
Chris Lattnerec0a6d92007-09-22 18:29:59 +00002745 QualType Ty;
Chris Lattner9a8d1d92008-06-30 18:32:54 +00002746 if (Literal.isFloat)
Chris Lattnerec0a6d92007-09-22 18:29:59 +00002747 Ty = Context.FloatTy;
Chris Lattner9a8d1d92008-06-30 18:32:54 +00002748 else if (!Literal.isLong)
Chris Lattnerec0a6d92007-09-22 18:29:59 +00002749 Ty = Context.DoubleTy;
Chris Lattner9a8d1d92008-06-30 18:32:54 +00002750 else
Chris Lattner7570e9c2008-03-08 08:52:55 +00002751 Ty = Context.LongDoubleTy;
Chris Lattner9a8d1d92008-06-30 18:32:54 +00002752
Richard Smith39570d002012-03-08 08:45:32 +00002753 Res = BuildFloatingLiteral(*this, Literal, Ty, Tok.getLocation());
Sebastian Redlffbcf962009-01-18 18:53:16 +00002754
Peter Collingbournec77f85b2011-03-11 19:24:59 +00002755 if (Ty == Context.DoubleTy) {
David Blaikiebbafb8a2012-03-11 07:00:24 +00002756 if (getLangOpts().SinglePrecisionConstants) {
John Wiegley01296292011-04-08 18:41:53 +00002757 Res = ImpCastExprToType(Res, Context.FloatTy, CK_FloatingCast).take();
David Blaikiebbafb8a2012-03-11 07:00:24 +00002758 } else if (getLangOpts().OpenCL && !getOpenCLOptions().cl_khr_fp64) {
Peter Collingbournec77f85b2011-03-11 19:24:59 +00002759 Diag(Tok.getLocation(), diag::warn_double_const_requires_fp64);
John Wiegley01296292011-04-08 18:41:53 +00002760 Res = ImpCastExprToType(Res, Context.FloatTy, CK_FloatingCast).take();
Peter Collingbournec77f85b2011-03-11 19:24:59 +00002761 }
2762 }
Chris Lattner1c20a172007-08-26 03:42:43 +00002763 } else if (!Literal.isIntegerLiteral()) {
Sebastian Redlffbcf962009-01-18 18:53:16 +00002764 return ExprError();
Chris Lattner1c20a172007-08-26 03:42:43 +00002765 } else {
Chris Lattner24d5bfe2008-04-02 04:24:33 +00002766 QualType Ty;
Chris Lattner67ca9252007-05-21 01:08:44 +00002767
Neil Boothac582c52007-08-29 22:00:19 +00002768 // long long is a C99 feature.
David Blaikiebbafb8a2012-03-11 07:00:24 +00002769 if (!getLangOpts().C99 && Literal.isLongLong)
Richard Smith0bf8a4922011-10-18 20:49:44 +00002770 Diag(Tok.getLocation(),
David Blaikiebbafb8a2012-03-11 07:00:24 +00002771 getLangOpts().CPlusPlus0x ?
Richard Smith0bf8a4922011-10-18 20:49:44 +00002772 diag::warn_cxx98_compat_longlong : diag::ext_longlong);
Neil Boothac582c52007-08-29 22:00:19 +00002773
Chris Lattner67ca9252007-05-21 01:08:44 +00002774 // Get the value in the widest-possible width.
Stephen Canonfdc6c1a2012-05-03 22:49:43 +00002775 unsigned MaxWidth = Context.getTargetInfo().getIntMaxTWidth();
2776 // The microsoft literal suffix extensions support 128-bit literals, which
2777 // may be wider than [u]intmax_t.
2778 if (Literal.isMicrosoftInteger && MaxWidth < 128)
2779 MaxWidth = 128;
2780 llvm::APInt ResultVal(MaxWidth, 0);
Sebastian Redlffbcf962009-01-18 18:53:16 +00002781
Chris Lattner67ca9252007-05-21 01:08:44 +00002782 if (Literal.GetIntegerValue(ResultVal)) {
2783 // If this value didn't fit into uintmax_t, warn and force to ull.
2784 Diag(Tok.getLocation(), diag::warn_integer_too_large);
Chris Lattner24d5bfe2008-04-02 04:24:33 +00002785 Ty = Context.UnsignedLongLongTy;
2786 assert(Context.getTypeSize(Ty) == ResultVal.getBitWidth() &&
Chris Lattner37e05872008-03-05 18:54:05 +00002787 "long long is not intmax_t?");
Steve Naroff09ef4742007-03-09 23:16:33 +00002788 } else {
Chris Lattner67ca9252007-05-21 01:08:44 +00002789 // If this value fits into a ULL, try to figure out what else it fits into
2790 // according to the rules of C99 6.4.4.1p5.
Sebastian Redlffbcf962009-01-18 18:53:16 +00002791
Chris Lattner67ca9252007-05-21 01:08:44 +00002792 // Octal, Hexadecimal, and integers with a U suffix are allowed to
2793 // be an unsigned int.
2794 bool AllowUnsigned = Literal.isUnsigned || Literal.getRadix() != 10;
2795
2796 // Check from smallest to largest, picking the smallest type we can.
Chris Lattner55258cf2008-05-09 05:59:00 +00002797 unsigned Width = 0;
Chris Lattner7b939cf2007-08-23 21:58:08 +00002798 if (!Literal.isLong && !Literal.isLongLong) {
2799 // Are int/unsigned possibilities?
Douglas Gregore8bbc122011-09-02 00:18:52 +00002800 unsigned IntSize = Context.getTargetInfo().getIntWidth();
Sebastian Redlffbcf962009-01-18 18:53:16 +00002801
Chris Lattner67ca9252007-05-21 01:08:44 +00002802 // Does it fit in a unsigned int?
2803 if (ResultVal.isIntN(IntSize)) {
2804 // Does it fit in a signed int?
2805 if (!Literal.isUnsigned && ResultVal[IntSize-1] == 0)
Chris Lattner24d5bfe2008-04-02 04:24:33 +00002806 Ty = Context.IntTy;
Chris Lattner67ca9252007-05-21 01:08:44 +00002807 else if (AllowUnsigned)
Chris Lattner24d5bfe2008-04-02 04:24:33 +00002808 Ty = Context.UnsignedIntTy;
Chris Lattner55258cf2008-05-09 05:59:00 +00002809 Width = IntSize;
Chris Lattner67ca9252007-05-21 01:08:44 +00002810 }
Chris Lattner67ca9252007-05-21 01:08:44 +00002811 }
Sebastian Redlffbcf962009-01-18 18:53:16 +00002812
Chris Lattner67ca9252007-05-21 01:08:44 +00002813 // Are long/unsigned long possibilities?
Chris Lattner24d5bfe2008-04-02 04:24:33 +00002814 if (Ty.isNull() && !Literal.isLongLong) {
Douglas Gregore8bbc122011-09-02 00:18:52 +00002815 unsigned LongSize = Context.getTargetInfo().getLongWidth();
Sebastian Redlffbcf962009-01-18 18:53:16 +00002816
Chris Lattner67ca9252007-05-21 01:08:44 +00002817 // Does it fit in a unsigned long?
2818 if (ResultVal.isIntN(LongSize)) {
2819 // Does it fit in a signed long?
2820 if (!Literal.isUnsigned && ResultVal[LongSize-1] == 0)
Chris Lattner24d5bfe2008-04-02 04:24:33 +00002821 Ty = Context.LongTy;
Chris Lattner67ca9252007-05-21 01:08:44 +00002822 else if (AllowUnsigned)
Chris Lattner24d5bfe2008-04-02 04:24:33 +00002823 Ty = Context.UnsignedLongTy;
Chris Lattner55258cf2008-05-09 05:59:00 +00002824 Width = LongSize;
Chris Lattner67ca9252007-05-21 01:08:44 +00002825 }
Sebastian Redlffbcf962009-01-18 18:53:16 +00002826 }
2827
Stephen Canonfdc6c1a2012-05-03 22:49:43 +00002828 // Check long long if needed.
Chris Lattner24d5bfe2008-04-02 04:24:33 +00002829 if (Ty.isNull()) {
Douglas Gregore8bbc122011-09-02 00:18:52 +00002830 unsigned LongLongSize = Context.getTargetInfo().getLongLongWidth();
Sebastian Redlffbcf962009-01-18 18:53:16 +00002831
Chris Lattner67ca9252007-05-21 01:08:44 +00002832 // Does it fit in a unsigned long long?
2833 if (ResultVal.isIntN(LongLongSize)) {
2834 // Does it fit in a signed long long?
Francois Pichetc3e73b32011-01-11 23:38:13 +00002835 // To be compatible with MSVC, hex integer literals ending with the
2836 // LL or i64 suffix are always signed in Microsoft mode.
Francois Pichetbf711d92011-01-11 12:23:00 +00002837 if (!Literal.isUnsigned && (ResultVal[LongLongSize-1] == 0 ||
David Blaikiebbafb8a2012-03-11 07:00:24 +00002838 (getLangOpts().MicrosoftExt && Literal.isLongLong)))
Chris Lattner24d5bfe2008-04-02 04:24:33 +00002839 Ty = Context.LongLongTy;
Chris Lattner67ca9252007-05-21 01:08:44 +00002840 else if (AllowUnsigned)
Chris Lattner24d5bfe2008-04-02 04:24:33 +00002841 Ty = Context.UnsignedLongLongTy;
Chris Lattner55258cf2008-05-09 05:59:00 +00002842 Width = LongLongSize;
Chris Lattner67ca9252007-05-21 01:08:44 +00002843 }
2844 }
Stephen Canonfdc6c1a2012-05-03 22:49:43 +00002845
2846 // If it doesn't fit in unsigned long long, and we're using Microsoft
2847 // extensions, then its a 128-bit integer literal.
2848 if (Ty.isNull() && Literal.isMicrosoftInteger) {
2849 if (Literal.isUnsigned)
2850 Ty = Context.UnsignedInt128Ty;
2851 else
2852 Ty = Context.Int128Ty;
2853 Width = 128;
2854 }
Sebastian Redlffbcf962009-01-18 18:53:16 +00002855
Chris Lattner67ca9252007-05-21 01:08:44 +00002856 // If we still couldn't decide a type, we probably have something that
2857 // does not fit in a signed long long, but has no U suffix.
Chris Lattner24d5bfe2008-04-02 04:24:33 +00002858 if (Ty.isNull()) {
Chris Lattner67ca9252007-05-21 01:08:44 +00002859 Diag(Tok.getLocation(), diag::warn_integer_too_large_for_signed);
Chris Lattner24d5bfe2008-04-02 04:24:33 +00002860 Ty = Context.UnsignedLongLongTy;
Douglas Gregore8bbc122011-09-02 00:18:52 +00002861 Width = Context.getTargetInfo().getLongLongWidth();
Chris Lattner67ca9252007-05-21 01:08:44 +00002862 }
Sebastian Redlffbcf962009-01-18 18:53:16 +00002863
Chris Lattner55258cf2008-05-09 05:59:00 +00002864 if (ResultVal.getBitWidth() != Width)
Jay Foad6d4db0c2010-12-07 08:25:34 +00002865 ResultVal = ResultVal.trunc(Width);
Steve Naroff09ef4742007-03-09 23:16:33 +00002866 }
Argyrios Kyrtzidis43b20572010-08-28 09:06:06 +00002867 Res = IntegerLiteral::Create(Context, ResultVal, Ty, Tok.getLocation());
Steve Naroff09ef4742007-03-09 23:16:33 +00002868 }
Sebastian Redlffbcf962009-01-18 18:53:16 +00002869
Chris Lattner1c20a172007-08-26 03:42:43 +00002870 // If this is an imaginary literal, create the ImaginaryLiteral wrapper.
2871 if (Literal.isImaginary)
Mike Stump11289f42009-09-09 15:08:12 +00002872 Res = new (Context) ImaginaryLiteral(Res,
Steve Narofff6009ed2009-01-21 00:14:39 +00002873 Context.getComplexType(Res->getType()));
Sebastian Redlffbcf962009-01-18 18:53:16 +00002874
2875 return Owned(Res);
Chris Lattnere168f762006-11-10 05:29:30 +00002876}
2877
Richard Trieuba63ce62011-09-09 01:45:06 +00002878ExprResult Sema::ActOnParenExpr(SourceLocation L, SourceLocation R, Expr *E) {
Chris Lattner24d5bfe2008-04-02 04:24:33 +00002879 assert((E != 0) && "ActOnParenExpr() missing expr");
Steve Narofff6009ed2009-01-21 00:14:39 +00002880 return Owned(new (Context) ParenExpr(L, R, E));
Chris Lattnere168f762006-11-10 05:29:30 +00002881}
2882
Chandler Carruth62da79c2011-05-26 08:53:12 +00002883static bool CheckVecStepTraitOperandType(Sema &S, QualType T,
2884 SourceLocation Loc,
2885 SourceRange ArgRange) {
2886 // [OpenCL 1.1 6.11.12] "The vec_step built-in function takes a built-in
2887 // scalar or vector data type argument..."
2888 // Every built-in scalar type (OpenCL 1.1 6.1.1) is either an arithmetic
2889 // type (C99 6.2.5p18) or void.
2890 if (!(T->isArithmeticType() || T->isVoidType() || T->isVectorType())) {
2891 S.Diag(Loc, diag::err_vecstep_non_scalar_vector_type)
2892 << T << ArgRange;
2893 return true;
2894 }
2895
2896 assert((T->isVoidType() || !T->isIncompleteType()) &&
2897 "Scalar types should always be complete");
2898 return false;
2899}
2900
Chandler Carruthcea1aac2011-05-26 08:53:16 +00002901static bool CheckExtensionTraitOperandType(Sema &S, QualType T,
2902 SourceLocation Loc,
2903 SourceRange ArgRange,
2904 UnaryExprOrTypeTrait TraitKind) {
2905 // C99 6.5.3.4p1:
2906 if (T->isFunctionType()) {
2907 // alignof(function) is allowed as an extension.
2908 if (TraitKind == UETT_SizeOf)
2909 S.Diag(Loc, diag::ext_sizeof_function_type) << ArgRange;
2910 return false;
2911 }
2912
2913 // Allow sizeof(void)/alignof(void) as an extension.
2914 if (T->isVoidType()) {
2915 S.Diag(Loc, diag::ext_sizeof_void_type) << TraitKind << ArgRange;
2916 return false;
2917 }
2918
2919 return true;
2920}
2921
2922static bool CheckObjCTraitOperandConstraints(Sema &S, QualType T,
2923 SourceLocation Loc,
2924 SourceRange ArgRange,
2925 UnaryExprOrTypeTrait TraitKind) {
John McCallf2538342012-07-31 05:14:30 +00002926 // Reject sizeof(interface) and sizeof(interface<proto>) if the
2927 // runtime doesn't allow it.
2928 if (!S.LangOpts.ObjCRuntime.allowsSizeofAlignof() && T->isObjCObjectType()) {
Chandler Carruthcea1aac2011-05-26 08:53:16 +00002929 S.Diag(Loc, diag::err_sizeof_nonfragile_interface)
2930 << T << (TraitKind == UETT_SizeOf)
2931 << ArgRange;
2932 return true;
2933 }
2934
2935 return false;
2936}
2937
Chandler Carruth14502c22011-05-26 08:53:10 +00002938/// \brief Check the constrains on expression operands to unary type expression
2939/// and type traits.
2940///
Chandler Carruth7c430c02011-05-27 01:33:31 +00002941/// Completes any types necessary and validates the constraints on the operand
2942/// expression. The logic mostly mirrors the type-based overload, but may modify
2943/// the expression as it completes the type for that expression through template
2944/// instantiation, etc.
Richard Trieuba63ce62011-09-09 01:45:06 +00002945bool Sema::CheckUnaryExprOrTypeTraitOperand(Expr *E,
Chandler Carruth14502c22011-05-26 08:53:10 +00002946 UnaryExprOrTypeTrait ExprKind) {
Richard Trieuba63ce62011-09-09 01:45:06 +00002947 QualType ExprTy = E->getType();
Chandler Carruth7c430c02011-05-27 01:33:31 +00002948
2949 // C++ [expr.sizeof]p2: "When applied to a reference or a reference type,
2950 // the result is the size of the referenced type."
2951 // C++ [expr.alignof]p3: "When alignof is applied to a reference type, the
2952 // result shall be the alignment of the referenced type."
2953 if (const ReferenceType *Ref = ExprTy->getAs<ReferenceType>())
2954 ExprTy = Ref->getPointeeType();
2955
2956 if (ExprKind == UETT_VecStep)
Richard Trieuba63ce62011-09-09 01:45:06 +00002957 return CheckVecStepTraitOperandType(*this, ExprTy, E->getExprLoc(),
2958 E->getSourceRange());
Chandler Carruth7c430c02011-05-27 01:33:31 +00002959
2960 // Whitelist some types as extensions
Richard Trieuba63ce62011-09-09 01:45:06 +00002961 if (!CheckExtensionTraitOperandType(*this, ExprTy, E->getExprLoc(),
2962 E->getSourceRange(), ExprKind))
Chandler Carruth7c430c02011-05-27 01:33:31 +00002963 return false;
2964
Richard Trieuba63ce62011-09-09 01:45:06 +00002965 if (RequireCompleteExprType(E,
Douglas Gregor7bfb2d02012-05-04 16:32:21 +00002966 diag::err_sizeof_alignof_incomplete_type,
2967 ExprKind, E->getSourceRange()))
Chandler Carruth7c430c02011-05-27 01:33:31 +00002968 return true;
2969
2970 // Completeing the expression's type may have changed it.
Richard Trieuba63ce62011-09-09 01:45:06 +00002971 ExprTy = E->getType();
Chandler Carruth7c430c02011-05-27 01:33:31 +00002972 if (const ReferenceType *Ref = ExprTy->getAs<ReferenceType>())
2973 ExprTy = Ref->getPointeeType();
2974
Richard Trieuba63ce62011-09-09 01:45:06 +00002975 if (CheckObjCTraitOperandConstraints(*this, ExprTy, E->getExprLoc(),
2976 E->getSourceRange(), ExprKind))
Chandler Carruth7c430c02011-05-27 01:33:31 +00002977 return true;
2978
Nico Weber0870deb2011-06-15 02:47:03 +00002979 if (ExprKind == UETT_SizeOf) {
Richard Trieuba63ce62011-09-09 01:45:06 +00002980 if (DeclRefExpr *DeclRef = dyn_cast<DeclRefExpr>(E->IgnoreParens())) {
Nico Weber0870deb2011-06-15 02:47:03 +00002981 if (ParmVarDecl *PVD = dyn_cast<ParmVarDecl>(DeclRef->getFoundDecl())) {
2982 QualType OType = PVD->getOriginalType();
2983 QualType Type = PVD->getType();
2984 if (Type->isPointerType() && OType->isArrayType()) {
Richard Trieuba63ce62011-09-09 01:45:06 +00002985 Diag(E->getExprLoc(), diag::warn_sizeof_array_param)
Nico Weber0870deb2011-06-15 02:47:03 +00002986 << Type << OType;
2987 Diag(PVD->getLocation(), diag::note_declared_at);
2988 }
2989 }
2990 }
2991 }
2992
Chandler Carruth7c430c02011-05-27 01:33:31 +00002993 return false;
Chandler Carruth14502c22011-05-26 08:53:10 +00002994}
2995
2996/// \brief Check the constraints on operands to unary expression and type
2997/// traits.
2998///
2999/// This will complete any types necessary, and validate the various constraints
3000/// on those operands.
3001///
Steve Naroff71b59a92007-06-04 22:22:31 +00003002/// The UsualUnaryConversions() function is *not* called by this routine.
Chandler Carruth14502c22011-05-26 08:53:10 +00003003/// C99 6.3.2.1p[2-4] all state:
3004/// Except when it is the operand of the sizeof operator ...
3005///
3006/// C++ [expr.sizeof]p4
3007/// The lvalue-to-rvalue, array-to-pointer, and function-to-pointer
3008/// standard conversions are not applied to the operand of sizeof.
3009///
3010/// This policy is followed for all of the unary trait expressions.
Richard Trieuba63ce62011-09-09 01:45:06 +00003011bool Sema::CheckUnaryExprOrTypeTraitOperand(QualType ExprType,
Peter Collingbournee190dee2011-03-11 19:24:49 +00003012 SourceLocation OpLoc,
3013 SourceRange ExprRange,
3014 UnaryExprOrTypeTrait ExprKind) {
Richard Trieuba63ce62011-09-09 01:45:06 +00003015 if (ExprType->isDependentType())
Sebastian Redl8d2ccae2009-02-26 14:39:58 +00003016 return false;
3017
Sebastian Redl22e2e5c2009-11-23 17:18:46 +00003018 // C++ [expr.sizeof]p2: "When applied to a reference or a reference type,
3019 // the result is the size of the referenced type."
3020 // C++ [expr.alignof]p3: "When alignof is applied to a reference type, the
3021 // result shall be the alignment of the referenced type."
Richard Trieuba63ce62011-09-09 01:45:06 +00003022 if (const ReferenceType *Ref = ExprType->getAs<ReferenceType>())
3023 ExprType = Ref->getPointeeType();
Sebastian Redl22e2e5c2009-11-23 17:18:46 +00003024
Chandler Carruth62da79c2011-05-26 08:53:12 +00003025 if (ExprKind == UETT_VecStep)
Richard Trieuba63ce62011-09-09 01:45:06 +00003026 return CheckVecStepTraitOperandType(*this, ExprType, OpLoc, ExprRange);
Peter Collingbournee190dee2011-03-11 19:24:49 +00003027
Chandler Carruthcea1aac2011-05-26 08:53:16 +00003028 // Whitelist some types as extensions
Richard Trieuba63ce62011-09-09 01:45:06 +00003029 if (!CheckExtensionTraitOperandType(*this, ExprType, OpLoc, ExprRange,
Chandler Carruthcea1aac2011-05-26 08:53:16 +00003030 ExprKind))
Chris Lattnerb1355b12009-01-24 19:46:37 +00003031 return false;
Mike Stump11289f42009-09-09 15:08:12 +00003032
Richard Trieuba63ce62011-09-09 01:45:06 +00003033 if (RequireCompleteType(OpLoc, ExprType,
Douglas Gregor7bfb2d02012-05-04 16:32:21 +00003034 diag::err_sizeof_alignof_incomplete_type,
3035 ExprKind, ExprRange))
Chris Lattner62975a72009-04-24 00:30:45 +00003036 return true;
Mike Stump11289f42009-09-09 15:08:12 +00003037
Richard Trieuba63ce62011-09-09 01:45:06 +00003038 if (CheckObjCTraitOperandConstraints(*this, ExprType, OpLoc, ExprRange,
Chandler Carruthcea1aac2011-05-26 08:53:16 +00003039 ExprKind))
Chris Lattnercd2a8c52009-04-24 22:30:50 +00003040 return true;
Mike Stump11289f42009-09-09 15:08:12 +00003041
Chris Lattner62975a72009-04-24 00:30:45 +00003042 return false;
Steve Naroff043d45d2007-05-15 02:32:35 +00003043}
3044
Chandler Carruth14502c22011-05-26 08:53:10 +00003045static bool CheckAlignOfExpr(Sema &S, Expr *E) {
Chris Lattner8dff0172009-01-24 20:17:12 +00003046 E = E->IgnoreParens();
Sebastian Redl8d2ccae2009-02-26 14:39:58 +00003047
Mike Stump11289f42009-09-09 15:08:12 +00003048 // alignof decl is always ok.
Chris Lattner8dff0172009-01-24 20:17:12 +00003049 if (isa<DeclRefExpr>(E))
3050 return false;
Sebastian Redl8d2ccae2009-02-26 14:39:58 +00003051
3052 // Cannot know anything else if the expression is dependent.
3053 if (E->isTypeDependent())
3054 return false;
3055
Douglas Gregor71235ec2009-05-02 02:18:30 +00003056 if (E->getBitField()) {
Chandler Carruth14502c22011-05-26 08:53:10 +00003057 S.Diag(E->getExprLoc(), diag::err_sizeof_alignof_bitfield)
3058 << 1 << E->getSourceRange();
Douglas Gregor71235ec2009-05-02 02:18:30 +00003059 return true;
Chris Lattner8dff0172009-01-24 20:17:12 +00003060 }
Douglas Gregor71235ec2009-05-02 02:18:30 +00003061
3062 // Alignment of a field access is always okay, so long as it isn't a
3063 // bit-field.
3064 if (MemberExpr *ME = dyn_cast<MemberExpr>(E))
Mike Stump212005c2009-07-22 18:58:19 +00003065 if (isa<FieldDecl>(ME->getMemberDecl()))
Douglas Gregor71235ec2009-05-02 02:18:30 +00003066 return false;
3067
Chandler Carruth14502c22011-05-26 08:53:10 +00003068 return S.CheckUnaryExprOrTypeTraitOperand(E, UETT_AlignOf);
Peter Collingbournee190dee2011-03-11 19:24:49 +00003069}
3070
Chandler Carruth14502c22011-05-26 08:53:10 +00003071bool Sema::CheckVecStepExpr(Expr *E) {
Peter Collingbournee190dee2011-03-11 19:24:49 +00003072 E = E->IgnoreParens();
3073
3074 // Cannot know anything else if the expression is dependent.
3075 if (E->isTypeDependent())
3076 return false;
3077
Chandler Carruth14502c22011-05-26 08:53:10 +00003078 return CheckUnaryExprOrTypeTraitOperand(E, UETT_VecStep);
Chris Lattner8dff0172009-01-24 20:17:12 +00003079}
3080
Douglas Gregor0950e412009-03-13 21:01:28 +00003081/// \brief Build a sizeof or alignof expression given a type operand.
John McCalldadc5752010-08-24 06:29:42 +00003082ExprResult
Peter Collingbournee190dee2011-03-11 19:24:49 +00003083Sema::CreateUnaryExprOrTypeTraitExpr(TypeSourceInfo *TInfo,
3084 SourceLocation OpLoc,
3085 UnaryExprOrTypeTrait ExprKind,
3086 SourceRange R) {
John McCallbcd03502009-12-07 02:54:59 +00003087 if (!TInfo)
Douglas Gregor0950e412009-03-13 21:01:28 +00003088 return ExprError();
3089
John McCallbcd03502009-12-07 02:54:59 +00003090 QualType T = TInfo->getType();
John McCall4c98fd82009-11-04 07:28:41 +00003091
Douglas Gregor0950e412009-03-13 21:01:28 +00003092 if (!T->isDependentType() &&
Peter Collingbournee190dee2011-03-11 19:24:49 +00003093 CheckUnaryExprOrTypeTraitOperand(T, OpLoc, R, ExprKind))
Douglas Gregor0950e412009-03-13 21:01:28 +00003094 return ExprError();
3095
3096 // C99 6.5.3.4p4: the type (an unsigned integer type) is size_t.
Peter Collingbournee190dee2011-03-11 19:24:49 +00003097 return Owned(new (Context) UnaryExprOrTypeTraitExpr(ExprKind, TInfo,
3098 Context.getSizeType(),
3099 OpLoc, R.getEnd()));
Douglas Gregor0950e412009-03-13 21:01:28 +00003100}
3101
3102/// \brief Build a sizeof or alignof expression given an expression
3103/// operand.
John McCalldadc5752010-08-24 06:29:42 +00003104ExprResult
Chandler Carrutha923fb22011-05-29 07:32:14 +00003105Sema::CreateUnaryExprOrTypeTraitExpr(Expr *E, SourceLocation OpLoc,
3106 UnaryExprOrTypeTrait ExprKind) {
Douglas Gregor835af982011-06-22 23:21:00 +00003107 ExprResult PE = CheckPlaceholderExpr(E);
3108 if (PE.isInvalid())
3109 return ExprError();
3110
3111 E = PE.get();
3112
Douglas Gregor0950e412009-03-13 21:01:28 +00003113 // Verify that the operand is valid.
3114 bool isInvalid = false;
3115 if (E->isTypeDependent()) {
3116 // Delay type-checking for type-dependent expressions.
Peter Collingbournee190dee2011-03-11 19:24:49 +00003117 } else if (ExprKind == UETT_AlignOf) {
Chandler Carruth14502c22011-05-26 08:53:10 +00003118 isInvalid = CheckAlignOfExpr(*this, E);
Peter Collingbournee190dee2011-03-11 19:24:49 +00003119 } else if (ExprKind == UETT_VecStep) {
Chandler Carruth14502c22011-05-26 08:53:10 +00003120 isInvalid = CheckVecStepExpr(E);
Douglas Gregor71235ec2009-05-02 02:18:30 +00003121 } else if (E->getBitField()) { // C99 6.5.3.4p1.
Chandler Carruth14502c22011-05-26 08:53:10 +00003122 Diag(E->getExprLoc(), diag::err_sizeof_alignof_bitfield) << 0;
Douglas Gregor0950e412009-03-13 21:01:28 +00003123 isInvalid = true;
3124 } else {
Chandler Carruth14502c22011-05-26 08:53:10 +00003125 isInvalid = CheckUnaryExprOrTypeTraitOperand(E, UETT_SizeOf);
Douglas Gregor0950e412009-03-13 21:01:28 +00003126 }
3127
3128 if (isInvalid)
3129 return ExprError();
3130
Eli Friedmane0afc982012-01-21 01:01:51 +00003131 if (ExprKind == UETT_SizeOf && E->getType()->isVariableArrayType()) {
3132 PE = TranformToPotentiallyEvaluated(E);
3133 if (PE.isInvalid()) return ExprError();
3134 E = PE.take();
3135 }
3136
Douglas Gregor0950e412009-03-13 21:01:28 +00003137 // C99 6.5.3.4p4: the type (an unsigned integer type) is size_t.
Chandler Carruth14502c22011-05-26 08:53:10 +00003138 return Owned(new (Context) UnaryExprOrTypeTraitExpr(
Chandler Carrutha923fb22011-05-29 07:32:14 +00003139 ExprKind, E, Context.getSizeType(), OpLoc,
Chandler Carruth14502c22011-05-26 08:53:10 +00003140 E->getSourceRange().getEnd()));
Douglas Gregor0950e412009-03-13 21:01:28 +00003141}
3142
Peter Collingbournee190dee2011-03-11 19:24:49 +00003143/// ActOnUnaryExprOrTypeTraitExpr - Handle @c sizeof(type) and @c sizeof @c
3144/// expr and the same for @c alignof and @c __alignof
Sebastian Redl6f282892008-11-11 17:56:53 +00003145/// Note that the ArgRange is invalid if isType is false.
John McCalldadc5752010-08-24 06:29:42 +00003146ExprResult
Peter Collingbournee190dee2011-03-11 19:24:49 +00003147Sema::ActOnUnaryExprOrTypeTraitExpr(SourceLocation OpLoc,
Richard Trieuba63ce62011-09-09 01:45:06 +00003148 UnaryExprOrTypeTrait ExprKind, bool IsType,
Peter Collingbournee190dee2011-03-11 19:24:49 +00003149 void *TyOrEx, const SourceRange &ArgRange) {
Chris Lattner0d8b1a12006-11-20 04:34:45 +00003150 // If error parsing type, ignore.
Sebastian Redlc215cfc2009-01-19 00:08:26 +00003151 if (TyOrEx == 0) return ExprError();
Steve Naroff043d45d2007-05-15 02:32:35 +00003152
Richard Trieuba63ce62011-09-09 01:45:06 +00003153 if (IsType) {
John McCallbcd03502009-12-07 02:54:59 +00003154 TypeSourceInfo *TInfo;
John McCallba7bf592010-08-24 05:47:05 +00003155 (void) GetTypeFromParser(ParsedType::getFromOpaquePtr(TyOrEx), &TInfo);
Peter Collingbournee190dee2011-03-11 19:24:49 +00003156 return CreateUnaryExprOrTypeTraitExpr(TInfo, OpLoc, ExprKind, ArgRange);
Mike Stump11289f42009-09-09 15:08:12 +00003157 }
Sebastian Redl6f282892008-11-11 17:56:53 +00003158
Douglas Gregor0950e412009-03-13 21:01:28 +00003159 Expr *ArgEx = (Expr *)TyOrEx;
Chandler Carrutha923fb22011-05-29 07:32:14 +00003160 ExprResult Result = CreateUnaryExprOrTypeTraitExpr(ArgEx, OpLoc, ExprKind);
Benjamin Kramer62b95d82012-08-23 21:35:17 +00003161 return Result;
Chris Lattnere168f762006-11-10 05:29:30 +00003162}
3163
John Wiegley01296292011-04-08 18:41:53 +00003164static QualType CheckRealImagOperand(Sema &S, ExprResult &V, SourceLocation Loc,
Richard Trieuba63ce62011-09-09 01:45:06 +00003165 bool IsReal) {
John Wiegley01296292011-04-08 18:41:53 +00003166 if (V.get()->isTypeDependent())
John McCall4bc41ae2010-11-18 19:01:18 +00003167 return S.Context.DependentTy;
Mike Stump11289f42009-09-09 15:08:12 +00003168
John McCall34376a62010-12-04 03:47:34 +00003169 // _Real and _Imag are only l-values for normal l-values.
John Wiegley01296292011-04-08 18:41:53 +00003170 if (V.get()->getObjectKind() != OK_Ordinary) {
3171 V = S.DefaultLvalueConversion(V.take());
3172 if (V.isInvalid())
3173 return QualType();
3174 }
John McCall34376a62010-12-04 03:47:34 +00003175
Chris Lattnere267f5d2007-08-26 05:39:26 +00003176 // These operators return the element type of a complex type.
John Wiegley01296292011-04-08 18:41:53 +00003177 if (const ComplexType *CT = V.get()->getType()->getAs<ComplexType>())
Chris Lattner30b5dd02007-08-24 21:16:53 +00003178 return CT->getElementType();
Mike Stump11289f42009-09-09 15:08:12 +00003179
Chris Lattnere267f5d2007-08-26 05:39:26 +00003180 // Otherwise they pass through real integer and floating point types here.
John Wiegley01296292011-04-08 18:41:53 +00003181 if (V.get()->getType()->isArithmeticType())
3182 return V.get()->getType();
Mike Stump11289f42009-09-09 15:08:12 +00003183
John McCall36226622010-10-12 02:09:17 +00003184 // Test for placeholders.
John McCall3aef3d82011-04-10 19:13:55 +00003185 ExprResult PR = S.CheckPlaceholderExpr(V.get());
John McCall36226622010-10-12 02:09:17 +00003186 if (PR.isInvalid()) return QualType();
John Wiegley01296292011-04-08 18:41:53 +00003187 if (PR.get() != V.get()) {
Benjamin Kramer62b95d82012-08-23 21:35:17 +00003188 V = PR;
Richard Trieuba63ce62011-09-09 01:45:06 +00003189 return CheckRealImagOperand(S, V, Loc, IsReal);
John McCall36226622010-10-12 02:09:17 +00003190 }
3191
Chris Lattnere267f5d2007-08-26 05:39:26 +00003192 // Reject anything else.
John Wiegley01296292011-04-08 18:41:53 +00003193 S.Diag(Loc, diag::err_realimag_invalid_type) << V.get()->getType()
Richard Trieuba63ce62011-09-09 01:45:06 +00003194 << (IsReal ? "__real" : "__imag");
Chris Lattnere267f5d2007-08-26 05:39:26 +00003195 return QualType();
Chris Lattner30b5dd02007-08-24 21:16:53 +00003196}
3197
3198
Chris Lattnere168f762006-11-10 05:29:30 +00003199
John McCalldadc5752010-08-24 06:29:42 +00003200ExprResult
Sebastian Redlc215cfc2009-01-19 00:08:26 +00003201Sema::ActOnPostfixUnaryOp(Scope *S, SourceLocation OpLoc,
John McCallb268a282010-08-23 23:25:46 +00003202 tok::TokenKind Kind, Expr *Input) {
John McCalle3027922010-08-25 11:45:40 +00003203 UnaryOperatorKind Opc;
Chris Lattnere168f762006-11-10 05:29:30 +00003204 switch (Kind) {
David Blaikie83d382b2011-09-23 05:06:16 +00003205 default: llvm_unreachable("Unknown unary op!");
John McCalle3027922010-08-25 11:45:40 +00003206 case tok::plusplus: Opc = UO_PostInc; break;
3207 case tok::minusminus: Opc = UO_PostDec; break;
Chris Lattnere168f762006-11-10 05:29:30 +00003208 }
Sebastian Redlc215cfc2009-01-19 00:08:26 +00003209
Sebastian Redla9351792012-02-11 23:51:47 +00003210 // Since this might is a postfix expression, get rid of ParenListExprs.
3211 ExprResult Result = MaybeConvertParenListExprToParenExpr(S, Input);
3212 if (Result.isInvalid()) return ExprError();
3213 Input = Result.take();
3214
John McCallb268a282010-08-23 23:25:46 +00003215 return BuildUnaryOp(S, OpLoc, Opc, Input);
Chris Lattnere168f762006-11-10 05:29:30 +00003216}
3217
John McCallf2538342012-07-31 05:14:30 +00003218/// \brief Diagnose if arithmetic on the given ObjC pointer is illegal.
3219///
3220/// \return true on error
3221static bool checkArithmeticOnObjCPointer(Sema &S,
3222 SourceLocation opLoc,
3223 Expr *op) {
3224 assert(op->getType()->isObjCObjectPointerType());
3225 if (S.LangOpts.ObjCRuntime.allowsPointerArithmetic())
3226 return false;
3227
3228 S.Diag(opLoc, diag::err_arithmetic_nonfragile_interface)
3229 << op->getType()->castAs<ObjCObjectPointerType>()->getPointeeType()
3230 << op->getSourceRange();
3231 return true;
3232}
3233
John McCalldadc5752010-08-24 06:29:42 +00003234ExprResult
John McCallb268a282010-08-23 23:25:46 +00003235Sema::ActOnArraySubscriptExpr(Scope *S, Expr *Base, SourceLocation LLoc,
3236 Expr *Idx, SourceLocation RLoc) {
Nate Begeman5ec4b312009-08-10 23:49:36 +00003237 // Since this might be a postfix expression, get rid of ParenListExprs.
John McCalldadc5752010-08-24 06:29:42 +00003238 ExprResult Result = MaybeConvertParenListExprToParenExpr(S, Base);
John McCallb268a282010-08-23 23:25:46 +00003239 if (Result.isInvalid()) return ExprError();
3240 Base = Result.take();
Nate Begeman5ec4b312009-08-10 23:49:36 +00003241
John McCallb268a282010-08-23 23:25:46 +00003242 Expr *LHSExp = Base, *RHSExp = Idx;
Mike Stump11289f42009-09-09 15:08:12 +00003243
David Blaikiebbafb8a2012-03-11 07:00:24 +00003244 if (getLangOpts().CPlusPlus &&
Douglas Gregor7a77a6b2009-05-19 00:01:19 +00003245 (LHSExp->isTypeDependent() || RHSExp->isTypeDependent())) {
Douglas Gregor7a77a6b2009-05-19 00:01:19 +00003246 return Owned(new (Context) ArraySubscriptExpr(LHSExp, RHSExp,
John McCall7decc9e2010-11-18 06:31:45 +00003247 Context.DependentTy,
3248 VK_LValue, OK_Ordinary,
3249 RLoc));
Douglas Gregor7a77a6b2009-05-19 00:01:19 +00003250 }
3251
David Blaikiebbafb8a2012-03-11 07:00:24 +00003252 if (getLangOpts().CPlusPlus &&
Sebastian Redlc215cfc2009-01-19 00:08:26 +00003253 (LHSExp->getType()->isRecordType() ||
Eli Friedman254a1a22008-12-15 22:34:21 +00003254 LHSExp->getType()->isEnumeralType() ||
3255 RHSExp->getType()->isRecordType() ||
Ted Kremeneke65b0862012-03-06 20:05:56 +00003256 RHSExp->getType()->isEnumeralType()) &&
3257 !LHSExp->getType()->isObjCObjectPointerType()) {
John McCallb268a282010-08-23 23:25:46 +00003258 return CreateOverloadedArraySubscriptExpr(LLoc, RLoc, Base, Idx);
Douglas Gregor40412ac2008-11-19 17:17:41 +00003259 }
3260
John McCallb268a282010-08-23 23:25:46 +00003261 return CreateBuiltinArraySubscriptExpr(Base, LLoc, Idx, RLoc);
Sebastian Redladba46e2009-10-29 20:17:01 +00003262}
3263
John McCalldadc5752010-08-24 06:29:42 +00003264ExprResult
John McCallb268a282010-08-23 23:25:46 +00003265Sema::CreateBuiltinArraySubscriptExpr(Expr *Base, SourceLocation LLoc,
Richard Trieuba63ce62011-09-09 01:45:06 +00003266 Expr *Idx, SourceLocation RLoc) {
John McCallb268a282010-08-23 23:25:46 +00003267 Expr *LHSExp = Base;
3268 Expr *RHSExp = Idx;
Sebastian Redladba46e2009-10-29 20:17:01 +00003269
Chris Lattner36d572b2007-07-16 00:14:47 +00003270 // Perform default conversions.
John Wiegley01296292011-04-08 18:41:53 +00003271 if (!LHSExp->getType()->getAs<VectorType>()) {
3272 ExprResult Result = DefaultFunctionArrayLvalueConversion(LHSExp);
3273 if (Result.isInvalid())
3274 return ExprError();
3275 LHSExp = Result.take();
3276 }
3277 ExprResult Result = DefaultFunctionArrayLvalueConversion(RHSExp);
3278 if (Result.isInvalid())
3279 return ExprError();
3280 RHSExp = Result.take();
Sebastian Redlc215cfc2009-01-19 00:08:26 +00003281
Chris Lattner36d572b2007-07-16 00:14:47 +00003282 QualType LHSTy = LHSExp->getType(), RHSTy = RHSExp->getType();
John McCall7decc9e2010-11-18 06:31:45 +00003283 ExprValueKind VK = VK_LValue;
3284 ExprObjectKind OK = OK_Ordinary;
Steve Narofff1e53692007-03-23 22:27:02 +00003285
Steve Naroffc1aadb12007-03-28 21:49:40 +00003286 // C99 6.5.2.1p2: the expression e1[e2] is by definition precisely equivalent
Chris Lattnerf17bd422007-08-30 17:45:32 +00003287 // to the expression *((e1)+(e2)). This means the array "Base" may actually be
Mike Stump4e1f26a2009-02-19 03:04:26 +00003288 // in the subscript position. As a result, we need to derive the array base
Steve Narofff1e53692007-03-23 22:27:02 +00003289 // and index from the expression types.
Chris Lattner36d572b2007-07-16 00:14:47 +00003290 Expr *BaseExpr, *IndexExpr;
3291 QualType ResultType;
Sebastian Redl8d2ccae2009-02-26 14:39:58 +00003292 if (LHSTy->isDependentType() || RHSTy->isDependentType()) {
3293 BaseExpr = LHSExp;
3294 IndexExpr = RHSExp;
3295 ResultType = Context.DependentTy;
Ted Kremenekc23c7e62009-07-29 21:53:49 +00003296 } else if (const PointerType *PTy = LHSTy->getAs<PointerType>()) {
Chris Lattner36d572b2007-07-16 00:14:47 +00003297 BaseExpr = LHSExp;
3298 IndexExpr = RHSExp;
Chris Lattner36d572b2007-07-16 00:14:47 +00003299 ResultType = PTy->getPointeeType();
Mike Stump11289f42009-09-09 15:08:12 +00003300 } else if (const ObjCObjectPointerType *PTy =
John McCallf2538342012-07-31 05:14:30 +00003301 LHSTy->getAs<ObjCObjectPointerType>()) {
Steve Naroff7cae42b2009-07-10 23:34:53 +00003302 BaseExpr = LHSExp;
3303 IndexExpr = RHSExp;
John McCallf2538342012-07-31 05:14:30 +00003304
3305 // Use custom logic if this should be the pseudo-object subscript
3306 // expression.
3307 if (!LangOpts.ObjCRuntime.isSubscriptPointerArithmetic())
3308 return BuildObjCSubscriptExpression(RLoc, BaseExpr, IndexExpr, 0, 0);
3309
Steve Naroff7cae42b2009-07-10 23:34:53 +00003310 ResultType = PTy->getPointeeType();
John McCallf2538342012-07-31 05:14:30 +00003311 if (!LangOpts.ObjCRuntime.allowsPointerArithmetic()) {
3312 Diag(LLoc, diag::err_subscript_nonfragile_interface)
3313 << ResultType << BaseExpr->getSourceRange();
3314 return ExprError();
3315 }
Fariborz Jahanianba0afde2012-03-28 17:56:49 +00003316 } else if (const PointerType *PTy = RHSTy->getAs<PointerType>()) {
3317 // Handle the uncommon case of "123[Ptr]".
3318 BaseExpr = RHSExp;
3319 IndexExpr = LHSExp;
3320 ResultType = PTy->getPointeeType();
Mike Stump11289f42009-09-09 15:08:12 +00003321 } else if (const ObjCObjectPointerType *PTy =
John McCall9dd450b2009-09-21 23:43:11 +00003322 RHSTy->getAs<ObjCObjectPointerType>()) {
Steve Naroff7cae42b2009-07-10 23:34:53 +00003323 // Handle the uncommon case of "123[Ptr]".
3324 BaseExpr = RHSExp;
3325 IndexExpr = LHSExp;
3326 ResultType = PTy->getPointeeType();
John McCallf2538342012-07-31 05:14:30 +00003327 if (!LangOpts.ObjCRuntime.allowsPointerArithmetic()) {
3328 Diag(LLoc, diag::err_subscript_nonfragile_interface)
3329 << ResultType << BaseExpr->getSourceRange();
3330 return ExprError();
3331 }
John McCall9dd450b2009-09-21 23:43:11 +00003332 } else if (const VectorType *VTy = LHSTy->getAs<VectorType>()) {
Chris Lattner41977962007-07-31 19:29:30 +00003333 BaseExpr = LHSExp; // vectors: V[123]
Chris Lattner36d572b2007-07-16 00:14:47 +00003334 IndexExpr = RHSExp;
John McCall7decc9e2010-11-18 06:31:45 +00003335 VK = LHSExp->getValueKind();
3336 if (VK != VK_RValue)
3337 OK = OK_VectorComponent;
Nate Begemanc1bf0612009-01-18 00:45:31 +00003338
Chris Lattner36d572b2007-07-16 00:14:47 +00003339 // FIXME: need to deal with const...
3340 ResultType = VTy->getElementType();
Eli Friedmanab2784f2009-04-25 23:46:54 +00003341 } else if (LHSTy->isArrayType()) {
3342 // If we see an array that wasn't promoted by
Douglas Gregorb92a1562010-02-03 00:27:59 +00003343 // DefaultFunctionArrayLvalueConversion, it must be an array that
Eli Friedmanab2784f2009-04-25 23:46:54 +00003344 // wasn't promoted because of the C90 rule that doesn't
3345 // allow promoting non-lvalue arrays. Warn, then
3346 // force the promotion here.
3347 Diag(LHSExp->getLocStart(), diag::ext_subscript_non_lvalue) <<
3348 LHSExp->getSourceRange();
John Wiegley01296292011-04-08 18:41:53 +00003349 LHSExp = ImpCastExprToType(LHSExp, Context.getArrayDecayedType(LHSTy),
3350 CK_ArrayToPointerDecay).take();
Eli Friedmanab2784f2009-04-25 23:46:54 +00003351 LHSTy = LHSExp->getType();
3352
3353 BaseExpr = LHSExp;
3354 IndexExpr = RHSExp;
Ted Kremenekc23c7e62009-07-29 21:53:49 +00003355 ResultType = LHSTy->getAs<PointerType>()->getPointeeType();
Eli Friedmanab2784f2009-04-25 23:46:54 +00003356 } else if (RHSTy->isArrayType()) {
3357 // Same as previous, except for 123[f().a] case
3358 Diag(RHSExp->getLocStart(), diag::ext_subscript_non_lvalue) <<
3359 RHSExp->getSourceRange();
John Wiegley01296292011-04-08 18:41:53 +00003360 RHSExp = ImpCastExprToType(RHSExp, Context.getArrayDecayedType(RHSTy),
3361 CK_ArrayToPointerDecay).take();
Eli Friedmanab2784f2009-04-25 23:46:54 +00003362 RHSTy = RHSExp->getType();
3363
3364 BaseExpr = RHSExp;
3365 IndexExpr = LHSExp;
Ted Kremenekc23c7e62009-07-29 21:53:49 +00003366 ResultType = RHSTy->getAs<PointerType>()->getPointeeType();
Steve Naroffb3096442007-06-09 03:47:53 +00003367 } else {
Chris Lattner003af242009-04-25 22:50:55 +00003368 return ExprError(Diag(LLoc, diag::err_typecheck_subscript_value)
3369 << LHSExp->getSourceRange() << RHSExp->getSourceRange());
Sebastian Redlc215cfc2009-01-19 00:08:26 +00003370 }
Steve Naroffc1aadb12007-03-28 21:49:40 +00003371 // C99 6.5.2.1p1
Douglas Gregor5cc2c8b2010-07-23 15:58:24 +00003372 if (!IndexExpr->getType()->isIntegerType() && !IndexExpr->isTypeDependent())
Chris Lattner003af242009-04-25 22:50:55 +00003373 return ExprError(Diag(LLoc, diag::err_typecheck_subscript_not_integer)
3374 << IndexExpr->getSourceRange());
Steve Naroffb29cdd52007-07-10 18:23:31 +00003375
Daniel Dunbar4782a6e2009-09-17 06:31:17 +00003376 if ((IndexExpr->getType()->isSpecificBuiltinType(BuiltinType::Char_S) ||
Sam Weinigb7608d72009-09-14 20:14:57 +00003377 IndexExpr->getType()->isSpecificBuiltinType(BuiltinType::Char_U))
3378 && !IndexExpr->isTypeDependent())
Sam Weinig914244e2009-09-14 01:58:58 +00003379 Diag(LLoc, diag::warn_subscript_is_char) << IndexExpr->getSourceRange();
3380
Douglas Gregorac1fb652009-03-24 19:52:54 +00003381 // C99 6.5.2.1p1: "shall have type "pointer to *object* type". Similarly,
Mike Stump11289f42009-09-09 15:08:12 +00003382 // C++ [expr.sub]p1: The type "T" shall be a completely-defined object
3383 // type. Note that Functions are not objects, and that (in C99 parlance)
Douglas Gregorac1fb652009-03-24 19:52:54 +00003384 // incomplete types are not object types.
3385 if (ResultType->isFunctionType()) {
3386 Diag(BaseExpr->getLocStart(), diag::err_subscript_function_type)
3387 << ResultType << BaseExpr->getSourceRange();
3388 return ExprError();
3389 }
Mike Stump11289f42009-09-09 15:08:12 +00003390
David Blaikiebbafb8a2012-03-11 07:00:24 +00003391 if (ResultType->isVoidType() && !getLangOpts().CPlusPlus) {
Abramo Bagnara3aabb4b2010-09-13 06:50:07 +00003392 // GNU extension: subscripting on pointer to void
Chandler Carruth4cc3f292011-06-27 16:32:27 +00003393 Diag(LLoc, diag::ext_gnu_subscript_void_type)
3394 << BaseExpr->getSourceRange();
John McCall4bc41ae2010-11-18 19:01:18 +00003395
3396 // C forbids expressions of unqualified void type from being l-values.
3397 // See IsCForbiddenLValueType.
3398 if (!ResultType.hasQualifiers()) VK = VK_RValue;
Abramo Bagnara3aabb4b2010-09-13 06:50:07 +00003399 } else if (!ResultType->isDependentType() &&
Mike Stump11289f42009-09-09 15:08:12 +00003400 RequireCompleteType(LLoc, ResultType,
Douglas Gregor7bfb2d02012-05-04 16:32:21 +00003401 diag::err_subscript_incomplete_type, BaseExpr))
Douglas Gregorac1fb652009-03-24 19:52:54 +00003402 return ExprError();
Mike Stump11289f42009-09-09 15:08:12 +00003403
John McCall4bc41ae2010-11-18 19:01:18 +00003404 assert(VK == VK_RValue || LangOpts.CPlusPlus ||
Douglas Gregor5476205b2011-06-23 00:49:38 +00003405 !ResultType.isCForbiddenLValueType());
John McCall4bc41ae2010-11-18 19:01:18 +00003406
Mike Stump4e1f26a2009-02-19 03:04:26 +00003407 return Owned(new (Context) ArraySubscriptExpr(LHSExp, RHSExp,
John McCall7decc9e2010-11-18 06:31:45 +00003408 ResultType, VK, OK, RLoc));
Chris Lattnere168f762006-11-10 05:29:30 +00003409}
3410
John McCalldadc5752010-08-24 06:29:42 +00003411ExprResult Sema::BuildCXXDefaultArgExpr(SourceLocation CallLoc,
Nico Weber44887f62010-11-29 18:19:25 +00003412 FunctionDecl *FD,
3413 ParmVarDecl *Param) {
Anders Carlsson355933d2009-08-25 03:49:14 +00003414 if (Param->hasUnparsedDefaultArg()) {
Douglas Gregor8a01b2a2010-09-11 20:24:53 +00003415 Diag(CallLoc,
Nico Weberebd45a02010-11-30 04:44:33 +00003416 diag::err_use_of_default_argument_to_function_declared_later) <<
Anders Carlsson355933d2009-08-25 03:49:14 +00003417 FD << cast<CXXRecordDecl>(FD->getDeclContext())->getDeclName();
Mike Stump11289f42009-09-09 15:08:12 +00003418 Diag(UnparsedDefaultArgLocs[Param],
Nico Weberebd45a02010-11-30 04:44:33 +00003419 diag::note_default_argument_declared_here);
Douglas Gregor8a01b2a2010-09-11 20:24:53 +00003420 return ExprError();
3421 }
3422
3423 if (Param->hasUninstantiatedDefaultArg()) {
3424 Expr *UninstExpr = Param->getUninstantiatedDefaultArg();
Anders Carlsson355933d2009-08-25 03:49:14 +00003425
Richard Smith505df232012-07-22 23:45:10 +00003426 EnterExpressionEvaluationContext EvalContext(*this, PotentiallyEvaluated,
3427 Param);
3428
Douglas Gregor8a01b2a2010-09-11 20:24:53 +00003429 // Instantiate the expression.
3430 MultiLevelTemplateArgumentList ArgList
3431 = getTemplateInstantiationArgs(FD, 0, /*RelativeToPrimary=*/true);
Anders Carlsson657bad42009-09-05 05:14:19 +00003432
Nico Weber44887f62010-11-29 18:19:25 +00003433 std::pair<const TemplateArgument *, unsigned> Innermost
Douglas Gregor8a01b2a2010-09-11 20:24:53 +00003434 = ArgList.getInnermost();
Richard Smith80934652012-07-16 01:09:10 +00003435 InstantiatingTemplate Inst(*this, CallLoc, Param,
3436 ArrayRef<TemplateArgument>(Innermost.first,
3437 Innermost.second));
Richard Smith8a874c92012-07-08 02:38:24 +00003438 if (Inst)
3439 return ExprError();
Anders Carlsson355933d2009-08-25 03:49:14 +00003440
Nico Weber44887f62010-11-29 18:19:25 +00003441 ExprResult Result;
3442 {
3443 // C++ [dcl.fct.default]p5:
3444 // The names in the [default argument] expression are bound, and
3445 // the semantic constraints are checked, at the point where the
3446 // default argument expression appears.
Nico Weberebd45a02010-11-30 04:44:33 +00003447 ContextRAII SavedContext(*this, FD);
Douglas Gregora86bc002012-02-16 21:36:18 +00003448 LocalInstantiationScope Local(*this);
Nico Weber44887f62010-11-29 18:19:25 +00003449 Result = SubstExpr(UninstExpr, ArgList);
3450 }
Douglas Gregor8a01b2a2010-09-11 20:24:53 +00003451 if (Result.isInvalid())
3452 return ExprError();
Mike Stump11289f42009-09-09 15:08:12 +00003453
Douglas Gregor8a01b2a2010-09-11 20:24:53 +00003454 // Check the expression as an initializer for the parameter.
3455 InitializedEntity Entity
Fariborz Jahanian8fb87ae2010-09-24 17:30:16 +00003456 = InitializedEntity::InitializeParameter(Context, Param);
Douglas Gregor8a01b2a2010-09-11 20:24:53 +00003457 InitializationKind Kind
3458 = InitializationKind::CreateCopy(Param->getLocation(),
Daniel Dunbar62ee6412012-03-09 18:35:03 +00003459 /*FIXME:EqualLoc*/UninstExpr->getLocStart());
Douglas Gregor8a01b2a2010-09-11 20:24:53 +00003460 Expr *ResultE = Result.takeAs<Expr>();
Douglas Gregor25ab25f2009-12-23 18:19:08 +00003461
Douglas Gregor8a01b2a2010-09-11 20:24:53 +00003462 InitializationSequence InitSeq(*this, Entity, Kind, &ResultE, 1);
Benjamin Kramercc4c49d2012-08-23 23:38:35 +00003463 Result = InitSeq.Perform(*this, Entity, Kind, ResultE);
Douglas Gregor8a01b2a2010-09-11 20:24:53 +00003464 if (Result.isInvalid())
3465 return ExprError();
Kovarththanan Rajaratnamba2c6522010-03-13 10:17:05 +00003466
David Blaikief68e8092012-04-30 18:21:31 +00003467 Expr *Arg = Result.takeAs<Expr>();
David Blaikie18e9ac72012-05-15 21:57:38 +00003468 CheckImplicitConversions(Arg, Param->getOuterLocStart());
Douglas Gregor8a01b2a2010-09-11 20:24:53 +00003469 // Build the default argument expression.
David Blaikief68e8092012-04-30 18:21:31 +00003470 return Owned(CXXDefaultArgExpr::Create(Context, CallLoc, Param, Arg));
Anders Carlsson355933d2009-08-25 03:49:14 +00003471 }
3472
Douglas Gregor8a01b2a2010-09-11 20:24:53 +00003473 // If the default expression creates temporaries, we need to
3474 // push them to the current stack of expression temporaries so they'll
3475 // be properly destroyed.
3476 // FIXME: We should really be rebuilding the default argument with new
3477 // bound temporaries; see the comment in PR5810.
John McCall28fc7092011-11-10 05:35:25 +00003478 // We don't need to do that with block decls, though, because
3479 // blocks in default argument expression can never capture anything.
3480 if (isa<ExprWithCleanups>(Param->getInit())) {
3481 // Set the "needs cleanups" bit regardless of whether there are
3482 // any explicit objects.
John McCall31168b02011-06-15 23:02:42 +00003483 ExprNeedsCleanups = true;
John McCall28fc7092011-11-10 05:35:25 +00003484
3485 // Append all the objects to the cleanup list. Right now, this
3486 // should always be a no-op, because blocks in default argument
3487 // expressions should never be able to capture anything.
3488 assert(!cast<ExprWithCleanups>(Param->getInit())->getNumObjects() &&
3489 "default argument expression has capturing blocks?");
Douglas Gregor6ed2fee2010-09-14 22:55:20 +00003490 }
Douglas Gregor8a01b2a2010-09-11 20:24:53 +00003491
3492 // We already type-checked the argument, so we know it works.
Douglas Gregor32b3de52010-09-11 23:32:50 +00003493 // Just mark all of the declarations in this potentially-evaluated expression
3494 // as being "referenced".
Douglas Gregor680e9e02012-02-21 19:11:17 +00003495 MarkDeclarationsReferencedInExpr(Param->getDefaultArg(),
3496 /*SkipLocalVariables=*/true);
Douglas Gregor033f6752009-12-23 23:03:06 +00003497 return Owned(CXXDefaultArgExpr::Create(Context, CallLoc, Param));
Anders Carlsson355933d2009-08-25 03:49:14 +00003498}
3499
Richard Smith55ce3522012-06-25 20:30:08 +00003500
3501Sema::VariadicCallType
3502Sema::getVariadicCallType(FunctionDecl *FDecl, const FunctionProtoType *Proto,
3503 Expr *Fn) {
3504 if (Proto && Proto->isVariadic()) {
3505 if (dyn_cast_or_null<CXXConstructorDecl>(FDecl))
3506 return VariadicConstructor;
3507 else if (Fn && Fn->getType()->isBlockPointerType())
3508 return VariadicBlock;
3509 else if (FDecl) {
3510 if (CXXMethodDecl *Method = dyn_cast_or_null<CXXMethodDecl>(FDecl))
3511 if (Method->isInstance())
3512 return VariadicMethod;
3513 }
3514 return VariadicFunction;
3515 }
3516 return VariadicDoesNotApply;
3517}
3518
Douglas Gregor97fd6e22008-12-22 05:46:06 +00003519/// ConvertArgumentsForCall - Converts the arguments specified in
3520/// Args/NumArgs to the parameter types of the function FDecl with
3521/// function prototype Proto. Call is the call expression itself, and
3522/// Fn is the function expression. For a C++ member function, this
3523/// routine does not attempt to convert the object argument. Returns
3524/// true if the call is ill-formed.
Mike Stump4e1f26a2009-02-19 03:04:26 +00003525bool
3526Sema::ConvertArgumentsForCall(CallExpr *Call, Expr *Fn,
Douglas Gregor97fd6e22008-12-22 05:46:06 +00003527 FunctionDecl *FDecl,
Douglas Gregordeaad8c2009-02-26 23:50:07 +00003528 const FunctionProtoType *Proto,
Douglas Gregor97fd6e22008-12-22 05:46:06 +00003529 Expr **Args, unsigned NumArgs,
Peter Collingbourne619a8c72011-10-02 23:49:29 +00003530 SourceLocation RParenLoc,
3531 bool IsExecConfig) {
John McCallbebede42011-02-26 05:39:39 +00003532 // Bail out early if calling a builtin with custom typechecking.
3533 // We don't need to do this in the
3534 if (FDecl)
3535 if (unsigned ID = FDecl->getBuiltinID())
3536 if (Context.BuiltinInfo.hasCustomTypechecking(ID))
3537 return false;
3538
Mike Stump4e1f26a2009-02-19 03:04:26 +00003539 // C99 6.5.2.2p7 - the arguments are implicitly converted, as if by
Douglas Gregor97fd6e22008-12-22 05:46:06 +00003540 // assignment, to the types of the corresponding parameter, ...
3541 unsigned NumArgsInProto = Proto->getNumArgs();
Douglas Gregorb6b99612009-01-23 21:30:56 +00003542 bool Invalid = false;
Peter Collingbourne740afe22011-10-02 23:49:20 +00003543 unsigned MinArgs = FDecl ? FDecl->getMinRequiredArguments() : NumArgsInProto;
Peter Collingbourne619a8c72011-10-02 23:49:29 +00003544 unsigned FnKind = Fn->getType()->isBlockPointerType()
3545 ? 1 /* block */
3546 : (IsExecConfig ? 3 /* kernel function (exec config) */
3547 : 0 /* function */);
Kovarththanan Rajaratnamba2c6522010-03-13 10:17:05 +00003548
Douglas Gregor97fd6e22008-12-22 05:46:06 +00003549 // If too few arguments are available (and we don't have default
3550 // arguments for the remaining parameters), don't make the call.
3551 if (NumArgs < NumArgsInProto) {
Peter Collingbourne740afe22011-10-02 23:49:20 +00003552 if (NumArgs < MinArgs) {
Richard Smith10ff50d2012-05-11 05:16:41 +00003553 if (MinArgs == 1 && FDecl && FDecl->getParamDecl(0)->getDeclName())
3554 Diag(RParenLoc, MinArgs == NumArgsInProto && !Proto->isVariadic()
3555 ? diag::err_typecheck_call_too_few_args_one
3556 : diag::err_typecheck_call_too_few_args_at_least_one)
3557 << FnKind
3558 << FDecl->getParamDecl(0) << Fn->getSourceRange();
3559 else
3560 Diag(RParenLoc, MinArgs == NumArgsInProto && !Proto->isVariadic()
3561 ? diag::err_typecheck_call_too_few_args
3562 : diag::err_typecheck_call_too_few_args_at_least)
3563 << FnKind
3564 << MinArgs << NumArgs << Fn->getSourceRange();
Peter Collingbourne3bc84ca2011-07-29 00:24:42 +00003565
3566 // Emit the location of the prototype.
Peter Collingbourne619a8c72011-10-02 23:49:29 +00003567 if (FDecl && !FDecl->getBuiltinID() && !IsExecConfig)
Peter Collingbourne3bc84ca2011-07-29 00:24:42 +00003568 Diag(FDecl->getLocStart(), diag::note_callee_decl)
3569 << FDecl;
3570
3571 return true;
3572 }
Ted Kremenek5a201952009-02-07 01:47:29 +00003573 Call->setNumArgs(Context, NumArgsInProto);
Douglas Gregor97fd6e22008-12-22 05:46:06 +00003574 }
3575
3576 // If too many are passed and not variadic, error on the extras and drop
3577 // them.
3578 if (NumArgs > NumArgsInProto) {
3579 if (!Proto->isVariadic()) {
Richard Smithd72da152012-05-15 06:21:54 +00003580 if (NumArgsInProto == 1 && FDecl && FDecl->getParamDecl(0)->getDeclName())
3581 Diag(Args[NumArgsInProto]->getLocStart(),
3582 MinArgs == NumArgsInProto
3583 ? diag::err_typecheck_call_too_many_args_one
3584 : diag::err_typecheck_call_too_many_args_at_most_one)
3585 << FnKind
3586 << FDecl->getParamDecl(0) << NumArgs << Fn->getSourceRange()
3587 << SourceRange(Args[NumArgsInProto]->getLocStart(),
3588 Args[NumArgs-1]->getLocEnd());
3589 else
3590 Diag(Args[NumArgsInProto]->getLocStart(),
3591 MinArgs == NumArgsInProto
3592 ? diag::err_typecheck_call_too_many_args
3593 : diag::err_typecheck_call_too_many_args_at_most)
3594 << FnKind
3595 << NumArgsInProto << NumArgs << Fn->getSourceRange()
3596 << SourceRange(Args[NumArgsInProto]->getLocStart(),
3597 Args[NumArgs-1]->getLocEnd());
Ted Kremenek99a337e2011-04-04 17:22:27 +00003598
3599 // Emit the location of the prototype.
Peter Collingbourne619a8c72011-10-02 23:49:29 +00003600 if (FDecl && !FDecl->getBuiltinID() && !IsExecConfig)
Peter Collingbourne3bc84ca2011-07-29 00:24:42 +00003601 Diag(FDecl->getLocStart(), diag::note_callee_decl)
3602 << FDecl;
Ted Kremenek99a337e2011-04-04 17:22:27 +00003603
Douglas Gregor97fd6e22008-12-22 05:46:06 +00003604 // This deletes the extra arguments.
Ted Kremenek5a201952009-02-07 01:47:29 +00003605 Call->setNumArgs(Context, NumArgsInProto);
Fariborz Jahanian835026e2009-11-24 18:29:37 +00003606 return true;
Douglas Gregor97fd6e22008-12-22 05:46:06 +00003607 }
Douglas Gregor97fd6e22008-12-22 05:46:06 +00003608 }
Chris Lattner0e62c1c2011-07-23 10:55:15 +00003609 SmallVector<Expr *, 8> AllArgs;
Richard Smith55ce3522012-06-25 20:30:08 +00003610 VariadicCallType CallType = getVariadicCallType(FDecl, Proto, Fn);
3611
Daniel Dunbar62ee6412012-03-09 18:35:03 +00003612 Invalid = GatherArgumentsForCall(Call->getLocStart(), FDecl,
Fariborz Jahanian4fa66ce2009-11-24 21:37:28 +00003613 Proto, 0, Args, NumArgs, AllArgs, CallType);
Fariborz Jahanian835026e2009-11-24 18:29:37 +00003614 if (Invalid)
3615 return true;
3616 unsigned TotalNumArgs = AllArgs.size();
3617 for (unsigned i = 0; i < TotalNumArgs; ++i)
3618 Call->setArg(i, AllArgs[i]);
Kovarththanan Rajaratnamba2c6522010-03-13 10:17:05 +00003619
Fariborz Jahanian835026e2009-11-24 18:29:37 +00003620 return false;
3621}
Mike Stump4e1f26a2009-02-19 03:04:26 +00003622
Fariborz Jahanian835026e2009-11-24 18:29:37 +00003623bool Sema::GatherArgumentsForCall(SourceLocation CallLoc,
3624 FunctionDecl *FDecl,
3625 const FunctionProtoType *Proto,
3626 unsigned FirstProtoArg,
3627 Expr **Args, unsigned NumArgs,
Chris Lattner0e62c1c2011-07-23 10:55:15 +00003628 SmallVector<Expr *, 8> &AllArgs,
Douglas Gregor6073dca2012-02-24 23:56:31 +00003629 VariadicCallType CallType,
3630 bool AllowExplicit) {
Fariborz Jahanian835026e2009-11-24 18:29:37 +00003631 unsigned NumArgsInProto = Proto->getNumArgs();
3632 unsigned NumArgsToCheck = NumArgs;
3633 bool Invalid = false;
3634 if (NumArgs != NumArgsInProto)
3635 // Use default arguments for missing arguments
3636 NumArgsToCheck = NumArgsInProto;
3637 unsigned ArgIx = 0;
Douglas Gregor97fd6e22008-12-22 05:46:06 +00003638 // Continue to check argument types (even if we have too few/many args).
Fariborz Jahanian835026e2009-11-24 18:29:37 +00003639 for (unsigned i = FirstProtoArg; i != NumArgsToCheck; i++) {
Douglas Gregor97fd6e22008-12-22 05:46:06 +00003640 QualType ProtoArgType = Proto->getArgType(i);
Kovarththanan Rajaratnamba2c6522010-03-13 10:17:05 +00003641
Douglas Gregor97fd6e22008-12-22 05:46:06 +00003642 Expr *Arg;
Peter Collingbournea48f33f2011-10-19 00:16:45 +00003643 ParmVarDecl *Param;
Fariborz Jahanian835026e2009-11-24 18:29:37 +00003644 if (ArgIx < NumArgs) {
3645 Arg = Args[ArgIx++];
Kovarththanan Rajaratnamba2c6522010-03-13 10:17:05 +00003646
Daniel Dunbar62ee6412012-03-09 18:35:03 +00003647 if (RequireCompleteType(Arg->getLocStart(),
Eli Friedman3164fb12009-03-22 22:00:50 +00003648 ProtoArgType,
Douglas Gregor7bfb2d02012-05-04 16:32:21 +00003649 diag::err_call_incomplete_argument, Arg))
Eli Friedman3164fb12009-03-22 22:00:50 +00003650 return true;
Kovarththanan Rajaratnamba2c6522010-03-13 10:17:05 +00003651
Douglas Gregorbbeb5c32009-12-22 16:09:06 +00003652 // Pass the argument
Peter Collingbournea48f33f2011-10-19 00:16:45 +00003653 Param = 0;
Douglas Gregorbbeb5c32009-12-22 16:09:06 +00003654 if (FDecl && i < FDecl->getNumParams())
3655 Param = FDecl->getParamDecl(i);
Douglas Gregor96596c92009-12-22 07:24:36 +00003656
John McCall4124c492011-10-17 18:40:02 +00003657 // Strip the unbridged-cast placeholder expression off, if applicable.
3658 if (Arg->getType() == Context.ARCUnbridgedCastTy &&
3659 FDecl && FDecl->hasAttr<CFAuditedTransferAttr>() &&
3660 (!Param || !Param->hasAttr<CFConsumedAttr>()))
3661 Arg = stripARCUnbridgedCast(Arg);
3662
Douglas Gregorbbeb5c32009-12-22 16:09:06 +00003663 InitializedEntity Entity =
Fariborz Jahanian8fb87ae2010-09-24 17:30:16 +00003664 Param? InitializedEntity::InitializeParameter(Context, Param)
John McCall31168b02011-06-15 23:02:42 +00003665 : InitializedEntity::InitializeParameter(Context, ProtoArgType,
3666 Proto->isArgConsumed(i));
John McCalldadc5752010-08-24 06:29:42 +00003667 ExprResult ArgE = PerformCopyInitialization(Entity,
John McCall34376a62010-12-04 03:47:34 +00003668 SourceLocation(),
Douglas Gregor6073dca2012-02-24 23:56:31 +00003669 Owned(Arg),
3670 /*TopLevelOfInitList=*/false,
3671 AllowExplicit);
Douglas Gregorbbeb5c32009-12-22 16:09:06 +00003672 if (ArgE.isInvalid())
3673 return true;
3674
3675 Arg = ArgE.takeAs<Expr>();
Anders Carlsson84613c42009-06-12 16:51:40 +00003676 } else {
Peter Collingbournea48f33f2011-10-19 00:16:45 +00003677 Param = FDecl->getParamDecl(i);
Kovarththanan Rajaratnamba2c6522010-03-13 10:17:05 +00003678
John McCalldadc5752010-08-24 06:29:42 +00003679 ExprResult ArgExpr =
Fariborz Jahanian835026e2009-11-24 18:29:37 +00003680 BuildCXXDefaultArgExpr(CallLoc, FDecl, Param);
Anders Carlsson355933d2009-08-25 03:49:14 +00003681 if (ArgExpr.isInvalid())
3682 return true;
Kovarththanan Rajaratnamba2c6522010-03-13 10:17:05 +00003683
Anders Carlsson355933d2009-08-25 03:49:14 +00003684 Arg = ArgExpr.takeAs<Expr>();
Anders Carlsson84613c42009-06-12 16:51:40 +00003685 }
Kaelyn Uhrain2e7aa5a2011-08-05 23:18:04 +00003686
3687 // Check for array bounds violations for each argument to the call. This
3688 // check only triggers warnings when the argument isn't a more complex Expr
3689 // with its own checking, such as a BinaryOperator.
3690 CheckArrayAccess(Arg);
3691
Peter Collingbournea48f33f2011-10-19 00:16:45 +00003692 // Check for violations of C99 static array rules (C99 6.7.5.3p7).
3693 CheckStaticArrayArgument(CallLoc, Param, Arg);
3694
Fariborz Jahanian835026e2009-11-24 18:29:37 +00003695 AllArgs.push_back(Arg);
Douglas Gregor97fd6e22008-12-22 05:46:06 +00003696 }
Kovarththanan Rajaratnamba2c6522010-03-13 10:17:05 +00003697
Douglas Gregor97fd6e22008-12-22 05:46:06 +00003698 // If this is a variadic call, handle args passed through "...".
Fariborz Jahanian6f2d25e2009-11-24 19:27:49 +00003699 if (CallType != VariadicDoesNotApply) {
John McCall2979fe02011-04-12 00:42:48 +00003700 // Assume that extern "C" functions with variadic arguments that
3701 // return __unknown_anytype aren't *really* variadic.
3702 if (Proto->getResultType() == Context.UnknownAnyTy &&
3703 FDecl && FDecl->isExternC()) {
3704 for (unsigned i = ArgIx; i != NumArgs; ++i) {
3705 ExprResult arg;
3706 if (isa<ExplicitCastExpr>(Args[i]->IgnoreParens()))
3707 arg = DefaultFunctionArrayLvalueConversion(Args[i]);
3708 else
3709 arg = DefaultVariadicArgumentPromotion(Args[i], CallType, FDecl);
3710 Invalid |= arg.isInvalid();
3711 AllArgs.push_back(arg.take());
3712 }
3713
3714 // Otherwise do argument promotion, (C99 6.5.2.2p7).
3715 } else {
3716 for (unsigned i = ArgIx; i != NumArgs; ++i) {
Richard Trieucfc491d2011-08-02 04:35:43 +00003717 ExprResult Arg = DefaultVariadicArgumentPromotion(Args[i], CallType,
3718 FDecl);
John McCall2979fe02011-04-12 00:42:48 +00003719 Invalid |= Arg.isInvalid();
3720 AllArgs.push_back(Arg.take());
3721 }
Douglas Gregor97fd6e22008-12-22 05:46:06 +00003722 }
Ted Kremenekd41f3462011-09-26 23:36:13 +00003723
3724 // Check for array bounds violations.
3725 for (unsigned i = ArgIx; i != NumArgs; ++i)
3726 CheckArrayAccess(Args[i]);
Douglas Gregor97fd6e22008-12-22 05:46:06 +00003727 }
Douglas Gregorb6b99612009-01-23 21:30:56 +00003728 return Invalid;
Douglas Gregor97fd6e22008-12-22 05:46:06 +00003729}
3730
Peter Collingbournea48f33f2011-10-19 00:16:45 +00003731static void DiagnoseCalleeStaticArrayParam(Sema &S, ParmVarDecl *PVD) {
3732 TypeLoc TL = PVD->getTypeSourceInfo()->getTypeLoc();
3733 if (ArrayTypeLoc *ATL = dyn_cast<ArrayTypeLoc>(&TL))
3734 S.Diag(PVD->getLocation(), diag::note_callee_static_array)
3735 << ATL->getLocalSourceRange();
3736}
3737
3738/// CheckStaticArrayArgument - If the given argument corresponds to a static
3739/// array parameter, check that it is non-null, and that if it is formed by
3740/// array-to-pointer decay, the underlying array is sufficiently large.
3741///
3742/// C99 6.7.5.3p7: If the keyword static also appears within the [ and ] of the
3743/// array type derivation, then for each call to the function, the value of the
3744/// corresponding actual argument shall provide access to the first element of
3745/// an array with at least as many elements as specified by the size expression.
3746void
3747Sema::CheckStaticArrayArgument(SourceLocation CallLoc,
3748 ParmVarDecl *Param,
3749 const Expr *ArgExpr) {
3750 // Static array parameters are not supported in C++.
David Blaikiebbafb8a2012-03-11 07:00:24 +00003751 if (!Param || getLangOpts().CPlusPlus)
Peter Collingbournea48f33f2011-10-19 00:16:45 +00003752 return;
3753
3754 QualType OrigTy = Param->getOriginalType();
3755
3756 const ArrayType *AT = Context.getAsArrayType(OrigTy);
3757 if (!AT || AT->getSizeModifier() != ArrayType::Static)
3758 return;
3759
3760 if (ArgExpr->isNullPointerConstant(Context,
3761 Expr::NPC_NeverValueDependent)) {
3762 Diag(CallLoc, diag::warn_null_arg) << ArgExpr->getSourceRange();
3763 DiagnoseCalleeStaticArrayParam(*this, Param);
3764 return;
3765 }
3766
3767 const ConstantArrayType *CAT = dyn_cast<ConstantArrayType>(AT);
3768 if (!CAT)
3769 return;
3770
3771 const ConstantArrayType *ArgCAT =
3772 Context.getAsConstantArrayType(ArgExpr->IgnoreParenImpCasts()->getType());
3773 if (!ArgCAT)
3774 return;
3775
3776 if (ArgCAT->getSize().ult(CAT->getSize())) {
3777 Diag(CallLoc, diag::warn_static_array_too_small)
3778 << ArgExpr->getSourceRange()
3779 << (unsigned) ArgCAT->getSize().getZExtValue()
3780 << (unsigned) CAT->getSize().getZExtValue();
3781 DiagnoseCalleeStaticArrayParam(*this, Param);
3782 }
3783}
3784
John McCall2979fe02011-04-12 00:42:48 +00003785/// Given a function expression of unknown-any type, try to rebuild it
3786/// to have a function type.
3787static ExprResult rebuildUnknownAnyFunction(Sema &S, Expr *fn);
3788
Steve Naroff83895f72007-09-16 03:34:24 +00003789/// ActOnCallExpr - Handle a call to Fn with the specified array of arguments.
Chris Lattnere168f762006-11-10 05:29:30 +00003790/// This provides the location of the left/right parens and a list of comma
3791/// locations.
John McCalldadc5752010-08-24 06:29:42 +00003792ExprResult
John McCallb268a282010-08-23 23:25:46 +00003793Sema::ActOnCallExpr(Scope *S, Expr *Fn, SourceLocation LParenLoc,
Richard Trieuba63ce62011-09-09 01:45:06 +00003794 MultiExprArg ArgExprs, SourceLocation RParenLoc,
Peter Collingbourne619a8c72011-10-02 23:49:29 +00003795 Expr *ExecConfig, bool IsExecConfig) {
Nate Begeman5ec4b312009-08-10 23:49:36 +00003796 // Since this might be a postfix expression, get rid of ParenListExprs.
John McCalldadc5752010-08-24 06:29:42 +00003797 ExprResult Result = MaybeConvertParenListExprToParenExpr(S, Fn);
John McCallb268a282010-08-23 23:25:46 +00003798 if (Result.isInvalid()) return ExprError();
3799 Fn = Result.take();
Mike Stump11289f42009-09-09 15:08:12 +00003800
David Blaikiebbafb8a2012-03-11 07:00:24 +00003801 if (getLangOpts().CPlusPlus) {
Douglas Gregorad8a3362009-09-04 17:36:40 +00003802 // If this is a pseudo-destructor expression, build the call immediately.
3803 if (isa<CXXPseudoDestructorExpr>(Fn)) {
Benjamin Kramerc215e762012-08-24 11:54:20 +00003804 if (!ArgExprs.empty()) {
Douglas Gregorad8a3362009-09-04 17:36:40 +00003805 // Pseudo-destructor calls should not have any arguments.
3806 Diag(Fn->getLocStart(), diag::err_pseudo_dtor_call_with_args)
Douglas Gregora771f462010-03-31 17:46:05 +00003807 << FixItHint::CreateRemoval(
Benjamin Kramerc215e762012-08-24 11:54:20 +00003808 SourceRange(ArgExprs[0]->getLocStart(),
3809 ArgExprs.back()->getLocEnd()));
Douglas Gregorad8a3362009-09-04 17:36:40 +00003810 }
Mike Stump11289f42009-09-09 15:08:12 +00003811
Benjamin Kramerc215e762012-08-24 11:54:20 +00003812 return Owned(new (Context) CallExpr(Context, Fn, MultiExprArg(),
3813 Context.VoidTy, VK_RValue,
3814 RParenLoc));
Douglas Gregorad8a3362009-09-04 17:36:40 +00003815 }
Mike Stump11289f42009-09-09 15:08:12 +00003816
Douglas Gregorb8a9a412009-02-04 15:01:18 +00003817 // Determine whether this is a dependent call inside a C++ template,
Mike Stump4e1f26a2009-02-19 03:04:26 +00003818 // in which case we won't do any semantic analysis now.
Mike Stump87c57ac2009-05-16 07:39:55 +00003819 // FIXME: Will need to cache the results of name lookup (including ADL) in
3820 // Fn.
Douglas Gregorb8a9a412009-02-04 15:01:18 +00003821 bool Dependent = false;
3822 if (Fn->isTypeDependent())
3823 Dependent = true;
Benjamin Kramerc215e762012-08-24 11:54:20 +00003824 else if (Expr::hasAnyTypeDependentArguments(ArgExprs))
Douglas Gregorb8a9a412009-02-04 15:01:18 +00003825 Dependent = true;
3826
Peter Collingbourne41f85462011-02-09 21:07:24 +00003827 if (Dependent) {
3828 if (ExecConfig) {
3829 return Owned(new (Context) CUDAKernelCallExpr(
Benjamin Kramerc215e762012-08-24 11:54:20 +00003830 Context, Fn, cast<CallExpr>(ExecConfig), ArgExprs,
Peter Collingbourne41f85462011-02-09 21:07:24 +00003831 Context.DependentTy, VK_RValue, RParenLoc));
3832 } else {
Benjamin Kramerc215e762012-08-24 11:54:20 +00003833 return Owned(new (Context) CallExpr(Context, Fn, ArgExprs,
Peter Collingbourne41f85462011-02-09 21:07:24 +00003834 Context.DependentTy, VK_RValue,
3835 RParenLoc));
3836 }
3837 }
Douglas Gregorb8a9a412009-02-04 15:01:18 +00003838
3839 // Determine whether this is a call to an object (C++ [over.call.object]).
3840 if (Fn->getType()->isRecordType())
Benjamin Kramerc215e762012-08-24 11:54:20 +00003841 return Owned(BuildCallToObjectOfClassType(S, Fn, LParenLoc,
3842 ArgExprs.data(),
3843 ArgExprs.size(), RParenLoc));
Douglas Gregorb8a9a412009-02-04 15:01:18 +00003844
John McCall2979fe02011-04-12 00:42:48 +00003845 if (Fn->getType() == Context.UnknownAnyTy) {
3846 ExprResult result = rebuildUnknownAnyFunction(*this, Fn);
3847 if (result.isInvalid()) return ExprError();
3848 Fn = result.take();
3849 }
3850
John McCall0009fcc2011-04-26 20:42:42 +00003851 if (Fn->getType() == Context.BoundMemberTy) {
Benjamin Kramerc215e762012-08-24 11:54:20 +00003852 return BuildCallToMemberFunction(S, Fn, LParenLoc, ArgExprs.data(),
3853 ArgExprs.size(), RParenLoc);
John McCall10eae182009-11-30 22:42:35 +00003854 }
John McCall0009fcc2011-04-26 20:42:42 +00003855 }
John McCall10eae182009-11-30 22:42:35 +00003856
John McCall0009fcc2011-04-26 20:42:42 +00003857 // Check for overloaded calls. This can happen even in C due to extensions.
3858 if (Fn->getType() == Context.OverloadTy) {
3859 OverloadExpr::FindResult find = OverloadExpr::find(Fn);
3860
Douglas Gregorcda22702011-10-13 18:10:35 +00003861 // We aren't supposed to apply this logic for if there's an '&' involved.
Douglas Gregorf4a06c22011-10-13 18:26:27 +00003862 if (!find.HasFormOfMemberPointer) {
John McCall0009fcc2011-04-26 20:42:42 +00003863 OverloadExpr *ovl = find.Expression;
3864 if (isa<UnresolvedLookupExpr>(ovl)) {
3865 UnresolvedLookupExpr *ULE = cast<UnresolvedLookupExpr>(ovl);
Benjamin Kramerc215e762012-08-24 11:54:20 +00003866 return BuildOverloadedCallExpr(S, Fn, ULE, LParenLoc, ArgExprs.data(),
3867 ArgExprs.size(), RParenLoc, ExecConfig);
John McCall0009fcc2011-04-26 20:42:42 +00003868 } else {
Benjamin Kramerc215e762012-08-24 11:54:20 +00003869 return BuildCallToMemberFunction(S, Fn, LParenLoc, ArgExprs.data(),
3870 ArgExprs.size(), RParenLoc);
Anders Carlsson61914b52009-10-03 17:40:22 +00003871 }
3872 }
Douglas Gregor97fd6e22008-12-22 05:46:06 +00003873 }
3874
Douglas Gregore254f902009-02-04 00:32:51 +00003875 // If we're directly calling a function, get the appropriate declaration.
Douglas Gregord8fb1e32011-12-01 01:37:36 +00003876 if (Fn->getType() == Context.UnknownAnyTy) {
3877 ExprResult result = rebuildUnknownAnyFunction(*this, Fn);
3878 if (result.isInvalid()) return ExprError();
3879 Fn = result.take();
3880 }
Mike Stump4e1f26a2009-02-19 03:04:26 +00003881
Eli Friedmane14b1992009-12-26 03:35:45 +00003882 Expr *NakedFn = Fn->IgnoreParens();
Douglas Gregor928479e2010-11-09 20:03:54 +00003883
John McCall57500772009-12-16 12:17:52 +00003884 NamedDecl *NDecl = 0;
Douglas Gregor59f16ed2010-10-25 20:48:33 +00003885 if (UnaryOperator *UnOp = dyn_cast<UnaryOperator>(NakedFn))
3886 if (UnOp->getOpcode() == UO_AddrOf)
3887 NakedFn = UnOp->getSubExpr()->IgnoreParens();
3888
John McCall57500772009-12-16 12:17:52 +00003889 if (isa<DeclRefExpr>(NakedFn))
3890 NDecl = cast<DeclRefExpr>(NakedFn)->getDecl();
John McCall0009fcc2011-04-26 20:42:42 +00003891 else if (isa<MemberExpr>(NakedFn))
3892 NDecl = cast<MemberExpr>(NakedFn)->getMemberDecl();
John McCall57500772009-12-16 12:17:52 +00003893
Benjamin Kramerc215e762012-08-24 11:54:20 +00003894 return BuildResolvedCallExpr(Fn, NDecl, LParenLoc, ArgExprs.data(),
3895 ArgExprs.size(), RParenLoc, ExecConfig,
3896 IsExecConfig);
Peter Collingbourne41f85462011-02-09 21:07:24 +00003897}
3898
3899ExprResult
3900Sema::ActOnCUDAExecConfigExpr(Scope *S, SourceLocation LLLLoc,
Richard Trieuba63ce62011-09-09 01:45:06 +00003901 MultiExprArg ExecConfig, SourceLocation GGGLoc) {
Peter Collingbourne41f85462011-02-09 21:07:24 +00003902 FunctionDecl *ConfigDecl = Context.getcudaConfigureCallDecl();
3903 if (!ConfigDecl)
3904 return ExprError(Diag(LLLLoc, diag::err_undeclared_var_use)
3905 << "cudaConfigureCall");
3906 QualType ConfigQTy = ConfigDecl->getType();
3907
3908 DeclRefExpr *ConfigDR = new (Context) DeclRefExpr(
John McCall113bee02012-03-10 09:33:50 +00003909 ConfigDecl, false, ConfigQTy, VK_LValue, LLLLoc);
Eli Friedmanfa0df832012-02-02 03:46:19 +00003910 MarkFunctionReferenced(LLLLoc, ConfigDecl);
Peter Collingbourne41f85462011-02-09 21:07:24 +00003911
Peter Collingbourne619a8c72011-10-02 23:49:29 +00003912 return ActOnCallExpr(S, ConfigDR, LLLLoc, ExecConfig, GGGLoc, 0,
3913 /*IsExecConfig=*/true);
John McCall2d74de92009-12-01 22:10:20 +00003914}
3915
Tanya Lattner55808c12011-06-04 00:47:47 +00003916/// ActOnAsTypeExpr - create a new asType (bitcast) from the arguments.
3917///
3918/// __builtin_astype( value, dst type )
3919///
Richard Trieuba63ce62011-09-09 01:45:06 +00003920ExprResult Sema::ActOnAsTypeExpr(Expr *E, ParsedType ParsedDestTy,
Tanya Lattner55808c12011-06-04 00:47:47 +00003921 SourceLocation BuiltinLoc,
3922 SourceLocation RParenLoc) {
3923 ExprValueKind VK = VK_RValue;
3924 ExprObjectKind OK = OK_Ordinary;
Richard Trieuba63ce62011-09-09 01:45:06 +00003925 QualType DstTy = GetTypeFromParser(ParsedDestTy);
3926 QualType SrcTy = E->getType();
Tanya Lattner55808c12011-06-04 00:47:47 +00003927 if (Context.getTypeSize(DstTy) != Context.getTypeSize(SrcTy))
3928 return ExprError(Diag(BuiltinLoc,
3929 diag::err_invalid_astype_of_different_size)
Peter Collingbourne23f1bee2011-06-08 15:15:17 +00003930 << DstTy
3931 << SrcTy
Richard Trieuba63ce62011-09-09 01:45:06 +00003932 << E->getSourceRange());
3933 return Owned(new (Context) AsTypeExpr(E, DstTy, VK, OK, BuiltinLoc,
Richard Trieucfc491d2011-08-02 04:35:43 +00003934 RParenLoc));
Tanya Lattner55808c12011-06-04 00:47:47 +00003935}
3936
John McCall57500772009-12-16 12:17:52 +00003937/// BuildResolvedCallExpr - Build a call to a resolved expression,
3938/// i.e. an expression not of \p OverloadTy. The expression should
John McCall2d74de92009-12-01 22:10:20 +00003939/// unary-convert to an expression of function-pointer or
3940/// block-pointer type.
3941///
3942/// \param NDecl the declaration being called, if available
John McCalldadc5752010-08-24 06:29:42 +00003943ExprResult
John McCall2d74de92009-12-01 22:10:20 +00003944Sema::BuildResolvedCallExpr(Expr *Fn, NamedDecl *NDecl,
3945 SourceLocation LParenLoc,
3946 Expr **Args, unsigned NumArgs,
Peter Collingbourne41f85462011-02-09 21:07:24 +00003947 SourceLocation RParenLoc,
Peter Collingbourne619a8c72011-10-02 23:49:29 +00003948 Expr *Config, bool IsExecConfig) {
John McCall2d74de92009-12-01 22:10:20 +00003949 FunctionDecl *FDecl = dyn_cast_or_null<FunctionDecl>(NDecl);
Eli Friedman34866c72012-08-31 00:14:07 +00003950 unsigned BuiltinID = (FDecl ? FDecl->getBuiltinID() : 0);
John McCall2d74de92009-12-01 22:10:20 +00003951
Chris Lattneraa9c7ae2008-04-08 04:40:51 +00003952 // Promote the function operand.
Eli Friedman34866c72012-08-31 00:14:07 +00003953 // We special-case function promotion here because we only allow promoting
3954 // builtin functions to function pointers in the callee of a call.
3955 ExprResult Result;
3956 if (BuiltinID &&
3957 Fn->getType()->isSpecificBuiltinType(BuiltinType::BuiltinFn)) {
3958 Result = ImpCastExprToType(Fn, Context.getPointerType(FDecl->getType()),
3959 CK_BuiltinFnToFnPtr).take();
3960 } else {
3961 Result = UsualUnaryConversions(Fn);
3962 }
John Wiegley01296292011-04-08 18:41:53 +00003963 if (Result.isInvalid())
3964 return ExprError();
3965 Fn = Result.take();
Chris Lattneraa9c7ae2008-04-08 04:40:51 +00003966
Chris Lattner08464942007-12-28 05:29:59 +00003967 // Make the call expr early, before semantic checks. This guarantees cleanup
3968 // of arguments and function on error.
Peter Collingbourne41f85462011-02-09 21:07:24 +00003969 CallExpr *TheCall;
Eric Christopher13586ab2012-05-30 01:14:28 +00003970 if (Config)
Peter Collingbourne41f85462011-02-09 21:07:24 +00003971 TheCall = new (Context) CUDAKernelCallExpr(Context, Fn,
3972 cast<CallExpr>(Config),
Benjamin Kramerc215e762012-08-24 11:54:20 +00003973 llvm::makeArrayRef(Args,NumArgs),
Peter Collingbourne41f85462011-02-09 21:07:24 +00003974 Context.BoolTy,
3975 VK_RValue,
3976 RParenLoc);
Eric Christopher13586ab2012-05-30 01:14:28 +00003977 else
Peter Collingbourne41f85462011-02-09 21:07:24 +00003978 TheCall = new (Context) CallExpr(Context, Fn,
Benjamin Kramerc215e762012-08-24 11:54:20 +00003979 llvm::makeArrayRef(Args, NumArgs),
Peter Collingbourne41f85462011-02-09 21:07:24 +00003980 Context.BoolTy,
3981 VK_RValue,
3982 RParenLoc);
Sebastian Redlc215cfc2009-01-19 00:08:26 +00003983
John McCallbebede42011-02-26 05:39:39 +00003984 // Bail out early if calling a builtin with custom typechecking.
3985 if (BuiltinID && Context.BuiltinInfo.hasCustomTypechecking(BuiltinID))
3986 return CheckBuiltinFunctionCall(BuiltinID, TheCall);
3987
John McCall31996342011-04-07 08:22:57 +00003988 retry:
Steve Naroff8de9c3a2008-09-05 22:11:13 +00003989 const FunctionType *FuncT;
John McCallbebede42011-02-26 05:39:39 +00003990 if (const PointerType *PT = Fn->getType()->getAs<PointerType>()) {
Steve Naroff8de9c3a2008-09-05 22:11:13 +00003991 // C99 6.5.2.2p1 - "The expression that denotes the called function shall
3992 // have type pointer to function".
John McCall9dd450b2009-09-21 23:43:11 +00003993 FuncT = PT->getPointeeType()->getAs<FunctionType>();
John McCallbebede42011-02-26 05:39:39 +00003994 if (FuncT == 0)
3995 return ExprError(Diag(LParenLoc, diag::err_typecheck_call_not_function)
3996 << Fn->getType() << Fn->getSourceRange());
3997 } else if (const BlockPointerType *BPT =
3998 Fn->getType()->getAs<BlockPointerType>()) {
3999 FuncT = BPT->getPointeeType()->castAs<FunctionType>();
4000 } else {
John McCall31996342011-04-07 08:22:57 +00004001 // Handle calls to expressions of unknown-any type.
4002 if (Fn->getType() == Context.UnknownAnyTy) {
John McCall2979fe02011-04-12 00:42:48 +00004003 ExprResult rewrite = rebuildUnknownAnyFunction(*this, Fn);
John McCall31996342011-04-07 08:22:57 +00004004 if (rewrite.isInvalid()) return ExprError();
4005 Fn = rewrite.take();
John McCall39439732011-04-09 22:50:59 +00004006 TheCall->setCallee(Fn);
John McCall31996342011-04-07 08:22:57 +00004007 goto retry;
4008 }
4009
Sebastian Redlc215cfc2009-01-19 00:08:26 +00004010 return ExprError(Diag(LParenLoc, diag::err_typecheck_call_not_function)
4011 << Fn->getType() << Fn->getSourceRange());
John McCallbebede42011-02-26 05:39:39 +00004012 }
Sebastian Redlc215cfc2009-01-19 00:08:26 +00004013
David Blaikiebbafb8a2012-03-11 07:00:24 +00004014 if (getLangOpts().CUDA) {
Peter Collingbourne4b66c472011-02-23 01:53:29 +00004015 if (Config) {
4016 // CUDA: Kernel calls must be to global functions
4017 if (FDecl && !FDecl->hasAttr<CUDAGlobalAttr>())
4018 return ExprError(Diag(LParenLoc,diag::err_kern_call_not_global_function)
4019 << FDecl->getName() << Fn->getSourceRange());
4020
4021 // CUDA: Kernel function must have 'void' return type
4022 if (!FuncT->getResultType()->isVoidType())
4023 return ExprError(Diag(LParenLoc, diag::err_kern_type_not_void_return)
4024 << Fn->getType() << Fn->getSourceRange());
Peter Collingbourne34a20b02011-10-02 23:49:15 +00004025 } else {
4026 // CUDA: Calls to global functions must be configured
4027 if (FDecl && FDecl->hasAttr<CUDAGlobalAttr>())
4028 return ExprError(Diag(LParenLoc, diag::err_global_call_not_config)
4029 << FDecl->getName() << Fn->getSourceRange());
Peter Collingbourne4b66c472011-02-23 01:53:29 +00004030 }
4031 }
4032
Eli Friedman3164fb12009-03-22 22:00:50 +00004033 // Check for a valid return type
Kovarththanan Rajaratnamba2c6522010-03-13 10:17:05 +00004034 if (CheckCallReturnType(FuncT->getResultType(),
Daniel Dunbar62ee6412012-03-09 18:35:03 +00004035 Fn->getLocStart(), TheCall,
Anders Carlsson7f84ed92009-10-09 23:51:55 +00004036 FDecl))
Eli Friedman3164fb12009-03-22 22:00:50 +00004037 return ExprError();
4038
Chris Lattner08464942007-12-28 05:29:59 +00004039 // We know the result type of the call, set it.
Douglas Gregor603d81b2010-07-13 08:18:22 +00004040 TheCall->setType(FuncT->getCallResultType(Context));
John McCall7decc9e2010-11-18 06:31:45 +00004041 TheCall->setValueKind(Expr::getValueKindForType(FuncT->getResultType()));
Sebastian Redlc215cfc2009-01-19 00:08:26 +00004042
Richard Smith55ce3522012-06-25 20:30:08 +00004043 const FunctionProtoType *Proto = dyn_cast<FunctionProtoType>(FuncT);
4044 if (Proto) {
John McCallb268a282010-08-23 23:25:46 +00004045 if (ConvertArgumentsForCall(TheCall, Fn, FDecl, Proto, Args, NumArgs,
Peter Collingbourne619a8c72011-10-02 23:49:29 +00004046 RParenLoc, IsExecConfig))
Sebastian Redlc215cfc2009-01-19 00:08:26 +00004047 return ExprError();
Chris Lattner08464942007-12-28 05:29:59 +00004048 } else {
Douglas Gregordeaad8c2009-02-26 23:50:07 +00004049 assert(isa<FunctionNoProtoType>(FuncT) && "Unknown FunctionType!");
Sebastian Redlc215cfc2009-01-19 00:08:26 +00004050
Douglas Gregord8e97de2009-04-02 15:37:10 +00004051 if (FDecl) {
4052 // Check if we have too few/too many template arguments, based
4053 // on our knowledge of the function definition.
4054 const FunctionDecl *Def = 0;
Argyrios Kyrtzidis36ea3222010-07-07 11:31:19 +00004055 if (FDecl->hasBody(Def) && NumArgs != Def->param_size()) {
Richard Smith55ce3522012-06-25 20:30:08 +00004056 Proto = Def->getType()->getAs<FunctionProtoType>();
Douglas Gregor8e09a722010-10-25 20:39:23 +00004057 if (!Proto || !(Proto->isVariadic() && NumArgs >= Def->param_size()))
Eli Friedmanfcbf7d22009-06-01 09:24:59 +00004058 Diag(RParenLoc, diag::warn_call_wrong_number_of_arguments)
4059 << (NumArgs > Def->param_size()) << FDecl << Fn->getSourceRange();
Eli Friedmanfcbf7d22009-06-01 09:24:59 +00004060 }
Douglas Gregor8e09a722010-10-25 20:39:23 +00004061
4062 // If the function we're calling isn't a function prototype, but we have
4063 // a function prototype from a prior declaratiom, use that prototype.
4064 if (!FDecl->hasPrototype())
4065 Proto = FDecl->getType()->getAs<FunctionProtoType>();
Douglas Gregord8e97de2009-04-02 15:37:10 +00004066 }
4067
Steve Naroff0b661582007-08-28 23:30:39 +00004068 // Promote the arguments (C99 6.5.2.2p6).
Chris Lattner08464942007-12-28 05:29:59 +00004069 for (unsigned i = 0; i != NumArgs; i++) {
4070 Expr *Arg = Args[i];
Douglas Gregor8e09a722010-10-25 20:39:23 +00004071
4072 if (Proto && i < Proto->getNumArgs()) {
Douglas Gregor8e09a722010-10-25 20:39:23 +00004073 InitializedEntity Entity
4074 = InitializedEntity::InitializeParameter(Context,
John McCall31168b02011-06-15 23:02:42 +00004075 Proto->getArgType(i),
4076 Proto->isArgConsumed(i));
Douglas Gregor8e09a722010-10-25 20:39:23 +00004077 ExprResult ArgE = PerformCopyInitialization(Entity,
4078 SourceLocation(),
4079 Owned(Arg));
4080 if (ArgE.isInvalid())
4081 return true;
4082
4083 Arg = ArgE.takeAs<Expr>();
4084
4085 } else {
John Wiegley01296292011-04-08 18:41:53 +00004086 ExprResult ArgE = DefaultArgumentPromotion(Arg);
4087
4088 if (ArgE.isInvalid())
4089 return true;
4090
4091 Arg = ArgE.takeAs<Expr>();
Douglas Gregor8e09a722010-10-25 20:39:23 +00004092 }
4093
Daniel Dunbar62ee6412012-03-09 18:35:03 +00004094 if (RequireCompleteType(Arg->getLocStart(),
Douglas Gregor83025412010-10-26 05:45:40 +00004095 Arg->getType(),
Douglas Gregor7bfb2d02012-05-04 16:32:21 +00004096 diag::err_call_incomplete_argument, Arg))
Douglas Gregor83025412010-10-26 05:45:40 +00004097 return ExprError();
4098
Chris Lattner08464942007-12-28 05:29:59 +00004099 TheCall->setArg(i, Arg);
Steve Naroff0b661582007-08-28 23:30:39 +00004100 }
Steve Naroffae4143e2007-04-26 20:39:23 +00004101 }
Chris Lattner08464942007-12-28 05:29:59 +00004102
Douglas Gregor97fd6e22008-12-22 05:46:06 +00004103 if (CXXMethodDecl *Method = dyn_cast_or_null<CXXMethodDecl>(FDecl))
4104 if (!Method->isStatic())
Sebastian Redlc215cfc2009-01-19 00:08:26 +00004105 return ExprError(Diag(LParenLoc, diag::err_member_call_without_object)
4106 << Fn->getSourceRange());
Douglas Gregor97fd6e22008-12-22 05:46:06 +00004107
Fariborz Jahanian0aa5c452009-05-15 20:33:25 +00004108 // Check for sentinels
4109 if (NDecl)
4110 DiagnoseSentinelCalls(NDecl, LParenLoc, Args, NumArgs);
Mike Stump11289f42009-09-09 15:08:12 +00004111
Chris Lattnerb87b1b32007-08-10 20:18:51 +00004112 // Do special checking on direct calls to functions.
Anders Carlssonbc4c1072009-08-16 01:56:34 +00004113 if (FDecl) {
Richard Smith55ce3522012-06-25 20:30:08 +00004114 if (CheckFunctionCall(FDecl, TheCall, Proto))
Anders Carlssonbc4c1072009-08-16 01:56:34 +00004115 return ExprError();
Mike Stump11289f42009-09-09 15:08:12 +00004116
John McCallbebede42011-02-26 05:39:39 +00004117 if (BuiltinID)
Fariborz Jahaniane8473c22010-11-30 17:35:24 +00004118 return CheckBuiltinFunctionCall(BuiltinID, TheCall);
Anders Carlssonbc4c1072009-08-16 01:56:34 +00004119 } else if (NDecl) {
Richard Smith55ce3522012-06-25 20:30:08 +00004120 if (CheckBlockCall(NDecl, TheCall, Proto))
Anders Carlssonbc4c1072009-08-16 01:56:34 +00004121 return ExprError();
4122 }
Chris Lattnerb87b1b32007-08-10 20:18:51 +00004123
John McCallb268a282010-08-23 23:25:46 +00004124 return MaybeBindToTemporary(TheCall);
Chris Lattnere168f762006-11-10 05:29:30 +00004125}
4126
John McCalldadc5752010-08-24 06:29:42 +00004127ExprResult
John McCallba7bf592010-08-24 05:47:05 +00004128Sema::ActOnCompoundLiteral(SourceLocation LParenLoc, ParsedType Ty,
John McCallb268a282010-08-23 23:25:46 +00004129 SourceLocation RParenLoc, Expr *InitExpr) {
Steve Naroff83895f72007-09-16 03:34:24 +00004130 assert((Ty != 0) && "ActOnCompoundLiteral(): missing type");
Steve Naroff57eb2c52007-07-19 21:32:11 +00004131 // FIXME: put back this assert when initializers are worked out.
Steve Naroff83895f72007-09-16 03:34:24 +00004132 //assert((InitExpr != 0) && "ActOnCompoundLiteral(): missing expression");
John McCalle15bbff2010-01-18 19:35:47 +00004133
4134 TypeSourceInfo *TInfo;
4135 QualType literalType = GetTypeFromParser(Ty, &TInfo);
4136 if (!TInfo)
4137 TInfo = Context.getTrivialTypeSourceInfo(literalType);
4138
John McCallb268a282010-08-23 23:25:46 +00004139 return BuildCompoundLiteralExpr(LParenLoc, TInfo, RParenLoc, InitExpr);
John McCalle15bbff2010-01-18 19:35:47 +00004140}
4141
John McCalldadc5752010-08-24 06:29:42 +00004142ExprResult
John McCalle15bbff2010-01-18 19:35:47 +00004143Sema::BuildCompoundLiteralExpr(SourceLocation LParenLoc, TypeSourceInfo *TInfo,
Richard Trieuba63ce62011-09-09 01:45:06 +00004144 SourceLocation RParenLoc, Expr *LiteralExpr) {
John McCalle15bbff2010-01-18 19:35:47 +00004145 QualType literalType = TInfo->getType();
Anders Carlsson2c1ec6d2007-12-05 07:24:19 +00004146
Eli Friedman37a186d2008-05-20 05:22:08 +00004147 if (literalType->isArrayType()) {
Argyrios Kyrtzidis85663562010-11-08 19:14:19 +00004148 if (RequireCompleteType(LParenLoc, Context.getBaseElementType(literalType),
Douglas Gregor7bfb2d02012-05-04 16:32:21 +00004149 diag::err_illegal_decl_array_incomplete_type,
4150 SourceRange(LParenLoc,
4151 LiteralExpr->getSourceRange().getEnd())))
Argyrios Kyrtzidis85663562010-11-08 19:14:19 +00004152 return ExprError();
Chris Lattner7adf0762008-08-04 07:31:14 +00004153 if (literalType->isVariableArrayType())
Sebastian Redlb5d49352009-01-19 22:31:54 +00004154 return ExprError(Diag(LParenLoc, diag::err_variable_object_no_init)
Richard Trieuba63ce62011-09-09 01:45:06 +00004155 << SourceRange(LParenLoc, LiteralExpr->getSourceRange().getEnd()));
Douglas Gregor1c37d9e2009-05-21 23:48:18 +00004156 } else if (!literalType->isDependentType() &&
4157 RequireCompleteType(LParenLoc, literalType,
Douglas Gregor7bfb2d02012-05-04 16:32:21 +00004158 diag::err_typecheck_decl_incomplete_type,
4159 SourceRange(LParenLoc, LiteralExpr->getSourceRange().getEnd())))
Sebastian Redlb5d49352009-01-19 22:31:54 +00004160 return ExprError();
Eli Friedman37a186d2008-05-20 05:22:08 +00004161
Douglas Gregor85dabae2009-12-16 01:38:02 +00004162 InitializedEntity Entity
Douglas Gregor1b303932009-12-22 15:35:07 +00004163 = InitializedEntity::InitializeTemporary(literalType);
Douglas Gregor85dabae2009-12-16 01:38:02 +00004164 InitializationKind Kind
John McCall31168b02011-06-15 23:02:42 +00004165 = InitializationKind::CreateCStyleCast(LParenLoc,
Sebastian Redl0501c632012-02-12 16:37:36 +00004166 SourceRange(LParenLoc, RParenLoc),
4167 /*InitList=*/true);
Richard Trieuba63ce62011-09-09 01:45:06 +00004168 InitializationSequence InitSeq(*this, Entity, Kind, &LiteralExpr, 1);
Benjamin Kramercc4c49d2012-08-23 23:38:35 +00004169 ExprResult Result = InitSeq.Perform(*this, Entity, Kind, LiteralExpr,
4170 &literalType);
Eli Friedmana553d4a2009-12-22 02:35:53 +00004171 if (Result.isInvalid())
Sebastian Redlb5d49352009-01-19 22:31:54 +00004172 return ExprError();
Richard Trieuba63ce62011-09-09 01:45:06 +00004173 LiteralExpr = Result.get();
Steve Naroffd32419d2008-01-14 18:19:28 +00004174
Chris Lattner79413952008-12-04 23:50:19 +00004175 bool isFileScope = getCurFunctionOrMethodDecl() == 0;
Steve Naroffd32419d2008-01-14 18:19:28 +00004176 if (isFileScope) { // 6.5.2.5p3
Richard Trieuba63ce62011-09-09 01:45:06 +00004177 if (CheckForConstantInitializer(LiteralExpr, literalType))
Sebastian Redlb5d49352009-01-19 22:31:54 +00004178 return ExprError();
Steve Naroff98f72032008-01-10 22:15:12 +00004179 }
Eli Friedmana553d4a2009-12-22 02:35:53 +00004180
John McCall7decc9e2010-11-18 06:31:45 +00004181 // In C, compound literals are l-values for some reason.
David Blaikiebbafb8a2012-03-11 07:00:24 +00004182 ExprValueKind VK = getLangOpts().CPlusPlus ? VK_RValue : VK_LValue;
John McCall7decc9e2010-11-18 06:31:45 +00004183
Douglas Gregor9b71f0c2011-06-17 04:59:12 +00004184 return MaybeBindToTemporary(
4185 new (Context) CompoundLiteralExpr(LParenLoc, TInfo, literalType,
Richard Trieuba63ce62011-09-09 01:45:06 +00004186 VK, LiteralExpr, isFileScope));
Steve Narofffbd09832007-07-19 01:06:55 +00004187}
4188
John McCalldadc5752010-08-24 06:29:42 +00004189ExprResult
Richard Trieuba63ce62011-09-09 01:45:06 +00004190Sema::ActOnInitList(SourceLocation LBraceLoc, MultiExprArg InitArgList,
Sebastian Redlb5d49352009-01-19 22:31:54 +00004191 SourceLocation RBraceLoc) {
John McCall526ab472011-10-25 17:37:35 +00004192 // Immediately handle non-overload placeholders. Overloads can be
4193 // resolved contextually, but everything else here can't.
Benjamin Kramerc215e762012-08-24 11:54:20 +00004194 for (unsigned I = 0, E = InitArgList.size(); I != E; ++I) {
4195 if (InitArgList[I]->getType()->isNonOverloadPlaceholderType()) {
4196 ExprResult result = CheckPlaceholderExpr(InitArgList[I]);
John McCall526ab472011-10-25 17:37:35 +00004197
4198 // Ignore failures; dropping the entire initializer list because
4199 // of one failure would be terrible for indexing/etc.
4200 if (result.isInvalid()) continue;
4201
Benjamin Kramerc215e762012-08-24 11:54:20 +00004202 InitArgList[I] = result.take();
John McCall526ab472011-10-25 17:37:35 +00004203 }
4204 }
4205
Steve Naroff30d242c2007-09-15 18:49:24 +00004206 // Semantic analysis for initializers is done by ActOnDeclarator() and
Mike Stump4e1f26a2009-02-19 03:04:26 +00004207 // CheckInitializer() - it requires knowledge of the object being intialized.
Sebastian Redlb5d49352009-01-19 22:31:54 +00004208
Benjamin Kramerc215e762012-08-24 11:54:20 +00004209 InitListExpr *E = new (Context) InitListExpr(Context, LBraceLoc, InitArgList,
4210 RBraceLoc);
Chris Lattner24d5bfe2008-04-02 04:24:33 +00004211 E->setType(Context.VoidTy); // FIXME: just a place holder for now.
Sebastian Redlb5d49352009-01-19 22:31:54 +00004212 return Owned(E);
Steve Narofffbd09832007-07-19 01:06:55 +00004213}
4214
John McCallcd78e802011-09-10 01:16:55 +00004215/// Do an explicit extend of the given block pointer if we're in ARC.
4216static void maybeExtendBlockObject(Sema &S, ExprResult &E) {
4217 assert(E.get()->getType()->isBlockPointerType());
4218 assert(E.get()->isRValue());
4219
4220 // Only do this in an r-value context.
David Blaikiebbafb8a2012-03-11 07:00:24 +00004221 if (!S.getLangOpts().ObjCAutoRefCount) return;
John McCallcd78e802011-09-10 01:16:55 +00004222
4223 E = ImplicitCastExpr::Create(S.Context, E.get()->getType(),
John McCall2d637d22011-09-10 06:18:15 +00004224 CK_ARCExtendBlockObject, E.get(),
John McCallcd78e802011-09-10 01:16:55 +00004225 /*base path*/ 0, VK_RValue);
4226 S.ExprNeedsCleanups = true;
4227}
4228
4229/// Prepare a conversion of the given expression to an ObjC object
4230/// pointer type.
4231CastKind Sema::PrepareCastToObjCObjectPointer(ExprResult &E) {
4232 QualType type = E.get()->getType();
4233 if (type->isObjCObjectPointerType()) {
4234 return CK_BitCast;
4235 } else if (type->isBlockPointerType()) {
4236 maybeExtendBlockObject(*this, E);
4237 return CK_BlockPointerToObjCPointerCast;
4238 } else {
4239 assert(type->isPointerType());
4240 return CK_CPointerToObjCPointerCast;
4241 }
4242}
4243
John McCalld7646252010-11-14 08:17:51 +00004244/// Prepares for a scalar cast, performing all the necessary stages
4245/// except the final cast and returning the kind required.
John McCall9776e432011-10-06 23:25:11 +00004246CastKind Sema::PrepareScalarCast(ExprResult &Src, QualType DestTy) {
John McCalld7646252010-11-14 08:17:51 +00004247 // Both Src and Dest are scalar types, i.e. arithmetic or pointer.
4248 // Also, callers should have filtered out the invalid cases with
4249 // pointers. Everything else should be possible.
4250
John Wiegley01296292011-04-08 18:41:53 +00004251 QualType SrcTy = Src.get()->getType();
John McCall9776e432011-10-06 23:25:11 +00004252 if (Context.hasSameUnqualifiedType(SrcTy, DestTy))
John McCalle3027922010-08-25 11:45:40 +00004253 return CK_NoOp;
Anders Carlsson094c4592009-10-18 18:12:03 +00004254
John McCall9320b872011-09-09 05:25:32 +00004255 switch (Type::ScalarTypeKind SrcKind = SrcTy->getScalarTypeKind()) {
John McCall8cb679e2010-11-15 09:13:47 +00004256 case Type::STK_MemberPointer:
4257 llvm_unreachable("member pointer type in C");
Abramo Bagnaraba854972011-01-04 09:50:03 +00004258
John McCall9320b872011-09-09 05:25:32 +00004259 case Type::STK_CPointer:
4260 case Type::STK_BlockPointer:
4261 case Type::STK_ObjCObjectPointer:
John McCall8cb679e2010-11-15 09:13:47 +00004262 switch (DestTy->getScalarTypeKind()) {
John McCall9320b872011-09-09 05:25:32 +00004263 case Type::STK_CPointer:
4264 return CK_BitCast;
4265 case Type::STK_BlockPointer:
4266 return (SrcKind == Type::STK_BlockPointer
4267 ? CK_BitCast : CK_AnyPointerToBlockPointerCast);
4268 case Type::STK_ObjCObjectPointer:
4269 if (SrcKind == Type::STK_ObjCObjectPointer)
4270 return CK_BitCast;
David Blaikie8a40f702012-01-17 06:56:22 +00004271 if (SrcKind == Type::STK_CPointer)
John McCall9320b872011-09-09 05:25:32 +00004272 return CK_CPointerToObjCPointerCast;
David Blaikie8a40f702012-01-17 06:56:22 +00004273 maybeExtendBlockObject(*this, Src);
4274 return CK_BlockPointerToObjCPointerCast;
John McCall8cb679e2010-11-15 09:13:47 +00004275 case Type::STK_Bool:
4276 return CK_PointerToBoolean;
4277 case Type::STK_Integral:
4278 return CK_PointerToIntegral;
4279 case Type::STK_Floating:
4280 case Type::STK_FloatingComplex:
4281 case Type::STK_IntegralComplex:
4282 case Type::STK_MemberPointer:
4283 llvm_unreachable("illegal cast from pointer");
4284 }
David Blaikie8a40f702012-01-17 06:56:22 +00004285 llvm_unreachable("Should have returned before this");
Kovarththanan Rajaratnamba2c6522010-03-13 10:17:05 +00004286
John McCall8cb679e2010-11-15 09:13:47 +00004287 case Type::STK_Bool: // casting from bool is like casting from an integer
4288 case Type::STK_Integral:
4289 switch (DestTy->getScalarTypeKind()) {
John McCall9320b872011-09-09 05:25:32 +00004290 case Type::STK_CPointer:
4291 case Type::STK_ObjCObjectPointer:
4292 case Type::STK_BlockPointer:
John McCall9776e432011-10-06 23:25:11 +00004293 if (Src.get()->isNullPointerConstant(Context,
Richard Trieucfc491d2011-08-02 04:35:43 +00004294 Expr::NPC_ValueDependentIsNull))
John McCalle84af4e2010-11-13 01:35:44 +00004295 return CK_NullToPointer;
John McCalle3027922010-08-25 11:45:40 +00004296 return CK_IntegralToPointer;
John McCall8cb679e2010-11-15 09:13:47 +00004297 case Type::STK_Bool:
4298 return CK_IntegralToBoolean;
4299 case Type::STK_Integral:
John McCalld7646252010-11-14 08:17:51 +00004300 return CK_IntegralCast;
John McCall8cb679e2010-11-15 09:13:47 +00004301 case Type::STK_Floating:
John McCalle3027922010-08-25 11:45:40 +00004302 return CK_IntegralToFloating;
John McCall8cb679e2010-11-15 09:13:47 +00004303 case Type::STK_IntegralComplex:
John McCall9776e432011-10-06 23:25:11 +00004304 Src = ImpCastExprToType(Src.take(),
4305 DestTy->castAs<ComplexType>()->getElementType(),
4306 CK_IntegralCast);
John McCalld7646252010-11-14 08:17:51 +00004307 return CK_IntegralRealToComplex;
John McCall8cb679e2010-11-15 09:13:47 +00004308 case Type::STK_FloatingComplex:
John McCall9776e432011-10-06 23:25:11 +00004309 Src = ImpCastExprToType(Src.take(),
4310 DestTy->castAs<ComplexType>()->getElementType(),
4311 CK_IntegralToFloating);
John McCalld7646252010-11-14 08:17:51 +00004312 return CK_FloatingRealToComplex;
John McCall8cb679e2010-11-15 09:13:47 +00004313 case Type::STK_MemberPointer:
4314 llvm_unreachable("member pointer type in C");
John McCalld7646252010-11-14 08:17:51 +00004315 }
David Blaikie8a40f702012-01-17 06:56:22 +00004316 llvm_unreachable("Should have returned before this");
Kovarththanan Rajaratnamba2c6522010-03-13 10:17:05 +00004317
John McCall8cb679e2010-11-15 09:13:47 +00004318 case Type::STK_Floating:
4319 switch (DestTy->getScalarTypeKind()) {
4320 case Type::STK_Floating:
John McCalle3027922010-08-25 11:45:40 +00004321 return CK_FloatingCast;
John McCall8cb679e2010-11-15 09:13:47 +00004322 case Type::STK_Bool:
4323 return CK_FloatingToBoolean;
4324 case Type::STK_Integral:
John McCalle3027922010-08-25 11:45:40 +00004325 return CK_FloatingToIntegral;
John McCall8cb679e2010-11-15 09:13:47 +00004326 case Type::STK_FloatingComplex:
John McCall9776e432011-10-06 23:25:11 +00004327 Src = ImpCastExprToType(Src.take(),
4328 DestTy->castAs<ComplexType>()->getElementType(),
4329 CK_FloatingCast);
John McCalld7646252010-11-14 08:17:51 +00004330 return CK_FloatingRealToComplex;
John McCall8cb679e2010-11-15 09:13:47 +00004331 case Type::STK_IntegralComplex:
John McCall9776e432011-10-06 23:25:11 +00004332 Src = ImpCastExprToType(Src.take(),
4333 DestTy->castAs<ComplexType>()->getElementType(),
4334 CK_FloatingToIntegral);
John McCalld7646252010-11-14 08:17:51 +00004335 return CK_IntegralRealToComplex;
John McCall9320b872011-09-09 05:25:32 +00004336 case Type::STK_CPointer:
4337 case Type::STK_ObjCObjectPointer:
4338 case Type::STK_BlockPointer:
John McCall8cb679e2010-11-15 09:13:47 +00004339 llvm_unreachable("valid float->pointer cast?");
4340 case Type::STK_MemberPointer:
4341 llvm_unreachable("member pointer type in C");
John McCalld7646252010-11-14 08:17:51 +00004342 }
David Blaikie8a40f702012-01-17 06:56:22 +00004343 llvm_unreachable("Should have returned before this");
John McCalld7646252010-11-14 08:17:51 +00004344
John McCall8cb679e2010-11-15 09:13:47 +00004345 case Type::STK_FloatingComplex:
4346 switch (DestTy->getScalarTypeKind()) {
4347 case Type::STK_FloatingComplex:
John McCalld7646252010-11-14 08:17:51 +00004348 return CK_FloatingComplexCast;
John McCall8cb679e2010-11-15 09:13:47 +00004349 case Type::STK_IntegralComplex:
John McCalld7646252010-11-14 08:17:51 +00004350 return CK_FloatingComplexToIntegralComplex;
John McCallfcef3cf2010-12-14 17:51:41 +00004351 case Type::STK_Floating: {
John McCall9776e432011-10-06 23:25:11 +00004352 QualType ET = SrcTy->castAs<ComplexType>()->getElementType();
4353 if (Context.hasSameType(ET, DestTy))
John McCallfcef3cf2010-12-14 17:51:41 +00004354 return CK_FloatingComplexToReal;
John McCall9776e432011-10-06 23:25:11 +00004355 Src = ImpCastExprToType(Src.take(), ET, CK_FloatingComplexToReal);
John McCallfcef3cf2010-12-14 17:51:41 +00004356 return CK_FloatingCast;
4357 }
John McCall8cb679e2010-11-15 09:13:47 +00004358 case Type::STK_Bool:
John McCalld7646252010-11-14 08:17:51 +00004359 return CK_FloatingComplexToBoolean;
John McCall8cb679e2010-11-15 09:13:47 +00004360 case Type::STK_Integral:
John McCall9776e432011-10-06 23:25:11 +00004361 Src = ImpCastExprToType(Src.take(),
4362 SrcTy->castAs<ComplexType>()->getElementType(),
4363 CK_FloatingComplexToReal);
John McCalld7646252010-11-14 08:17:51 +00004364 return CK_FloatingToIntegral;
John McCall9320b872011-09-09 05:25:32 +00004365 case Type::STK_CPointer:
4366 case Type::STK_ObjCObjectPointer:
4367 case Type::STK_BlockPointer:
John McCall8cb679e2010-11-15 09:13:47 +00004368 llvm_unreachable("valid complex float->pointer cast?");
4369 case Type::STK_MemberPointer:
4370 llvm_unreachable("member pointer type in C");
John McCalld7646252010-11-14 08:17:51 +00004371 }
David Blaikie8a40f702012-01-17 06:56:22 +00004372 llvm_unreachable("Should have returned before this");
John McCalld7646252010-11-14 08:17:51 +00004373
John McCall8cb679e2010-11-15 09:13:47 +00004374 case Type::STK_IntegralComplex:
4375 switch (DestTy->getScalarTypeKind()) {
4376 case Type::STK_FloatingComplex:
John McCalld7646252010-11-14 08:17:51 +00004377 return CK_IntegralComplexToFloatingComplex;
John McCall8cb679e2010-11-15 09:13:47 +00004378 case Type::STK_IntegralComplex:
John McCalld7646252010-11-14 08:17:51 +00004379 return CK_IntegralComplexCast;
John McCallfcef3cf2010-12-14 17:51:41 +00004380 case Type::STK_Integral: {
John McCall9776e432011-10-06 23:25:11 +00004381 QualType ET = SrcTy->castAs<ComplexType>()->getElementType();
4382 if (Context.hasSameType(ET, DestTy))
John McCallfcef3cf2010-12-14 17:51:41 +00004383 return CK_IntegralComplexToReal;
John McCall9776e432011-10-06 23:25:11 +00004384 Src = ImpCastExprToType(Src.take(), ET, CK_IntegralComplexToReal);
John McCallfcef3cf2010-12-14 17:51:41 +00004385 return CK_IntegralCast;
4386 }
John McCall8cb679e2010-11-15 09:13:47 +00004387 case Type::STK_Bool:
John McCalld7646252010-11-14 08:17:51 +00004388 return CK_IntegralComplexToBoolean;
John McCall8cb679e2010-11-15 09:13:47 +00004389 case Type::STK_Floating:
John McCall9776e432011-10-06 23:25:11 +00004390 Src = ImpCastExprToType(Src.take(),
4391 SrcTy->castAs<ComplexType>()->getElementType(),
4392 CK_IntegralComplexToReal);
John McCalld7646252010-11-14 08:17:51 +00004393 return CK_IntegralToFloating;
John McCall9320b872011-09-09 05:25:32 +00004394 case Type::STK_CPointer:
4395 case Type::STK_ObjCObjectPointer:
4396 case Type::STK_BlockPointer:
John McCall8cb679e2010-11-15 09:13:47 +00004397 llvm_unreachable("valid complex int->pointer cast?");
4398 case Type::STK_MemberPointer:
4399 llvm_unreachable("member pointer type in C");
John McCalld7646252010-11-14 08:17:51 +00004400 }
David Blaikie8a40f702012-01-17 06:56:22 +00004401 llvm_unreachable("Should have returned before this");
Anders Carlsson094c4592009-10-18 18:12:03 +00004402 }
Kovarththanan Rajaratnamba2c6522010-03-13 10:17:05 +00004403
John McCalld7646252010-11-14 08:17:51 +00004404 llvm_unreachable("Unhandled scalar cast");
Anders Carlsson094c4592009-10-18 18:12:03 +00004405}
4406
Anders Carlsson525b76b2009-10-16 02:48:28 +00004407bool Sema::CheckVectorCast(SourceRange R, QualType VectorTy, QualType Ty,
John McCalle3027922010-08-25 11:45:40 +00004408 CastKind &Kind) {
Anders Carlssonde71adf2007-11-27 05:51:55 +00004409 assert(VectorTy->isVectorType() && "Not a vector type!");
Mike Stump4e1f26a2009-02-19 03:04:26 +00004410
Anders Carlssonde71adf2007-11-27 05:51:55 +00004411 if (Ty->isVectorType() || Ty->isIntegerType()) {
Chris Lattner37e05872008-03-05 18:54:05 +00004412 if (Context.getTypeSize(VectorTy) != Context.getTypeSize(Ty))
Anders Carlssonde71adf2007-11-27 05:51:55 +00004413 return Diag(R.getBegin(),
Mike Stump4e1f26a2009-02-19 03:04:26 +00004414 Ty->isVectorType() ?
Anders Carlssonde71adf2007-11-27 05:51:55 +00004415 diag::err_invalid_conversion_between_vectors :
Chris Lattner3b054132008-11-19 05:08:23 +00004416 diag::err_invalid_conversion_between_vector_and_integer)
Chris Lattner1e5665e2008-11-24 06:25:27 +00004417 << VectorTy << Ty << R;
Anders Carlssonde71adf2007-11-27 05:51:55 +00004418 } else
4419 return Diag(R.getBegin(),
Chris Lattner3b054132008-11-19 05:08:23 +00004420 diag::err_invalid_conversion_between_vector_and_scalar)
Chris Lattner1e5665e2008-11-24 06:25:27 +00004421 << VectorTy << Ty << R;
Mike Stump4e1f26a2009-02-19 03:04:26 +00004422
John McCalle3027922010-08-25 11:45:40 +00004423 Kind = CK_BitCast;
Anders Carlssonde71adf2007-11-27 05:51:55 +00004424 return false;
4425}
4426
John Wiegley01296292011-04-08 18:41:53 +00004427ExprResult Sema::CheckExtVectorCast(SourceRange R, QualType DestTy,
4428 Expr *CastExpr, CastKind &Kind) {
Nate Begemanc69b7402009-06-26 00:50:28 +00004429 assert(DestTy->isExtVectorType() && "Not an extended vector type!");
Kovarththanan Rajaratnamba2c6522010-03-13 10:17:05 +00004430
Anders Carlsson43d70f82009-10-16 05:23:41 +00004431 QualType SrcTy = CastExpr->getType();
Kovarththanan Rajaratnamba2c6522010-03-13 10:17:05 +00004432
Nate Begemanc8961a42009-06-27 22:05:55 +00004433 // If SrcTy is a VectorType, the total size must match to explicitly cast to
4434 // an ExtVectorType.
Tobias Grosser766bcc22011-09-22 13:03:14 +00004435 // In OpenCL, casts between vectors of different types are not allowed.
4436 // (See OpenCL 6.2).
Nate Begemanc69b7402009-06-26 00:50:28 +00004437 if (SrcTy->isVectorType()) {
Tobias Grosser766bcc22011-09-22 13:03:14 +00004438 if (Context.getTypeSize(DestTy) != Context.getTypeSize(SrcTy)
David Blaikiebbafb8a2012-03-11 07:00:24 +00004439 || (getLangOpts().OpenCL &&
Tobias Grosser766bcc22011-09-22 13:03:14 +00004440 (DestTy.getCanonicalType() != SrcTy.getCanonicalType()))) {
John Wiegley01296292011-04-08 18:41:53 +00004441 Diag(R.getBegin(),diag::err_invalid_conversion_between_ext_vectors)
Nate Begemanc69b7402009-06-26 00:50:28 +00004442 << DestTy << SrcTy << R;
John Wiegley01296292011-04-08 18:41:53 +00004443 return ExprError();
4444 }
John McCalle3027922010-08-25 11:45:40 +00004445 Kind = CK_BitCast;
John Wiegley01296292011-04-08 18:41:53 +00004446 return Owned(CastExpr);
Nate Begemanc69b7402009-06-26 00:50:28 +00004447 }
4448
Nate Begemanbd956c42009-06-28 02:36:38 +00004449 // All non-pointer scalars can be cast to ExtVector type. The appropriate
Nate Begemanc69b7402009-06-26 00:50:28 +00004450 // conversion will take place first from scalar to elt type, and then
4451 // splat from elt type to vector.
Nate Begemanbd956c42009-06-28 02:36:38 +00004452 if (SrcTy->isPointerType())
4453 return Diag(R.getBegin(),
4454 diag::err_invalid_conversion_between_vector_and_scalar)
4455 << DestTy << SrcTy << R;
Eli Friedman06ed2a52009-10-20 08:27:19 +00004456
4457 QualType DestElemTy = DestTy->getAs<ExtVectorType>()->getElementType();
John Wiegley01296292011-04-08 18:41:53 +00004458 ExprResult CastExprRes = Owned(CastExpr);
John McCall9776e432011-10-06 23:25:11 +00004459 CastKind CK = PrepareScalarCast(CastExprRes, DestElemTy);
John Wiegley01296292011-04-08 18:41:53 +00004460 if (CastExprRes.isInvalid())
4461 return ExprError();
4462 CastExpr = ImpCastExprToType(CastExprRes.take(), DestElemTy, CK).take();
Kovarththanan Rajaratnamba2c6522010-03-13 10:17:05 +00004463
John McCalle3027922010-08-25 11:45:40 +00004464 Kind = CK_VectorSplat;
John Wiegley01296292011-04-08 18:41:53 +00004465 return Owned(CastExpr);
Nate Begemanc69b7402009-06-26 00:50:28 +00004466}
4467
John McCalldadc5752010-08-24 06:29:42 +00004468ExprResult
Argyrios Kyrtzidis7192a3b2011-07-01 22:22:59 +00004469Sema::ActOnCastExpr(Scope *S, SourceLocation LParenLoc,
4470 Declarator &D, ParsedType &Ty,
Richard Trieuba63ce62011-09-09 01:45:06 +00004471 SourceLocation RParenLoc, Expr *CastExpr) {
4472 assert(!D.isInvalidType() && (CastExpr != 0) &&
Sebastian Redlb5d49352009-01-19 22:31:54 +00004473 "ActOnCastExpr(): missing type or expr");
Steve Naroff1a2cf6b2007-07-16 23:25:18 +00004474
Richard Trieuba63ce62011-09-09 01:45:06 +00004475 TypeSourceInfo *castTInfo = GetTypeForDeclaratorCast(D, CastExpr->getType());
Argyrios Kyrtzidis7192a3b2011-07-01 22:22:59 +00004476 if (D.isInvalidType())
4477 return ExprError();
4478
David Blaikiebbafb8a2012-03-11 07:00:24 +00004479 if (getLangOpts().CPlusPlus) {
Argyrios Kyrtzidis7192a3b2011-07-01 22:22:59 +00004480 // Check that there are no default arguments (C++ only).
4481 CheckExtraCXXDefaultArguments(D);
4482 }
4483
John McCall42856de2011-10-01 05:17:03 +00004484 checkUnusedDeclAttributes(D);
4485
Argyrios Kyrtzidis7192a3b2011-07-01 22:22:59 +00004486 QualType castType = castTInfo->getType();
4487 Ty = CreateParsedType(castType, castTInfo);
Mike Stump11289f42009-09-09 15:08:12 +00004488
Argyrios Kyrtzidisd8701b62011-07-01 22:22:54 +00004489 bool isVectorLiteral = false;
4490
4491 // Check for an altivec or OpenCL literal,
4492 // i.e. all the elements are integer constants.
Richard Trieuba63ce62011-09-09 01:45:06 +00004493 ParenExpr *PE = dyn_cast<ParenExpr>(CastExpr);
4494 ParenListExpr *PLE = dyn_cast<ParenListExpr>(CastExpr);
David Blaikiebbafb8a2012-03-11 07:00:24 +00004495 if ((getLangOpts().AltiVec || getLangOpts().OpenCL)
Tobias Grosser0a3a22f2011-09-21 18:28:29 +00004496 && castType->isVectorType() && (PE || PLE)) {
Argyrios Kyrtzidisd8701b62011-07-01 22:22:54 +00004497 if (PLE && PLE->getNumExprs() == 0) {
4498 Diag(PLE->getExprLoc(), diag::err_altivec_empty_initializer);
4499 return ExprError();
4500 }
4501 if (PE || PLE->getNumExprs() == 1) {
4502 Expr *E = (PE ? PE->getSubExpr() : PLE->getExpr(0));
4503 if (!E->getType()->isVectorType())
4504 isVectorLiteral = true;
4505 }
4506 else
4507 isVectorLiteral = true;
4508 }
4509
4510 // If this is a vector initializer, '(' type ')' '(' init, ..., init ')'
4511 // then handle it as such.
4512 if (isVectorLiteral)
Richard Trieuba63ce62011-09-09 01:45:06 +00004513 return BuildVectorLiteral(LParenLoc, RParenLoc, CastExpr, castTInfo);
Argyrios Kyrtzidisd8701b62011-07-01 22:22:54 +00004514
Nate Begeman5ec4b312009-08-10 23:49:36 +00004515 // If the Expr being casted is a ParenListExpr, handle it specially.
Argyrios Kyrtzidisd8701b62011-07-01 22:22:54 +00004516 // This is not an AltiVec-style cast, so turn the ParenListExpr into a
4517 // sequence of BinOp comma operators.
Richard Trieuba63ce62011-09-09 01:45:06 +00004518 if (isa<ParenListExpr>(CastExpr)) {
4519 ExprResult Result = MaybeConvertParenListExprToParenExpr(S, CastExpr);
Argyrios Kyrtzidisd8701b62011-07-01 22:22:54 +00004520 if (Result.isInvalid()) return ExprError();
Richard Trieuba63ce62011-09-09 01:45:06 +00004521 CastExpr = Result.take();
Argyrios Kyrtzidisd8701b62011-07-01 22:22:54 +00004522 }
John McCallebe54742010-01-15 18:56:44 +00004523
Richard Trieuba63ce62011-09-09 01:45:06 +00004524 return BuildCStyleCastExpr(LParenLoc, castTInfo, RParenLoc, CastExpr);
John McCallebe54742010-01-15 18:56:44 +00004525}
4526
Argyrios Kyrtzidisd8701b62011-07-01 22:22:54 +00004527ExprResult Sema::BuildVectorLiteral(SourceLocation LParenLoc,
4528 SourceLocation RParenLoc, Expr *E,
4529 TypeSourceInfo *TInfo) {
4530 assert((isa<ParenListExpr>(E) || isa<ParenExpr>(E)) &&
4531 "Expected paren or paren list expression");
4532
4533 Expr **exprs;
4534 unsigned numExprs;
4535 Expr *subExpr;
4536 if (ParenListExpr *PE = dyn_cast<ParenListExpr>(E)) {
4537 exprs = PE->getExprs();
4538 numExprs = PE->getNumExprs();
4539 } else {
4540 subExpr = cast<ParenExpr>(E)->getSubExpr();
4541 exprs = &subExpr;
4542 numExprs = 1;
4543 }
4544
4545 QualType Ty = TInfo->getType();
4546 assert(Ty->isVectorType() && "Expected vector type");
4547
Chris Lattner0e62c1c2011-07-23 10:55:15 +00004548 SmallVector<Expr *, 8> initExprs;
Tanya Lattner83559382011-07-15 23:07:01 +00004549 const VectorType *VTy = Ty->getAs<VectorType>();
4550 unsigned numElems = Ty->getAs<VectorType>()->getNumElements();
4551
Argyrios Kyrtzidisd8701b62011-07-01 22:22:54 +00004552 // '(...)' form of vector initialization in AltiVec: the number of
4553 // initializers must be one or must match the size of the vector.
4554 // If a single value is specified in the initializer then it will be
4555 // replicated to all the components of the vector
Tanya Lattner83559382011-07-15 23:07:01 +00004556 if (VTy->getVectorKind() == VectorType::AltiVecVector) {
Argyrios Kyrtzidisd8701b62011-07-01 22:22:54 +00004557 // The number of initializers must be one or must match the size of the
4558 // vector. If a single value is specified in the initializer then it will
4559 // be replicated to all the components of the vector
4560 if (numExprs == 1) {
4561 QualType ElemTy = Ty->getAs<VectorType>()->getElementType();
Richard Smith01ebacd2011-10-27 23:31:58 +00004562 ExprResult Literal = DefaultLvalueConversion(exprs[0]);
4563 if (Literal.isInvalid())
4564 return ExprError();
Argyrios Kyrtzidisd8701b62011-07-01 22:22:54 +00004565 Literal = ImpCastExprToType(Literal.take(), ElemTy,
John McCall9776e432011-10-06 23:25:11 +00004566 PrepareScalarCast(Literal, ElemTy));
Argyrios Kyrtzidisd8701b62011-07-01 22:22:54 +00004567 return BuildCStyleCastExpr(LParenLoc, TInfo, RParenLoc, Literal.take());
4568 }
4569 else if (numExprs < numElems) {
4570 Diag(E->getExprLoc(),
4571 diag::err_incorrect_number_of_vector_initializers);
4572 return ExprError();
4573 }
4574 else
Benjamin Kramer8001f742012-02-14 12:06:21 +00004575 initExprs.append(exprs, exprs + numExprs);
Argyrios Kyrtzidisd8701b62011-07-01 22:22:54 +00004576 }
Tanya Lattner83559382011-07-15 23:07:01 +00004577 else {
4578 // For OpenCL, when the number of initializers is a single value,
4579 // it will be replicated to all components of the vector.
David Blaikiebbafb8a2012-03-11 07:00:24 +00004580 if (getLangOpts().OpenCL &&
Tanya Lattner83559382011-07-15 23:07:01 +00004581 VTy->getVectorKind() == VectorType::GenericVector &&
4582 numExprs == 1) {
4583 QualType ElemTy = Ty->getAs<VectorType>()->getElementType();
Richard Smith01ebacd2011-10-27 23:31:58 +00004584 ExprResult Literal = DefaultLvalueConversion(exprs[0]);
4585 if (Literal.isInvalid())
4586 return ExprError();
Tanya Lattner83559382011-07-15 23:07:01 +00004587 Literal = ImpCastExprToType(Literal.take(), ElemTy,
John McCall9776e432011-10-06 23:25:11 +00004588 PrepareScalarCast(Literal, ElemTy));
Tanya Lattner83559382011-07-15 23:07:01 +00004589 return BuildCStyleCastExpr(LParenLoc, TInfo, RParenLoc, Literal.take());
4590 }
4591
Benjamin Kramer8001f742012-02-14 12:06:21 +00004592 initExprs.append(exprs, exprs + numExprs);
Tanya Lattner83559382011-07-15 23:07:01 +00004593 }
Argyrios Kyrtzidisd8701b62011-07-01 22:22:54 +00004594 // FIXME: This means that pretty-printing the final AST will produce curly
4595 // braces instead of the original commas.
4596 InitListExpr *initE = new (Context) InitListExpr(Context, LParenLoc,
Benjamin Kramerc215e762012-08-24 11:54:20 +00004597 initExprs, RParenLoc);
Argyrios Kyrtzidisd8701b62011-07-01 22:22:54 +00004598 initE->setType(Ty);
4599 return BuildCompoundLiteralExpr(LParenLoc, TInfo, RParenLoc, initE);
4600}
4601
Sebastian Redla9351792012-02-11 23:51:47 +00004602/// This is not an AltiVec-style cast or or C++ direct-initialization, so turn
4603/// the ParenListExpr into a sequence of comma binary operators.
John McCalldadc5752010-08-24 06:29:42 +00004604ExprResult
Richard Trieuba63ce62011-09-09 01:45:06 +00004605Sema::MaybeConvertParenListExprToParenExpr(Scope *S, Expr *OrigExpr) {
4606 ParenListExpr *E = dyn_cast<ParenListExpr>(OrigExpr);
Nate Begeman5ec4b312009-08-10 23:49:36 +00004607 if (!E)
Richard Trieuba63ce62011-09-09 01:45:06 +00004608 return Owned(OrigExpr);
Mike Stump11289f42009-09-09 15:08:12 +00004609
John McCalldadc5752010-08-24 06:29:42 +00004610 ExprResult Result(E->getExpr(0));
Mike Stump11289f42009-09-09 15:08:12 +00004611
Nate Begeman5ec4b312009-08-10 23:49:36 +00004612 for (unsigned i = 1, e = E->getNumExprs(); i != e && !Result.isInvalid(); ++i)
John McCallb268a282010-08-23 23:25:46 +00004613 Result = ActOnBinOp(S, E->getExprLoc(), tok::comma, Result.get(),
4614 E->getExpr(i));
Mike Stump11289f42009-09-09 15:08:12 +00004615
John McCallb268a282010-08-23 23:25:46 +00004616 if (Result.isInvalid()) return ExprError();
4617
4618 return ActOnParenExpr(E->getLParenLoc(), E->getRParenLoc(), Result.get());
Nate Begeman5ec4b312009-08-10 23:49:36 +00004619}
4620
Sebastian Redla9351792012-02-11 23:51:47 +00004621ExprResult Sema::ActOnParenListExpr(SourceLocation L,
4622 SourceLocation R,
4623 MultiExprArg Val) {
Benjamin Kramerc215e762012-08-24 11:54:20 +00004624 assert(Val.data() != 0 && "ActOnParenOrParenListExpr() missing expr list");
4625 Expr *expr = new (Context) ParenListExpr(Context, L, Val, R);
Nate Begeman5ec4b312009-08-10 23:49:36 +00004626 return Owned(expr);
4627}
4628
Chandler Carrutha8bea4b2011-02-18 23:54:50 +00004629/// \brief Emit a specialized diagnostic when one expression is a null pointer
Richard Trieu27ae4cb2011-09-02 01:51:02 +00004630/// constant and the other is not a pointer. Returns true if a diagnostic is
4631/// emitted.
Richard Trieud33e46e2011-09-06 20:06:39 +00004632bool Sema::DiagnoseConditionalForNull(Expr *LHSExpr, Expr *RHSExpr,
Chandler Carrutha8bea4b2011-02-18 23:54:50 +00004633 SourceLocation QuestionLoc) {
Richard Trieud33e46e2011-09-06 20:06:39 +00004634 Expr *NullExpr = LHSExpr;
4635 Expr *NonPointerExpr = RHSExpr;
Chandler Carrutha8bea4b2011-02-18 23:54:50 +00004636 Expr::NullPointerConstantKind NullKind =
4637 NullExpr->isNullPointerConstant(Context,
4638 Expr::NPC_ValueDependentIsNotNull);
4639
4640 if (NullKind == Expr::NPCK_NotNull) {
Richard Trieud33e46e2011-09-06 20:06:39 +00004641 NullExpr = RHSExpr;
4642 NonPointerExpr = LHSExpr;
Chandler Carrutha8bea4b2011-02-18 23:54:50 +00004643 NullKind =
4644 NullExpr->isNullPointerConstant(Context,
4645 Expr::NPC_ValueDependentIsNotNull);
4646 }
4647
4648 if (NullKind == Expr::NPCK_NotNull)
4649 return false;
4650
David Blaikie1c7c8f72012-08-08 17:33:31 +00004651 if (NullKind == Expr::NPCK_ZeroExpression)
4652 return false;
4653
4654 if (NullKind == Expr::NPCK_ZeroLiteral) {
Chandler Carrutha8bea4b2011-02-18 23:54:50 +00004655 // In this case, check to make sure that we got here from a "NULL"
4656 // string in the source code.
4657 NullExpr = NullExpr->IgnoreParenImpCasts();
John McCall462c0552011-03-08 07:59:04 +00004658 SourceLocation loc = NullExpr->getExprLoc();
4659 if (!findMacroSpelling(loc, "NULL"))
Chandler Carrutha8bea4b2011-02-18 23:54:50 +00004660 return false;
4661 }
4662
4663 int DiagType = (NullKind == Expr::NPCK_CXX0X_nullptr);
4664 Diag(QuestionLoc, diag::err_typecheck_cond_incompatible_operands_null)
4665 << NonPointerExpr->getType() << DiagType
4666 << NonPointerExpr->getSourceRange();
4667 return true;
4668}
4669
Richard Trieu27ae4cb2011-09-02 01:51:02 +00004670/// \brief Return false if the condition expression is valid, true otherwise.
4671static bool checkCondition(Sema &S, Expr *Cond) {
4672 QualType CondTy = Cond->getType();
4673
4674 // C99 6.5.15p2
4675 if (CondTy->isScalarType()) return false;
4676
4677 // OpenCL: Sec 6.3.i says the condition is allowed to be a vector or scalar.
David Blaikiebbafb8a2012-03-11 07:00:24 +00004678 if (S.getLangOpts().OpenCL && CondTy->isVectorType())
Richard Trieu27ae4cb2011-09-02 01:51:02 +00004679 return false;
4680
4681 // Emit the proper error message.
David Blaikiebbafb8a2012-03-11 07:00:24 +00004682 S.Diag(Cond->getLocStart(), S.getLangOpts().OpenCL ?
Richard Trieu27ae4cb2011-09-02 01:51:02 +00004683 diag::err_typecheck_cond_expect_scalar :
4684 diag::err_typecheck_cond_expect_scalar_or_vector)
4685 << CondTy;
4686 return true;
4687}
4688
4689/// \brief Return false if the two expressions can be converted to a vector,
4690/// true otherwise
4691static bool checkConditionalConvertScalarsToVectors(Sema &S, ExprResult &LHS,
4692 ExprResult &RHS,
4693 QualType CondTy) {
4694 // Both operands should be of scalar type.
4695 if (!LHS.get()->getType()->isScalarType()) {
4696 S.Diag(LHS.get()->getLocStart(), diag::err_typecheck_cond_expect_scalar)
4697 << CondTy;
4698 return true;
4699 }
4700 if (!RHS.get()->getType()->isScalarType()) {
4701 S.Diag(RHS.get()->getLocStart(), diag::err_typecheck_cond_expect_scalar)
4702 << CondTy;
4703 return true;
4704 }
4705
4706 // Implicity convert these scalars to the type of the condition.
4707 LHS = S.ImpCastExprToType(LHS.take(), CondTy, CK_IntegralCast);
4708 RHS = S.ImpCastExprToType(RHS.take(), CondTy, CK_IntegralCast);
4709 return false;
4710}
4711
4712/// \brief Handle when one or both operands are void type.
4713static QualType checkConditionalVoidType(Sema &S, ExprResult &LHS,
4714 ExprResult &RHS) {
4715 Expr *LHSExpr = LHS.get();
4716 Expr *RHSExpr = RHS.get();
4717
4718 if (!LHSExpr->getType()->isVoidType())
4719 S.Diag(RHSExpr->getLocStart(), diag::ext_typecheck_cond_one_void)
4720 << RHSExpr->getSourceRange();
4721 if (!RHSExpr->getType()->isVoidType())
4722 S.Diag(LHSExpr->getLocStart(), diag::ext_typecheck_cond_one_void)
4723 << LHSExpr->getSourceRange();
4724 LHS = S.ImpCastExprToType(LHS.take(), S.Context.VoidTy, CK_ToVoid);
4725 RHS = S.ImpCastExprToType(RHS.take(), S.Context.VoidTy, CK_ToVoid);
4726 return S.Context.VoidTy;
4727}
4728
4729/// \brief Return false if the NullExpr can be promoted to PointerTy,
4730/// true otherwise.
4731static bool checkConditionalNullPointer(Sema &S, ExprResult &NullExpr,
4732 QualType PointerTy) {
4733 if ((!PointerTy->isAnyPointerType() && !PointerTy->isBlockPointerType()) ||
4734 !NullExpr.get()->isNullPointerConstant(S.Context,
4735 Expr::NPC_ValueDependentIsNull))
4736 return true;
4737
4738 NullExpr = S.ImpCastExprToType(NullExpr.take(), PointerTy, CK_NullToPointer);
4739 return false;
4740}
4741
4742/// \brief Checks compatibility between two pointers and return the resulting
4743/// type.
4744static QualType checkConditionalPointerCompatibility(Sema &S, ExprResult &LHS,
4745 ExprResult &RHS,
4746 SourceLocation Loc) {
4747 QualType LHSTy = LHS.get()->getType();
4748 QualType RHSTy = RHS.get()->getType();
4749
4750 if (S.Context.hasSameType(LHSTy, RHSTy)) {
4751 // Two identical pointers types are always compatible.
4752 return LHSTy;
4753 }
4754
4755 QualType lhptee, rhptee;
4756
4757 // Get the pointee types.
John McCall9320b872011-09-09 05:25:32 +00004758 if (const BlockPointerType *LHSBTy = LHSTy->getAs<BlockPointerType>()) {
4759 lhptee = LHSBTy->getPointeeType();
4760 rhptee = RHSTy->castAs<BlockPointerType>()->getPointeeType();
Richard Trieu27ae4cb2011-09-02 01:51:02 +00004761 } else {
John McCall9320b872011-09-09 05:25:32 +00004762 lhptee = LHSTy->castAs<PointerType>()->getPointeeType();
4763 rhptee = RHSTy->castAs<PointerType>()->getPointeeType();
Richard Trieu27ae4cb2011-09-02 01:51:02 +00004764 }
4765
Eli Friedman57a75392012-04-05 22:30:04 +00004766 // C99 6.5.15p6: If both operands are pointers to compatible types or to
4767 // differently qualified versions of compatible types, the result type is
4768 // a pointer to an appropriately qualified version of the composite
4769 // type.
4770
4771 // Only CVR-qualifiers exist in the standard, and the differently-qualified
4772 // clause doesn't make sense for our extensions. E.g. address space 2 should
4773 // be incompatible with address space 3: they may live on different devices or
4774 // anything.
4775 Qualifiers lhQual = lhptee.getQualifiers();
4776 Qualifiers rhQual = rhptee.getQualifiers();
4777
4778 unsigned MergedCVRQual = lhQual.getCVRQualifiers() | rhQual.getCVRQualifiers();
4779 lhQual.removeCVRQualifiers();
4780 rhQual.removeCVRQualifiers();
4781
4782 lhptee = S.Context.getQualifiedType(lhptee.getUnqualifiedType(), lhQual);
4783 rhptee = S.Context.getQualifiedType(rhptee.getUnqualifiedType(), rhQual);
4784
4785 QualType CompositeTy = S.Context.mergeTypes(lhptee, rhptee);
4786
4787 if (CompositeTy.isNull()) {
Richard Trieu27ae4cb2011-09-02 01:51:02 +00004788 S.Diag(Loc, diag::warn_typecheck_cond_incompatible_pointers)
4789 << LHSTy << RHSTy << LHS.get()->getSourceRange()
4790 << RHS.get()->getSourceRange();
4791 // In this situation, we assume void* type. No especially good
4792 // reason, but this is what gcc does, and we do have to pick
4793 // to get a consistent AST.
4794 QualType incompatTy = S.Context.getPointerType(S.Context.VoidTy);
4795 LHS = S.ImpCastExprToType(LHS.take(), incompatTy, CK_BitCast);
4796 RHS = S.ImpCastExprToType(RHS.take(), incompatTy, CK_BitCast);
4797 return incompatTy;
4798 }
4799
4800 // The pointer types are compatible.
Eli Friedman57a75392012-04-05 22:30:04 +00004801 QualType ResultTy = CompositeTy.withCVRQualifiers(MergedCVRQual);
4802 ResultTy = S.Context.getPointerType(ResultTy);
Richard Trieu27ae4cb2011-09-02 01:51:02 +00004803
Eli Friedman57a75392012-04-05 22:30:04 +00004804 LHS = S.ImpCastExprToType(LHS.take(), ResultTy, CK_BitCast);
4805 RHS = S.ImpCastExprToType(RHS.take(), ResultTy, CK_BitCast);
4806 return ResultTy;
Richard Trieu27ae4cb2011-09-02 01:51:02 +00004807}
4808
4809/// \brief Return the resulting type when the operands are both block pointers.
4810static QualType checkConditionalBlockPointerCompatibility(Sema &S,
4811 ExprResult &LHS,
4812 ExprResult &RHS,
4813 SourceLocation Loc) {
4814 QualType LHSTy = LHS.get()->getType();
4815 QualType RHSTy = RHS.get()->getType();
4816
4817 if (!LHSTy->isBlockPointerType() || !RHSTy->isBlockPointerType()) {
4818 if (LHSTy->isVoidPointerType() || RHSTy->isVoidPointerType()) {
4819 QualType destType = S.Context.getPointerType(S.Context.VoidTy);
4820 LHS = S.ImpCastExprToType(LHS.take(), destType, CK_BitCast);
4821 RHS = S.ImpCastExprToType(RHS.take(), destType, CK_BitCast);
4822 return destType;
4823 }
4824 S.Diag(Loc, diag::err_typecheck_cond_incompatible_operands)
4825 << LHSTy << RHSTy << LHS.get()->getSourceRange()
4826 << RHS.get()->getSourceRange();
4827 return QualType();
4828 }
4829
4830 // We have 2 block pointer types.
4831 return checkConditionalPointerCompatibility(S, LHS, RHS, Loc);
4832}
4833
4834/// \brief Return the resulting type when the operands are both pointers.
4835static QualType
4836checkConditionalObjectPointersCompatibility(Sema &S, ExprResult &LHS,
4837 ExprResult &RHS,
4838 SourceLocation Loc) {
4839 // get the pointer types
4840 QualType LHSTy = LHS.get()->getType();
4841 QualType RHSTy = RHS.get()->getType();
4842
4843 // get the "pointed to" types
4844 QualType lhptee = LHSTy->getAs<PointerType>()->getPointeeType();
4845 QualType rhptee = RHSTy->getAs<PointerType>()->getPointeeType();
4846
4847 // ignore qualifiers on void (C99 6.5.15p3, clause 6)
4848 if (lhptee->isVoidType() && rhptee->isIncompleteOrObjectType()) {
4849 // Figure out necessary qualifiers (C99 6.5.15p6)
4850 QualType destPointee
4851 = S.Context.getQualifiedType(lhptee, rhptee.getQualifiers());
4852 QualType destType = S.Context.getPointerType(destPointee);
4853 // Add qualifiers if necessary.
4854 LHS = S.ImpCastExprToType(LHS.take(), destType, CK_NoOp);
4855 // Promote to void*.
4856 RHS = S.ImpCastExprToType(RHS.take(), destType, CK_BitCast);
4857 return destType;
4858 }
4859 if (rhptee->isVoidType() && lhptee->isIncompleteOrObjectType()) {
4860 QualType destPointee
4861 = S.Context.getQualifiedType(rhptee, lhptee.getQualifiers());
4862 QualType destType = S.Context.getPointerType(destPointee);
4863 // Add qualifiers if necessary.
4864 RHS = S.ImpCastExprToType(RHS.take(), destType, CK_NoOp);
4865 // Promote to void*.
4866 LHS = S.ImpCastExprToType(LHS.take(), destType, CK_BitCast);
4867 return destType;
4868 }
4869
4870 return checkConditionalPointerCompatibility(S, LHS, RHS, Loc);
4871}
4872
4873/// \brief Return false if the first expression is not an integer and the second
4874/// expression is not a pointer, true otherwise.
4875static bool checkPointerIntegerMismatch(Sema &S, ExprResult &Int,
4876 Expr* PointerExpr, SourceLocation Loc,
Richard Trieuba63ce62011-09-09 01:45:06 +00004877 bool IsIntFirstExpr) {
Richard Trieu27ae4cb2011-09-02 01:51:02 +00004878 if (!PointerExpr->getType()->isPointerType() ||
4879 !Int.get()->getType()->isIntegerType())
4880 return false;
4881
Richard Trieuba63ce62011-09-09 01:45:06 +00004882 Expr *Expr1 = IsIntFirstExpr ? Int.get() : PointerExpr;
4883 Expr *Expr2 = IsIntFirstExpr ? PointerExpr : Int.get();
Richard Trieu27ae4cb2011-09-02 01:51:02 +00004884
4885 S.Diag(Loc, diag::warn_typecheck_cond_pointer_integer_mismatch)
4886 << Expr1->getType() << Expr2->getType()
4887 << Expr1->getSourceRange() << Expr2->getSourceRange();
4888 Int = S.ImpCastExprToType(Int.take(), PointerExpr->getType(),
4889 CK_IntegralToPointer);
4890 return true;
4891}
4892
Richard Trieud33e46e2011-09-06 20:06:39 +00004893/// Note that LHS is not null here, even if this is the gnu "x ?: y" extension.
4894/// In that case, LHS = cond.
Chris Lattner2c486602009-02-18 04:38:20 +00004895/// C99 6.5.15
Richard Trieucfc491d2011-08-02 04:35:43 +00004896QualType Sema::CheckConditionalOperands(ExprResult &Cond, ExprResult &LHS,
4897 ExprResult &RHS, ExprValueKind &VK,
4898 ExprObjectKind &OK,
Chris Lattner2c486602009-02-18 04:38:20 +00004899 SourceLocation QuestionLoc) {
Douglas Gregor1beec452011-03-12 01:48:56 +00004900
Richard Trieud33e46e2011-09-06 20:06:39 +00004901 ExprResult LHSResult = CheckPlaceholderExpr(LHS.get());
4902 if (!LHSResult.isUsable()) return QualType();
Benjamin Kramer62b95d82012-08-23 21:35:17 +00004903 LHS = LHSResult;
Douglas Gregor0124e9b2010-11-09 21:07:58 +00004904
Richard Trieud33e46e2011-09-06 20:06:39 +00004905 ExprResult RHSResult = CheckPlaceholderExpr(RHS.get());
4906 if (!RHSResult.isUsable()) return QualType();
Benjamin Kramer62b95d82012-08-23 21:35:17 +00004907 RHS = RHSResult;
Douglas Gregor0124e9b2010-11-09 21:07:58 +00004908
Sebastian Redl1a99f442009-04-16 17:51:27 +00004909 // C++ is sufficiently different to merit its own checker.
David Blaikiebbafb8a2012-03-11 07:00:24 +00004910 if (getLangOpts().CPlusPlus)
John McCallc07a0c72011-02-17 10:25:35 +00004911 return CXXCheckConditionalOperands(Cond, LHS, RHS, VK, OK, QuestionLoc);
John McCall7decc9e2010-11-18 06:31:45 +00004912
4913 VK = VK_RValue;
John McCall4bc41ae2010-11-18 19:01:18 +00004914 OK = OK_Ordinary;
Sebastian Redl1a99f442009-04-16 17:51:27 +00004915
John Wiegley01296292011-04-08 18:41:53 +00004916 Cond = UsualUnaryConversions(Cond.take());
4917 if (Cond.isInvalid())
4918 return QualType();
4919 LHS = UsualUnaryConversions(LHS.take());
4920 if (LHS.isInvalid())
4921 return QualType();
4922 RHS = UsualUnaryConversions(RHS.take());
4923 if (RHS.isInvalid())
4924 return QualType();
4925
4926 QualType CondTy = Cond.get()->getType();
4927 QualType LHSTy = LHS.get()->getType();
4928 QualType RHSTy = RHS.get()->getType();
Steve Naroff31090012007-07-16 21:54:35 +00004929
Steve Naroffa78fe7e2007-05-16 19:47:19 +00004930 // first, check the condition.
Richard Trieu27ae4cb2011-09-02 01:51:02 +00004931 if (checkCondition(*this, Cond.get()))
4932 return QualType();
Mike Stump4e1f26a2009-02-19 03:04:26 +00004933
Chris Lattnere2949f42008-01-06 22:42:25 +00004934 // Now check the two expressions.
Nate Begeman5ec4b312009-08-10 23:49:36 +00004935 if (LHSTy->isVectorType() || RHSTy->isVectorType())
Eli Friedman1408bc92011-06-23 18:10:35 +00004936 return CheckVectorOperands(LHS, RHS, QuestionLoc, /*isCompAssign*/false);
Douglas Gregor4619e432008-12-05 23:32:09 +00004937
Nate Begemanabb5a732010-09-20 22:41:17 +00004938 // OpenCL: If the condition is a vector, and both operands are scalar,
4939 // attempt to implicity convert them to the vector type to act like the
4940 // built in select.
David Blaikiebbafb8a2012-03-11 07:00:24 +00004941 if (getLangOpts().OpenCL && CondTy->isVectorType())
Richard Trieu27ae4cb2011-09-02 01:51:02 +00004942 if (checkConditionalConvertScalarsToVectors(*this, LHS, RHS, CondTy))
Nate Begemanabb5a732010-09-20 22:41:17 +00004943 return QualType();
Nate Begemanabb5a732010-09-20 22:41:17 +00004944
Chris Lattnere2949f42008-01-06 22:42:25 +00004945 // If both operands have arithmetic type, do the usual arithmetic conversions
4946 // to find a common type: C99 6.5.15p3,5.
Chris Lattner432cff52009-02-18 04:28:32 +00004947 if (LHSTy->isArithmeticType() && RHSTy->isArithmeticType()) {
4948 UsualArithmeticConversions(LHS, RHS);
John Wiegley01296292011-04-08 18:41:53 +00004949 if (LHS.isInvalid() || RHS.isInvalid())
4950 return QualType();
4951 return LHS.get()->getType();
Steve Naroffdbd9e892007-07-17 00:58:39 +00004952 }
Mike Stump4e1f26a2009-02-19 03:04:26 +00004953
Chris Lattnere2949f42008-01-06 22:42:25 +00004954 // If both operands are the same structure or union type, the result is that
4955 // type.
Ted Kremenekc23c7e62009-07-29 21:53:49 +00004956 if (const RecordType *LHSRT = LHSTy->getAs<RecordType>()) { // C99 6.5.15p3
4957 if (const RecordType *RHSRT = RHSTy->getAs<RecordType>())
Chris Lattner2ab40a62007-11-26 01:40:58 +00004958 if (LHSRT->getDecl() == RHSRT->getDecl())
Mike Stump4e1f26a2009-02-19 03:04:26 +00004959 // "If both the operands have structure or union type, the result has
Chris Lattnere2949f42008-01-06 22:42:25 +00004960 // that type." This implies that CV qualifiers are dropped.
Chris Lattner432cff52009-02-18 04:28:32 +00004961 return LHSTy.getUnqualifiedType();
Eli Friedmanba961a92009-03-23 00:24:07 +00004962 // FIXME: Type of conditional expression must be complete in C mode.
Steve Naroffa78fe7e2007-05-16 19:47:19 +00004963 }
Mike Stump4e1f26a2009-02-19 03:04:26 +00004964
Chris Lattnere2949f42008-01-06 22:42:25 +00004965 // C99 6.5.15p5: "If both operands have void type, the result has void type."
Steve Naroffbf1516c2008-05-12 21:44:38 +00004966 // The following || allows only one side to be void (a GCC-ism).
Chris Lattner432cff52009-02-18 04:28:32 +00004967 if (LHSTy->isVoidType() || RHSTy->isVoidType()) {
Richard Trieu27ae4cb2011-09-02 01:51:02 +00004968 return checkConditionalVoidType(*this, LHS, RHS);
Steve Naroffbf1516c2008-05-12 21:44:38 +00004969 }
Richard Trieu27ae4cb2011-09-02 01:51:02 +00004970
Steve Naroff039ad3c2008-01-08 01:11:38 +00004971 // C99 6.5.15p6 - "if one operand is a null pointer constant, the result has
4972 // the type of the other operand."
Richard Trieu27ae4cb2011-09-02 01:51:02 +00004973 if (!checkConditionalNullPointer(*this, RHS, LHSTy)) return LHSTy;
4974 if (!checkConditionalNullPointer(*this, LHS, RHSTy)) return RHSTy;
Kovarththanan Rajaratnamba2c6522010-03-13 10:17:05 +00004975
Fariborz Jahaniana430f712009-12-10 19:47:41 +00004976 // All objective-c pointer type analysis is done here.
4977 QualType compositeType = FindCompositeObjCPointerType(LHS, RHS,
4978 QuestionLoc);
John Wiegley01296292011-04-08 18:41:53 +00004979 if (LHS.isInvalid() || RHS.isInvalid())
4980 return QualType();
Fariborz Jahaniana430f712009-12-10 19:47:41 +00004981 if (!compositeType.isNull())
4982 return compositeType;
Kovarththanan Rajaratnamba2c6522010-03-13 10:17:05 +00004983
4984
Steve Naroff05efa972009-07-01 14:36:47 +00004985 // Handle block pointer types.
Richard Trieu27ae4cb2011-09-02 01:51:02 +00004986 if (LHSTy->isBlockPointerType() || RHSTy->isBlockPointerType())
4987 return checkConditionalBlockPointerCompatibility(*this, LHS, RHS,
4988 QuestionLoc);
Kovarththanan Rajaratnamba2c6522010-03-13 10:17:05 +00004989
Steve Naroff05efa972009-07-01 14:36:47 +00004990 // Check constraints for C object pointers types (C99 6.5.15p3,6).
Richard Trieu27ae4cb2011-09-02 01:51:02 +00004991 if (LHSTy->isPointerType() && RHSTy->isPointerType())
4992 return checkConditionalObjectPointersCompatibility(*this, LHS, RHS,
4993 QuestionLoc);
Mike Stump11289f42009-09-09 15:08:12 +00004994
John McCalle84af4e2010-11-13 01:35:44 +00004995 // GCC compatibility: soften pointer/integer mismatch. Note that
4996 // null pointers have been filtered out by this point.
Richard Trieu27ae4cb2011-09-02 01:51:02 +00004997 if (checkPointerIntegerMismatch(*this, LHS, RHS.get(), QuestionLoc,
4998 /*isIntFirstExpr=*/true))
Steve Naroff05efa972009-07-01 14:36:47 +00004999 return RHSTy;
Richard Trieu27ae4cb2011-09-02 01:51:02 +00005000 if (checkPointerIntegerMismatch(*this, RHS, LHS.get(), QuestionLoc,
5001 /*isIntFirstExpr=*/false))
Steve Naroff05efa972009-07-01 14:36:47 +00005002 return LHSTy;
Daniel Dunbar484603b2008-09-11 23:12:46 +00005003
Chandler Carrutha8bea4b2011-02-18 23:54:50 +00005004 // Emit a better diagnostic if one of the expressions is a null pointer
5005 // constant and the other is not a pointer type. In this case, the user most
5006 // likely forgot to take the address of the other expression.
John Wiegley01296292011-04-08 18:41:53 +00005007 if (DiagnoseConditionalForNull(LHS.get(), RHS.get(), QuestionLoc))
Chandler Carrutha8bea4b2011-02-18 23:54:50 +00005008 return QualType();
5009
Chris Lattnere2949f42008-01-06 22:42:25 +00005010 // Otherwise, the operands are not compatible.
Chris Lattner432cff52009-02-18 04:28:32 +00005011 Diag(QuestionLoc, diag::err_typecheck_cond_incompatible_operands)
Richard Trieucfc491d2011-08-02 04:35:43 +00005012 << LHSTy << RHSTy << LHS.get()->getSourceRange()
5013 << RHS.get()->getSourceRange();
Steve Naroffa78fe7e2007-05-16 19:47:19 +00005014 return QualType();
Steve Narofff8a28c52007-05-15 20:29:32 +00005015}
5016
Fariborz Jahaniana430f712009-12-10 19:47:41 +00005017/// FindCompositeObjCPointerType - Helper method to find composite type of
5018/// two objective-c pointer types of the two input expressions.
John Wiegley01296292011-04-08 18:41:53 +00005019QualType Sema::FindCompositeObjCPointerType(ExprResult &LHS, ExprResult &RHS,
Richard Trieucfc491d2011-08-02 04:35:43 +00005020 SourceLocation QuestionLoc) {
John Wiegley01296292011-04-08 18:41:53 +00005021 QualType LHSTy = LHS.get()->getType();
5022 QualType RHSTy = RHS.get()->getType();
Kovarththanan Rajaratnamba2c6522010-03-13 10:17:05 +00005023
Fariborz Jahaniana430f712009-12-10 19:47:41 +00005024 // Handle things like Class and struct objc_class*. Here we case the result
5025 // to the pseudo-builtin, because that will be implicitly cast back to the
5026 // redefinition type if an attempt is made to access its fields.
5027 if (LHSTy->isObjCClassType() &&
Douglas Gregor97673472011-08-11 20:58:55 +00005028 (Context.hasSameType(RHSTy, Context.getObjCClassRedefinitionType()))) {
John McCall9320b872011-09-09 05:25:32 +00005029 RHS = ImpCastExprToType(RHS.take(), LHSTy, CK_CPointerToObjCPointerCast);
Fariborz Jahaniana430f712009-12-10 19:47:41 +00005030 return LHSTy;
5031 }
5032 if (RHSTy->isObjCClassType() &&
Douglas Gregor97673472011-08-11 20:58:55 +00005033 (Context.hasSameType(LHSTy, Context.getObjCClassRedefinitionType()))) {
John McCall9320b872011-09-09 05:25:32 +00005034 LHS = ImpCastExprToType(LHS.take(), RHSTy, CK_CPointerToObjCPointerCast);
Fariborz Jahaniana430f712009-12-10 19:47:41 +00005035 return RHSTy;
5036 }
5037 // And the same for struct objc_object* / id
5038 if (LHSTy->isObjCIdType() &&
Douglas Gregor97673472011-08-11 20:58:55 +00005039 (Context.hasSameType(RHSTy, Context.getObjCIdRedefinitionType()))) {
John McCall9320b872011-09-09 05:25:32 +00005040 RHS = ImpCastExprToType(RHS.take(), LHSTy, CK_CPointerToObjCPointerCast);
Fariborz Jahaniana430f712009-12-10 19:47:41 +00005041 return LHSTy;
5042 }
5043 if (RHSTy->isObjCIdType() &&
Douglas Gregor97673472011-08-11 20:58:55 +00005044 (Context.hasSameType(LHSTy, Context.getObjCIdRedefinitionType()))) {
John McCall9320b872011-09-09 05:25:32 +00005045 LHS = ImpCastExprToType(LHS.take(), RHSTy, CK_CPointerToObjCPointerCast);
Fariborz Jahaniana430f712009-12-10 19:47:41 +00005046 return RHSTy;
5047 }
5048 // And the same for struct objc_selector* / SEL
5049 if (Context.isObjCSelType(LHSTy) &&
Douglas Gregor97673472011-08-11 20:58:55 +00005050 (Context.hasSameType(RHSTy, Context.getObjCSelRedefinitionType()))) {
John Wiegley01296292011-04-08 18:41:53 +00005051 RHS = ImpCastExprToType(RHS.take(), LHSTy, CK_BitCast);
Fariborz Jahaniana430f712009-12-10 19:47:41 +00005052 return LHSTy;
5053 }
5054 if (Context.isObjCSelType(RHSTy) &&
Douglas Gregor97673472011-08-11 20:58:55 +00005055 (Context.hasSameType(LHSTy, Context.getObjCSelRedefinitionType()))) {
John Wiegley01296292011-04-08 18:41:53 +00005056 LHS = ImpCastExprToType(LHS.take(), RHSTy, CK_BitCast);
Fariborz Jahaniana430f712009-12-10 19:47:41 +00005057 return RHSTy;
5058 }
5059 // Check constraints for Objective-C object pointers types.
5060 if (LHSTy->isObjCObjectPointerType() && RHSTy->isObjCObjectPointerType()) {
Kovarththanan Rajaratnamba2c6522010-03-13 10:17:05 +00005061
Fariborz Jahaniana430f712009-12-10 19:47:41 +00005062 if (Context.getCanonicalType(LHSTy) == Context.getCanonicalType(RHSTy)) {
5063 // Two identical object pointer types are always compatible.
5064 return LHSTy;
5065 }
John McCall9320b872011-09-09 05:25:32 +00005066 const ObjCObjectPointerType *LHSOPT = LHSTy->castAs<ObjCObjectPointerType>();
5067 const ObjCObjectPointerType *RHSOPT = RHSTy->castAs<ObjCObjectPointerType>();
Fariborz Jahaniana430f712009-12-10 19:47:41 +00005068 QualType compositeType = LHSTy;
Kovarththanan Rajaratnamba2c6522010-03-13 10:17:05 +00005069
Fariborz Jahaniana430f712009-12-10 19:47:41 +00005070 // If both operands are interfaces and either operand can be
5071 // assigned to the other, use that type as the composite
5072 // type. This allows
5073 // xxx ? (A*) a : (B*) b
5074 // where B is a subclass of A.
5075 //
5076 // Additionally, as for assignment, if either type is 'id'
5077 // allow silent coercion. Finally, if the types are
5078 // incompatible then make sure to use 'id' as the composite
5079 // type so the result is acceptable for sending messages to.
Kovarththanan Rajaratnamba2c6522010-03-13 10:17:05 +00005080
Fariborz Jahaniana430f712009-12-10 19:47:41 +00005081 // FIXME: Consider unifying with 'areComparableObjCPointerTypes'.
5082 // It could return the composite type.
5083 if (Context.canAssignObjCInterfaces(LHSOPT, RHSOPT)) {
5084 compositeType = RHSOPT->isObjCBuiltinType() ? RHSTy : LHSTy;
5085 } else if (Context.canAssignObjCInterfaces(RHSOPT, LHSOPT)) {
5086 compositeType = LHSOPT->isObjCBuiltinType() ? LHSTy : RHSTy;
5087 } else if ((LHSTy->isObjCQualifiedIdType() ||
5088 RHSTy->isObjCQualifiedIdType()) &&
5089 Context.ObjCQualifiedIdTypesAreCompatible(LHSTy, RHSTy, true)) {
5090 // Need to handle "id<xx>" explicitly.
5091 // GCC allows qualified id and any Objective-C type to devolve to
5092 // id. Currently localizing to here until clear this should be
5093 // part of ObjCQualifiedIdTypesAreCompatible.
5094 compositeType = Context.getObjCIdType();
5095 } else if (LHSTy->isObjCIdType() || RHSTy->isObjCIdType()) {
5096 compositeType = Context.getObjCIdType();
Kovarththanan Rajaratnamba2c6522010-03-13 10:17:05 +00005097 } else if (!(compositeType =
Fariborz Jahaniana430f712009-12-10 19:47:41 +00005098 Context.areCommonBaseCompatible(LHSOPT, RHSOPT)).isNull())
5099 ;
5100 else {
5101 Diag(QuestionLoc, diag::ext_typecheck_cond_incompatible_operands)
5102 << LHSTy << RHSTy
John Wiegley01296292011-04-08 18:41:53 +00005103 << LHS.get()->getSourceRange() << RHS.get()->getSourceRange();
Fariborz Jahaniana430f712009-12-10 19:47:41 +00005104 QualType incompatTy = Context.getObjCIdType();
John Wiegley01296292011-04-08 18:41:53 +00005105 LHS = ImpCastExprToType(LHS.take(), incompatTy, CK_BitCast);
5106 RHS = ImpCastExprToType(RHS.take(), incompatTy, CK_BitCast);
Fariborz Jahaniana430f712009-12-10 19:47:41 +00005107 return incompatTy;
5108 }
5109 // The object pointer types are compatible.
John Wiegley01296292011-04-08 18:41:53 +00005110 LHS = ImpCastExprToType(LHS.take(), compositeType, CK_BitCast);
5111 RHS = ImpCastExprToType(RHS.take(), compositeType, CK_BitCast);
Fariborz Jahaniana430f712009-12-10 19:47:41 +00005112 return compositeType;
5113 }
5114 // Check Objective-C object pointer types and 'void *'
5115 if (LHSTy->isVoidPointerType() && RHSTy->isObjCObjectPointerType()) {
David Blaikiebbafb8a2012-03-11 07:00:24 +00005116 if (getLangOpts().ObjCAutoRefCount) {
Eli Friedman8a78a582012-02-25 00:23:44 +00005117 // ARC forbids the implicit conversion of object pointers to 'void *',
5118 // so these types are not compatible.
5119 Diag(QuestionLoc, diag::err_cond_voidptr_arc) << LHSTy << RHSTy
5120 << LHS.get()->getSourceRange() << RHS.get()->getSourceRange();
5121 LHS = RHS = true;
5122 return QualType();
5123 }
Fariborz Jahaniana430f712009-12-10 19:47:41 +00005124 QualType lhptee = LHSTy->getAs<PointerType>()->getPointeeType();
5125 QualType rhptee = RHSTy->getAs<ObjCObjectPointerType>()->getPointeeType();
5126 QualType destPointee
5127 = Context.getQualifiedType(lhptee, rhptee.getQualifiers());
5128 QualType destType = Context.getPointerType(destPointee);
5129 // Add qualifiers if necessary.
John Wiegley01296292011-04-08 18:41:53 +00005130 LHS = ImpCastExprToType(LHS.take(), destType, CK_NoOp);
Fariborz Jahaniana430f712009-12-10 19:47:41 +00005131 // Promote to void*.
John Wiegley01296292011-04-08 18:41:53 +00005132 RHS = ImpCastExprToType(RHS.take(), destType, CK_BitCast);
Fariborz Jahaniana430f712009-12-10 19:47:41 +00005133 return destType;
5134 }
5135 if (LHSTy->isObjCObjectPointerType() && RHSTy->isVoidPointerType()) {
David Blaikiebbafb8a2012-03-11 07:00:24 +00005136 if (getLangOpts().ObjCAutoRefCount) {
Eli Friedman8a78a582012-02-25 00:23:44 +00005137 // ARC forbids the implicit conversion of object pointers to 'void *',
5138 // so these types are not compatible.
5139 Diag(QuestionLoc, diag::err_cond_voidptr_arc) << LHSTy << RHSTy
5140 << LHS.get()->getSourceRange() << RHS.get()->getSourceRange();
5141 LHS = RHS = true;
5142 return QualType();
5143 }
Fariborz Jahaniana430f712009-12-10 19:47:41 +00005144 QualType lhptee = LHSTy->getAs<ObjCObjectPointerType>()->getPointeeType();
5145 QualType rhptee = RHSTy->getAs<PointerType>()->getPointeeType();
5146 QualType destPointee
5147 = Context.getQualifiedType(rhptee, lhptee.getQualifiers());
5148 QualType destType = Context.getPointerType(destPointee);
5149 // Add qualifiers if necessary.
John Wiegley01296292011-04-08 18:41:53 +00005150 RHS = ImpCastExprToType(RHS.take(), destType, CK_NoOp);
Fariborz Jahaniana430f712009-12-10 19:47:41 +00005151 // Promote to void*.
John Wiegley01296292011-04-08 18:41:53 +00005152 LHS = ImpCastExprToType(LHS.take(), destType, CK_BitCast);
Fariborz Jahaniana430f712009-12-10 19:47:41 +00005153 return destType;
5154 }
5155 return QualType();
5156}
5157
Chandler Carruthb00e8c02011-06-16 01:05:14 +00005158/// SuggestParentheses - Emit a note with a fixit hint that wraps
Hans Wennborgcf9bac42011-06-03 18:00:36 +00005159/// ParenRange in parentheses.
5160static void SuggestParentheses(Sema &Self, SourceLocation Loc,
Chandler Carruthb00e8c02011-06-16 01:05:14 +00005161 const PartialDiagnostic &Note,
5162 SourceRange ParenRange) {
5163 SourceLocation EndLoc = Self.PP.getLocForEndOfToken(ParenRange.getEnd());
5164 if (ParenRange.getBegin().isFileID() && ParenRange.getEnd().isFileID() &&
5165 EndLoc.isValid()) {
5166 Self.Diag(Loc, Note)
5167 << FixItHint::CreateInsertion(ParenRange.getBegin(), "(")
5168 << FixItHint::CreateInsertion(EndLoc, ")");
5169 } else {
5170 // We can't display the parentheses, so just show the bare note.
5171 Self.Diag(Loc, Note) << ParenRange;
Hans Wennborgcf9bac42011-06-03 18:00:36 +00005172 }
Hans Wennborgcf9bac42011-06-03 18:00:36 +00005173}
5174
5175static bool IsArithmeticOp(BinaryOperatorKind Opc) {
5176 return Opc >= BO_Mul && Opc <= BO_Shr;
5177}
5178
Hans Wennborgde2e67e2011-06-09 17:06:51 +00005179/// IsArithmeticBinaryExpr - Returns true if E is an arithmetic binary
5180/// expression, either using a built-in or overloaded operator,
Richard Trieud33e46e2011-09-06 20:06:39 +00005181/// and sets *OpCode to the opcode and *RHSExprs to the right-hand side
5182/// expression.
Hans Wennborgde2e67e2011-06-09 17:06:51 +00005183static bool IsArithmeticBinaryExpr(Expr *E, BinaryOperatorKind *Opcode,
Richard Trieud33e46e2011-09-06 20:06:39 +00005184 Expr **RHSExprs) {
Hans Wennborgbe207b32011-09-12 12:07:30 +00005185 // Don't strip parenthesis: we should not warn if E is in parenthesis.
5186 E = E->IgnoreImpCasts();
Hans Wennborgde2e67e2011-06-09 17:06:51 +00005187 E = E->IgnoreConversionOperator();
Hans Wennborgbe207b32011-09-12 12:07:30 +00005188 E = E->IgnoreImpCasts();
Hans Wennborgde2e67e2011-06-09 17:06:51 +00005189
5190 // Built-in binary operator.
5191 if (BinaryOperator *OP = dyn_cast<BinaryOperator>(E)) {
5192 if (IsArithmeticOp(OP->getOpcode())) {
5193 *Opcode = OP->getOpcode();
Richard Trieud33e46e2011-09-06 20:06:39 +00005194 *RHSExprs = OP->getRHS();
Hans Wennborgde2e67e2011-06-09 17:06:51 +00005195 return true;
5196 }
5197 }
5198
5199 // Overloaded operator.
5200 if (CXXOperatorCallExpr *Call = dyn_cast<CXXOperatorCallExpr>(E)) {
5201 if (Call->getNumArgs() != 2)
5202 return false;
5203
5204 // Make sure this is really a binary operator that is safe to pass into
5205 // BinaryOperator::getOverloadedOpcode(), e.g. it's not a subscript op.
5206 OverloadedOperatorKind OO = Call->getOperator();
5207 if (OO < OO_Plus || OO > OO_Arrow)
5208 return false;
5209
5210 BinaryOperatorKind OpKind = BinaryOperator::getOverloadedOpcode(OO);
5211 if (IsArithmeticOp(OpKind)) {
5212 *Opcode = OpKind;
Richard Trieud33e46e2011-09-06 20:06:39 +00005213 *RHSExprs = Call->getArg(1);
Hans Wennborgde2e67e2011-06-09 17:06:51 +00005214 return true;
5215 }
5216 }
5217
5218 return false;
5219}
5220
Hans Wennborgcf9bac42011-06-03 18:00:36 +00005221static bool IsLogicOp(BinaryOperatorKind Opc) {
5222 return (Opc >= BO_LT && Opc <= BO_NE) || (Opc >= BO_LAnd && Opc <= BO_LOr);
5223}
5224
Hans Wennborgde2e67e2011-06-09 17:06:51 +00005225/// ExprLooksBoolean - Returns true if E looks boolean, i.e. it has boolean type
5226/// or is a logical expression such as (x==y) which has int type, but is
5227/// commonly interpreted as boolean.
5228static bool ExprLooksBoolean(Expr *E) {
5229 E = E->IgnoreParenImpCasts();
5230
5231 if (E->getType()->isBooleanType())
5232 return true;
5233 if (BinaryOperator *OP = dyn_cast<BinaryOperator>(E))
5234 return IsLogicOp(OP->getOpcode());
5235 if (UnaryOperator *OP = dyn_cast<UnaryOperator>(E))
5236 return OP->getOpcode() == UO_LNot;
5237
5238 return false;
5239}
5240
Hans Wennborgcf9bac42011-06-03 18:00:36 +00005241/// DiagnoseConditionalPrecedence - Emit a warning when a conditional operator
5242/// and binary operator are mixed in a way that suggests the programmer assumed
5243/// the conditional operator has higher precedence, for example:
5244/// "int x = a + someBinaryCondition ? 1 : 2".
5245static void DiagnoseConditionalPrecedence(Sema &Self,
5246 SourceLocation OpLoc,
Chandler Carruth08dc2ba2011-06-16 01:05:08 +00005247 Expr *Condition,
Richard Trieud33e46e2011-09-06 20:06:39 +00005248 Expr *LHSExpr,
5249 Expr *RHSExpr) {
Hans Wennborgde2e67e2011-06-09 17:06:51 +00005250 BinaryOperatorKind CondOpcode;
5251 Expr *CondRHS;
Hans Wennborgcf9bac42011-06-03 18:00:36 +00005252
Chandler Carruth08dc2ba2011-06-16 01:05:08 +00005253 if (!IsArithmeticBinaryExpr(Condition, &CondOpcode, &CondRHS))
Hans Wennborgde2e67e2011-06-09 17:06:51 +00005254 return;
5255 if (!ExprLooksBoolean(CondRHS))
5256 return;
Hans Wennborgcf9bac42011-06-03 18:00:36 +00005257
Hans Wennborgde2e67e2011-06-09 17:06:51 +00005258 // The condition is an arithmetic binary expression, with a right-
5259 // hand side that looks boolean, so warn.
Hans Wennborgcf9bac42011-06-03 18:00:36 +00005260
Chandler Carruthb00e8c02011-06-16 01:05:14 +00005261 Self.Diag(OpLoc, diag::warn_precedence_conditional)
Chandler Carruth08dc2ba2011-06-16 01:05:08 +00005262 << Condition->getSourceRange()
Hans Wennborgde2e67e2011-06-09 17:06:51 +00005263 << BinaryOperator::getOpcodeStr(CondOpcode);
Hans Wennborgcf9bac42011-06-03 18:00:36 +00005264
Chandler Carruthb00e8c02011-06-16 01:05:14 +00005265 SuggestParentheses(Self, OpLoc,
5266 Self.PDiag(diag::note_precedence_conditional_silence)
5267 << BinaryOperator::getOpcodeStr(CondOpcode),
5268 SourceRange(Condition->getLocStart(), Condition->getLocEnd()));
Chandler Carruthf51c5a52011-06-21 23:04:18 +00005269
5270 SuggestParentheses(Self, OpLoc,
5271 Self.PDiag(diag::note_precedence_conditional_first),
Richard Trieud33e46e2011-09-06 20:06:39 +00005272 SourceRange(CondRHS->getLocStart(), RHSExpr->getLocEnd()));
Hans Wennborgcf9bac42011-06-03 18:00:36 +00005273}
5274
Steve Naroff83895f72007-09-16 03:34:24 +00005275/// ActOnConditionalOp - Parse a ?: operation. Note that 'LHS' may be null
Chris Lattnere168f762006-11-10 05:29:30 +00005276/// in the case of a the GNU conditional expr extension.
John McCalldadc5752010-08-24 06:29:42 +00005277ExprResult Sema::ActOnConditionalOp(SourceLocation QuestionLoc,
John McCallc07a0c72011-02-17 10:25:35 +00005278 SourceLocation ColonLoc,
5279 Expr *CondExpr, Expr *LHSExpr,
5280 Expr *RHSExpr) {
Chris Lattner2ab40a62007-11-26 01:40:58 +00005281 // If this is the gnu "x ?: y" extension, analyze the types as though the LHS
5282 // was the condition.
John McCallc07a0c72011-02-17 10:25:35 +00005283 OpaqueValueExpr *opaqueValue = 0;
5284 Expr *commonExpr = 0;
5285 if (LHSExpr == 0) {
5286 commonExpr = CondExpr;
5287
5288 // We usually want to apply unary conversions *before* saving, except
5289 // in the special case of a C++ l-value conditional.
David Blaikiebbafb8a2012-03-11 07:00:24 +00005290 if (!(getLangOpts().CPlusPlus
John McCallc07a0c72011-02-17 10:25:35 +00005291 && !commonExpr->isTypeDependent()
5292 && commonExpr->getValueKind() == RHSExpr->getValueKind()
5293 && commonExpr->isGLValue()
5294 && commonExpr->isOrdinaryOrBitFieldObject()
5295 && RHSExpr->isOrdinaryOrBitFieldObject()
5296 && Context.hasSameType(commonExpr->getType(), RHSExpr->getType()))) {
John Wiegley01296292011-04-08 18:41:53 +00005297 ExprResult commonRes = UsualUnaryConversions(commonExpr);
5298 if (commonRes.isInvalid())
5299 return ExprError();
5300 commonExpr = commonRes.take();
John McCallc07a0c72011-02-17 10:25:35 +00005301 }
5302
5303 opaqueValue = new (Context) OpaqueValueExpr(commonExpr->getExprLoc(),
5304 commonExpr->getType(),
5305 commonExpr->getValueKind(),
Douglas Gregor2d5aea02012-02-23 22:17:26 +00005306 commonExpr->getObjectKind(),
5307 commonExpr);
John McCallc07a0c72011-02-17 10:25:35 +00005308 LHSExpr = CondExpr = opaqueValue;
Fariborz Jahanianc6bf0bd2010-08-31 18:02:20 +00005309 }
Sebastian Redlb5d49352009-01-19 22:31:54 +00005310
John McCall7decc9e2010-11-18 06:31:45 +00005311 ExprValueKind VK = VK_RValue;
John McCall4bc41ae2010-11-18 19:01:18 +00005312 ExprObjectKind OK = OK_Ordinary;
John Wiegley01296292011-04-08 18:41:53 +00005313 ExprResult Cond = Owned(CondExpr), LHS = Owned(LHSExpr), RHS = Owned(RHSExpr);
5314 QualType result = CheckConditionalOperands(Cond, LHS, RHS,
John McCallc07a0c72011-02-17 10:25:35 +00005315 VK, OK, QuestionLoc);
John Wiegley01296292011-04-08 18:41:53 +00005316 if (result.isNull() || Cond.isInvalid() || LHS.isInvalid() ||
5317 RHS.isInvalid())
Sebastian Redlb5d49352009-01-19 22:31:54 +00005318 return ExprError();
5319
Hans Wennborgcf9bac42011-06-03 18:00:36 +00005320 DiagnoseConditionalPrecedence(*this, QuestionLoc, Cond.get(), LHS.get(),
5321 RHS.get());
5322
John McCallc07a0c72011-02-17 10:25:35 +00005323 if (!commonExpr)
John Wiegley01296292011-04-08 18:41:53 +00005324 return Owned(new (Context) ConditionalOperator(Cond.take(), QuestionLoc,
5325 LHS.take(), ColonLoc,
5326 RHS.take(), result, VK, OK));
John McCallc07a0c72011-02-17 10:25:35 +00005327
5328 return Owned(new (Context)
John Wiegley01296292011-04-08 18:41:53 +00005329 BinaryConditionalOperator(commonExpr, opaqueValue, Cond.take(), LHS.take(),
Richard Trieucfc491d2011-08-02 04:35:43 +00005330 RHS.take(), QuestionLoc, ColonLoc, result, VK,
5331 OK));
Chris Lattnere168f762006-11-10 05:29:30 +00005332}
5333
John McCallaba90822011-01-31 23:13:11 +00005334// checkPointerTypesForAssignment - This is a very tricky routine (despite
Mike Stump4e1f26a2009-02-19 03:04:26 +00005335// being closely modeled after the C99 spec:-). The odd characteristic of this
Steve Naroff3f597292007-05-11 22:18:03 +00005336// routine is it effectively iqnores the qualifiers on the top level pointee.
5337// This circumvents the usual type rules specified in 6.2.7p1 & 6.7.5.[1-3].
5338// FIXME: add a couple examples in this comment.
John McCallaba90822011-01-31 23:13:11 +00005339static Sema::AssignConvertType
Richard Trieua871b972011-09-06 20:21:22 +00005340checkPointerTypesForAssignment(Sema &S, QualType LHSType, QualType RHSType) {
5341 assert(LHSType.isCanonical() && "LHS not canonicalized!");
5342 assert(RHSType.isCanonical() && "RHS not canonicalized!");
Mike Stump4e1f26a2009-02-19 03:04:26 +00005343
Steve Naroff1f4d7272007-05-11 04:00:31 +00005344 // get the "pointed to" type (ignoring qualifiers at the top level)
John McCall4fff8f62011-02-01 00:10:29 +00005345 const Type *lhptee, *rhptee;
5346 Qualifiers lhq, rhq;
Richard Trieua871b972011-09-06 20:21:22 +00005347 llvm::tie(lhptee, lhq) = cast<PointerType>(LHSType)->getPointeeType().split();
5348 llvm::tie(rhptee, rhq) = cast<PointerType>(RHSType)->getPointeeType().split();
Mike Stump4e1f26a2009-02-19 03:04:26 +00005349
John McCallaba90822011-01-31 23:13:11 +00005350 Sema::AssignConvertType ConvTy = Sema::Compatible;
Mike Stump4e1f26a2009-02-19 03:04:26 +00005351
5352 // C99 6.5.16.1p1: This following citation is common to constraints
5353 // 3 & 4 (below). ...and the type *pointed to* by the left has all the
5354 // qualifiers of the type *pointed to* by the right;
John McCall4fff8f62011-02-01 00:10:29 +00005355 Qualifiers lq;
5356
John McCall31168b02011-06-15 23:02:42 +00005357 // As a special case, 'non-__weak A *' -> 'non-__weak const *' is okay.
5358 if (lhq.getObjCLifetime() != rhq.getObjCLifetime() &&
5359 lhq.compatiblyIncludesObjCLifetime(rhq)) {
5360 // Ignore lifetime for further calculation.
5361 lhq.removeObjCLifetime();
5362 rhq.removeObjCLifetime();
5363 }
5364
John McCall4fff8f62011-02-01 00:10:29 +00005365 if (!lhq.compatiblyIncludes(rhq)) {
5366 // Treat address-space mismatches as fatal. TODO: address subspaces
5367 if (lhq.getAddressSpace() != rhq.getAddressSpace())
5368 ConvTy = Sema::IncompatiblePointerDiscardsQualifiers;
5369
John McCall31168b02011-06-15 23:02:42 +00005370 // It's okay to add or remove GC or lifetime qualifiers when converting to
John McCall78535952011-03-26 02:56:45 +00005371 // and from void*.
John McCall18ce25e2012-02-08 00:46:36 +00005372 else if (lhq.withoutObjCGCAttr().withoutObjCLifetime()
John McCall31168b02011-06-15 23:02:42 +00005373 .compatiblyIncludes(
John McCall18ce25e2012-02-08 00:46:36 +00005374 rhq.withoutObjCGCAttr().withoutObjCLifetime())
John McCall78535952011-03-26 02:56:45 +00005375 && (lhptee->isVoidType() || rhptee->isVoidType()))
5376 ; // keep old
5377
John McCall31168b02011-06-15 23:02:42 +00005378 // Treat lifetime mismatches as fatal.
5379 else if (lhq.getObjCLifetime() != rhq.getObjCLifetime())
5380 ConvTy = Sema::IncompatiblePointerDiscardsQualifiers;
5381
John McCall4fff8f62011-02-01 00:10:29 +00005382 // For GCC compatibility, other qualifier mismatches are treated
5383 // as still compatible in C.
5384 else ConvTy = Sema::CompatiblePointerDiscardsQualifiers;
5385 }
Steve Naroff3f597292007-05-11 22:18:03 +00005386
Mike Stump4e1f26a2009-02-19 03:04:26 +00005387 // C99 6.5.16.1p1 (constraint 4): If one operand is a pointer to an object or
5388 // incomplete type and the other is a pointer to a qualified or unqualified
Steve Naroff3f597292007-05-11 22:18:03 +00005389 // version of void...
Chris Lattner0a788432008-01-03 22:56:36 +00005390 if (lhptee->isVoidType()) {
Chris Lattnerb3a176d2008-04-02 06:59:01 +00005391 if (rhptee->isIncompleteOrObjectType())
Chris Lattner9bad62c2008-01-04 18:04:52 +00005392 return ConvTy;
Mike Stump4e1f26a2009-02-19 03:04:26 +00005393
Chris Lattner0a788432008-01-03 22:56:36 +00005394 // As an extension, we allow cast to/from void* to function pointer.
Chris Lattnerb3a176d2008-04-02 06:59:01 +00005395 assert(rhptee->isFunctionType());
John McCallaba90822011-01-31 23:13:11 +00005396 return Sema::FunctionVoidPointer;
Chris Lattner0a788432008-01-03 22:56:36 +00005397 }
Mike Stump4e1f26a2009-02-19 03:04:26 +00005398
Chris Lattner0a788432008-01-03 22:56:36 +00005399 if (rhptee->isVoidType()) {
Chris Lattnerb3a176d2008-04-02 06:59:01 +00005400 if (lhptee->isIncompleteOrObjectType())
Chris Lattner9bad62c2008-01-04 18:04:52 +00005401 return ConvTy;
Chris Lattner0a788432008-01-03 22:56:36 +00005402
5403 // As an extension, we allow cast to/from void* to function pointer.
Chris Lattnerb3a176d2008-04-02 06:59:01 +00005404 assert(lhptee->isFunctionType());
John McCallaba90822011-01-31 23:13:11 +00005405 return Sema::FunctionVoidPointer;
Chris Lattner0a788432008-01-03 22:56:36 +00005406 }
John McCall4fff8f62011-02-01 00:10:29 +00005407
Mike Stump4e1f26a2009-02-19 03:04:26 +00005408 // C99 6.5.16.1p1 (constraint 3): both operands are pointers to qualified or
Steve Naroff3f597292007-05-11 22:18:03 +00005409 // unqualified versions of compatible types, ...
John McCall4fff8f62011-02-01 00:10:29 +00005410 QualType ltrans = QualType(lhptee, 0), rtrans = QualType(rhptee, 0);
5411 if (!S.Context.typesAreCompatible(ltrans, rtrans)) {
Eli Friedman80160bd2009-03-22 23:59:44 +00005412 // Check if the pointee types are compatible ignoring the sign.
5413 // We explicitly check for char so that we catch "char" vs
5414 // "unsigned char" on systems where "char" is unsigned.
Chris Lattnerec3a1562009-10-17 20:33:28 +00005415 if (lhptee->isCharType())
John McCall4fff8f62011-02-01 00:10:29 +00005416 ltrans = S.Context.UnsignedCharTy;
Douglas Gregor5cc2c8b2010-07-23 15:58:24 +00005417 else if (lhptee->hasSignedIntegerRepresentation())
John McCall4fff8f62011-02-01 00:10:29 +00005418 ltrans = S.Context.getCorrespondingUnsignedType(ltrans);
Kovarththanan Rajaratnamba2c6522010-03-13 10:17:05 +00005419
Chris Lattnerec3a1562009-10-17 20:33:28 +00005420 if (rhptee->isCharType())
John McCall4fff8f62011-02-01 00:10:29 +00005421 rtrans = S.Context.UnsignedCharTy;
Douglas Gregor5cc2c8b2010-07-23 15:58:24 +00005422 else if (rhptee->hasSignedIntegerRepresentation())
John McCall4fff8f62011-02-01 00:10:29 +00005423 rtrans = S.Context.getCorrespondingUnsignedType(rtrans);
Chris Lattnerec3a1562009-10-17 20:33:28 +00005424
John McCall4fff8f62011-02-01 00:10:29 +00005425 if (ltrans == rtrans) {
Eli Friedman80160bd2009-03-22 23:59:44 +00005426 // Types are compatible ignoring the sign. Qualifier incompatibility
5427 // takes priority over sign incompatibility because the sign
5428 // warning can be disabled.
John McCallaba90822011-01-31 23:13:11 +00005429 if (ConvTy != Sema::Compatible)
Eli Friedman80160bd2009-03-22 23:59:44 +00005430 return ConvTy;
John McCall4fff8f62011-02-01 00:10:29 +00005431
John McCallaba90822011-01-31 23:13:11 +00005432 return Sema::IncompatiblePointerSign;
Eli Friedman80160bd2009-03-22 23:59:44 +00005433 }
Kovarththanan Rajaratnamba2c6522010-03-13 10:17:05 +00005434
Fariborz Jahaniand7aa9d82009-11-07 20:20:40 +00005435 // If we are a multi-level pointer, it's possible that our issue is simply
5436 // one of qualification - e.g. char ** -> const char ** is not allowed. If
5437 // the eventual target type is the same and the pointers have the same
5438 // level of indirection, this must be the issue.
John McCallaba90822011-01-31 23:13:11 +00005439 if (isa<PointerType>(lhptee) && isa<PointerType>(rhptee)) {
Fariborz Jahaniand7aa9d82009-11-07 20:20:40 +00005440 do {
John McCall4fff8f62011-02-01 00:10:29 +00005441 lhptee = cast<PointerType>(lhptee)->getPointeeType().getTypePtr();
5442 rhptee = cast<PointerType>(rhptee)->getPointeeType().getTypePtr();
John McCallaba90822011-01-31 23:13:11 +00005443 } while (isa<PointerType>(lhptee) && isa<PointerType>(rhptee));
Kovarththanan Rajaratnamba2c6522010-03-13 10:17:05 +00005444
John McCall4fff8f62011-02-01 00:10:29 +00005445 if (lhptee == rhptee)
John McCallaba90822011-01-31 23:13:11 +00005446 return Sema::IncompatibleNestedPointerQualifiers;
Fariborz Jahaniand7aa9d82009-11-07 20:20:40 +00005447 }
Kovarththanan Rajaratnamba2c6522010-03-13 10:17:05 +00005448
Eli Friedman80160bd2009-03-22 23:59:44 +00005449 // General pointer incompatibility takes priority over qualifiers.
John McCallaba90822011-01-31 23:13:11 +00005450 return Sema::IncompatiblePointer;
Eli Friedman80160bd2009-03-22 23:59:44 +00005451 }
David Blaikiebbafb8a2012-03-11 07:00:24 +00005452 if (!S.getLangOpts().CPlusPlus &&
Fariborz Jahanian48c69102011-10-05 00:05:34 +00005453 S.IsNoReturnConversion(ltrans, rtrans, ltrans))
5454 return Sema::IncompatiblePointer;
Chris Lattner9bad62c2008-01-04 18:04:52 +00005455 return ConvTy;
Steve Naroff1f4d7272007-05-11 04:00:31 +00005456}
5457
John McCallaba90822011-01-31 23:13:11 +00005458/// checkBlockPointerTypesForAssignment - This routine determines whether two
Steve Naroff081c7422008-09-04 15:10:53 +00005459/// block pointer types are compatible or whether a block and normal pointer
5460/// are compatible. It is more restrict than comparing two function pointer
5461// types.
John McCallaba90822011-01-31 23:13:11 +00005462static Sema::AssignConvertType
Richard Trieua871b972011-09-06 20:21:22 +00005463checkBlockPointerTypesForAssignment(Sema &S, QualType LHSType,
5464 QualType RHSType) {
5465 assert(LHSType.isCanonical() && "LHS not canonicalized!");
5466 assert(RHSType.isCanonical() && "RHS not canonicalized!");
John McCallaba90822011-01-31 23:13:11 +00005467
Steve Naroff081c7422008-09-04 15:10:53 +00005468 QualType lhptee, rhptee;
Mike Stump4e1f26a2009-02-19 03:04:26 +00005469
Steve Naroff081c7422008-09-04 15:10:53 +00005470 // get the "pointed to" type (ignoring qualifiers at the top level)
Richard Trieua871b972011-09-06 20:21:22 +00005471 lhptee = cast<BlockPointerType>(LHSType)->getPointeeType();
5472 rhptee = cast<BlockPointerType>(RHSType)->getPointeeType();
Mike Stump4e1f26a2009-02-19 03:04:26 +00005473
John McCallaba90822011-01-31 23:13:11 +00005474 // In C++, the types have to match exactly.
David Blaikiebbafb8a2012-03-11 07:00:24 +00005475 if (S.getLangOpts().CPlusPlus)
John McCallaba90822011-01-31 23:13:11 +00005476 return Sema::IncompatibleBlockPointer;
Mike Stump4e1f26a2009-02-19 03:04:26 +00005477
John McCallaba90822011-01-31 23:13:11 +00005478 Sema::AssignConvertType ConvTy = Sema::Compatible;
Mike Stump4e1f26a2009-02-19 03:04:26 +00005479
Steve Naroff081c7422008-09-04 15:10:53 +00005480 // For blocks we enforce that qualifiers are identical.
John McCallaba90822011-01-31 23:13:11 +00005481 if (lhptee.getLocalQualifiers() != rhptee.getLocalQualifiers())
5482 ConvTy = Sema::CompatiblePointerDiscardsQualifiers;
Mike Stump4e1f26a2009-02-19 03:04:26 +00005483
Richard Trieua871b972011-09-06 20:21:22 +00005484 if (!S.Context.typesAreBlockPointerCompatible(LHSType, RHSType))
John McCallaba90822011-01-31 23:13:11 +00005485 return Sema::IncompatibleBlockPointer;
5486
Steve Naroff081c7422008-09-04 15:10:53 +00005487 return ConvTy;
5488}
5489
John McCallaba90822011-01-31 23:13:11 +00005490/// checkObjCPointerTypesForAssignment - Compares two objective-c pointer types
Fariborz Jahanian410f2eb2009-12-08 18:24:49 +00005491/// for assignment compatibility.
John McCallaba90822011-01-31 23:13:11 +00005492static Sema::AssignConvertType
Richard Trieua871b972011-09-06 20:21:22 +00005493checkObjCPointerTypesForAssignment(Sema &S, QualType LHSType,
5494 QualType RHSType) {
5495 assert(LHSType.isCanonical() && "LHS was not canonicalized!");
5496 assert(RHSType.isCanonical() && "RHS was not canonicalized!");
John McCallaba90822011-01-31 23:13:11 +00005497
Richard Trieua871b972011-09-06 20:21:22 +00005498 if (LHSType->isObjCBuiltinType()) {
Fariborz Jahaniand5bb8cb2010-03-19 18:06:10 +00005499 // Class is not compatible with ObjC object pointers.
Richard Trieua871b972011-09-06 20:21:22 +00005500 if (LHSType->isObjCClassType() && !RHSType->isObjCBuiltinType() &&
5501 !RHSType->isObjCQualifiedClassType())
John McCallaba90822011-01-31 23:13:11 +00005502 return Sema::IncompatiblePointer;
5503 return Sema::Compatible;
Fariborz Jahaniand5bb8cb2010-03-19 18:06:10 +00005504 }
Richard Trieua871b972011-09-06 20:21:22 +00005505 if (RHSType->isObjCBuiltinType()) {
Richard Trieua871b972011-09-06 20:21:22 +00005506 if (RHSType->isObjCClassType() && !LHSType->isObjCBuiltinType() &&
5507 !LHSType->isObjCQualifiedClassType())
Fariborz Jahaniand923eb02011-09-15 20:40:18 +00005508 return Sema::IncompatiblePointer;
John McCallaba90822011-01-31 23:13:11 +00005509 return Sema::Compatible;
Fariborz Jahaniand5bb8cb2010-03-19 18:06:10 +00005510 }
Richard Trieua871b972011-09-06 20:21:22 +00005511 QualType lhptee = LHSType->getAs<ObjCObjectPointerType>()->getPointeeType();
5512 QualType rhptee = RHSType->getAs<ObjCObjectPointerType>()->getPointeeType();
Kovarththanan Rajaratnamba2c6522010-03-13 10:17:05 +00005513
Fariborz Jahaniane74d47e2012-01-12 22:12:08 +00005514 if (!lhptee.isAtLeastAsQualifiedAs(rhptee) &&
5515 // make an exception for id<P>
5516 !LHSType->isObjCQualifiedIdType())
John McCallaba90822011-01-31 23:13:11 +00005517 return Sema::CompatiblePointerDiscardsQualifiers;
5518
Richard Trieua871b972011-09-06 20:21:22 +00005519 if (S.Context.typesAreCompatible(LHSType, RHSType))
John McCallaba90822011-01-31 23:13:11 +00005520 return Sema::Compatible;
Richard Trieua871b972011-09-06 20:21:22 +00005521 if (LHSType->isObjCQualifiedIdType() || RHSType->isObjCQualifiedIdType())
John McCallaba90822011-01-31 23:13:11 +00005522 return Sema::IncompatibleObjCQualifiedId;
5523 return Sema::IncompatiblePointer;
Fariborz Jahanian410f2eb2009-12-08 18:24:49 +00005524}
5525
John McCall29600e12010-11-16 02:32:08 +00005526Sema::AssignConvertType
Douglas Gregorc03a1082011-01-28 02:26:04 +00005527Sema::CheckAssignmentConstraints(SourceLocation Loc,
Richard Trieua871b972011-09-06 20:21:22 +00005528 QualType LHSType, QualType RHSType) {
John McCall29600e12010-11-16 02:32:08 +00005529 // Fake up an opaque expression. We don't actually care about what
5530 // cast operations are required, so if CheckAssignmentConstraints
5531 // adds casts to this they'll be wasted, but fortunately that doesn't
5532 // usually happen on valid code.
Richard Trieua871b972011-09-06 20:21:22 +00005533 OpaqueValueExpr RHSExpr(Loc, RHSType, VK_RValue);
5534 ExprResult RHSPtr = &RHSExpr;
John McCall29600e12010-11-16 02:32:08 +00005535 CastKind K = CK_Invalid;
5536
Richard Trieua871b972011-09-06 20:21:22 +00005537 return CheckAssignmentConstraints(LHSType, RHSPtr, K);
John McCall29600e12010-11-16 02:32:08 +00005538}
5539
Mike Stump4e1f26a2009-02-19 03:04:26 +00005540/// CheckAssignmentConstraints (C99 6.5.16) - This routine currently
5541/// has code to accommodate several GCC extensions when type checking
Steve Naroff17f76e02007-05-03 21:03:48 +00005542/// pointers. Here are some objectionable examples that GCC considers warnings:
5543///
5544/// int a, *pint;
5545/// short *pshort;
5546/// struct foo *pfoo;
5547///
5548/// pint = pshort; // warning: assignment from incompatible pointer type
5549/// a = pint; // warning: assignment makes integer from pointer without a cast
5550/// pint = a; // warning: assignment makes pointer from integer without a cast
5551/// pint = pfoo; // warning: assignment from incompatible pointer type
5552///
5553/// As a result, the code for dealing with pointers is more complex than the
Mike Stump4e1f26a2009-02-19 03:04:26 +00005554/// C99 spec dictates.
Steve Naroff17f76e02007-05-03 21:03:48 +00005555///
John McCall8cb679e2010-11-15 09:13:47 +00005556/// Sets 'Kind' for any result kind except Incompatible.
Chris Lattner9bad62c2008-01-04 18:04:52 +00005557Sema::AssignConvertType
Richard Trieude4958f2011-09-06 20:30:53 +00005558Sema::CheckAssignmentConstraints(QualType LHSType, ExprResult &RHS,
John McCall8cb679e2010-11-15 09:13:47 +00005559 CastKind &Kind) {
Richard Trieude4958f2011-09-06 20:30:53 +00005560 QualType RHSType = RHS.get()->getType();
5561 QualType OrigLHSType = LHSType;
John McCall29600e12010-11-16 02:32:08 +00005562
Chris Lattnera52c2f22008-01-04 23:18:45 +00005563 // Get canonical types. We're not formatting these types, just comparing
5564 // them.
Richard Trieude4958f2011-09-06 20:30:53 +00005565 LHSType = Context.getCanonicalType(LHSType).getUnqualifiedType();
5566 RHSType = Context.getCanonicalType(RHSType).getUnqualifiedType();
Eli Friedman3360d892008-05-30 18:07:22 +00005567
Eli Friedman0dfb8892011-10-06 23:00:33 +00005568
John McCalle5255932011-01-31 22:28:28 +00005569 // Common case: no conversion required.
Richard Trieude4958f2011-09-06 20:30:53 +00005570 if (LHSType == RHSType) {
John McCall8cb679e2010-11-15 09:13:47 +00005571 Kind = CK_NoOp;
John McCall8cb679e2010-11-15 09:13:47 +00005572 return Compatible;
David Chisnall9f57c292009-08-17 16:35:33 +00005573 }
5574
Eli Friedman93ee5ca2012-06-16 02:19:17 +00005575 // If we have an atomic type, try a non-atomic assignment, then just add an
5576 // atomic qualification step.
David Chisnallfa35df62012-01-16 17:27:18 +00005577 if (const AtomicType *AtomicTy = dyn_cast<AtomicType>(LHSType)) {
Eli Friedman93ee5ca2012-06-16 02:19:17 +00005578 Sema::AssignConvertType result =
5579 CheckAssignmentConstraints(AtomicTy->getValueType(), RHS, Kind);
5580 if (result != Compatible)
5581 return result;
5582 if (Kind != CK_NoOp)
5583 RHS = ImpCastExprToType(RHS.take(), AtomicTy->getValueType(), Kind);
5584 Kind = CK_NonAtomicToAtomic;
5585 return Compatible;
David Chisnallfa35df62012-01-16 17:27:18 +00005586 }
5587
Douglas Gregor6b754842008-10-28 00:22:11 +00005588 // If the left-hand side is a reference type, then we are in a
5589 // (rare!) case where we've allowed the use of references in C,
5590 // e.g., as a parameter type in a built-in function. In this case,
5591 // just make sure that the type referenced is compatible with the
5592 // right-hand side type. The caller is responsible for adjusting
Richard Trieude4958f2011-09-06 20:30:53 +00005593 // LHSType so that the resulting expression does not have reference
Douglas Gregor6b754842008-10-28 00:22:11 +00005594 // type.
Richard Trieude4958f2011-09-06 20:30:53 +00005595 if (const ReferenceType *LHSTypeRef = LHSType->getAs<ReferenceType>()) {
5596 if (Context.typesAreCompatible(LHSTypeRef->getPointeeType(), RHSType)) {
John McCall8cb679e2010-11-15 09:13:47 +00005597 Kind = CK_LValueBitCast;
Anders Carlsson24ebce62007-10-12 23:56:29 +00005598 return Compatible;
John McCall8cb679e2010-11-15 09:13:47 +00005599 }
Chris Lattnera52c2f22008-01-04 23:18:45 +00005600 return Incompatible;
Fariborz Jahaniana1e34202007-12-19 17:45:58 +00005601 }
John McCalle5255932011-01-31 22:28:28 +00005602
Nate Begemanbd956c42009-06-28 02:36:38 +00005603 // Allow scalar to ExtVector assignments, and assignments of an ExtVector type
5604 // to the same ExtVector type.
Richard Trieude4958f2011-09-06 20:30:53 +00005605 if (LHSType->isExtVectorType()) {
5606 if (RHSType->isExtVectorType())
John McCall8cb679e2010-11-15 09:13:47 +00005607 return Incompatible;
Richard Trieude4958f2011-09-06 20:30:53 +00005608 if (RHSType->isArithmeticType()) {
John McCall29600e12010-11-16 02:32:08 +00005609 // CK_VectorSplat does T -> vector T, so first cast to the
5610 // element type.
Richard Trieude4958f2011-09-06 20:30:53 +00005611 QualType elType = cast<ExtVectorType>(LHSType)->getElementType();
5612 if (elType != RHSType) {
John McCall9776e432011-10-06 23:25:11 +00005613 Kind = PrepareScalarCast(RHS, elType);
Richard Trieude4958f2011-09-06 20:30:53 +00005614 RHS = ImpCastExprToType(RHS.take(), elType, Kind);
John McCall29600e12010-11-16 02:32:08 +00005615 }
5616 Kind = CK_VectorSplat;
Nate Begemanbd956c42009-06-28 02:36:38 +00005617 return Compatible;
John McCall8cb679e2010-11-15 09:13:47 +00005618 }
Nate Begemanbd956c42009-06-28 02:36:38 +00005619 }
Mike Stump11289f42009-09-09 15:08:12 +00005620
John McCalle5255932011-01-31 22:28:28 +00005621 // Conversions to or from vector type.
Richard Trieude4958f2011-09-06 20:30:53 +00005622 if (LHSType->isVectorType() || RHSType->isVectorType()) {
5623 if (LHSType->isVectorType() && RHSType->isVectorType()) {
Bob Wilson01856f32010-12-02 00:25:15 +00005624 // Allow assignments of an AltiVec vector type to an equivalent GCC
5625 // vector type and vice versa
Richard Trieude4958f2011-09-06 20:30:53 +00005626 if (Context.areCompatibleVectorTypes(LHSType, RHSType)) {
Bob Wilson01856f32010-12-02 00:25:15 +00005627 Kind = CK_BitCast;
5628 return Compatible;
5629 }
5630
Douglas Gregor59e8b3b2010-08-06 10:14:59 +00005631 // If we are allowing lax vector conversions, and LHS and RHS are both
5632 // vectors, the total size only needs to be the same. This is a bitcast;
5633 // no bits are changed but the result type is different.
David Blaikiebbafb8a2012-03-11 07:00:24 +00005634 if (getLangOpts().LaxVectorConversions &&
Richard Trieude4958f2011-09-06 20:30:53 +00005635 (Context.getTypeSize(LHSType) == Context.getTypeSize(RHSType))) {
John McCall3065d042010-11-15 10:08:00 +00005636 Kind = CK_BitCast;
Anders Carlssondb5a9b62009-01-30 23:17:46 +00005637 return IncompatibleVectors;
John McCall8cb679e2010-11-15 09:13:47 +00005638 }
Chris Lattner881a2122008-01-04 23:32:24 +00005639 }
5640 return Incompatible;
Mike Stump4e1f26a2009-02-19 03:04:26 +00005641 }
Eli Friedman3360d892008-05-30 18:07:22 +00005642
John McCalle5255932011-01-31 22:28:28 +00005643 // Arithmetic conversions.
Richard Trieude4958f2011-09-06 20:30:53 +00005644 if (LHSType->isArithmeticType() && RHSType->isArithmeticType() &&
David Blaikiebbafb8a2012-03-11 07:00:24 +00005645 !(getLangOpts().CPlusPlus && LHSType->isEnumeralType())) {
John McCall9776e432011-10-06 23:25:11 +00005646 Kind = PrepareScalarCast(RHS, LHSType);
Steve Naroff98cf3e92007-06-06 18:38:38 +00005647 return Compatible;
John McCall8cb679e2010-11-15 09:13:47 +00005648 }
Eli Friedman3360d892008-05-30 18:07:22 +00005649
John McCalle5255932011-01-31 22:28:28 +00005650 // Conversions to normal pointers.
Richard Trieude4958f2011-09-06 20:30:53 +00005651 if (const PointerType *LHSPointer = dyn_cast<PointerType>(LHSType)) {
John McCalle5255932011-01-31 22:28:28 +00005652 // U* -> T*
Richard Trieude4958f2011-09-06 20:30:53 +00005653 if (isa<PointerType>(RHSType)) {
John McCall8cb679e2010-11-15 09:13:47 +00005654 Kind = CK_BitCast;
Richard Trieude4958f2011-09-06 20:30:53 +00005655 return checkPointerTypesForAssignment(*this, LHSType, RHSType);
John McCall8cb679e2010-11-15 09:13:47 +00005656 }
Mike Stump4e1f26a2009-02-19 03:04:26 +00005657
John McCalle5255932011-01-31 22:28:28 +00005658 // int -> T*
Richard Trieude4958f2011-09-06 20:30:53 +00005659 if (RHSType->isIntegerType()) {
John McCalle5255932011-01-31 22:28:28 +00005660 Kind = CK_IntegralToPointer; // FIXME: null?
5661 return IntToPointer;
Steve Naroff7cae42b2009-07-10 23:34:53 +00005662 }
John McCalle5255932011-01-31 22:28:28 +00005663
5664 // C pointers are not compatible with ObjC object pointers,
5665 // with two exceptions:
Richard Trieude4958f2011-09-06 20:30:53 +00005666 if (isa<ObjCObjectPointerType>(RHSType)) {
John McCalle5255932011-01-31 22:28:28 +00005667 // - conversions to void*
Richard Trieude4958f2011-09-06 20:30:53 +00005668 if (LHSPointer->getPointeeType()->isVoidType()) {
John McCall9320b872011-09-09 05:25:32 +00005669 Kind = CK_BitCast;
John McCalle5255932011-01-31 22:28:28 +00005670 return Compatible;
5671 }
5672
5673 // - conversions from 'Class' to the redefinition type
Richard Trieude4958f2011-09-06 20:30:53 +00005674 if (RHSType->isObjCClassType() &&
5675 Context.hasSameType(LHSType,
Douglas Gregor97673472011-08-11 20:58:55 +00005676 Context.getObjCClassRedefinitionType())) {
John McCall8cb679e2010-11-15 09:13:47 +00005677 Kind = CK_BitCast;
Douglas Gregore7dd1452008-11-27 00:44:28 +00005678 return Compatible;
John McCall8cb679e2010-11-15 09:13:47 +00005679 }
Douglas Gregor486b74e2011-09-27 16:10:05 +00005680
John McCalle5255932011-01-31 22:28:28 +00005681 Kind = CK_BitCast;
5682 return IncompatiblePointer;
5683 }
5684
5685 // U^ -> void*
Richard Trieude4958f2011-09-06 20:30:53 +00005686 if (RHSType->getAs<BlockPointerType>()) {
5687 if (LHSPointer->getPointeeType()->isVoidType()) {
John McCalle5255932011-01-31 22:28:28 +00005688 Kind = CK_BitCast;
Steve Naroff32d072c2008-09-29 18:10:17 +00005689 return Compatible;
John McCall8cb679e2010-11-15 09:13:47 +00005690 }
Steve Naroff32d072c2008-09-29 18:10:17 +00005691 }
John McCalle5255932011-01-31 22:28:28 +00005692
Steve Naroff081c7422008-09-04 15:10:53 +00005693 return Incompatible;
5694 }
5695
John McCalle5255932011-01-31 22:28:28 +00005696 // Conversions to block pointers.
Richard Trieude4958f2011-09-06 20:30:53 +00005697 if (isa<BlockPointerType>(LHSType)) {
John McCalle5255932011-01-31 22:28:28 +00005698 // U^ -> T^
Richard Trieude4958f2011-09-06 20:30:53 +00005699 if (RHSType->isBlockPointerType()) {
John McCall9320b872011-09-09 05:25:32 +00005700 Kind = CK_BitCast;
Richard Trieude4958f2011-09-06 20:30:53 +00005701 return checkBlockPointerTypesForAssignment(*this, LHSType, RHSType);
John McCalle5255932011-01-31 22:28:28 +00005702 }
5703
5704 // int or null -> T^
Richard Trieude4958f2011-09-06 20:30:53 +00005705 if (RHSType->isIntegerType()) {
John McCall8cb679e2010-11-15 09:13:47 +00005706 Kind = CK_IntegralToPointer; // FIXME: null
Eli Friedman8163b7a2009-02-25 04:20:42 +00005707 return IntToBlockPointer;
John McCall8cb679e2010-11-15 09:13:47 +00005708 }
5709
John McCalle5255932011-01-31 22:28:28 +00005710 // id -> T^
David Blaikiebbafb8a2012-03-11 07:00:24 +00005711 if (getLangOpts().ObjC1 && RHSType->isObjCIdType()) {
John McCalle5255932011-01-31 22:28:28 +00005712 Kind = CK_AnyPointerToBlockPointerCast;
Steve Naroff32d072c2008-09-29 18:10:17 +00005713 return Compatible;
John McCalle5255932011-01-31 22:28:28 +00005714 }
Steve Naroff32d072c2008-09-29 18:10:17 +00005715
John McCalle5255932011-01-31 22:28:28 +00005716 // void* -> T^
Richard Trieude4958f2011-09-06 20:30:53 +00005717 if (const PointerType *RHSPT = RHSType->getAs<PointerType>())
John McCalle5255932011-01-31 22:28:28 +00005718 if (RHSPT->getPointeeType()->isVoidType()) {
5719 Kind = CK_AnyPointerToBlockPointerCast;
Douglas Gregore7dd1452008-11-27 00:44:28 +00005720 return Compatible;
John McCalle5255932011-01-31 22:28:28 +00005721 }
John McCall8cb679e2010-11-15 09:13:47 +00005722
Chris Lattnera52c2f22008-01-04 23:18:45 +00005723 return Incompatible;
5724 }
5725
John McCalle5255932011-01-31 22:28:28 +00005726 // Conversions to Objective-C pointers.
Richard Trieude4958f2011-09-06 20:30:53 +00005727 if (isa<ObjCObjectPointerType>(LHSType)) {
John McCalle5255932011-01-31 22:28:28 +00005728 // A* -> B*
Richard Trieude4958f2011-09-06 20:30:53 +00005729 if (RHSType->isObjCObjectPointerType()) {
John McCalle5255932011-01-31 22:28:28 +00005730 Kind = CK_BitCast;
Fariborz Jahanian6f472e82011-07-07 18:55:47 +00005731 Sema::AssignConvertType result =
Richard Trieude4958f2011-09-06 20:30:53 +00005732 checkObjCPointerTypesForAssignment(*this, LHSType, RHSType);
David Blaikiebbafb8a2012-03-11 07:00:24 +00005733 if (getLangOpts().ObjCAutoRefCount &&
Fariborz Jahanian6f472e82011-07-07 18:55:47 +00005734 result == Compatible &&
Richard Trieude4958f2011-09-06 20:30:53 +00005735 !CheckObjCARCUnavailableWeakConversion(OrigLHSType, RHSType))
Fariborz Jahanian7fcce682011-07-07 23:04:17 +00005736 result = IncompatibleObjCWeakRef;
Fariborz Jahanian6f472e82011-07-07 18:55:47 +00005737 return result;
John McCalle5255932011-01-31 22:28:28 +00005738 }
5739
5740 // int or null -> A*
Richard Trieude4958f2011-09-06 20:30:53 +00005741 if (RHSType->isIntegerType()) {
John McCall8cb679e2010-11-15 09:13:47 +00005742 Kind = CK_IntegralToPointer; // FIXME: null
Steve Naroff7cae42b2009-07-10 23:34:53 +00005743 return IntToPointer;
John McCall8cb679e2010-11-15 09:13:47 +00005744 }
5745
John McCalle5255932011-01-31 22:28:28 +00005746 // In general, C pointers are not compatible with ObjC object pointers,
5747 // with two exceptions:
Richard Trieude4958f2011-09-06 20:30:53 +00005748 if (isa<PointerType>(RHSType)) {
John McCall9320b872011-09-09 05:25:32 +00005749 Kind = CK_CPointerToObjCPointerCast;
5750
John McCalle5255932011-01-31 22:28:28 +00005751 // - conversions from 'void*'
Richard Trieude4958f2011-09-06 20:30:53 +00005752 if (RHSType->isVoidPointerType()) {
Steve Naroffaccc4882009-07-20 17:56:53 +00005753 return Compatible;
John McCalle5255932011-01-31 22:28:28 +00005754 }
5755
5756 // - conversions to 'Class' from its redefinition type
Richard Trieude4958f2011-09-06 20:30:53 +00005757 if (LHSType->isObjCClassType() &&
5758 Context.hasSameType(RHSType,
Douglas Gregor97673472011-08-11 20:58:55 +00005759 Context.getObjCClassRedefinitionType())) {
John McCalle5255932011-01-31 22:28:28 +00005760 return Compatible;
5761 }
5762
Steve Naroffaccc4882009-07-20 17:56:53 +00005763 return IncompatiblePointer;
Steve Naroff7cae42b2009-07-10 23:34:53 +00005764 }
John McCalle5255932011-01-31 22:28:28 +00005765
5766 // T^ -> A*
Richard Trieude4958f2011-09-06 20:30:53 +00005767 if (RHSType->isBlockPointerType()) {
John McCallcd78e802011-09-10 01:16:55 +00005768 maybeExtendBlockObject(*this, RHS);
John McCall9320b872011-09-09 05:25:32 +00005769 Kind = CK_BlockPointerToObjCPointerCast;
Steve Naroff7cae42b2009-07-10 23:34:53 +00005770 return Compatible;
John McCalle5255932011-01-31 22:28:28 +00005771 }
5772
Steve Naroff7cae42b2009-07-10 23:34:53 +00005773 return Incompatible;
5774 }
John McCalle5255932011-01-31 22:28:28 +00005775
5776 // Conversions from pointers that are not covered by the above.
Richard Trieude4958f2011-09-06 20:30:53 +00005777 if (isa<PointerType>(RHSType)) {
John McCalle5255932011-01-31 22:28:28 +00005778 // T* -> _Bool
Richard Trieude4958f2011-09-06 20:30:53 +00005779 if (LHSType == Context.BoolTy) {
John McCall8cb679e2010-11-15 09:13:47 +00005780 Kind = CK_PointerToBoolean;
Eli Friedman3360d892008-05-30 18:07:22 +00005781 return Compatible;
John McCall8cb679e2010-11-15 09:13:47 +00005782 }
Eli Friedman3360d892008-05-30 18:07:22 +00005783
John McCalle5255932011-01-31 22:28:28 +00005784 // T* -> int
Richard Trieude4958f2011-09-06 20:30:53 +00005785 if (LHSType->isIntegerType()) {
John McCall8cb679e2010-11-15 09:13:47 +00005786 Kind = CK_PointerToIntegral;
Chris Lattner940cfeb2008-01-04 18:22:42 +00005787 return PointerToInt;
John McCall8cb679e2010-11-15 09:13:47 +00005788 }
Mike Stump4e1f26a2009-02-19 03:04:26 +00005789
Chris Lattnera52c2f22008-01-04 23:18:45 +00005790 return Incompatible;
Chris Lattnera52c2f22008-01-04 23:18:45 +00005791 }
John McCalle5255932011-01-31 22:28:28 +00005792
5793 // Conversions from Objective-C pointers that are not covered by the above.
Richard Trieude4958f2011-09-06 20:30:53 +00005794 if (isa<ObjCObjectPointerType>(RHSType)) {
John McCalle5255932011-01-31 22:28:28 +00005795 // T* -> _Bool
Richard Trieude4958f2011-09-06 20:30:53 +00005796 if (LHSType == Context.BoolTy) {
John McCall8cb679e2010-11-15 09:13:47 +00005797 Kind = CK_PointerToBoolean;
Steve Naroff7cae42b2009-07-10 23:34:53 +00005798 return Compatible;
John McCall8cb679e2010-11-15 09:13:47 +00005799 }
Steve Naroff7cae42b2009-07-10 23:34:53 +00005800
John McCalle5255932011-01-31 22:28:28 +00005801 // T* -> int
Richard Trieude4958f2011-09-06 20:30:53 +00005802 if (LHSType->isIntegerType()) {
John McCall8cb679e2010-11-15 09:13:47 +00005803 Kind = CK_PointerToIntegral;
Steve Naroff7cae42b2009-07-10 23:34:53 +00005804 return PointerToInt;
John McCall8cb679e2010-11-15 09:13:47 +00005805 }
5806
Steve Naroff7cae42b2009-07-10 23:34:53 +00005807 return Incompatible;
5808 }
Eli Friedman3360d892008-05-30 18:07:22 +00005809
John McCalle5255932011-01-31 22:28:28 +00005810 // struct A -> struct B
Richard Trieude4958f2011-09-06 20:30:53 +00005811 if (isa<TagType>(LHSType) && isa<TagType>(RHSType)) {
5812 if (Context.typesAreCompatible(LHSType, RHSType)) {
John McCall8cb679e2010-11-15 09:13:47 +00005813 Kind = CK_NoOp;
Steve Naroff98cf3e92007-06-06 18:38:38 +00005814 return Compatible;
John McCall8cb679e2010-11-15 09:13:47 +00005815 }
Bill Wendling216423b2007-05-30 06:30:29 +00005816 }
John McCalle5255932011-01-31 22:28:28 +00005817
Steve Naroff98cf3e92007-06-06 18:38:38 +00005818 return Incompatible;
Steve Naroff9eb24652007-05-02 21:58:15 +00005819}
5820
Douglas Gregor0cfbdab2009-04-29 22:16:16 +00005821/// \brief Constructs a transparent union from an expression that is
5822/// used to initialize the transparent union.
Richard Trieucfc491d2011-08-02 04:35:43 +00005823static void ConstructTransparentUnion(Sema &S, ASTContext &C,
5824 ExprResult &EResult, QualType UnionType,
5825 FieldDecl *Field) {
Douglas Gregor0cfbdab2009-04-29 22:16:16 +00005826 // Build an initializer list that designates the appropriate member
5827 // of the transparent union.
John Wiegley01296292011-04-08 18:41:53 +00005828 Expr *E = EResult.take();
Ted Kremenekac034612010-04-13 23:39:13 +00005829 InitListExpr *Initializer = new (C) InitListExpr(C, SourceLocation(),
Benjamin Kramerc215e762012-08-24 11:54:20 +00005830 E, SourceLocation());
Douglas Gregor0cfbdab2009-04-29 22:16:16 +00005831 Initializer->setType(UnionType);
5832 Initializer->setInitializedFieldInUnion(Field);
5833
5834 // Build a compound literal constructing a value of the transparent
5835 // union type from this initializer list.
John McCalle15bbff2010-01-18 19:35:47 +00005836 TypeSourceInfo *unionTInfo = C.getTrivialTypeSourceInfo(UnionType);
John Wiegley01296292011-04-08 18:41:53 +00005837 EResult = S.Owned(
5838 new (C) CompoundLiteralExpr(SourceLocation(), unionTInfo, UnionType,
5839 VK_RValue, Initializer, false));
Douglas Gregor0cfbdab2009-04-29 22:16:16 +00005840}
5841
5842Sema::AssignConvertType
Richard Trieucfc491d2011-08-02 04:35:43 +00005843Sema::CheckTransparentUnionArgumentConstraints(QualType ArgType,
Richard Trieueb299142011-09-06 20:40:12 +00005844 ExprResult &RHS) {
5845 QualType RHSType = RHS.get()->getType();
Douglas Gregor0cfbdab2009-04-29 22:16:16 +00005846
Mike Stump11289f42009-09-09 15:08:12 +00005847 // If the ArgType is a Union type, we want to handle a potential
Douglas Gregor0cfbdab2009-04-29 22:16:16 +00005848 // transparent_union GCC extension.
5849 const RecordType *UT = ArgType->getAsUnionType();
Argyrios Kyrtzidisb4b64ca2009-06-30 02:34:44 +00005850 if (!UT || !UT->getDecl()->hasAttr<TransparentUnionAttr>())
Douglas Gregor0cfbdab2009-04-29 22:16:16 +00005851 return Incompatible;
5852
5853 // The field to initialize within the transparent union.
5854 RecordDecl *UD = UT->getDecl();
5855 FieldDecl *InitField = 0;
5856 // It's compatible if the expression matches any of the fields.
Argyrios Kyrtzidiscfbfe782009-06-30 02:36:12 +00005857 for (RecordDecl::field_iterator it = UD->field_begin(),
5858 itend = UD->field_end();
Douglas Gregor0cfbdab2009-04-29 22:16:16 +00005859 it != itend; ++it) {
5860 if (it->getType()->isPointerType()) {
5861 // If the transparent union contains a pointer type, we allow:
5862 // 1) void pointer
5863 // 2) null pointer constant
Richard Trieueb299142011-09-06 20:40:12 +00005864 if (RHSType->isPointerType())
John McCall9320b872011-09-09 05:25:32 +00005865 if (RHSType->castAs<PointerType>()->getPointeeType()->isVoidType()) {
Richard Trieueb299142011-09-06 20:40:12 +00005866 RHS = ImpCastExprToType(RHS.take(), it->getType(), CK_BitCast);
David Blaikie40ed2972012-06-06 20:45:41 +00005867 InitField = *it;
Douglas Gregor0cfbdab2009-04-29 22:16:16 +00005868 break;
5869 }
Mike Stump11289f42009-09-09 15:08:12 +00005870
Richard Trieueb299142011-09-06 20:40:12 +00005871 if (RHS.get()->isNullPointerConstant(Context,
5872 Expr::NPC_ValueDependentIsNull)) {
5873 RHS = ImpCastExprToType(RHS.take(), it->getType(),
5874 CK_NullToPointer);
David Blaikie40ed2972012-06-06 20:45:41 +00005875 InitField = *it;
Douglas Gregor0cfbdab2009-04-29 22:16:16 +00005876 break;
5877 }
5878 }
5879
John McCall8cb679e2010-11-15 09:13:47 +00005880 CastKind Kind = CK_Invalid;
Richard Trieueb299142011-09-06 20:40:12 +00005881 if (CheckAssignmentConstraints(it->getType(), RHS, Kind)
Douglas Gregor0cfbdab2009-04-29 22:16:16 +00005882 == Compatible) {
Richard Trieueb299142011-09-06 20:40:12 +00005883 RHS = ImpCastExprToType(RHS.take(), it->getType(), Kind);
David Blaikie40ed2972012-06-06 20:45:41 +00005884 InitField = *it;
Douglas Gregor0cfbdab2009-04-29 22:16:16 +00005885 break;
5886 }
5887 }
5888
5889 if (!InitField)
5890 return Incompatible;
5891
Richard Trieueb299142011-09-06 20:40:12 +00005892 ConstructTransparentUnion(*this, Context, RHS, ArgType, InitField);
Douglas Gregor0cfbdab2009-04-29 22:16:16 +00005893 return Compatible;
5894}
5895
Chris Lattner9bad62c2008-01-04 18:04:52 +00005896Sema::AssignConvertType
Sebastian Redlb49c46c2011-09-24 17:48:00 +00005897Sema::CheckSingleAssignmentConstraints(QualType LHSType, ExprResult &RHS,
5898 bool Diagnose) {
David Blaikiebbafb8a2012-03-11 07:00:24 +00005899 if (getLangOpts().CPlusPlus) {
Eli Friedman0dfb8892011-10-06 23:00:33 +00005900 if (!LHSType->isRecordType() && !LHSType->isAtomicType()) {
Douglas Gregor9a657932008-10-21 23:43:52 +00005901 // C++ 5.17p3: If the left operand is not of class type, the
5902 // expression is implicitly converted (C++ 4) to the
5903 // cv-unqualified type of the left operand.
Sebastian Redlcc152642011-10-16 18:19:06 +00005904 ExprResult Res;
5905 if (Diagnose) {
5906 Res = PerformImplicitConversion(RHS.get(), LHSType.getUnqualifiedType(),
5907 AA_Assigning);
5908 } else {
5909 ImplicitConversionSequence ICS =
5910 TryImplicitConversion(RHS.get(), LHSType.getUnqualifiedType(),
5911 /*SuppressUserConversions=*/false,
5912 /*AllowExplicit=*/false,
5913 /*InOverloadResolution=*/false,
5914 /*CStyle=*/false,
5915 /*AllowObjCWritebackConversion=*/false);
5916 if (ICS.isFailure())
5917 return Incompatible;
5918 Res = PerformImplicitConversion(RHS.get(), LHSType.getUnqualifiedType(),
5919 ICS, AA_Assigning);
5920 }
John Wiegley01296292011-04-08 18:41:53 +00005921 if (Res.isInvalid())
Douglas Gregor9a657932008-10-21 23:43:52 +00005922 return Incompatible;
Fariborz Jahanian7fcce682011-07-07 23:04:17 +00005923 Sema::AssignConvertType result = Compatible;
David Blaikiebbafb8a2012-03-11 07:00:24 +00005924 if (getLangOpts().ObjCAutoRefCount &&
Richard Trieueb299142011-09-06 20:40:12 +00005925 !CheckObjCARCUnavailableWeakConversion(LHSType,
5926 RHS.get()->getType()))
Fariborz Jahanian7fcce682011-07-07 23:04:17 +00005927 result = IncompatibleObjCWeakRef;
Benjamin Kramer62b95d82012-08-23 21:35:17 +00005928 RHS = Res;
Fariborz Jahanian7fcce682011-07-07 23:04:17 +00005929 return result;
Douglas Gregor9a657932008-10-21 23:43:52 +00005930 }
5931
5932 // FIXME: Currently, we fall through and treat C++ classes like C
5933 // structures.
Eli Friedman0dfb8892011-10-06 23:00:33 +00005934 // FIXME: We also fall through for atomics; not sure what should
5935 // happen there, though.
Sebastian Redlb49c46c2011-09-24 17:48:00 +00005936 }
Douglas Gregor9a657932008-10-21 23:43:52 +00005937
Steve Naroff0ee0b0a2007-11-27 17:58:44 +00005938 // C99 6.5.16.1p1: the left operand is a pointer and the right is
5939 // a null pointer constant.
Richard Trieueb299142011-09-06 20:40:12 +00005940 if ((LHSType->isPointerType() ||
5941 LHSType->isObjCObjectPointerType() ||
5942 LHSType->isBlockPointerType())
5943 && RHS.get()->isNullPointerConstant(Context,
5944 Expr::NPC_ValueDependentIsNull)) {
5945 RHS = ImpCastExprToType(RHS.take(), LHSType, CK_NullToPointer);
Steve Naroff0ee0b0a2007-11-27 17:58:44 +00005946 return Compatible;
5947 }
Mike Stump4e1f26a2009-02-19 03:04:26 +00005948
Chris Lattnere6dcd502007-10-16 02:55:40 +00005949 // This check seems unnatural, however it is necessary to ensure the proper
Steve Naroffb8ea4fb2007-07-13 23:32:42 +00005950 // conversion of functions/arrays. If the conversion were done for all
Douglas Gregora121b752009-11-03 16:56:39 +00005951 // DeclExpr's (created by ActOnIdExpression), it would mess up the unary
Nick Lewyckyef7c0ff2010-08-05 06:27:49 +00005952 // expressions that suppress this implicit conversion (&, sizeof).
Chris Lattnere6dcd502007-10-16 02:55:40 +00005953 //
Mike Stump4e1f26a2009-02-19 03:04:26 +00005954 // Suppress this for references: C++ 8.5.3p5.
Richard Trieueb299142011-09-06 20:40:12 +00005955 if (!LHSType->isReferenceType()) {
5956 RHS = DefaultFunctionArrayLvalueConversion(RHS.take());
5957 if (RHS.isInvalid())
John Wiegley01296292011-04-08 18:41:53 +00005958 return Incompatible;
5959 }
Steve Naroff0c1c7ed2007-08-24 22:33:52 +00005960
John McCall8cb679e2010-11-15 09:13:47 +00005961 CastKind Kind = CK_Invalid;
Chris Lattner9bad62c2008-01-04 18:04:52 +00005962 Sema::AssignConvertType result =
Richard Trieueb299142011-09-06 20:40:12 +00005963 CheckAssignmentConstraints(LHSType, RHS, Kind);
Mike Stump4e1f26a2009-02-19 03:04:26 +00005964
Steve Naroff0c1c7ed2007-08-24 22:33:52 +00005965 // C99 6.5.16.1p2: The value of the right operand is converted to the
5966 // type of the assignment expression.
Douglas Gregor6b754842008-10-28 00:22:11 +00005967 // CheckAssignmentConstraints allows the left-hand side to be a reference,
5968 // so that we can use references in built-in functions even in C.
5969 // The getNonReferenceType() call makes sure that the resulting expression
5970 // does not have reference type.
Richard Trieueb299142011-09-06 20:40:12 +00005971 if (result != Incompatible && RHS.get()->getType() != LHSType)
5972 RHS = ImpCastExprToType(RHS.take(),
5973 LHSType.getNonLValueExprType(Context), Kind);
Steve Naroff0c1c7ed2007-08-24 22:33:52 +00005974 return result;
Steve Naroffb8ea4fb2007-07-13 23:32:42 +00005975}
5976
Richard Trieueb299142011-09-06 20:40:12 +00005977QualType Sema::InvalidOperands(SourceLocation Loc, ExprResult &LHS,
5978 ExprResult &RHS) {
Chris Lattner377d1f82008-11-18 22:52:51 +00005979 Diag(Loc, diag::err_typecheck_invalid_operands)
Richard Trieueb299142011-09-06 20:40:12 +00005980 << LHS.get()->getType() << RHS.get()->getType()
5981 << LHS.get()->getSourceRange() << RHS.get()->getSourceRange();
Chris Lattner5c11c412007-12-12 05:47:28 +00005982 return QualType();
Steve Naroff6f49f5d2007-05-29 14:23:36 +00005983}
5984
Richard Trieu859d23f2011-09-06 21:01:04 +00005985QualType Sema::CheckVectorOperands(ExprResult &LHS, ExprResult &RHS,
Richard Trieuba63ce62011-09-09 01:45:06 +00005986 SourceLocation Loc, bool IsCompAssign) {
Richard Smith508ebf32011-10-28 03:31:48 +00005987 if (!IsCompAssign) {
5988 LHS = DefaultFunctionArrayLvalueConversion(LHS.take());
5989 if (LHS.isInvalid())
5990 return QualType();
5991 }
5992 RHS = DefaultFunctionArrayLvalueConversion(RHS.take());
5993 if (RHS.isInvalid())
5994 return QualType();
5995
Mike Stump4e1f26a2009-02-19 03:04:26 +00005996 // For conversion purposes, we ignore any qualifiers.
Nate Begeman002e4bd2008-04-04 01:30:25 +00005997 // For example, "const float" and "float" are equivalent.
Richard Trieu859d23f2011-09-06 21:01:04 +00005998 QualType LHSType =
5999 Context.getCanonicalType(LHS.get()->getType()).getUnqualifiedType();
6000 QualType RHSType =
6001 Context.getCanonicalType(RHS.get()->getType()).getUnqualifiedType();
Mike Stump4e1f26a2009-02-19 03:04:26 +00006002
Nate Begeman191a6b12008-07-14 18:02:46 +00006003 // If the vector types are identical, return.
Richard Trieu859d23f2011-09-06 21:01:04 +00006004 if (LHSType == RHSType)
6005 return LHSType;
Nate Begeman330aaa72007-12-30 02:59:45 +00006006
Douglas Gregor59e8b3b2010-08-06 10:14:59 +00006007 // Handle the case of equivalent AltiVec and GCC vector types
Richard Trieu859d23f2011-09-06 21:01:04 +00006008 if (LHSType->isVectorType() && RHSType->isVectorType() &&
6009 Context.areCompatibleVectorTypes(LHSType, RHSType)) {
6010 if (LHSType->isExtVectorType()) {
6011 RHS = ImpCastExprToType(RHS.take(), LHSType, CK_BitCast);
6012 return LHSType;
Eli Friedman1408bc92011-06-23 18:10:35 +00006013 }
6014
Richard Trieuba63ce62011-09-09 01:45:06 +00006015 if (!IsCompAssign)
Richard Trieu859d23f2011-09-06 21:01:04 +00006016 LHS = ImpCastExprToType(LHS.take(), RHSType, CK_BitCast);
6017 return RHSType;
Douglas Gregor59e8b3b2010-08-06 10:14:59 +00006018 }
6019
David Blaikiebbafb8a2012-03-11 07:00:24 +00006020 if (getLangOpts().LaxVectorConversions &&
Richard Trieu859d23f2011-09-06 21:01:04 +00006021 Context.getTypeSize(LHSType) == Context.getTypeSize(RHSType)) {
Eli Friedman1408bc92011-06-23 18:10:35 +00006022 // If we are allowing lax vector conversions, and LHS and RHS are both
6023 // vectors, the total size only needs to be the same. This is a
6024 // bitcast; no bits are changed but the result type is different.
6025 // FIXME: Should we really be allowing this?
Richard Trieu859d23f2011-09-06 21:01:04 +00006026 RHS = ImpCastExprToType(RHS.take(), LHSType, CK_BitCast);
6027 return LHSType;
Eli Friedman1408bc92011-06-23 18:10:35 +00006028 }
6029
Nate Begemanbd956c42009-06-28 02:36:38 +00006030 // Canonicalize the ExtVector to the LHS, remember if we swapped so we can
6031 // swap back (so that we don't reverse the inputs to a subtract, for instance.
6032 bool swapped = false;
Richard Trieuba63ce62011-09-09 01:45:06 +00006033 if (RHSType->isExtVectorType() && !IsCompAssign) {
Nate Begemanbd956c42009-06-28 02:36:38 +00006034 swapped = true;
Richard Trieu859d23f2011-09-06 21:01:04 +00006035 std::swap(RHS, LHS);
6036 std::swap(RHSType, LHSType);
Nate Begemanbd956c42009-06-28 02:36:38 +00006037 }
Mike Stump11289f42009-09-09 15:08:12 +00006038
Nate Begeman886448d2009-06-28 19:12:57 +00006039 // Handle the case of an ext vector and scalar.
Richard Trieu859d23f2011-09-06 21:01:04 +00006040 if (const ExtVectorType *LV = LHSType->getAs<ExtVectorType>()) {
Nate Begemanbd956c42009-06-28 02:36:38 +00006041 QualType EltTy = LV->getElementType();
Richard Trieu859d23f2011-09-06 21:01:04 +00006042 if (EltTy->isIntegralType(Context) && RHSType->isIntegralType(Context)) {
6043 int order = Context.getIntegerTypeOrder(EltTy, RHSType);
John McCall8cb679e2010-11-15 09:13:47 +00006044 if (order > 0)
Richard Trieu859d23f2011-09-06 21:01:04 +00006045 RHS = ImpCastExprToType(RHS.take(), EltTy, CK_IntegralCast);
John McCall8cb679e2010-11-15 09:13:47 +00006046 if (order >= 0) {
Richard Trieu859d23f2011-09-06 21:01:04 +00006047 RHS = ImpCastExprToType(RHS.take(), LHSType, CK_VectorSplat);
6048 if (swapped) std::swap(RHS, LHS);
6049 return LHSType;
Nate Begemanbd956c42009-06-28 02:36:38 +00006050 }
6051 }
Richard Trieu859d23f2011-09-06 21:01:04 +00006052 if (EltTy->isRealFloatingType() && RHSType->isScalarType() &&
6053 RHSType->isRealFloatingType()) {
6054 int order = Context.getFloatingTypeOrder(EltTy, RHSType);
John McCall8cb679e2010-11-15 09:13:47 +00006055 if (order > 0)
Richard Trieu859d23f2011-09-06 21:01:04 +00006056 RHS = ImpCastExprToType(RHS.take(), EltTy, CK_FloatingCast);
John McCall8cb679e2010-11-15 09:13:47 +00006057 if (order >= 0) {
Richard Trieu859d23f2011-09-06 21:01:04 +00006058 RHS = ImpCastExprToType(RHS.take(), LHSType, CK_VectorSplat);
6059 if (swapped) std::swap(RHS, LHS);
6060 return LHSType;
Nate Begemanbd956c42009-06-28 02:36:38 +00006061 }
Nate Begeman330aaa72007-12-30 02:59:45 +00006062 }
6063 }
Mike Stump11289f42009-09-09 15:08:12 +00006064
Nate Begeman886448d2009-06-28 19:12:57 +00006065 // Vectors of different size or scalar and non-ext-vector are errors.
Richard Trieu859d23f2011-09-06 21:01:04 +00006066 if (swapped) std::swap(RHS, LHS);
Chris Lattner377d1f82008-11-18 22:52:51 +00006067 Diag(Loc, diag::err_typecheck_vector_not_convertable)
Richard Trieu859d23f2011-09-06 21:01:04 +00006068 << LHS.get()->getType() << RHS.get()->getType()
6069 << LHS.get()->getSourceRange() << RHS.get()->getSourceRange();
Steve Naroff84ff4b42007-07-09 21:31:10 +00006070 return QualType();
Sebastian Redl112a97662009-02-07 00:15:38 +00006071}
6072
Richard Trieuf8916e12011-09-16 00:53:10 +00006073// checkArithmeticNull - Detect when a NULL constant is used improperly in an
6074// expression. These are mainly cases where the null pointer is used as an
6075// integer instead of a pointer.
6076static void checkArithmeticNull(Sema &S, ExprResult &LHS, ExprResult &RHS,
6077 SourceLocation Loc, bool IsCompare) {
6078 // The canonical way to check for a GNU null is with isNullPointerConstant,
6079 // but we use a bit of a hack here for speed; this is a relatively
6080 // hot path, and isNullPointerConstant is slow.
6081 bool LHSNull = isa<GNUNullExpr>(LHS.get()->IgnoreParenImpCasts());
6082 bool RHSNull = isa<GNUNullExpr>(RHS.get()->IgnoreParenImpCasts());
6083
6084 QualType NonNullType = LHSNull ? RHS.get()->getType() : LHS.get()->getType();
6085
6086 // Avoid analyzing cases where the result will either be invalid (and
6087 // diagnosed as such) or entirely valid and not something to warn about.
6088 if ((!LHSNull && !RHSNull) || NonNullType->isBlockPointerType() ||
6089 NonNullType->isMemberPointerType() || NonNullType->isFunctionType())
6090 return;
6091
6092 // Comparison operations would not make sense with a null pointer no matter
6093 // what the other expression is.
6094 if (!IsCompare) {
6095 S.Diag(Loc, diag::warn_null_in_arithmetic_operation)
6096 << (LHSNull ? LHS.get()->getSourceRange() : SourceRange())
6097 << (RHSNull ? RHS.get()->getSourceRange() : SourceRange());
6098 return;
6099 }
6100
6101 // The rest of the operations only make sense with a null pointer
6102 // if the other expression is a pointer.
6103 if (LHSNull == RHSNull || NonNullType->isAnyPointerType() ||
6104 NonNullType->canDecayToPointerType())
6105 return;
6106
6107 S.Diag(Loc, diag::warn_null_in_comparison_operation)
6108 << LHSNull /* LHS is NULL */ << NonNullType
6109 << LHS.get()->getSourceRange() << RHS.get()->getSourceRange();
6110}
6111
Richard Trieu859d23f2011-09-06 21:01:04 +00006112QualType Sema::CheckMultiplyDivideOperands(ExprResult &LHS, ExprResult &RHS,
Richard Trieucfc491d2011-08-02 04:35:43 +00006113 SourceLocation Loc,
Richard Trieuba63ce62011-09-09 01:45:06 +00006114 bool IsCompAssign, bool IsDiv) {
Richard Trieuf8916e12011-09-16 00:53:10 +00006115 checkArithmeticNull(*this, LHS, RHS, Loc, /*isCompare=*/false);
6116
Richard Trieu859d23f2011-09-06 21:01:04 +00006117 if (LHS.get()->getType()->isVectorType() ||
6118 RHS.get()->getType()->isVectorType())
Richard Trieuba63ce62011-09-09 01:45:06 +00006119 return CheckVectorOperands(LHS, RHS, Loc, IsCompAssign);
Mike Stump4e1f26a2009-02-19 03:04:26 +00006120
Richard Trieuba63ce62011-09-09 01:45:06 +00006121 QualType compType = UsualArithmeticConversions(LHS, RHS, IsCompAssign);
Richard Trieu859d23f2011-09-06 21:01:04 +00006122 if (LHS.isInvalid() || RHS.isInvalid())
John Wiegley01296292011-04-08 18:41:53 +00006123 return QualType();
Mike Stump4e1f26a2009-02-19 03:04:26 +00006124
David Chisnallfa35df62012-01-16 17:27:18 +00006125
Eli Friedman93ee5ca2012-06-16 02:19:17 +00006126 if (compType.isNull() || !compType->isArithmeticType())
Richard Trieu859d23f2011-09-06 21:01:04 +00006127 return InvalidOperands(Loc, LHS, RHS);
Kovarththanan Rajaratnamba2c6522010-03-13 10:17:05 +00006128
Chris Lattnerfaa54172010-01-12 21:23:57 +00006129 // Check for division by zero.
Richard Trieuba63ce62011-09-09 01:45:06 +00006130 if (IsDiv &&
Richard Trieu859d23f2011-09-06 21:01:04 +00006131 RHS.get()->isNullPointerConstant(Context,
Richard Trieucfc491d2011-08-02 04:35:43 +00006132 Expr::NPC_ValueDependentIsNotNull))
Richard Trieu859d23f2011-09-06 21:01:04 +00006133 DiagRuntimeBehavior(Loc, RHS.get(), PDiag(diag::warn_division_by_zero)
6134 << RHS.get()->getSourceRange());
Kovarththanan Rajaratnamba2c6522010-03-13 10:17:05 +00006135
Chris Lattnerfaa54172010-01-12 21:23:57 +00006136 return compType;
Steve Naroff26c8ea52007-03-21 21:08:52 +00006137}
6138
Chris Lattnerfaa54172010-01-12 21:23:57 +00006139QualType Sema::CheckRemainderOperands(
Richard Trieuba63ce62011-09-09 01:45:06 +00006140 ExprResult &LHS, ExprResult &RHS, SourceLocation Loc, bool IsCompAssign) {
Richard Trieuf8916e12011-09-16 00:53:10 +00006141 checkArithmeticNull(*this, LHS, RHS, Loc, /*isCompare=*/false);
6142
Richard Trieu859d23f2011-09-06 21:01:04 +00006143 if (LHS.get()->getType()->isVectorType() ||
6144 RHS.get()->getType()->isVectorType()) {
6145 if (LHS.get()->getType()->hasIntegerRepresentation() &&
6146 RHS.get()->getType()->hasIntegerRepresentation())
Richard Trieuba63ce62011-09-09 01:45:06 +00006147 return CheckVectorOperands(LHS, RHS, Loc, IsCompAssign);
Richard Trieu859d23f2011-09-06 21:01:04 +00006148 return InvalidOperands(Loc, LHS, RHS);
Daniel Dunbar0d2bfec2009-01-05 22:55:36 +00006149 }
Steve Naroffb8ea4fb2007-07-13 23:32:42 +00006150
Richard Trieuba63ce62011-09-09 01:45:06 +00006151 QualType compType = UsualArithmeticConversions(LHS, RHS, IsCompAssign);
Richard Trieu859d23f2011-09-06 21:01:04 +00006152 if (LHS.isInvalid() || RHS.isInvalid())
John Wiegley01296292011-04-08 18:41:53 +00006153 return QualType();
Mike Stump4e1f26a2009-02-19 03:04:26 +00006154
Eli Friedman93ee5ca2012-06-16 02:19:17 +00006155 if (compType.isNull() || !compType->isIntegerType())
Richard Trieu859d23f2011-09-06 21:01:04 +00006156 return InvalidOperands(Loc, LHS, RHS);
Kovarththanan Rajaratnamba2c6522010-03-13 10:17:05 +00006157
Chris Lattnerfaa54172010-01-12 21:23:57 +00006158 // Check for remainder by zero.
Richard Trieu859d23f2011-09-06 21:01:04 +00006159 if (RHS.get()->isNullPointerConstant(Context,
Richard Trieucfc491d2011-08-02 04:35:43 +00006160 Expr::NPC_ValueDependentIsNotNull))
Richard Trieu859d23f2011-09-06 21:01:04 +00006161 DiagRuntimeBehavior(Loc, RHS.get(), PDiag(diag::warn_remainder_by_zero)
6162 << RHS.get()->getSourceRange());
Kovarththanan Rajaratnamba2c6522010-03-13 10:17:05 +00006163
Chris Lattnerfaa54172010-01-12 21:23:57 +00006164 return compType;
Steve Naroff218bc2b2007-05-04 21:54:46 +00006165}
6166
Chandler Carruthc9332212011-06-27 08:02:19 +00006167/// \brief Diagnose invalid arithmetic on two void pointers.
6168static void diagnoseArithmeticOnTwoVoidPointers(Sema &S, SourceLocation Loc,
Richard Trieu4ae7e972011-09-06 21:13:51 +00006169 Expr *LHSExpr, Expr *RHSExpr) {
David Blaikiebbafb8a2012-03-11 07:00:24 +00006170 S.Diag(Loc, S.getLangOpts().CPlusPlus
Chandler Carruthc9332212011-06-27 08:02:19 +00006171 ? diag::err_typecheck_pointer_arith_void_type
6172 : diag::ext_gnu_void_ptr)
Richard Trieu4ae7e972011-09-06 21:13:51 +00006173 << 1 /* two pointers */ << LHSExpr->getSourceRange()
6174 << RHSExpr->getSourceRange();
Chandler Carruthc9332212011-06-27 08:02:19 +00006175}
6176
6177/// \brief Diagnose invalid arithmetic on a void pointer.
6178static void diagnoseArithmeticOnVoidPointer(Sema &S, SourceLocation Loc,
6179 Expr *Pointer) {
David Blaikiebbafb8a2012-03-11 07:00:24 +00006180 S.Diag(Loc, S.getLangOpts().CPlusPlus
Chandler Carruthc9332212011-06-27 08:02:19 +00006181 ? diag::err_typecheck_pointer_arith_void_type
6182 : diag::ext_gnu_void_ptr)
6183 << 0 /* one pointer */ << Pointer->getSourceRange();
6184}
6185
6186/// \brief Diagnose invalid arithmetic on two function pointers.
6187static void diagnoseArithmeticOnTwoFunctionPointers(Sema &S, SourceLocation Loc,
6188 Expr *LHS, Expr *RHS) {
6189 assert(LHS->getType()->isAnyPointerType());
6190 assert(RHS->getType()->isAnyPointerType());
David Blaikiebbafb8a2012-03-11 07:00:24 +00006191 S.Diag(Loc, S.getLangOpts().CPlusPlus
Chandler Carruthc9332212011-06-27 08:02:19 +00006192 ? diag::err_typecheck_pointer_arith_function_type
6193 : diag::ext_gnu_ptr_func_arith)
6194 << 1 /* two pointers */ << LHS->getType()->getPointeeType()
6195 // We only show the second type if it differs from the first.
6196 << (unsigned)!S.Context.hasSameUnqualifiedType(LHS->getType(),
6197 RHS->getType())
6198 << RHS->getType()->getPointeeType()
6199 << LHS->getSourceRange() << RHS->getSourceRange();
6200}
6201
6202/// \brief Diagnose invalid arithmetic on a function pointer.
6203static void diagnoseArithmeticOnFunctionPointer(Sema &S, SourceLocation Loc,
6204 Expr *Pointer) {
6205 assert(Pointer->getType()->isAnyPointerType());
David Blaikiebbafb8a2012-03-11 07:00:24 +00006206 S.Diag(Loc, S.getLangOpts().CPlusPlus
Chandler Carruthc9332212011-06-27 08:02:19 +00006207 ? diag::err_typecheck_pointer_arith_function_type
6208 : diag::ext_gnu_ptr_func_arith)
6209 << 0 /* one pointer */ << Pointer->getType()->getPointeeType()
6210 << 0 /* one pointer, so only one type */
6211 << Pointer->getSourceRange();
6212}
6213
Richard Trieu993f3ab2011-09-12 18:08:02 +00006214/// \brief Emit error if Operand is incomplete pointer type
Richard Trieuaba22802011-09-02 02:15:37 +00006215///
6216/// \returns True if pointer has incomplete type
6217static bool checkArithmeticIncompletePointerType(Sema &S, SourceLocation Loc,
6218 Expr *Operand) {
John McCallf2538342012-07-31 05:14:30 +00006219 assert(Operand->getType()->isAnyPointerType() &&
6220 !Operand->getType()->isDependentType());
6221 QualType PointeeTy = Operand->getType()->getPointeeType();
6222 return S.RequireCompleteType(Loc, PointeeTy,
6223 diag::err_typecheck_arithmetic_incomplete_type,
6224 PointeeTy, Operand->getSourceRange());
Richard Trieuaba22802011-09-02 02:15:37 +00006225}
6226
Chandler Carruthc9332212011-06-27 08:02:19 +00006227/// \brief Check the validity of an arithmetic pointer operand.
6228///
6229/// If the operand has pointer type, this code will check for pointer types
6230/// which are invalid in arithmetic operations. These will be diagnosed
6231/// appropriately, including whether or not the use is supported as an
6232/// extension.
6233///
6234/// \returns True when the operand is valid to use (even if as an extension).
6235static bool checkArithmeticOpPointerOperand(Sema &S, SourceLocation Loc,
6236 Expr *Operand) {
6237 if (!Operand->getType()->isAnyPointerType()) return true;
6238
6239 QualType PointeeTy = Operand->getType()->getPointeeType();
6240 if (PointeeTy->isVoidType()) {
6241 diagnoseArithmeticOnVoidPointer(S, Loc, Operand);
David Blaikiebbafb8a2012-03-11 07:00:24 +00006242 return !S.getLangOpts().CPlusPlus;
Chandler Carruthc9332212011-06-27 08:02:19 +00006243 }
6244 if (PointeeTy->isFunctionType()) {
6245 diagnoseArithmeticOnFunctionPointer(S, Loc, Operand);
David Blaikiebbafb8a2012-03-11 07:00:24 +00006246 return !S.getLangOpts().CPlusPlus;
Chandler Carruthc9332212011-06-27 08:02:19 +00006247 }
6248
Richard Trieuaba22802011-09-02 02:15:37 +00006249 if (checkArithmeticIncompletePointerType(S, Loc, Operand)) return false;
Chandler Carruthc9332212011-06-27 08:02:19 +00006250
6251 return true;
6252}
6253
6254/// \brief Check the validity of a binary arithmetic operation w.r.t. pointer
6255/// operands.
6256///
6257/// This routine will diagnose any invalid arithmetic on pointer operands much
6258/// like \see checkArithmeticOpPointerOperand. However, it has special logic
6259/// for emitting a single diagnostic even for operations where both LHS and RHS
6260/// are (potentially problematic) pointers.
6261///
6262/// \returns True when the operand is valid to use (even if as an extension).
6263static bool checkArithmeticBinOpPointerOperands(Sema &S, SourceLocation Loc,
Richard Trieu4ae7e972011-09-06 21:13:51 +00006264 Expr *LHSExpr, Expr *RHSExpr) {
6265 bool isLHSPointer = LHSExpr->getType()->isAnyPointerType();
6266 bool isRHSPointer = RHSExpr->getType()->isAnyPointerType();
Chandler Carruthc9332212011-06-27 08:02:19 +00006267 if (!isLHSPointer && !isRHSPointer) return true;
6268
6269 QualType LHSPointeeTy, RHSPointeeTy;
Richard Trieu4ae7e972011-09-06 21:13:51 +00006270 if (isLHSPointer) LHSPointeeTy = LHSExpr->getType()->getPointeeType();
6271 if (isRHSPointer) RHSPointeeTy = RHSExpr->getType()->getPointeeType();
Chandler Carruthc9332212011-06-27 08:02:19 +00006272
6273 // Check for arithmetic on pointers to incomplete types.
6274 bool isLHSVoidPtr = isLHSPointer && LHSPointeeTy->isVoidType();
6275 bool isRHSVoidPtr = isRHSPointer && RHSPointeeTy->isVoidType();
6276 if (isLHSVoidPtr || isRHSVoidPtr) {
Richard Trieu4ae7e972011-09-06 21:13:51 +00006277 if (!isRHSVoidPtr) diagnoseArithmeticOnVoidPointer(S, Loc, LHSExpr);
6278 else if (!isLHSVoidPtr) diagnoseArithmeticOnVoidPointer(S, Loc, RHSExpr);
6279 else diagnoseArithmeticOnTwoVoidPointers(S, Loc, LHSExpr, RHSExpr);
Chandler Carruthc9332212011-06-27 08:02:19 +00006280
David Blaikiebbafb8a2012-03-11 07:00:24 +00006281 return !S.getLangOpts().CPlusPlus;
Chandler Carruthc9332212011-06-27 08:02:19 +00006282 }
6283
6284 bool isLHSFuncPtr = isLHSPointer && LHSPointeeTy->isFunctionType();
6285 bool isRHSFuncPtr = isRHSPointer && RHSPointeeTy->isFunctionType();
6286 if (isLHSFuncPtr || isRHSFuncPtr) {
Richard Trieu4ae7e972011-09-06 21:13:51 +00006287 if (!isRHSFuncPtr) diagnoseArithmeticOnFunctionPointer(S, Loc, LHSExpr);
6288 else if (!isLHSFuncPtr) diagnoseArithmeticOnFunctionPointer(S, Loc,
6289 RHSExpr);
6290 else diagnoseArithmeticOnTwoFunctionPointers(S, Loc, LHSExpr, RHSExpr);
Chandler Carruthc9332212011-06-27 08:02:19 +00006291
David Blaikiebbafb8a2012-03-11 07:00:24 +00006292 return !S.getLangOpts().CPlusPlus;
Chandler Carruthc9332212011-06-27 08:02:19 +00006293 }
6294
John McCallf2538342012-07-31 05:14:30 +00006295 if (isLHSPointer && checkArithmeticIncompletePointerType(S, Loc, LHSExpr))
6296 return false;
6297 if (isRHSPointer && checkArithmeticIncompletePointerType(S, Loc, RHSExpr))
6298 return false;
Richard Trieuaba22802011-09-02 02:15:37 +00006299
Chandler Carruthc9332212011-06-27 08:02:19 +00006300 return true;
6301}
6302
Nico Weberccec40d2012-03-02 22:01:22 +00006303/// diagnoseStringPlusInt - Emit a warning when adding an integer to a string
6304/// literal.
6305static void diagnoseStringPlusInt(Sema &Self, SourceLocation OpLoc,
6306 Expr *LHSExpr, Expr *RHSExpr) {
6307 StringLiteral* StrExpr = dyn_cast<StringLiteral>(LHSExpr->IgnoreImpCasts());
6308 Expr* IndexExpr = RHSExpr;
6309 if (!StrExpr) {
6310 StrExpr = dyn_cast<StringLiteral>(RHSExpr->IgnoreImpCasts());
6311 IndexExpr = LHSExpr;
6312 }
6313
6314 bool IsStringPlusInt = StrExpr &&
6315 IndexExpr->getType()->isIntegralOrUnscopedEnumerationType();
6316 if (!IsStringPlusInt)
6317 return;
6318
6319 llvm::APSInt index;
6320 if (IndexExpr->EvaluateAsInt(index, Self.getASTContext())) {
6321 unsigned StrLenWithNull = StrExpr->getLength() + 1;
6322 if (index.isNonNegative() &&
6323 index <= llvm::APSInt(llvm::APInt(index.getBitWidth(), StrLenWithNull),
6324 index.isUnsigned()))
6325 return;
6326 }
6327
6328 SourceRange DiagRange(LHSExpr->getLocStart(), RHSExpr->getLocEnd());
6329 Self.Diag(OpLoc, diag::warn_string_plus_int)
6330 << DiagRange << IndexExpr->IgnoreImpCasts()->getType();
6331
6332 // Only print a fixit for "str" + int, not for int + "str".
6333 if (IndexExpr == RHSExpr) {
6334 SourceLocation EndLoc = Self.PP.getLocForEndOfToken(RHSExpr->getLocEnd());
6335 Self.Diag(OpLoc, diag::note_string_plus_int_silence)
6336 << FixItHint::CreateInsertion(LHSExpr->getLocStart(), "&")
6337 << FixItHint::CreateReplacement(SourceRange(OpLoc), "[")
6338 << FixItHint::CreateInsertion(EndLoc, "]");
6339 } else
6340 Self.Diag(OpLoc, diag::note_string_plus_int_silence);
6341}
6342
Richard Trieu993f3ab2011-09-12 18:08:02 +00006343/// \brief Emit error when two pointers are incompatible.
Richard Trieub10c6312011-09-01 22:53:23 +00006344static void diagnosePointerIncompatibility(Sema &S, SourceLocation Loc,
Richard Trieu4ae7e972011-09-06 21:13:51 +00006345 Expr *LHSExpr, Expr *RHSExpr) {
6346 assert(LHSExpr->getType()->isAnyPointerType());
6347 assert(RHSExpr->getType()->isAnyPointerType());
Richard Trieub10c6312011-09-01 22:53:23 +00006348 S.Diag(Loc, diag::err_typecheck_sub_ptr_compatible)
Richard Trieu4ae7e972011-09-06 21:13:51 +00006349 << LHSExpr->getType() << RHSExpr->getType() << LHSExpr->getSourceRange()
6350 << RHSExpr->getSourceRange();
Richard Trieub10c6312011-09-01 22:53:23 +00006351}
6352
Chris Lattnerfaa54172010-01-12 21:23:57 +00006353QualType Sema::CheckAdditionOperands( // C99 6.5.6
Nico Weberccec40d2012-03-02 22:01:22 +00006354 ExprResult &LHS, ExprResult &RHS, SourceLocation Loc, unsigned Opc,
6355 QualType* CompLHSTy) {
Richard Trieuf8916e12011-09-16 00:53:10 +00006356 checkArithmeticNull(*this, LHS, RHS, Loc, /*isCompare=*/false);
6357
Richard Trieu4ae7e972011-09-06 21:13:51 +00006358 if (LHS.get()->getType()->isVectorType() ||
6359 RHS.get()->getType()->isVectorType()) {
6360 QualType compType = CheckVectorOperands(LHS, RHS, Loc, CompLHSTy);
Eli Friedman8b7b1b12009-03-28 01:22:36 +00006361 if (CompLHSTy) *CompLHSTy = compType;
6362 return compType;
6363 }
Steve Naroff7a5af782007-07-13 16:58:59 +00006364
Richard Trieu4ae7e972011-09-06 21:13:51 +00006365 QualType compType = UsualArithmeticConversions(LHS, RHS, CompLHSTy);
6366 if (LHS.isInvalid() || RHS.isInvalid())
John Wiegley01296292011-04-08 18:41:53 +00006367 return QualType();
Eli Friedman8e122982008-05-18 18:08:51 +00006368
Nico Weberccec40d2012-03-02 22:01:22 +00006369 // Diagnose "string literal" '+' int.
6370 if (Opc == BO_Add)
6371 diagnoseStringPlusInt(*this, Loc, LHS.get(), RHS.get());
6372
Steve Naroffe4718892007-04-27 18:30:00 +00006373 // handle the common case first (both operands are arithmetic).
Eli Friedman93ee5ca2012-06-16 02:19:17 +00006374 if (!compType.isNull() && compType->isArithmeticType()) {
Eli Friedman8b7b1b12009-03-28 01:22:36 +00006375 if (CompLHSTy) *CompLHSTy = compType;
Steve Naroffbe4c4d12007-08-24 19:07:16 +00006376 return compType;
Eli Friedman8b7b1b12009-03-28 01:22:36 +00006377 }
Steve Naroff218bc2b2007-05-04 21:54:46 +00006378
John McCallf2538342012-07-31 05:14:30 +00006379 // Type-checking. Ultimately the pointer's going to be in PExp;
6380 // note that we bias towards the LHS being the pointer.
6381 Expr *PExp = LHS.get(), *IExp = RHS.get();
Eli Friedman8e122982008-05-18 18:08:51 +00006382
John McCallf2538342012-07-31 05:14:30 +00006383 bool isObjCPointer;
6384 if (PExp->getType()->isPointerType()) {
6385 isObjCPointer = false;
6386 } else if (PExp->getType()->isObjCObjectPointerType()) {
6387 isObjCPointer = true;
6388 } else {
6389 std::swap(PExp, IExp);
6390 if (PExp->getType()->isPointerType()) {
6391 isObjCPointer = false;
6392 } else if (PExp->getType()->isObjCObjectPointerType()) {
6393 isObjCPointer = true;
6394 } else {
6395 return InvalidOperands(Loc, LHS, RHS);
6396 }
6397 }
6398 assert(PExp->getType()->isAnyPointerType());
Chandler Carruthc9332212011-06-27 08:02:19 +00006399
Richard Trieub420bca2011-09-12 18:37:54 +00006400 if (!IExp->getType()->isIntegerType())
6401 return InvalidOperands(Loc, LHS, RHS);
Mike Stump11289f42009-09-09 15:08:12 +00006402
Richard Trieub420bca2011-09-12 18:37:54 +00006403 if (!checkArithmeticOpPointerOperand(*this, Loc, PExp))
6404 return QualType();
Kaelyn Uhrain2e7aa5a2011-08-05 23:18:04 +00006405
John McCallf2538342012-07-31 05:14:30 +00006406 if (isObjCPointer && checkArithmeticOnObjCPointer(*this, Loc, PExp))
Richard Trieub420bca2011-09-12 18:37:54 +00006407 return QualType();
6408
6409 // Check array bounds for pointer arithemtic
6410 CheckArrayAccess(PExp, IExp);
6411
6412 if (CompLHSTy) {
6413 QualType LHSTy = Context.isPromotableBitField(LHS.get());
6414 if (LHSTy.isNull()) {
6415 LHSTy = LHS.get()->getType();
6416 if (LHSTy->isPromotableIntegerType())
6417 LHSTy = Context.getPromotedIntegerType(LHSTy);
Eli Friedman8e122982008-05-18 18:08:51 +00006418 }
Richard Trieub420bca2011-09-12 18:37:54 +00006419 *CompLHSTy = LHSTy;
Eli Friedman8e122982008-05-18 18:08:51 +00006420 }
6421
Richard Trieub420bca2011-09-12 18:37:54 +00006422 return PExp->getType();
Steve Naroff26c8ea52007-03-21 21:08:52 +00006423}
6424
Chris Lattner2a3569b2008-04-07 05:30:13 +00006425// C99 6.5.6
Richard Trieu4ae7e972011-09-06 21:13:51 +00006426QualType Sema::CheckSubtractionOperands(ExprResult &LHS, ExprResult &RHS,
Richard Trieucfc491d2011-08-02 04:35:43 +00006427 SourceLocation Loc,
6428 QualType* CompLHSTy) {
Richard Trieuf8916e12011-09-16 00:53:10 +00006429 checkArithmeticNull(*this, LHS, RHS, Loc, /*isCompare=*/false);
6430
Richard Trieu4ae7e972011-09-06 21:13:51 +00006431 if (LHS.get()->getType()->isVectorType() ||
6432 RHS.get()->getType()->isVectorType()) {
6433 QualType compType = CheckVectorOperands(LHS, RHS, Loc, CompLHSTy);
Eli Friedman8b7b1b12009-03-28 01:22:36 +00006434 if (CompLHSTy) *CompLHSTy = compType;
6435 return compType;
6436 }
Mike Stump4e1f26a2009-02-19 03:04:26 +00006437
Richard Trieu4ae7e972011-09-06 21:13:51 +00006438 QualType compType = UsualArithmeticConversions(LHS, RHS, CompLHSTy);
6439 if (LHS.isInvalid() || RHS.isInvalid())
John Wiegley01296292011-04-08 18:41:53 +00006440 return QualType();
Mike Stump4e1f26a2009-02-19 03:04:26 +00006441
Chris Lattner4d62f422007-12-09 21:53:25 +00006442 // Enforce type constraints: C99 6.5.6p3.
Mike Stump4e1f26a2009-02-19 03:04:26 +00006443
Chris Lattner4d62f422007-12-09 21:53:25 +00006444 // Handle the common case first (both operands are arithmetic).
Eli Friedman93ee5ca2012-06-16 02:19:17 +00006445 if (!compType.isNull() && compType->isArithmeticType()) {
Eli Friedman8b7b1b12009-03-28 01:22:36 +00006446 if (CompLHSTy) *CompLHSTy = compType;
Steve Naroffbe4c4d12007-08-24 19:07:16 +00006447 return compType;
Eli Friedman8b7b1b12009-03-28 01:22:36 +00006448 }
Mike Stump11289f42009-09-09 15:08:12 +00006449
Chris Lattner4d62f422007-12-09 21:53:25 +00006450 // Either ptr - int or ptr - ptr.
Richard Trieu4ae7e972011-09-06 21:13:51 +00006451 if (LHS.get()->getType()->isAnyPointerType()) {
6452 QualType lpointee = LHS.get()->getType()->getPointeeType();
Mike Stump4e1f26a2009-02-19 03:04:26 +00006453
Chris Lattner12bdebb2009-04-24 23:50:08 +00006454 // Diagnose bad cases where we step over interface counts.
John McCallf2538342012-07-31 05:14:30 +00006455 if (LHS.get()->getType()->isObjCObjectPointerType() &&
6456 checkArithmeticOnObjCPointer(*this, Loc, LHS.get()))
Chris Lattner12bdebb2009-04-24 23:50:08 +00006457 return QualType();
Mike Stump11289f42009-09-09 15:08:12 +00006458
Chris Lattner4d62f422007-12-09 21:53:25 +00006459 // The result type of a pointer-int computation is the pointer type.
Richard Trieu4ae7e972011-09-06 21:13:51 +00006460 if (RHS.get()->getType()->isIntegerType()) {
6461 if (!checkArithmeticOpPointerOperand(*this, Loc, LHS.get()))
Chandler Carruthc9332212011-06-27 08:02:19 +00006462 return QualType();
Douglas Gregorac1fb652009-03-24 19:52:54 +00006463
Kaelyn Uhrain2e7aa5a2011-08-05 23:18:04 +00006464 // Check array bounds for pointer arithemtic
Richard Smith13f67182011-12-16 19:31:14 +00006465 CheckArrayAccess(LHS.get(), RHS.get(), /*ArraySubscriptExpr*/0,
6466 /*AllowOnePastEnd*/true, /*IndexNegated*/true);
Kaelyn Uhrain2e7aa5a2011-08-05 23:18:04 +00006467
Richard Trieu4ae7e972011-09-06 21:13:51 +00006468 if (CompLHSTy) *CompLHSTy = LHS.get()->getType();
6469 return LHS.get()->getType();
Douglas Gregorac1fb652009-03-24 19:52:54 +00006470 }
Mike Stump4e1f26a2009-02-19 03:04:26 +00006471
Chris Lattner4d62f422007-12-09 21:53:25 +00006472 // Handle pointer-pointer subtractions.
Richard Trieucfc491d2011-08-02 04:35:43 +00006473 if (const PointerType *RHSPTy
Richard Trieu4ae7e972011-09-06 21:13:51 +00006474 = RHS.get()->getType()->getAs<PointerType>()) {
Eli Friedman1974e532008-02-08 01:19:44 +00006475 QualType rpointee = RHSPTy->getPointeeType();
Mike Stump4e1f26a2009-02-19 03:04:26 +00006476
David Blaikiebbafb8a2012-03-11 07:00:24 +00006477 if (getLangOpts().CPlusPlus) {
Eli Friedman168fe152009-05-16 13:54:38 +00006478 // Pointee types must be the same: C++ [expr.add]
6479 if (!Context.hasSameUnqualifiedType(lpointee, rpointee)) {
Richard Trieu4ae7e972011-09-06 21:13:51 +00006480 diagnosePointerIncompatibility(*this, Loc, LHS.get(), RHS.get());
Eli Friedman168fe152009-05-16 13:54:38 +00006481 }
6482 } else {
6483 // Pointee types must be compatible C99 6.5.6p3
6484 if (!Context.typesAreCompatible(
6485 Context.getCanonicalType(lpointee).getUnqualifiedType(),
6486 Context.getCanonicalType(rpointee).getUnqualifiedType())) {
Richard Trieu4ae7e972011-09-06 21:13:51 +00006487 diagnosePointerIncompatibility(*this, Loc, LHS.get(), RHS.get());
Eli Friedman168fe152009-05-16 13:54:38 +00006488 return QualType();
6489 }
Chris Lattner4d62f422007-12-09 21:53:25 +00006490 }
Mike Stump4e1f26a2009-02-19 03:04:26 +00006491
Chandler Carruthc9332212011-06-27 08:02:19 +00006492 if (!checkArithmeticBinOpPointerOperands(*this, Loc,
Richard Trieu4ae7e972011-09-06 21:13:51 +00006493 LHS.get(), RHS.get()))
Chandler Carruthc9332212011-06-27 08:02:19 +00006494 return QualType();
Eli Friedman8b7b1b12009-03-28 01:22:36 +00006495
Richard Trieu4ae7e972011-09-06 21:13:51 +00006496 if (CompLHSTy) *CompLHSTy = LHS.get()->getType();
Chris Lattner4d62f422007-12-09 21:53:25 +00006497 return Context.getPointerDiffType();
6498 }
6499 }
Mike Stump4e1f26a2009-02-19 03:04:26 +00006500
Richard Trieu4ae7e972011-09-06 21:13:51 +00006501 return InvalidOperands(Loc, LHS, RHS);
Steve Naroff218bc2b2007-05-04 21:54:46 +00006502}
6503
Douglas Gregor0bf31402010-10-08 23:50:27 +00006504static bool isScopedEnumerationType(QualType T) {
6505 if (const EnumType *ET = dyn_cast<EnumType>(T))
6506 return ET->getDecl()->isScoped();
6507 return false;
6508}
6509
Richard Trieue4a19fb2011-09-06 21:21:28 +00006510static void DiagnoseBadShiftValues(Sema& S, ExprResult &LHS, ExprResult &RHS,
Chandler Carruth4c6fdca2011-02-23 23:34:11 +00006511 SourceLocation Loc, unsigned Opc,
Richard Trieue4a19fb2011-09-06 21:21:28 +00006512 QualType LHSType) {
Chandler Carruth4c6fdca2011-02-23 23:34:11 +00006513 llvm::APSInt Right;
6514 // Check right/shifter operand
Richard Trieue4a19fb2011-09-06 21:21:28 +00006515 if (RHS.get()->isValueDependent() ||
6516 !RHS.get()->isIntegerConstantExpr(Right, S.Context))
Chandler Carruth4c6fdca2011-02-23 23:34:11 +00006517 return;
6518
6519 if (Right.isNegative()) {
Richard Trieue4a19fb2011-09-06 21:21:28 +00006520 S.DiagRuntimeBehavior(Loc, RHS.get(),
Ted Kremenek63657fe2011-03-01 18:09:31 +00006521 S.PDiag(diag::warn_shift_negative)
Richard Trieue4a19fb2011-09-06 21:21:28 +00006522 << RHS.get()->getSourceRange());
Chandler Carruth4c6fdca2011-02-23 23:34:11 +00006523 return;
6524 }
6525 llvm::APInt LeftBits(Right.getBitWidth(),
Richard Trieue4a19fb2011-09-06 21:21:28 +00006526 S.Context.getTypeSize(LHS.get()->getType()));
Chandler Carruth4c6fdca2011-02-23 23:34:11 +00006527 if (Right.uge(LeftBits)) {
Richard Trieue4a19fb2011-09-06 21:21:28 +00006528 S.DiagRuntimeBehavior(Loc, RHS.get(),
Ted Kremenek26bbc3d2011-03-01 19:13:22 +00006529 S.PDiag(diag::warn_shift_gt_typewidth)
Richard Trieue4a19fb2011-09-06 21:21:28 +00006530 << RHS.get()->getSourceRange());
Chandler Carruth4c6fdca2011-02-23 23:34:11 +00006531 return;
6532 }
6533 if (Opc != BO_Shl)
6534 return;
6535
6536 // When left shifting an ICE which is signed, we can check for overflow which
6537 // according to C++ has undefined behavior ([expr.shift] 5.8/2). Unsigned
6538 // integers have defined behavior modulo one more than the maximum value
6539 // representable in the result type, so never warn for those.
6540 llvm::APSInt Left;
Richard Trieue4a19fb2011-09-06 21:21:28 +00006541 if (LHS.get()->isValueDependent() ||
6542 !LHS.get()->isIntegerConstantExpr(Left, S.Context) ||
6543 LHSType->hasUnsignedIntegerRepresentation())
Chandler Carruth4c6fdca2011-02-23 23:34:11 +00006544 return;
6545 llvm::APInt ResultBits =
6546 static_cast<llvm::APInt&>(Right) + Left.getMinSignedBits();
6547 if (LeftBits.uge(ResultBits))
6548 return;
6549 llvm::APSInt Result = Left.extend(ResultBits.getLimitedValue());
6550 Result = Result.shl(Right);
6551
Ted Kremenek70f05fd2011-06-15 00:54:52 +00006552 // Print the bit representation of the signed integer as an unsigned
6553 // hexadecimal number.
Dylan Noblesmith2c1dd272012-02-05 02:13:05 +00006554 SmallString<40> HexResult;
Ted Kremenek70f05fd2011-06-15 00:54:52 +00006555 Result.toString(HexResult, 16, /*Signed =*/false, /*Literal =*/true);
6556
Chandler Carruth4c6fdca2011-02-23 23:34:11 +00006557 // If we are only missing a sign bit, this is less likely to result in actual
6558 // bugs -- if the result is cast back to an unsigned type, it will have the
6559 // expected value. Thus we place this behind a different warning that can be
6560 // turned off separately if needed.
6561 if (LeftBits == ResultBits - 1) {
Ted Kremenek70f05fd2011-06-15 00:54:52 +00006562 S.Diag(Loc, diag::warn_shift_result_sets_sign_bit)
Richard Trieue4a19fb2011-09-06 21:21:28 +00006563 << HexResult.str() << LHSType
6564 << LHS.get()->getSourceRange() << RHS.get()->getSourceRange();
Chandler Carruth4c6fdca2011-02-23 23:34:11 +00006565 return;
6566 }
6567
6568 S.Diag(Loc, diag::warn_shift_result_gt_typewidth)
Richard Trieue4a19fb2011-09-06 21:21:28 +00006569 << HexResult.str() << Result.getMinSignedBits() << LHSType
6570 << Left.getBitWidth() << LHS.get()->getSourceRange()
6571 << RHS.get()->getSourceRange();
Chandler Carruth4c6fdca2011-02-23 23:34:11 +00006572}
6573
Chris Lattner2a3569b2008-04-07 05:30:13 +00006574// C99 6.5.7
Richard Trieue4a19fb2011-09-06 21:21:28 +00006575QualType Sema::CheckShiftOperands(ExprResult &LHS, ExprResult &RHS,
Richard Trieucfc491d2011-08-02 04:35:43 +00006576 SourceLocation Loc, unsigned Opc,
Richard Trieuba63ce62011-09-09 01:45:06 +00006577 bool IsCompAssign) {
Richard Trieuf8916e12011-09-16 00:53:10 +00006578 checkArithmeticNull(*this, LHS, RHS, Loc, /*isCompare=*/false);
6579
Chris Lattner5c11c412007-12-12 05:47:28 +00006580 // C99 6.5.7p2: Each of the operands shall have integer type.
Richard Trieue4a19fb2011-09-06 21:21:28 +00006581 if (!LHS.get()->getType()->hasIntegerRepresentation() ||
6582 !RHS.get()->getType()->hasIntegerRepresentation())
6583 return InvalidOperands(Loc, LHS, RHS);
Mike Stump4e1f26a2009-02-19 03:04:26 +00006584
Douglas Gregor0bf31402010-10-08 23:50:27 +00006585 // C++0x: Don't allow scoped enums. FIXME: Use something better than
6586 // hasIntegerRepresentation() above instead of this.
Richard Trieue4a19fb2011-09-06 21:21:28 +00006587 if (isScopedEnumerationType(LHS.get()->getType()) ||
6588 isScopedEnumerationType(RHS.get()->getType())) {
6589 return InvalidOperands(Loc, LHS, RHS);
Douglas Gregor0bf31402010-10-08 23:50:27 +00006590 }
6591
Nate Begemane46ee9a2009-10-25 02:26:48 +00006592 // Vector shifts promote their scalar inputs to vector type.
Richard Trieue4a19fb2011-09-06 21:21:28 +00006593 if (LHS.get()->getType()->isVectorType() ||
6594 RHS.get()->getType()->isVectorType())
Richard Trieuba63ce62011-09-09 01:45:06 +00006595 return CheckVectorOperands(LHS, RHS, Loc, IsCompAssign);
Nate Begemane46ee9a2009-10-25 02:26:48 +00006596
Chris Lattner5c11c412007-12-12 05:47:28 +00006597 // Shifts don't perform usual arithmetic conversions, they just do integer
6598 // promotions on each operand. C99 6.5.7p3
Eli Friedman8b7b1b12009-03-28 01:22:36 +00006599
John McCall57cdd882010-12-16 19:28:59 +00006600 // For the LHS, do usual unary conversions, but then reset them away
6601 // if this is a compound assignment.
Richard Trieue4a19fb2011-09-06 21:21:28 +00006602 ExprResult OldLHS = LHS;
6603 LHS = UsualUnaryConversions(LHS.take());
6604 if (LHS.isInvalid())
John Wiegley01296292011-04-08 18:41:53 +00006605 return QualType();
Richard Trieue4a19fb2011-09-06 21:21:28 +00006606 QualType LHSType = LHS.get()->getType();
Richard Trieuba63ce62011-09-09 01:45:06 +00006607 if (IsCompAssign) LHS = OldLHS;
John McCall57cdd882010-12-16 19:28:59 +00006608
6609 // The RHS is simpler.
Richard Trieue4a19fb2011-09-06 21:21:28 +00006610 RHS = UsualUnaryConversions(RHS.take());
6611 if (RHS.isInvalid())
John Wiegley01296292011-04-08 18:41:53 +00006612 return QualType();
Mike Stump4e1f26a2009-02-19 03:04:26 +00006613
Ryan Flynnf53fab82009-08-07 16:20:20 +00006614 // Sanity-check shift operands
Richard Trieue4a19fb2011-09-06 21:21:28 +00006615 DiagnoseBadShiftValues(*this, LHS, RHS, Loc, Opc, LHSType);
Ryan Flynnf53fab82009-08-07 16:20:20 +00006616
Chris Lattner5c11c412007-12-12 05:47:28 +00006617 // "The type of the result is that of the promoted left operand."
Richard Trieue4a19fb2011-09-06 21:21:28 +00006618 return LHSType;
Steve Naroff26c8ea52007-03-21 21:08:52 +00006619}
6620
Chandler Carruth17773fc2010-07-10 12:30:03 +00006621static bool IsWithinTemplateSpecialization(Decl *D) {
6622 if (DeclContext *DC = D->getDeclContext()) {
6623 if (isa<ClassTemplateSpecializationDecl>(DC))
6624 return true;
6625 if (FunctionDecl *FD = dyn_cast<FunctionDecl>(DC))
6626 return FD->isFunctionTemplateSpecialization();
6627 }
6628 return false;
6629}
6630
Richard Trieueea56f72011-09-02 03:48:46 +00006631/// If two different enums are compared, raise a warning.
Richard Trieu1762d7c2011-09-06 21:27:33 +00006632static void checkEnumComparison(Sema &S, SourceLocation Loc, ExprResult &LHS,
6633 ExprResult &RHS) {
6634 QualType LHSStrippedType = LHS.get()->IgnoreParenImpCasts()->getType();
6635 QualType RHSStrippedType = RHS.get()->IgnoreParenImpCasts()->getType();
Richard Trieueea56f72011-09-02 03:48:46 +00006636
6637 const EnumType *LHSEnumType = LHSStrippedType->getAs<EnumType>();
6638 if (!LHSEnumType)
6639 return;
6640 const EnumType *RHSEnumType = RHSStrippedType->getAs<EnumType>();
6641 if (!RHSEnumType)
6642 return;
6643
6644 // Ignore anonymous enums.
6645 if (!LHSEnumType->getDecl()->getIdentifier())
6646 return;
6647 if (!RHSEnumType->getDecl()->getIdentifier())
6648 return;
6649
6650 if (S.Context.hasSameUnqualifiedType(LHSStrippedType, RHSStrippedType))
6651 return;
6652
6653 S.Diag(Loc, diag::warn_comparison_of_mixed_enum_types)
6654 << LHSStrippedType << RHSStrippedType
Richard Trieu1762d7c2011-09-06 21:27:33 +00006655 << LHS.get()->getSourceRange() << RHS.get()->getSourceRange();
Richard Trieueea56f72011-09-02 03:48:46 +00006656}
6657
Richard Trieudd82a5c2011-09-02 02:55:45 +00006658/// \brief Diagnose bad pointer comparisons.
6659static void diagnoseDistinctPointerComparison(Sema &S, SourceLocation Loc,
Richard Trieu1762d7c2011-09-06 21:27:33 +00006660 ExprResult &LHS, ExprResult &RHS,
Richard Trieuba63ce62011-09-09 01:45:06 +00006661 bool IsError) {
6662 S.Diag(Loc, IsError ? diag::err_typecheck_comparison_of_distinct_pointers
Richard Trieudd82a5c2011-09-02 02:55:45 +00006663 : diag::ext_typecheck_comparison_of_distinct_pointers)
Richard Trieu1762d7c2011-09-06 21:27:33 +00006664 << LHS.get()->getType() << RHS.get()->getType()
6665 << LHS.get()->getSourceRange() << RHS.get()->getSourceRange();
Richard Trieudd82a5c2011-09-02 02:55:45 +00006666}
6667
6668/// \brief Returns false if the pointers are converted to a composite type,
6669/// true otherwise.
6670static bool convertPointersToCompositeType(Sema &S, SourceLocation Loc,
Richard Trieu1762d7c2011-09-06 21:27:33 +00006671 ExprResult &LHS, ExprResult &RHS) {
Richard Trieudd82a5c2011-09-02 02:55:45 +00006672 // C++ [expr.rel]p2:
6673 // [...] Pointer conversions (4.10) and qualification
6674 // conversions (4.4) are performed on pointer operands (or on
6675 // a pointer operand and a null pointer constant) to bring
6676 // them to their composite pointer type. [...]
6677 //
6678 // C++ [expr.eq]p1 uses the same notion for (in)equality
6679 // comparisons of pointers.
6680
6681 // C++ [expr.eq]p2:
6682 // In addition, pointers to members can be compared, or a pointer to
6683 // member and a null pointer constant. Pointer to member conversions
6684 // (4.11) and qualification conversions (4.4) are performed to bring
6685 // them to a common type. If one operand is a null pointer constant,
6686 // the common type is the type of the other operand. Otherwise, the
6687 // common type is a pointer to member type similar (4.4) to the type
6688 // of one of the operands, with a cv-qualification signature (4.4)
6689 // that is the union of the cv-qualification signatures of the operand
6690 // types.
6691
Richard Trieu1762d7c2011-09-06 21:27:33 +00006692 QualType LHSType = LHS.get()->getType();
6693 QualType RHSType = RHS.get()->getType();
6694 assert((LHSType->isPointerType() && RHSType->isPointerType()) ||
6695 (LHSType->isMemberPointerType() && RHSType->isMemberPointerType()));
Richard Trieudd82a5c2011-09-02 02:55:45 +00006696
6697 bool NonStandardCompositeType = false;
Richard Trieu48277e52011-09-02 21:44:27 +00006698 bool *BoolPtr = S.isSFINAEContext() ? 0 : &NonStandardCompositeType;
Richard Trieu1762d7c2011-09-06 21:27:33 +00006699 QualType T = S.FindCompositePointerType(Loc, LHS, RHS, BoolPtr);
Richard Trieudd82a5c2011-09-02 02:55:45 +00006700 if (T.isNull()) {
Richard Trieu1762d7c2011-09-06 21:27:33 +00006701 diagnoseDistinctPointerComparison(S, Loc, LHS, RHS, /*isError*/true);
Richard Trieudd82a5c2011-09-02 02:55:45 +00006702 return true;
6703 }
6704
6705 if (NonStandardCompositeType)
6706 S.Diag(Loc, diag::ext_typecheck_comparison_of_distinct_pointers_nonstandard)
Richard Trieu1762d7c2011-09-06 21:27:33 +00006707 << LHSType << RHSType << T << LHS.get()->getSourceRange()
6708 << RHS.get()->getSourceRange();
Richard Trieudd82a5c2011-09-02 02:55:45 +00006709
Richard Trieu1762d7c2011-09-06 21:27:33 +00006710 LHS = S.ImpCastExprToType(LHS.take(), T, CK_BitCast);
6711 RHS = S.ImpCastExprToType(RHS.take(), T, CK_BitCast);
Richard Trieudd82a5c2011-09-02 02:55:45 +00006712 return false;
6713}
6714
6715static void diagnoseFunctionPointerToVoidComparison(Sema &S, SourceLocation Loc,
Richard Trieu1762d7c2011-09-06 21:27:33 +00006716 ExprResult &LHS,
6717 ExprResult &RHS,
Richard Trieuba63ce62011-09-09 01:45:06 +00006718 bool IsError) {
6719 S.Diag(Loc, IsError ? diag::err_typecheck_comparison_of_fptr_to_void
6720 : diag::ext_typecheck_comparison_of_fptr_to_void)
Richard Trieu1762d7c2011-09-06 21:27:33 +00006721 << LHS.get()->getType() << RHS.get()->getType()
6722 << LHS.get()->getSourceRange() << RHS.get()->getSourceRange();
Richard Trieudd82a5c2011-09-02 02:55:45 +00006723}
6724
Jordan Rosed49a33e2012-06-08 21:14:25 +00006725static bool isObjCObjectLiteral(ExprResult &E) {
6726 switch (E.get()->getStmtClass()) {
6727 case Stmt::ObjCArrayLiteralClass:
6728 case Stmt::ObjCDictionaryLiteralClass:
6729 case Stmt::ObjCStringLiteralClass:
6730 case Stmt::ObjCBoxedExprClass:
6731 return true;
6732 default:
6733 // Note that ObjCBoolLiteral is NOT an object literal!
6734 return false;
6735 }
6736}
6737
Jordan Rose7660f782012-07-17 17:46:40 +00006738static bool hasIsEqualMethod(Sema &S, const Expr *LHS, const Expr *RHS) {
6739 // Get the LHS object's interface type.
6740 QualType Type = LHS->getType();
6741 QualType InterfaceType;
6742 if (const ObjCObjectPointerType *PTy = Type->getAs<ObjCObjectPointerType>()) {
6743 InterfaceType = PTy->getPointeeType();
6744 if (const ObjCObjectType *iQFaceTy =
6745 InterfaceType->getAsObjCQualifiedInterfaceType())
6746 InterfaceType = iQFaceTy->getBaseType();
6747 } else {
6748 // If this is not actually an Objective-C object, bail out.
6749 return false;
6750 }
6751
6752 // If the RHS isn't an Objective-C object, bail out.
6753 if (!RHS->getType()->isObjCObjectPointerType())
6754 return false;
6755
6756 // Try to find the -isEqual: method.
6757 Selector IsEqualSel = S.NSAPIObj->getIsEqualSelector();
6758 ObjCMethodDecl *Method = S.LookupMethodInObjectType(IsEqualSel,
6759 InterfaceType,
6760 /*instance=*/true);
6761 if (!Method) {
6762 if (Type->isObjCIdType()) {
6763 // For 'id', just check the global pool.
6764 Method = S.LookupInstanceMethodInGlobalPool(IsEqualSel, SourceRange(),
6765 /*receiverId=*/true,
6766 /*warn=*/false);
6767 } else {
6768 // Check protocols.
6769 Method = S.LookupMethodInQualifiedType(IsEqualSel,
6770 cast<ObjCObjectPointerType>(Type),
6771 /*instance=*/true);
6772 }
6773 }
6774
6775 if (!Method)
6776 return false;
6777
6778 QualType T = Method->param_begin()[0]->getType();
6779 if (!T->isObjCObjectPointerType())
6780 return false;
6781
6782 QualType R = Method->getResultType();
6783 if (!R->isScalarType())
6784 return false;
6785
6786 return true;
6787}
6788
6789static void diagnoseObjCLiteralComparison(Sema &S, SourceLocation Loc,
6790 ExprResult &LHS, ExprResult &RHS,
6791 BinaryOperator::Opcode Opc){
Jordan Rose63ffaa82012-07-17 17:46:48 +00006792 Expr *Literal;
6793 Expr *Other;
6794 if (isObjCObjectLiteral(LHS)) {
6795 Literal = LHS.get();
6796 Other = RHS.get();
6797 } else {
6798 Literal = RHS.get();
6799 Other = LHS.get();
6800 }
6801
6802 // Don't warn on comparisons against nil.
6803 Other = Other->IgnoreParenCasts();
6804 if (Other->isNullPointerConstant(S.getASTContext(),
6805 Expr::NPC_ValueDependentIsNotNull))
6806 return;
Jordan Rosed49a33e2012-06-08 21:14:25 +00006807
Jordan Roseea70bf72012-07-17 17:46:44 +00006808 // This should be kept in sync with warn_objc_literal_comparison.
Jordan Rose63ffaa82012-07-17 17:46:48 +00006809 // LK_String should always be last, since it has its own warning flag.
Jordan Roseea70bf72012-07-17 17:46:44 +00006810 enum {
6811 LK_Array,
6812 LK_Dictionary,
6813 LK_Numeric,
6814 LK_Boxed,
6815 LK_String
6816 } LiteralKind;
6817
Jordan Rosed49a33e2012-06-08 21:14:25 +00006818 switch (Literal->getStmtClass()) {
6819 case Stmt::ObjCStringLiteralClass:
6820 // "string literal"
Jordan Roseea70bf72012-07-17 17:46:44 +00006821 LiteralKind = LK_String;
Jordan Rosed49a33e2012-06-08 21:14:25 +00006822 break;
6823 case Stmt::ObjCArrayLiteralClass:
6824 // "array literal"
Jordan Roseea70bf72012-07-17 17:46:44 +00006825 LiteralKind = LK_Array;
Jordan Rosed49a33e2012-06-08 21:14:25 +00006826 break;
6827 case Stmt::ObjCDictionaryLiteralClass:
6828 // "dictionary literal"
Jordan Roseea70bf72012-07-17 17:46:44 +00006829 LiteralKind = LK_Dictionary;
Jordan Rosed49a33e2012-06-08 21:14:25 +00006830 break;
6831 case Stmt::ObjCBoxedExprClass: {
6832 Expr *Inner = cast<ObjCBoxedExpr>(Literal)->getSubExpr();
6833 switch (Inner->getStmtClass()) {
6834 case Stmt::IntegerLiteralClass:
6835 case Stmt::FloatingLiteralClass:
6836 case Stmt::CharacterLiteralClass:
6837 case Stmt::ObjCBoolLiteralExprClass:
6838 case Stmt::CXXBoolLiteralExprClass:
6839 // "numeric literal"
Jordan Roseea70bf72012-07-17 17:46:44 +00006840 LiteralKind = LK_Numeric;
Jordan Rosed49a33e2012-06-08 21:14:25 +00006841 break;
6842 case Stmt::ImplicitCastExprClass: {
6843 CastKind CK = cast<CastExpr>(Inner)->getCastKind();
6844 // Boolean literals can be represented by implicit casts.
6845 if (CK == CK_IntegralToBoolean || CK == CK_IntegralCast) {
Jordan Roseea70bf72012-07-17 17:46:44 +00006846 LiteralKind = LK_Numeric;
Jordan Rosed49a33e2012-06-08 21:14:25 +00006847 break;
6848 }
6849 // FALLTHROUGH
6850 }
6851 default:
6852 // "boxed expression"
Jordan Roseea70bf72012-07-17 17:46:44 +00006853 LiteralKind = LK_Boxed;
Jordan Rosed49a33e2012-06-08 21:14:25 +00006854 break;
6855 }
6856 break;
6857 }
6858 default:
6859 llvm_unreachable("Unknown Objective-C object literal kind");
6860 }
6861
Jordan Roseea70bf72012-07-17 17:46:44 +00006862 if (LiteralKind == LK_String)
6863 S.Diag(Loc, diag::warn_objc_string_literal_comparison)
6864 << Literal->getSourceRange();
6865 else
6866 S.Diag(Loc, diag::warn_objc_literal_comparison)
6867 << LiteralKind << Literal->getSourceRange();
Jordan Rosed49a33e2012-06-08 21:14:25 +00006868
Jordan Rose7660f782012-07-17 17:46:40 +00006869 if (BinaryOperator::isEqualityOp(Opc) &&
6870 hasIsEqualMethod(S, LHS.get(), RHS.get())) {
6871 SourceLocation Start = LHS.get()->getLocStart();
6872 SourceLocation End = S.PP.getLocForEndOfToken(RHS.get()->getLocEnd());
6873 SourceRange OpRange(Loc, S.PP.getLocForEndOfToken(Loc));
Jordan Rosef9198032012-07-09 16:54:44 +00006874
Jordan Rose7660f782012-07-17 17:46:40 +00006875 S.Diag(Loc, diag::note_objc_literal_comparison_isequal)
6876 << FixItHint::CreateInsertion(Start, Opc == BO_EQ ? "[" : "![")
6877 << FixItHint::CreateReplacement(OpRange, "isEqual:")
6878 << FixItHint::CreateInsertion(End, "]");
Jordan Rosed49a33e2012-06-08 21:14:25 +00006879 }
Jordan Rosed49a33e2012-06-08 21:14:25 +00006880}
6881
Douglas Gregor5b07c7e2009-05-04 06:07:12 +00006882// C99 6.5.8, C++ [expr.rel]
Richard Trieub80728f2011-09-06 21:43:51 +00006883QualType Sema::CheckCompareOperands(ExprResult &LHS, ExprResult &RHS,
Richard Trieucfc491d2011-08-02 04:35:43 +00006884 SourceLocation Loc, unsigned OpaqueOpc,
Richard Trieuba63ce62011-09-09 01:45:06 +00006885 bool IsRelational) {
Richard Trieuf8916e12011-09-16 00:53:10 +00006886 checkArithmeticNull(*this, LHS, RHS, Loc, /*isCompare=*/true);
6887
John McCalle3027922010-08-25 11:45:40 +00006888 BinaryOperatorKind Opc = (BinaryOperatorKind) OpaqueOpc;
Douglas Gregor7a5bc762009-04-06 18:45:53 +00006889
Chris Lattner9a152e22009-12-05 05:40:13 +00006890 // Handle vector comparisons separately.
Richard Trieub80728f2011-09-06 21:43:51 +00006891 if (LHS.get()->getType()->isVectorType() ||
6892 RHS.get()->getType()->isVectorType())
Richard Trieuba63ce62011-09-09 01:45:06 +00006893 return CheckVectorCompareOperands(LHS, RHS, Loc, IsRelational);
Mike Stump4e1f26a2009-02-19 03:04:26 +00006894
Richard Trieub80728f2011-09-06 21:43:51 +00006895 QualType LHSType = LHS.get()->getType();
6896 QualType RHSType = RHS.get()->getType();
Benjamin Kramera66aaa92011-09-03 08:46:20 +00006897
Richard Trieub80728f2011-09-06 21:43:51 +00006898 Expr *LHSStripped = LHS.get()->IgnoreParenImpCasts();
6899 Expr *RHSStripped = RHS.get()->IgnoreParenImpCasts();
Chandler Carruth712563b2011-02-17 08:37:06 +00006900
Richard Trieub80728f2011-09-06 21:43:51 +00006901 checkEnumComparison(*this, Loc, LHS, RHS);
Chandler Carruth712563b2011-02-17 08:37:06 +00006902
Richard Trieub80728f2011-09-06 21:43:51 +00006903 if (!LHSType->hasFloatingRepresentation() &&
Richard Trieuba63ce62011-09-09 01:45:06 +00006904 !(LHSType->isBlockPointerType() && IsRelational) &&
Richard Trieub80728f2011-09-06 21:43:51 +00006905 !LHS.get()->getLocStart().isMacroID() &&
6906 !RHS.get()->getLocStart().isMacroID()) {
Chris Lattner222b8bd2009-03-08 19:39:53 +00006907 // For non-floating point types, check for self-comparisons of the form
6908 // x == x, x != x, x < x, etc. These always evaluate to a constant, and
6909 // often indicate logic errors in the program.
Chandler Carruth65a38182010-07-12 06:23:38 +00006910 //
6911 // NOTE: Don't warn about comparison expressions resulting from macro
6912 // expansion. Also don't warn about comparisons which are only self
6913 // comparisons within a template specialization. The warnings should catch
6914 // obvious cases in the definition of the template anyways. The idea is to
6915 // warn when the typed comparison operator will always evaluate to the same
6916 // result.
Chandler Carruth17773fc2010-07-10 12:30:03 +00006917 if (DeclRefExpr* DRL = dyn_cast<DeclRefExpr>(LHSStripped)) {
Douglas Gregorec170db2010-06-08 19:50:34 +00006918 if (DeclRefExpr* DRR = dyn_cast<DeclRefExpr>(RHSStripped)) {
Ted Kremenek853734e2010-09-16 00:03:01 +00006919 if (DRL->getDecl() == DRR->getDecl() &&
Chandler Carruth17773fc2010-07-10 12:30:03 +00006920 !IsWithinTemplateSpecialization(DRL->getDecl())) {
Ted Kremenek3427fac2011-02-23 01:52:04 +00006921 DiagRuntimeBehavior(Loc, 0, PDiag(diag::warn_comparison_always)
Douglas Gregorec170db2010-06-08 19:50:34 +00006922 << 0 // self-
John McCalle3027922010-08-25 11:45:40 +00006923 << (Opc == BO_EQ
6924 || Opc == BO_LE
6925 || Opc == BO_GE));
Richard Trieub80728f2011-09-06 21:43:51 +00006926 } else if (LHSType->isArrayType() && RHSType->isArrayType() &&
Douglas Gregorec170db2010-06-08 19:50:34 +00006927 !DRL->getDecl()->getType()->isReferenceType() &&
6928 !DRR->getDecl()->getType()->isReferenceType()) {
6929 // what is it always going to eval to?
6930 char always_evals_to;
6931 switch(Opc) {
John McCalle3027922010-08-25 11:45:40 +00006932 case BO_EQ: // e.g. array1 == array2
Douglas Gregorec170db2010-06-08 19:50:34 +00006933 always_evals_to = 0; // false
6934 break;
John McCalle3027922010-08-25 11:45:40 +00006935 case BO_NE: // e.g. array1 != array2
Douglas Gregorec170db2010-06-08 19:50:34 +00006936 always_evals_to = 1; // true
6937 break;
6938 default:
6939 // best we can say is 'a constant'
6940 always_evals_to = 2; // e.g. array1 <= array2
6941 break;
6942 }
Ted Kremenek3427fac2011-02-23 01:52:04 +00006943 DiagRuntimeBehavior(Loc, 0, PDiag(diag::warn_comparison_always)
Douglas Gregorec170db2010-06-08 19:50:34 +00006944 << 1 // array
6945 << always_evals_to);
6946 }
6947 }
Chandler Carruth17773fc2010-07-10 12:30:03 +00006948 }
Mike Stump11289f42009-09-09 15:08:12 +00006949
Chris Lattner222b8bd2009-03-08 19:39:53 +00006950 if (isa<CastExpr>(LHSStripped))
6951 LHSStripped = LHSStripped->IgnoreParenCasts();
6952 if (isa<CastExpr>(RHSStripped))
6953 RHSStripped = RHSStripped->IgnoreParenCasts();
Mike Stump11289f42009-09-09 15:08:12 +00006954
Chris Lattner222b8bd2009-03-08 19:39:53 +00006955 // Warn about comparisons against a string constant (unless the other
6956 // operand is null), the user probably wants strcmp.
Douglas Gregor7a5bc762009-04-06 18:45:53 +00006957 Expr *literalString = 0;
6958 Expr *literalStringStripped = 0;
Chris Lattner222b8bd2009-03-08 19:39:53 +00006959 if ((isa<StringLiteral>(LHSStripped) || isa<ObjCEncodeExpr>(LHSStripped)) &&
Kovarththanan Rajaratnamba2c6522010-03-13 10:17:05 +00006960 !RHSStripped->isNullPointerConstant(Context,
Douglas Gregor56751b52009-09-25 04:25:58 +00006961 Expr::NPC_ValueDependentIsNull)) {
Richard Trieub80728f2011-09-06 21:43:51 +00006962 literalString = LHS.get();
Douglas Gregor7a5bc762009-04-06 18:45:53 +00006963 literalStringStripped = LHSStripped;
Mike Stump12b8ce12009-08-04 21:02:39 +00006964 } else if ((isa<StringLiteral>(RHSStripped) ||
6965 isa<ObjCEncodeExpr>(RHSStripped)) &&
Kovarththanan Rajaratnamba2c6522010-03-13 10:17:05 +00006966 !LHSStripped->isNullPointerConstant(Context,
Douglas Gregor56751b52009-09-25 04:25:58 +00006967 Expr::NPC_ValueDependentIsNull)) {
Richard Trieub80728f2011-09-06 21:43:51 +00006968 literalString = RHS.get();
Douglas Gregor7a5bc762009-04-06 18:45:53 +00006969 literalStringStripped = RHSStripped;
6970 }
6971
6972 if (literalString) {
6973 std::string resultComparison;
6974 switch (Opc) {
John McCalle3027922010-08-25 11:45:40 +00006975 case BO_LT: resultComparison = ") < 0"; break;
6976 case BO_GT: resultComparison = ") > 0"; break;
6977 case BO_LE: resultComparison = ") <= 0"; break;
6978 case BO_GE: resultComparison = ") >= 0"; break;
6979 case BO_EQ: resultComparison = ") == 0"; break;
6980 case BO_NE: resultComparison = ") != 0"; break;
David Blaikie83d382b2011-09-23 05:06:16 +00006981 default: llvm_unreachable("Invalid comparison operator");
Douglas Gregor7a5bc762009-04-06 18:45:53 +00006982 }
Kovarththanan Rajaratnamba2c6522010-03-13 10:17:05 +00006983
Ted Kremenek3427fac2011-02-23 01:52:04 +00006984 DiagRuntimeBehavior(Loc, 0,
Douglas Gregor49862b82010-01-12 23:18:54 +00006985 PDiag(diag::warn_stringcompare)
6986 << isa<ObjCEncodeExpr>(literalStringStripped)
Ted Kremenek800b66b2010-04-09 20:26:53 +00006987 << literalString->getSourceRange());
Douglas Gregor7a5bc762009-04-06 18:45:53 +00006988 }
Ted Kremeneke451eae2007-10-29 16:58:49 +00006989 }
Mike Stump4e1f26a2009-02-19 03:04:26 +00006990
Douglas Gregorec170db2010-06-08 19:50:34 +00006991 // C99 6.5.8p3 / C99 6.5.9p4
Richard Trieub80728f2011-09-06 21:43:51 +00006992 if (LHS.get()->getType()->isArithmeticType() &&
6993 RHS.get()->getType()->isArithmeticType()) {
6994 UsualArithmeticConversions(LHS, RHS);
6995 if (LHS.isInvalid() || RHS.isInvalid())
John Wiegley01296292011-04-08 18:41:53 +00006996 return QualType();
6997 }
Douglas Gregorec170db2010-06-08 19:50:34 +00006998 else {
Richard Trieub80728f2011-09-06 21:43:51 +00006999 LHS = UsualUnaryConversions(LHS.take());
7000 if (LHS.isInvalid())
John Wiegley01296292011-04-08 18:41:53 +00007001 return QualType();
7002
Richard Trieub80728f2011-09-06 21:43:51 +00007003 RHS = UsualUnaryConversions(RHS.take());
7004 if (RHS.isInvalid())
John Wiegley01296292011-04-08 18:41:53 +00007005 return QualType();
Douglas Gregorec170db2010-06-08 19:50:34 +00007006 }
7007
Richard Trieub80728f2011-09-06 21:43:51 +00007008 LHSType = LHS.get()->getType();
7009 RHSType = RHS.get()->getType();
Douglas Gregorec170db2010-06-08 19:50:34 +00007010
Douglas Gregorca63811b2008-11-19 03:25:36 +00007011 // The result of comparisons is 'bool' in C++, 'int' in C.
Argyrios Kyrtzidis1bdd6882011-02-18 20:55:15 +00007012 QualType ResultTy = Context.getLogicalOperationType();
Douglas Gregorca63811b2008-11-19 03:25:36 +00007013
Richard Trieuba63ce62011-09-09 01:45:06 +00007014 if (IsRelational) {
Richard Trieub80728f2011-09-06 21:43:51 +00007015 if (LHSType->isRealType() && RHSType->isRealType())
Douglas Gregorca63811b2008-11-19 03:25:36 +00007016 return ResultTy;
Chris Lattnerb620c342007-08-26 01:18:55 +00007017 } else {
Ted Kremeneke2763b02007-10-29 17:13:39 +00007018 // Check for comparisons of floating point operands using != and ==.
Richard Trieub80728f2011-09-06 21:43:51 +00007019 if (LHSType->hasFloatingRepresentation())
7020 CheckFloatComparison(Loc, LHS.get(), RHS.get());
Mike Stump4e1f26a2009-02-19 03:04:26 +00007021
Richard Trieub80728f2011-09-06 21:43:51 +00007022 if (LHSType->isArithmeticType() && RHSType->isArithmeticType())
Douglas Gregorca63811b2008-11-19 03:25:36 +00007023 return ResultTy;
Chris Lattnerb620c342007-08-26 01:18:55 +00007024 }
Mike Stump4e1f26a2009-02-19 03:04:26 +00007025
Richard Trieub80728f2011-09-06 21:43:51 +00007026 bool LHSIsNull = LHS.get()->isNullPointerConstant(Context,
Douglas Gregor56751b52009-09-25 04:25:58 +00007027 Expr::NPC_ValueDependentIsNull);
Richard Trieub80728f2011-09-06 21:43:51 +00007028 bool RHSIsNull = RHS.get()->isNullPointerConstant(Context,
Douglas Gregor56751b52009-09-25 04:25:58 +00007029 Expr::NPC_ValueDependentIsNull);
Mike Stump4e1f26a2009-02-19 03:04:26 +00007030
Douglas Gregorf267edd2010-06-15 21:38:40 +00007031 // All of the following pointer-related warnings are GCC extensions, except
7032 // when handling null pointer constants.
Richard Trieub80728f2011-09-06 21:43:51 +00007033 if (LHSType->isPointerType() && RHSType->isPointerType()) { // C99 6.5.8p2
Chris Lattner3a0702e2008-04-03 05:07:25 +00007034 QualType LCanPointeeTy =
John McCall9320b872011-09-09 05:25:32 +00007035 LHSType->castAs<PointerType>()->getPointeeType().getCanonicalType();
Chris Lattner3a0702e2008-04-03 05:07:25 +00007036 QualType RCanPointeeTy =
John McCall9320b872011-09-09 05:25:32 +00007037 RHSType->castAs<PointerType>()->getPointeeType().getCanonicalType();
Mike Stump4e1f26a2009-02-19 03:04:26 +00007038
David Blaikiebbafb8a2012-03-11 07:00:24 +00007039 if (getLangOpts().CPlusPlus) {
Eli Friedman16c209612009-08-23 00:27:47 +00007040 if (LCanPointeeTy == RCanPointeeTy)
7041 return ResultTy;
Richard Trieuba63ce62011-09-09 01:45:06 +00007042 if (!IsRelational &&
Fariborz Jahanianffc420c2009-12-21 18:19:17 +00007043 (LCanPointeeTy->isVoidType() || RCanPointeeTy->isVoidType())) {
7044 // Valid unless comparison between non-null pointer and function pointer
7045 // This is a gcc extension compatibility comparison.
Douglas Gregorf267edd2010-06-15 21:38:40 +00007046 // In a SFINAE context, we treat this as a hard error to maintain
7047 // conformance with the C++ standard.
Fariborz Jahanianffc420c2009-12-21 18:19:17 +00007048 if ((LCanPointeeTy->isFunctionType() || RCanPointeeTy->isFunctionType())
7049 && !LHSIsNull && !RHSIsNull) {
Richard Trieudd82a5c2011-09-02 02:55:45 +00007050 diagnoseFunctionPointerToVoidComparison(
Richard Trieub80728f2011-09-06 21:43:51 +00007051 *this, Loc, LHS, RHS, /*isError*/ isSFINAEContext());
Douglas Gregorf267edd2010-06-15 21:38:40 +00007052
7053 if (isSFINAEContext())
7054 return QualType();
7055
Richard Trieub80728f2011-09-06 21:43:51 +00007056 RHS = ImpCastExprToType(RHS.take(), LHSType, CK_BitCast);
Fariborz Jahanianffc420c2009-12-21 18:19:17 +00007057 return ResultTy;
7058 }
7059 }
Anders Carlssona95069c2010-11-04 03:17:43 +00007060
Richard Trieub80728f2011-09-06 21:43:51 +00007061 if (convertPointersToCompositeType(*this, Loc, LHS, RHS))
Douglas Gregor5b07c7e2009-05-04 06:07:12 +00007062 return QualType();
Richard Trieudd82a5c2011-09-02 02:55:45 +00007063 else
7064 return ResultTy;
Douglas Gregor5b07c7e2009-05-04 06:07:12 +00007065 }
Eli Friedman16c209612009-08-23 00:27:47 +00007066 // C99 6.5.9p2 and C99 6.5.8p2
7067 if (Context.typesAreCompatible(LCanPointeeTy.getUnqualifiedType(),
7068 RCanPointeeTy.getUnqualifiedType())) {
7069 // Valid unless a relational comparison of function pointers
Richard Trieuba63ce62011-09-09 01:45:06 +00007070 if (IsRelational && LCanPointeeTy->isFunctionType()) {
Eli Friedman16c209612009-08-23 00:27:47 +00007071 Diag(Loc, diag::ext_typecheck_ordered_comparison_of_function_pointers)
Richard Trieub80728f2011-09-06 21:43:51 +00007072 << LHSType << RHSType << LHS.get()->getSourceRange()
7073 << RHS.get()->getSourceRange();
Eli Friedman16c209612009-08-23 00:27:47 +00007074 }
Richard Trieuba63ce62011-09-09 01:45:06 +00007075 } else if (!IsRelational &&
Eli Friedman16c209612009-08-23 00:27:47 +00007076 (LCanPointeeTy->isVoidType() || RCanPointeeTy->isVoidType())) {
7077 // Valid unless comparison between non-null pointer and function pointer
7078 if ((LCanPointeeTy->isFunctionType() || RCanPointeeTy->isFunctionType())
Richard Trieudd82a5c2011-09-02 02:55:45 +00007079 && !LHSIsNull && !RHSIsNull)
Richard Trieub80728f2011-09-06 21:43:51 +00007080 diagnoseFunctionPointerToVoidComparison(*this, Loc, LHS, RHS,
Richard Trieudd82a5c2011-09-02 02:55:45 +00007081 /*isError*/false);
Eli Friedman16c209612009-08-23 00:27:47 +00007082 } else {
7083 // Invalid
Richard Trieub80728f2011-09-06 21:43:51 +00007084 diagnoseDistinctPointerComparison(*this, Loc, LHS, RHS, /*isError*/false);
Steve Naroff75c17232007-06-13 21:41:08 +00007085 }
John McCall7684dde2011-03-11 04:25:25 +00007086 if (LCanPointeeTy != RCanPointeeTy) {
7087 if (LHSIsNull && !RHSIsNull)
Richard Trieub80728f2011-09-06 21:43:51 +00007088 LHS = ImpCastExprToType(LHS.take(), RHSType, CK_BitCast);
John McCall7684dde2011-03-11 04:25:25 +00007089 else
Richard Trieub80728f2011-09-06 21:43:51 +00007090 RHS = ImpCastExprToType(RHS.take(), LHSType, CK_BitCast);
John McCall7684dde2011-03-11 04:25:25 +00007091 }
Douglas Gregorca63811b2008-11-19 03:25:36 +00007092 return ResultTy;
Steve Naroffcdee44c2007-08-16 21:48:38 +00007093 }
Mike Stump11289f42009-09-09 15:08:12 +00007094
David Blaikiebbafb8a2012-03-11 07:00:24 +00007095 if (getLangOpts().CPlusPlus) {
Anders Carlssona95069c2010-11-04 03:17:43 +00007096 // Comparison of nullptr_t with itself.
Richard Trieub80728f2011-09-06 21:43:51 +00007097 if (LHSType->isNullPtrType() && RHSType->isNullPtrType())
Anders Carlssona95069c2010-11-04 03:17:43 +00007098 return ResultTy;
7099
Mike Stump11289f42009-09-09 15:08:12 +00007100 // Comparison of pointers with null pointer constants and equality
Douglas Gregorb00b10e2009-08-24 17:42:35 +00007101 // comparisons of member pointers to null pointer constants.
Mike Stump11289f42009-09-09 15:08:12 +00007102 if (RHSIsNull &&
Richard Trieub80728f2011-09-06 21:43:51 +00007103 ((LHSType->isAnyPointerType() || LHSType->isNullPtrType()) ||
Richard Trieuba63ce62011-09-09 01:45:06 +00007104 (!IsRelational &&
Richard Trieub80728f2011-09-06 21:43:51 +00007105 (LHSType->isMemberPointerType() || LHSType->isBlockPointerType())))) {
7106 RHS = ImpCastExprToType(RHS.take(), LHSType,
7107 LHSType->isMemberPointerType()
John McCalle3027922010-08-25 11:45:40 +00007108 ? CK_NullToMemberPointer
John McCalle84af4e2010-11-13 01:35:44 +00007109 : CK_NullToPointer);
Sebastian Redl576fd422009-05-10 18:38:11 +00007110 return ResultTy;
7111 }
Douglas Gregorb00b10e2009-08-24 17:42:35 +00007112 if (LHSIsNull &&
Richard Trieub80728f2011-09-06 21:43:51 +00007113 ((RHSType->isAnyPointerType() || RHSType->isNullPtrType()) ||
Richard Trieuba63ce62011-09-09 01:45:06 +00007114 (!IsRelational &&
Richard Trieub80728f2011-09-06 21:43:51 +00007115 (RHSType->isMemberPointerType() || RHSType->isBlockPointerType())))) {
7116 LHS = ImpCastExprToType(LHS.take(), RHSType,
7117 RHSType->isMemberPointerType()
John McCalle3027922010-08-25 11:45:40 +00007118 ? CK_NullToMemberPointer
John McCalle84af4e2010-11-13 01:35:44 +00007119 : CK_NullToPointer);
Sebastian Redl576fd422009-05-10 18:38:11 +00007120 return ResultTy;
7121 }
Douglas Gregorb00b10e2009-08-24 17:42:35 +00007122
7123 // Comparison of member pointers.
Richard Trieuba63ce62011-09-09 01:45:06 +00007124 if (!IsRelational &&
Richard Trieub80728f2011-09-06 21:43:51 +00007125 LHSType->isMemberPointerType() && RHSType->isMemberPointerType()) {
7126 if (convertPointersToCompositeType(*this, Loc, LHS, RHS))
Douglas Gregorb00b10e2009-08-24 17:42:35 +00007127 return QualType();
Richard Trieudd82a5c2011-09-02 02:55:45 +00007128 else
7129 return ResultTy;
Douglas Gregorb00b10e2009-08-24 17:42:35 +00007130 }
Douglas Gregor48e6bbf2011-03-01 17:16:20 +00007131
7132 // Handle scoped enumeration types specifically, since they don't promote
7133 // to integers.
Richard Trieub80728f2011-09-06 21:43:51 +00007134 if (LHS.get()->getType()->isEnumeralType() &&
7135 Context.hasSameUnqualifiedType(LHS.get()->getType(),
7136 RHS.get()->getType()))
Douglas Gregor48e6bbf2011-03-01 17:16:20 +00007137 return ResultTy;
Sebastian Redl576fd422009-05-10 18:38:11 +00007138 }
Mike Stump11289f42009-09-09 15:08:12 +00007139
Steve Naroff081c7422008-09-04 15:10:53 +00007140 // Handle block pointer types.
Richard Trieuba63ce62011-09-09 01:45:06 +00007141 if (!IsRelational && LHSType->isBlockPointerType() &&
Richard Trieub80728f2011-09-06 21:43:51 +00007142 RHSType->isBlockPointerType()) {
John McCall9320b872011-09-09 05:25:32 +00007143 QualType lpointee = LHSType->castAs<BlockPointerType>()->getPointeeType();
7144 QualType rpointee = RHSType->castAs<BlockPointerType>()->getPointeeType();
Mike Stump4e1f26a2009-02-19 03:04:26 +00007145
Steve Naroff081c7422008-09-04 15:10:53 +00007146 if (!LHSIsNull && !RHSIsNull &&
Eli Friedmana6638ca2009-06-08 05:08:54 +00007147 !Context.typesAreCompatible(lpointee, rpointee)) {
Chris Lattner377d1f82008-11-18 22:52:51 +00007148 Diag(Loc, diag::err_typecheck_comparison_of_distinct_blocks)
Richard Trieub80728f2011-09-06 21:43:51 +00007149 << LHSType << RHSType << LHS.get()->getSourceRange()
7150 << RHS.get()->getSourceRange();
Steve Naroff081c7422008-09-04 15:10:53 +00007151 }
Richard Trieub80728f2011-09-06 21:43:51 +00007152 RHS = ImpCastExprToType(RHS.take(), LHSType, CK_BitCast);
Douglas Gregorca63811b2008-11-19 03:25:36 +00007153 return ResultTy;
Steve Naroff081c7422008-09-04 15:10:53 +00007154 }
John Wiegley01296292011-04-08 18:41:53 +00007155
Steve Naroffe18f94c2008-09-28 01:11:11 +00007156 // Allow block pointers to be compared with null pointer constants.
Richard Trieuba63ce62011-09-09 01:45:06 +00007157 if (!IsRelational
Richard Trieub80728f2011-09-06 21:43:51 +00007158 && ((LHSType->isBlockPointerType() && RHSType->isPointerType())
7159 || (LHSType->isPointerType() && RHSType->isBlockPointerType()))) {
Steve Naroffe18f94c2008-09-28 01:11:11 +00007160 if (!LHSIsNull && !RHSIsNull) {
Richard Trieub80728f2011-09-06 21:43:51 +00007161 if (!((RHSType->isPointerType() && RHSType->castAs<PointerType>()
Mike Stump1b821b42009-05-07 03:14:14 +00007162 ->getPointeeType()->isVoidType())
Richard Trieub80728f2011-09-06 21:43:51 +00007163 || (LHSType->isPointerType() && LHSType->castAs<PointerType>()
Mike Stump1b821b42009-05-07 03:14:14 +00007164 ->getPointeeType()->isVoidType())))
7165 Diag(Loc, diag::err_typecheck_comparison_of_distinct_blocks)
Richard Trieub80728f2011-09-06 21:43:51 +00007166 << LHSType << RHSType << LHS.get()->getSourceRange()
7167 << RHS.get()->getSourceRange();
Steve Naroffe18f94c2008-09-28 01:11:11 +00007168 }
John McCall7684dde2011-03-11 04:25:25 +00007169 if (LHSIsNull && !RHSIsNull)
John McCall9320b872011-09-09 05:25:32 +00007170 LHS = ImpCastExprToType(LHS.take(), RHSType,
7171 RHSType->isPointerType() ? CK_BitCast
7172 : CK_AnyPointerToBlockPointerCast);
John McCall7684dde2011-03-11 04:25:25 +00007173 else
John McCall9320b872011-09-09 05:25:32 +00007174 RHS = ImpCastExprToType(RHS.take(), LHSType,
7175 LHSType->isPointerType() ? CK_BitCast
7176 : CK_AnyPointerToBlockPointerCast);
Douglas Gregorca63811b2008-11-19 03:25:36 +00007177 return ResultTy;
Steve Naroffe18f94c2008-09-28 01:11:11 +00007178 }
Steve Naroff081c7422008-09-04 15:10:53 +00007179
Richard Trieub80728f2011-09-06 21:43:51 +00007180 if (LHSType->isObjCObjectPointerType() ||
7181 RHSType->isObjCObjectPointerType()) {
7182 const PointerType *LPT = LHSType->getAs<PointerType>();
7183 const PointerType *RPT = RHSType->getAs<PointerType>();
John McCall7684dde2011-03-11 04:25:25 +00007184 if (LPT || RPT) {
7185 bool LPtrToVoid = LPT ? LPT->getPointeeType()->isVoidType() : false;
7186 bool RPtrToVoid = RPT ? RPT->getPointeeType()->isVoidType() : false;
Mike Stump4e1f26a2009-02-19 03:04:26 +00007187
Steve Naroff753567f2008-11-17 19:49:16 +00007188 if (!LPtrToVoid && !RPtrToVoid &&
Richard Trieub80728f2011-09-06 21:43:51 +00007189 !Context.typesAreCompatible(LHSType, RHSType)) {
7190 diagnoseDistinctPointerComparison(*this, Loc, LHS, RHS,
Richard Trieudd82a5c2011-09-02 02:55:45 +00007191 /*isError*/false);
Steve Naroff1d4a9a32008-10-27 10:33:19 +00007192 }
John McCall7684dde2011-03-11 04:25:25 +00007193 if (LHSIsNull && !RHSIsNull)
John McCall9320b872011-09-09 05:25:32 +00007194 LHS = ImpCastExprToType(LHS.take(), RHSType,
7195 RPT ? CK_BitCast :CK_CPointerToObjCPointerCast);
John McCall7684dde2011-03-11 04:25:25 +00007196 else
John McCall9320b872011-09-09 05:25:32 +00007197 RHS = ImpCastExprToType(RHS.take(), LHSType,
7198 LPT ? CK_BitCast :CK_CPointerToObjCPointerCast);
Douglas Gregorca63811b2008-11-19 03:25:36 +00007199 return ResultTy;
Steve Naroffea54d9e2008-10-20 18:19:10 +00007200 }
Richard Trieub80728f2011-09-06 21:43:51 +00007201 if (LHSType->isObjCObjectPointerType() &&
7202 RHSType->isObjCObjectPointerType()) {
7203 if (!Context.areComparableObjCPointerTypes(LHSType, RHSType))
7204 diagnoseDistinctPointerComparison(*this, Loc, LHS, RHS,
Richard Trieudd82a5c2011-09-02 02:55:45 +00007205 /*isError*/false);
Jordan Rosed49a33e2012-06-08 21:14:25 +00007206 if (isObjCObjectLiteral(LHS) || isObjCObjectLiteral(RHS))
Jordan Rose7660f782012-07-17 17:46:40 +00007207 diagnoseObjCLiteralComparison(*this, Loc, LHS, RHS, Opc);
Jordan Rosed49a33e2012-06-08 21:14:25 +00007208
John McCall7684dde2011-03-11 04:25:25 +00007209 if (LHSIsNull && !RHSIsNull)
Richard Trieub80728f2011-09-06 21:43:51 +00007210 LHS = ImpCastExprToType(LHS.take(), RHSType, CK_BitCast);
John McCall7684dde2011-03-11 04:25:25 +00007211 else
Richard Trieub80728f2011-09-06 21:43:51 +00007212 RHS = ImpCastExprToType(RHS.take(), LHSType, CK_BitCast);
Douglas Gregorca63811b2008-11-19 03:25:36 +00007213 return ResultTy;
Steve Naroffb788d9b2008-06-03 14:04:54 +00007214 }
Fariborz Jahanian134cbef2007-12-20 01:06:58 +00007215 }
Richard Trieub80728f2011-09-06 21:43:51 +00007216 if ((LHSType->isAnyPointerType() && RHSType->isIntegerType()) ||
7217 (LHSType->isIntegerType() && RHSType->isAnyPointerType())) {
Chris Lattnerd99bd522009-08-23 00:03:44 +00007218 unsigned DiagID = 0;
Douglas Gregorf267edd2010-06-15 21:38:40 +00007219 bool isError = false;
Richard Trieub80728f2011-09-06 21:43:51 +00007220 if ((LHSIsNull && LHSType->isIntegerType()) ||
7221 (RHSIsNull && RHSType->isIntegerType())) {
David Blaikiebbafb8a2012-03-11 07:00:24 +00007222 if (IsRelational && !getLangOpts().CPlusPlus)
Chris Lattnerd99bd522009-08-23 00:03:44 +00007223 DiagID = diag::ext_typecheck_ordered_comparison_of_pointer_and_zero;
David Blaikiebbafb8a2012-03-11 07:00:24 +00007224 } else if (IsRelational && !getLangOpts().CPlusPlus)
Chris Lattnerd99bd522009-08-23 00:03:44 +00007225 DiagID = diag::ext_typecheck_ordered_comparison_of_pointer_integer;
David Blaikiebbafb8a2012-03-11 07:00:24 +00007226 else if (getLangOpts().CPlusPlus) {
Douglas Gregorf267edd2010-06-15 21:38:40 +00007227 DiagID = diag::err_typecheck_comparison_of_pointer_integer;
7228 isError = true;
7229 } else
Chris Lattnerd99bd522009-08-23 00:03:44 +00007230 DiagID = diag::ext_typecheck_comparison_of_pointer_integer;
Mike Stump11289f42009-09-09 15:08:12 +00007231
Chris Lattnerd99bd522009-08-23 00:03:44 +00007232 if (DiagID) {
Chris Lattnerf8344db2009-08-22 18:58:31 +00007233 Diag(Loc, DiagID)
Richard Trieub80728f2011-09-06 21:43:51 +00007234 << LHSType << RHSType << LHS.get()->getSourceRange()
7235 << RHS.get()->getSourceRange();
Douglas Gregorf267edd2010-06-15 21:38:40 +00007236 if (isError)
7237 return QualType();
Chris Lattnerf8344db2009-08-22 18:58:31 +00007238 }
Douglas Gregorf267edd2010-06-15 21:38:40 +00007239
Richard Trieub80728f2011-09-06 21:43:51 +00007240 if (LHSType->isIntegerType())
7241 LHS = ImpCastExprToType(LHS.take(), RHSType,
John McCalle84af4e2010-11-13 01:35:44 +00007242 LHSIsNull ? CK_NullToPointer : CK_IntegralToPointer);
Chris Lattnerd99bd522009-08-23 00:03:44 +00007243 else
Richard Trieub80728f2011-09-06 21:43:51 +00007244 RHS = ImpCastExprToType(RHS.take(), LHSType,
John McCalle84af4e2010-11-13 01:35:44 +00007245 RHSIsNull ? CK_NullToPointer : CK_IntegralToPointer);
Douglas Gregorca63811b2008-11-19 03:25:36 +00007246 return ResultTy;
Steve Naroff043d45d2007-05-15 02:32:35 +00007247 }
Douglas Gregorf267edd2010-06-15 21:38:40 +00007248
Steve Naroff4b191572008-09-04 16:56:14 +00007249 // Handle block pointers.
Richard Trieuba63ce62011-09-09 01:45:06 +00007250 if (!IsRelational && RHSIsNull
Richard Trieub80728f2011-09-06 21:43:51 +00007251 && LHSType->isBlockPointerType() && RHSType->isIntegerType()) {
7252 RHS = ImpCastExprToType(RHS.take(), LHSType, CK_NullToPointer);
Douglas Gregorca63811b2008-11-19 03:25:36 +00007253 return ResultTy;
Steve Naroff4b191572008-09-04 16:56:14 +00007254 }
Richard Trieuba63ce62011-09-09 01:45:06 +00007255 if (!IsRelational && LHSIsNull
Richard Trieub80728f2011-09-06 21:43:51 +00007256 && LHSType->isIntegerType() && RHSType->isBlockPointerType()) {
7257 LHS = ImpCastExprToType(LHS.take(), RHSType, CK_NullToPointer);
Douglas Gregorca63811b2008-11-19 03:25:36 +00007258 return ResultTy;
Steve Naroff4b191572008-09-04 16:56:14 +00007259 }
Douglas Gregor48e6bbf2011-03-01 17:16:20 +00007260
Richard Trieub80728f2011-09-06 21:43:51 +00007261 return InvalidOperands(Loc, LHS, RHS);
Steve Naroff26c8ea52007-03-21 21:08:52 +00007262}
7263
Tanya Lattner20248222012-01-16 21:02:28 +00007264
7265// Return a signed type that is of identical size and number of elements.
7266// For floating point vectors, return an integer type of identical size
7267// and number of elements.
7268QualType Sema::GetSignedVectorType(QualType V) {
7269 const VectorType *VTy = V->getAs<VectorType>();
7270 unsigned TypeSize = Context.getTypeSize(VTy->getElementType());
7271 if (TypeSize == Context.getTypeSize(Context.CharTy))
7272 return Context.getExtVectorType(Context.CharTy, VTy->getNumElements());
7273 else if (TypeSize == Context.getTypeSize(Context.ShortTy))
7274 return Context.getExtVectorType(Context.ShortTy, VTy->getNumElements());
7275 else if (TypeSize == Context.getTypeSize(Context.IntTy))
7276 return Context.getExtVectorType(Context.IntTy, VTy->getNumElements());
7277 else if (TypeSize == Context.getTypeSize(Context.LongTy))
7278 return Context.getExtVectorType(Context.LongTy, VTy->getNumElements());
7279 assert(TypeSize == Context.getTypeSize(Context.LongLongTy) &&
7280 "Unhandled vector element size in vector compare");
7281 return Context.getExtVectorType(Context.LongLongTy, VTy->getNumElements());
7282}
7283
Nate Begeman191a6b12008-07-14 18:02:46 +00007284/// CheckVectorCompareOperands - vector comparisons are a clang extension that
Mike Stump4e1f26a2009-02-19 03:04:26 +00007285/// operates on extended vector types. Instead of producing an IntTy result,
Nate Begeman191a6b12008-07-14 18:02:46 +00007286/// like a scalar comparison, a vector comparison produces a vector of integer
7287/// types.
Richard Trieubcce2f72011-09-07 01:19:57 +00007288QualType Sema::CheckVectorCompareOperands(ExprResult &LHS, ExprResult &RHS,
Chris Lattner326f7572008-11-18 01:30:42 +00007289 SourceLocation Loc,
Richard Trieuba63ce62011-09-09 01:45:06 +00007290 bool IsRelational) {
Nate Begeman191a6b12008-07-14 18:02:46 +00007291 // Check to make sure we're operating on vectors of the same type and width,
7292 // Allowing one side to be a scalar of element type.
Richard Trieubcce2f72011-09-07 01:19:57 +00007293 QualType vType = CheckVectorOperands(LHS, RHS, Loc, /*isCompAssign*/false);
Nate Begeman191a6b12008-07-14 18:02:46 +00007294 if (vType.isNull())
7295 return vType;
Mike Stump4e1f26a2009-02-19 03:04:26 +00007296
Richard Trieubcce2f72011-09-07 01:19:57 +00007297 QualType LHSType = LHS.get()->getType();
Mike Stump4e1f26a2009-02-19 03:04:26 +00007298
Anton Yartsev530deb92011-03-27 15:36:07 +00007299 // If AltiVec, the comparison results in a numeric type, i.e.
7300 // bool for C++, int for C
Anton Yartsev93900c72011-03-28 21:00:05 +00007301 if (vType->getAs<VectorType>()->getVectorKind() == VectorType::AltiVecVector)
Anton Yartsev530deb92011-03-27 15:36:07 +00007302 return Context.getLogicalOperationType();
7303
Nate Begeman191a6b12008-07-14 18:02:46 +00007304 // For non-floating point types, check for self-comparisons of the form
7305 // x == x, x != x, x < x, etc. These always evaluate to a constant, and
7306 // often indicate logic errors in the program.
Richard Trieubcce2f72011-09-07 01:19:57 +00007307 if (!LHSType->hasFloatingRepresentation()) {
Richard Smith508ebf32011-10-28 03:31:48 +00007308 if (DeclRefExpr* DRL
7309 = dyn_cast<DeclRefExpr>(LHS.get()->IgnoreParenImpCasts()))
7310 if (DeclRefExpr* DRR
7311 = dyn_cast<DeclRefExpr>(RHS.get()->IgnoreParenImpCasts()))
Nate Begeman191a6b12008-07-14 18:02:46 +00007312 if (DRL->getDecl() == DRR->getDecl())
Ted Kremenek3427fac2011-02-23 01:52:04 +00007313 DiagRuntimeBehavior(Loc, 0,
Douglas Gregorec170db2010-06-08 19:50:34 +00007314 PDiag(diag::warn_comparison_always)
7315 << 0 // self-
7316 << 2 // "a constant"
7317 );
Nate Begeman191a6b12008-07-14 18:02:46 +00007318 }
Mike Stump4e1f26a2009-02-19 03:04:26 +00007319
Nate Begeman191a6b12008-07-14 18:02:46 +00007320 // Check for comparisons of floating point operands using != and ==.
Richard Trieuba63ce62011-09-09 01:45:06 +00007321 if (!IsRelational && LHSType->hasFloatingRepresentation()) {
David Blaikieca043222012-01-16 05:16:03 +00007322 assert (RHS.get()->getType()->hasFloatingRepresentation());
Richard Trieubcce2f72011-09-07 01:19:57 +00007323 CheckFloatComparison(Loc, LHS.get(), RHS.get());
Nate Begeman191a6b12008-07-14 18:02:46 +00007324 }
Tanya Lattner20248222012-01-16 21:02:28 +00007325
7326 // Return a signed type for the vector.
7327 return GetSignedVectorType(LHSType);
7328}
Mike Stump4e1f26a2009-02-19 03:04:26 +00007329
Tanya Lattner3dd33b22012-01-19 01:16:16 +00007330QualType Sema::CheckVectorLogicalOperands(ExprResult &LHS, ExprResult &RHS,
7331 SourceLocation Loc) {
Tanya Lattner20248222012-01-16 21:02:28 +00007332 // Ensure that either both operands are of the same vector type, or
7333 // one operand is of a vector type and the other is of its element type.
7334 QualType vType = CheckVectorOperands(LHS, RHS, Loc, false);
7335 if (vType.isNull() || vType->isFloatingType())
7336 return InvalidOperands(Loc, LHS, RHS);
7337
7338 return GetSignedVectorType(LHS.get()->getType());
Nate Begeman191a6b12008-07-14 18:02:46 +00007339}
7340
Steve Naroff218bc2b2007-05-04 21:54:46 +00007341inline QualType Sema::CheckBitwiseOperands(
Richard Trieuba63ce62011-09-09 01:45:06 +00007342 ExprResult &LHS, ExprResult &RHS, SourceLocation Loc, bool IsCompAssign) {
Richard Trieuf8916e12011-09-16 00:53:10 +00007343 checkArithmeticNull(*this, LHS, RHS, Loc, /*isCompare=*/false);
7344
Richard Trieubcce2f72011-09-07 01:19:57 +00007345 if (LHS.get()->getType()->isVectorType() ||
7346 RHS.get()->getType()->isVectorType()) {
7347 if (LHS.get()->getType()->hasIntegerRepresentation() &&
7348 RHS.get()->getType()->hasIntegerRepresentation())
Richard Trieuba63ce62011-09-09 01:45:06 +00007349 return CheckVectorOperands(LHS, RHS, Loc, IsCompAssign);
Douglas Gregor5cc2c8b2010-07-23 15:58:24 +00007350
Richard Trieubcce2f72011-09-07 01:19:57 +00007351 return InvalidOperands(Loc, LHS, RHS);
Douglas Gregor5cc2c8b2010-07-23 15:58:24 +00007352 }
Steve Naroffb8ea4fb2007-07-13 23:32:42 +00007353
Richard Trieubcce2f72011-09-07 01:19:57 +00007354 ExprResult LHSResult = Owned(LHS), RHSResult = Owned(RHS);
7355 QualType compType = UsualArithmeticConversions(LHSResult, RHSResult,
Richard Trieuba63ce62011-09-09 01:45:06 +00007356 IsCompAssign);
Richard Trieubcce2f72011-09-07 01:19:57 +00007357 if (LHSResult.isInvalid() || RHSResult.isInvalid())
John Wiegley01296292011-04-08 18:41:53 +00007358 return QualType();
Richard Trieubcce2f72011-09-07 01:19:57 +00007359 LHS = LHSResult.take();
7360 RHS = RHSResult.take();
Mike Stump4e1f26a2009-02-19 03:04:26 +00007361
Eli Friedman93ee5ca2012-06-16 02:19:17 +00007362 if (!compType.isNull() && compType->isIntegralOrUnscopedEnumerationType())
Steve Naroffbe4c4d12007-08-24 19:07:16 +00007363 return compType;
Richard Trieubcce2f72011-09-07 01:19:57 +00007364 return InvalidOperands(Loc, LHS, RHS);
Steve Naroff26c8ea52007-03-21 21:08:52 +00007365}
7366
Steve Naroff218bc2b2007-05-04 21:54:46 +00007367inline QualType Sema::CheckLogicalOperands( // C99 6.5.[13,14]
Richard Trieubcce2f72011-09-07 01:19:57 +00007368 ExprResult &LHS, ExprResult &RHS, SourceLocation Loc, unsigned Opc) {
Chris Lattner8406c512010-07-13 19:41:32 +00007369
Tanya Lattner20248222012-01-16 21:02:28 +00007370 // Check vector operands differently.
7371 if (LHS.get()->getType()->isVectorType() || RHS.get()->getType()->isVectorType())
7372 return CheckVectorLogicalOperands(LHS, RHS, Loc);
7373
Chris Lattner8406c512010-07-13 19:41:32 +00007374 // Diagnose cases where the user write a logical and/or but probably meant a
7375 // bitwise one. We do this when the LHS is a non-bool integer and the RHS
7376 // is a constant.
Richard Trieubcce2f72011-09-07 01:19:57 +00007377 if (LHS.get()->getType()->isIntegerType() &&
7378 !LHS.get()->getType()->isBooleanType() &&
7379 RHS.get()->getType()->isIntegerType() && !RHS.get()->isValueDependent() &&
Richard Trieucfe39262011-07-15 00:00:51 +00007380 // Don't warn in macros or template instantiations.
7381 !Loc.isMacroID() && ActiveTemplateInstantiations.empty()) {
Chris Lattner938533d2010-07-24 01:10:11 +00007382 // If the RHS can be constant folded, and if it constant folds to something
7383 // that isn't 0 or 1 (which indicate a potential logical operation that
7384 // happened to fold to true/false) then warn.
Chandler Carruthe54ff6c2011-05-31 05:41:42 +00007385 // Parens on the RHS are ignored.
Richard Smith00ab3ae2011-10-16 23:01:09 +00007386 llvm::APSInt Result;
7387 if (RHS.get()->EvaluateAsInt(Result, Context))
David Blaikiebbafb8a2012-03-11 07:00:24 +00007388 if ((getLangOpts().Bool && !RHS.get()->getType()->isBooleanType()) ||
Richard Smith00ab3ae2011-10-16 23:01:09 +00007389 (Result != 0 && Result != 1)) {
Chandler Carruthe54ff6c2011-05-31 05:41:42 +00007390 Diag(Loc, diag::warn_logical_instead_of_bitwise)
Richard Trieubcce2f72011-09-07 01:19:57 +00007391 << RHS.get()->getSourceRange()
Matt Beaumont-Gay0a0ba9d2011-08-15 17:50:06 +00007392 << (Opc == BO_LAnd ? "&&" : "||");
7393 // Suggest replacing the logical operator with the bitwise version
7394 Diag(Loc, diag::note_logical_instead_of_bitwise_change_operator)
7395 << (Opc == BO_LAnd ? "&" : "|")
7396 << FixItHint::CreateReplacement(SourceRange(
7397 Loc, Lexer::getLocForEndOfToken(Loc, 0, getSourceManager(),
David Blaikiebbafb8a2012-03-11 07:00:24 +00007398 getLangOpts())),
Matt Beaumont-Gay0a0ba9d2011-08-15 17:50:06 +00007399 Opc == BO_LAnd ? "&" : "|");
7400 if (Opc == BO_LAnd)
7401 // Suggest replacing "Foo() && kNonZero" with "Foo()"
7402 Diag(Loc, diag::note_logical_instead_of_bitwise_remove_constant)
7403 << FixItHint::CreateRemoval(
7404 SourceRange(
Richard Trieubcce2f72011-09-07 01:19:57 +00007405 Lexer::getLocForEndOfToken(LHS.get()->getLocEnd(),
Matt Beaumont-Gay0a0ba9d2011-08-15 17:50:06 +00007406 0, getSourceManager(),
David Blaikiebbafb8a2012-03-11 07:00:24 +00007407 getLangOpts()),
Richard Trieubcce2f72011-09-07 01:19:57 +00007408 RHS.get()->getLocEnd()));
Matt Beaumont-Gay0a0ba9d2011-08-15 17:50:06 +00007409 }
Chris Lattner938533d2010-07-24 01:10:11 +00007410 }
Chris Lattner8406c512010-07-13 19:41:32 +00007411
David Blaikiebbafb8a2012-03-11 07:00:24 +00007412 if (!Context.getLangOpts().CPlusPlus) {
Richard Trieubcce2f72011-09-07 01:19:57 +00007413 LHS = UsualUnaryConversions(LHS.take());
7414 if (LHS.isInvalid())
John Wiegley01296292011-04-08 18:41:53 +00007415 return QualType();
Mike Stump4e1f26a2009-02-19 03:04:26 +00007416
Richard Trieubcce2f72011-09-07 01:19:57 +00007417 RHS = UsualUnaryConversions(RHS.take());
7418 if (RHS.isInvalid())
John Wiegley01296292011-04-08 18:41:53 +00007419 return QualType();
7420
Richard Trieubcce2f72011-09-07 01:19:57 +00007421 if (!LHS.get()->getType()->isScalarType() ||
7422 !RHS.get()->getType()->isScalarType())
7423 return InvalidOperands(Loc, LHS, RHS);
Kovarththanan Rajaratnamba2c6522010-03-13 10:17:05 +00007424
Anders Carlsson2e7bc112009-11-23 21:47:44 +00007425 return Context.IntTy;
Anders Carlsson35a99d92009-10-16 01:44:21 +00007426 }
Kovarththanan Rajaratnamba2c6522010-03-13 10:17:05 +00007427
John McCall4a2429a2010-06-04 00:29:51 +00007428 // The following is safe because we only use this method for
7429 // non-overloadable operands.
7430
Anders Carlsson2e7bc112009-11-23 21:47:44 +00007431 // C++ [expr.log.and]p1
7432 // C++ [expr.log.or]p1
John McCall4a2429a2010-06-04 00:29:51 +00007433 // The operands are both contextually converted to type bool.
Richard Trieubcce2f72011-09-07 01:19:57 +00007434 ExprResult LHSRes = PerformContextuallyConvertToBool(LHS.get());
7435 if (LHSRes.isInvalid())
7436 return InvalidOperands(Loc, LHS, RHS);
Benjamin Kramer62b95d82012-08-23 21:35:17 +00007437 LHS = LHSRes;
John Wiegley01296292011-04-08 18:41:53 +00007438
Richard Trieubcce2f72011-09-07 01:19:57 +00007439 ExprResult RHSRes = PerformContextuallyConvertToBool(RHS.get());
7440 if (RHSRes.isInvalid())
7441 return InvalidOperands(Loc, LHS, RHS);
Benjamin Kramer62b95d82012-08-23 21:35:17 +00007442 RHS = RHSRes;
Kovarththanan Rajaratnamba2c6522010-03-13 10:17:05 +00007443
Anders Carlsson2e7bc112009-11-23 21:47:44 +00007444 // C++ [expr.log.and]p2
7445 // C++ [expr.log.or]p2
7446 // The result is a bool.
7447 return Context.BoolTy;
Steve Naroffae4143e2007-04-26 20:39:23 +00007448}
7449
Fariborz Jahanian8e1555c2009-01-12 19:55:42 +00007450/// IsReadonlyProperty - Verify that otherwise a valid l-value expression
7451/// is a read-only property; return true if so. A readonly property expression
7452/// depends on various declarations and thus must be treated specially.
7453///
Mike Stump11289f42009-09-09 15:08:12 +00007454static bool IsReadonlyProperty(Expr *E, Sema &S) {
John McCall526ab472011-10-25 17:37:35 +00007455 const ObjCPropertyRefExpr *PropExpr = dyn_cast<ObjCPropertyRefExpr>(E);
7456 if (!PropExpr) return false;
7457 if (PropExpr->isImplicitProperty()) return false;
John McCallb7bd14f2010-12-02 01:19:52 +00007458
John McCall526ab472011-10-25 17:37:35 +00007459 ObjCPropertyDecl *PDecl = PropExpr->getExplicitProperty();
7460 QualType BaseType = PropExpr->isSuperReceiver() ?
John McCallb7bd14f2010-12-02 01:19:52 +00007461 PropExpr->getSuperReceiverType() :
Fariborz Jahanian681c0752010-10-14 16:04:05 +00007462 PropExpr->getBase()->getType();
7463
John McCall526ab472011-10-25 17:37:35 +00007464 if (const ObjCObjectPointerType *OPT =
7465 BaseType->getAsObjCInterfacePointerType())
7466 if (ObjCInterfaceDecl *IFace = OPT->getInterfaceDecl())
7467 if (S.isPropertyReadonly(PDecl, IFace))
7468 return true;
Fariborz Jahanian8e1555c2009-01-12 19:55:42 +00007469 return false;
7470}
7471
Fariborz Jahanian071caef2011-03-26 19:48:30 +00007472static bool IsReadonlyMessage(Expr *E, Sema &S) {
John McCall526ab472011-10-25 17:37:35 +00007473 const MemberExpr *ME = dyn_cast<MemberExpr>(E);
7474 if (!ME) return false;
7475 if (!isa<FieldDecl>(ME->getMemberDecl())) return false;
7476 ObjCMessageExpr *Base =
7477 dyn_cast<ObjCMessageExpr>(ME->getBase()->IgnoreParenImpCasts());
7478 if (!Base) return false;
7479 return Base->getMethodDecl() != 0;
Fariborz Jahanian071caef2011-03-26 19:48:30 +00007480}
7481
John McCall5fa2ef42012-03-13 00:37:01 +00007482/// Is the given expression (which must be 'const') a reference to a
7483/// variable which was originally non-const, but which has become
7484/// 'const' due to being captured within a block?
7485enum NonConstCaptureKind { NCCK_None, NCCK_Block, NCCK_Lambda };
7486static NonConstCaptureKind isReferenceToNonConstCapture(Sema &S, Expr *E) {
7487 assert(E->isLValue() && E->getType().isConstQualified());
7488 E = E->IgnoreParens();
7489
7490 // Must be a reference to a declaration from an enclosing scope.
7491 DeclRefExpr *DRE = dyn_cast<DeclRefExpr>(E);
7492 if (!DRE) return NCCK_None;
7493 if (!DRE->refersToEnclosingLocal()) return NCCK_None;
7494
7495 // The declaration must be a variable which is not declared 'const'.
7496 VarDecl *var = dyn_cast<VarDecl>(DRE->getDecl());
7497 if (!var) return NCCK_None;
7498 if (var->getType().isConstQualified()) return NCCK_None;
7499 assert(var->hasLocalStorage() && "capture added 'const' to non-local?");
7500
7501 // Decide whether the first capture was for a block or a lambda.
7502 DeclContext *DC = S.CurContext;
7503 while (DC->getParent() != var->getDeclContext())
7504 DC = DC->getParent();
7505 return (isa<BlockDecl>(DC) ? NCCK_Block : NCCK_Lambda);
7506}
7507
Chris Lattner30bd3272008-11-18 01:22:49 +00007508/// CheckForModifiableLvalue - Verify that E is a modifiable lvalue. If not,
7509/// emit an error and return true. If so, return false.
7510static bool CheckForModifiableLvalue(Expr *E, SourceLocation Loc, Sema &S) {
Fariborz Jahanianca5c5972012-04-10 17:30:10 +00007511 assert(!E->hasPlaceholderType(BuiltinType::PseudoObject));
Daniel Dunbarc2223ab2009-04-15 00:08:05 +00007512 SourceLocation OrigLoc = Loc;
Mike Stump11289f42009-09-09 15:08:12 +00007513 Expr::isModifiableLvalueResult IsLV = E->isModifiableLvalue(S.Context,
Daniel Dunbarc2223ab2009-04-15 00:08:05 +00007514 &Loc);
Fariborz Jahanian8e1555c2009-01-12 19:55:42 +00007515 if (IsLV == Expr::MLV_Valid && IsReadonlyProperty(E, S))
7516 IsLV = Expr::MLV_ReadonlyProperty;
Fariborz Jahanian071caef2011-03-26 19:48:30 +00007517 else if (IsLV == Expr::MLV_ClassTemporary && IsReadonlyMessage(E, S))
7518 IsLV = Expr::MLV_InvalidMessageExpression;
Chris Lattner30bd3272008-11-18 01:22:49 +00007519 if (IsLV == Expr::MLV_Valid)
7520 return false;
Mike Stump4e1f26a2009-02-19 03:04:26 +00007521
Chris Lattner30bd3272008-11-18 01:22:49 +00007522 unsigned Diag = 0;
7523 bool NeedType = false;
7524 switch (IsLV) { // C99 6.5.16p2
John McCall31168b02011-06-15 23:02:42 +00007525 case Expr::MLV_ConstQualified:
7526 Diag = diag::err_typecheck_assign_const;
7527
John McCall5fa2ef42012-03-13 00:37:01 +00007528 // Use a specialized diagnostic when we're assigning to an object
7529 // from an enclosing function or block.
7530 if (NonConstCaptureKind NCCK = isReferenceToNonConstCapture(S, E)) {
7531 if (NCCK == NCCK_Block)
7532 Diag = diag::err_block_decl_ref_not_modifiable_lvalue;
7533 else
7534 Diag = diag::err_lambda_decl_ref_not_modifiable_lvalue;
7535 break;
7536 }
7537
John McCalld4631322011-06-17 06:42:21 +00007538 // In ARC, use some specialized diagnostics for occasions where we
7539 // infer 'const'. These are always pseudo-strong variables.
David Blaikiebbafb8a2012-03-11 07:00:24 +00007540 if (S.getLangOpts().ObjCAutoRefCount) {
John McCall31168b02011-06-15 23:02:42 +00007541 DeclRefExpr *declRef = dyn_cast<DeclRefExpr>(E->IgnoreParenCasts());
7542 if (declRef && isa<VarDecl>(declRef->getDecl())) {
7543 VarDecl *var = cast<VarDecl>(declRef->getDecl());
7544
John McCalld4631322011-06-17 06:42:21 +00007545 // Use the normal diagnostic if it's pseudo-__strong but the
7546 // user actually wrote 'const'.
7547 if (var->isARCPseudoStrong() &&
7548 (!var->getTypeSourceInfo() ||
7549 !var->getTypeSourceInfo()->getType().isConstQualified())) {
7550 // There are two pseudo-strong cases:
7551 // - self
John McCall31168b02011-06-15 23:02:42 +00007552 ObjCMethodDecl *method = S.getCurMethodDecl();
7553 if (method && var == method->getSelfDecl())
Ted Kremenek1fcdaa92011-11-14 21:59:25 +00007554 Diag = method->isClassMethod()
7555 ? diag::err_typecheck_arc_assign_self_class_method
7556 : diag::err_typecheck_arc_assign_self;
John McCalld4631322011-06-17 06:42:21 +00007557
7558 // - fast enumeration variables
7559 else
John McCall31168b02011-06-15 23:02:42 +00007560 Diag = diag::err_typecheck_arr_assign_enumeration;
John McCalld4631322011-06-17 06:42:21 +00007561
John McCall31168b02011-06-15 23:02:42 +00007562 SourceRange Assign;
7563 if (Loc != OrigLoc)
7564 Assign = SourceRange(OrigLoc, OrigLoc);
7565 S.Diag(Loc, Diag) << E->getSourceRange() << Assign;
7566 // We need to preserve the AST regardless, so migration tool
7567 // can do its job.
7568 return false;
7569 }
7570 }
7571 }
7572
7573 break;
Mike Stump4e1f26a2009-02-19 03:04:26 +00007574 case Expr::MLV_ArrayType:
Richard Smitheb3cad52012-06-04 22:27:30 +00007575 case Expr::MLV_ArrayTemporary:
Chris Lattner30bd3272008-11-18 01:22:49 +00007576 Diag = diag::err_typecheck_array_not_modifiable_lvalue;
7577 NeedType = true;
7578 break;
Mike Stump4e1f26a2009-02-19 03:04:26 +00007579 case Expr::MLV_NotObjectType:
Chris Lattner30bd3272008-11-18 01:22:49 +00007580 Diag = diag::err_typecheck_non_object_not_modifiable_lvalue;
7581 NeedType = true;
7582 break;
Chris Lattner9b3bbe92008-11-17 19:51:54 +00007583 case Expr::MLV_LValueCast:
Chris Lattner30bd3272008-11-18 01:22:49 +00007584 Diag = diag::err_typecheck_lvalue_casts_not_supported;
7585 break;
Douglas Gregorb154fdc2010-02-16 21:39:57 +00007586 case Expr::MLV_Valid:
7587 llvm_unreachable("did not take early return for MLV_Valid");
Chris Lattner9bad62c2008-01-04 18:04:52 +00007588 case Expr::MLV_InvalidExpression:
Douglas Gregorb154fdc2010-02-16 21:39:57 +00007589 case Expr::MLV_MemberFunction:
7590 case Expr::MLV_ClassTemporary:
Chris Lattner30bd3272008-11-18 01:22:49 +00007591 Diag = diag::err_typecheck_expression_not_modifiable_lvalue;
7592 break;
Chris Lattner9bad62c2008-01-04 18:04:52 +00007593 case Expr::MLV_IncompleteType:
7594 case Expr::MLV_IncompleteVoidType:
Douglas Gregored0cfbd2009-03-09 16:13:40 +00007595 return S.RequireCompleteType(Loc, E->getType(),
Douglas Gregor7bfb2d02012-05-04 16:32:21 +00007596 diag::err_typecheck_incomplete_type_not_modifiable_lvalue, E);
Chris Lattner9bad62c2008-01-04 18:04:52 +00007597 case Expr::MLV_DuplicateVectorComponents:
Chris Lattner30bd3272008-11-18 01:22:49 +00007598 Diag = diag::err_typecheck_duplicate_vector_components_not_mlvalue;
7599 break;
Fariborz Jahanian8a1810f2008-11-22 18:39:36 +00007600 case Expr::MLV_ReadonlyProperty:
Fariborz Jahanian5118c412008-11-22 20:25:50 +00007601 case Expr::MLV_NoSetterProperty:
John McCall526ab472011-10-25 17:37:35 +00007602 llvm_unreachable("readonly properties should be processed differently");
Fariborz Jahanian071caef2011-03-26 19:48:30 +00007603 case Expr::MLV_InvalidMessageExpression:
7604 Diag = diag::error_readonly_message_assignment;
7605 break;
Fariborz Jahaniane8d28902009-12-15 23:59:41 +00007606 case Expr::MLV_SubObjCPropertySetting:
7607 Diag = diag::error_no_subobject_property_setting;
7608 break;
Steve Naroff218bc2b2007-05-04 21:54:46 +00007609 }
Steve Naroffad373bd2007-07-31 12:34:36 +00007610
Daniel Dunbarc2223ab2009-04-15 00:08:05 +00007611 SourceRange Assign;
7612 if (Loc != OrigLoc)
7613 Assign = SourceRange(OrigLoc, OrigLoc);
Chris Lattner30bd3272008-11-18 01:22:49 +00007614 if (NeedType)
Daniel Dunbarc2223ab2009-04-15 00:08:05 +00007615 S.Diag(Loc, Diag) << E->getType() << E->getSourceRange() << Assign;
Chris Lattner30bd3272008-11-18 01:22:49 +00007616 else
Mike Stump11289f42009-09-09 15:08:12 +00007617 S.Diag(Loc, Diag) << E->getSourceRange() << Assign;
Chris Lattner30bd3272008-11-18 01:22:49 +00007618 return true;
7619}
7620
Nico Weberb8124d12012-07-03 02:03:06 +00007621static void CheckIdentityFieldAssignment(Expr *LHSExpr, Expr *RHSExpr,
7622 SourceLocation Loc,
7623 Sema &Sema) {
7624 // C / C++ fields
Nico Weber33fd5232012-06-28 23:53:12 +00007625 MemberExpr *ML = dyn_cast<MemberExpr>(LHSExpr);
7626 MemberExpr *MR = dyn_cast<MemberExpr>(RHSExpr);
7627 if (ML && MR && ML->getMemberDecl() == MR->getMemberDecl()) {
7628 if (isa<CXXThisExpr>(ML->getBase()) && isa<CXXThisExpr>(MR->getBase()))
Nico Weberb8124d12012-07-03 02:03:06 +00007629 Sema.Diag(Loc, diag::warn_identity_field_assign) << 0;
Nico Weber33fd5232012-06-28 23:53:12 +00007630 }
Chris Lattner30bd3272008-11-18 01:22:49 +00007631
Nico Weberb8124d12012-07-03 02:03:06 +00007632 // Objective-C instance variables
Nico Weber33fd5232012-06-28 23:53:12 +00007633 ObjCIvarRefExpr *OL = dyn_cast<ObjCIvarRefExpr>(LHSExpr);
7634 ObjCIvarRefExpr *OR = dyn_cast<ObjCIvarRefExpr>(RHSExpr);
7635 if (OL && OR && OL->getDecl() == OR->getDecl()) {
7636 DeclRefExpr *RL = dyn_cast<DeclRefExpr>(OL->getBase()->IgnoreImpCasts());
7637 DeclRefExpr *RR = dyn_cast<DeclRefExpr>(OR->getBase()->IgnoreImpCasts());
7638 if (RL && RR && RL->getDecl() == RR->getDecl())
Nico Weberb8124d12012-07-03 02:03:06 +00007639 Sema.Diag(Loc, diag::warn_identity_field_assign) << 1;
Nico Weber33fd5232012-06-28 23:53:12 +00007640 }
7641}
Chris Lattner30bd3272008-11-18 01:22:49 +00007642
7643// C99 6.5.16.1
Richard Trieuda4f43a62011-09-07 01:33:52 +00007644QualType Sema::CheckAssignmentOperands(Expr *LHSExpr, ExprResult &RHS,
Chris Lattner326f7572008-11-18 01:30:42 +00007645 SourceLocation Loc,
7646 QualType CompoundType) {
John McCall526ab472011-10-25 17:37:35 +00007647 assert(!LHSExpr->hasPlaceholderType(BuiltinType::PseudoObject));
7648
Chris Lattner326f7572008-11-18 01:30:42 +00007649 // Verify that LHS is a modifiable lvalue, and emit error if not.
Richard Trieuda4f43a62011-09-07 01:33:52 +00007650 if (CheckForModifiableLvalue(LHSExpr, Loc, *this))
Chris Lattner30bd3272008-11-18 01:22:49 +00007651 return QualType();
Chris Lattner326f7572008-11-18 01:30:42 +00007652
Richard Trieuda4f43a62011-09-07 01:33:52 +00007653 QualType LHSType = LHSExpr->getType();
Richard Trieucfc491d2011-08-02 04:35:43 +00007654 QualType RHSType = CompoundType.isNull() ? RHS.get()->getType() :
7655 CompoundType;
Chris Lattner9bad62c2008-01-04 18:04:52 +00007656 AssignConvertType ConvTy;
Chris Lattner326f7572008-11-18 01:30:42 +00007657 if (CompoundType.isNull()) {
Nico Weber33fd5232012-06-28 23:53:12 +00007658 Expr *RHSCheck = RHS.get();
7659
Nico Weberb8124d12012-07-03 02:03:06 +00007660 CheckIdentityFieldAssignment(LHSExpr, RHSCheck, Loc, *this);
Nico Weber33fd5232012-06-28 23:53:12 +00007661
Fariborz Jahanianbe21aa32010-06-07 22:02:01 +00007662 QualType LHSTy(LHSType);
Fariborz Jahanianbe21aa32010-06-07 22:02:01 +00007663 ConvTy = CheckSingleAssignmentConstraints(LHSTy, RHS);
John Wiegley01296292011-04-08 18:41:53 +00007664 if (RHS.isInvalid())
7665 return QualType();
Fariborz Jahanian255c0952009-01-13 23:34:40 +00007666 // Special case of NSObject attributes on c-style pointer types.
7667 if (ConvTy == IncompatiblePointer &&
7668 ((Context.isObjCNSObjectType(LHSType) &&
Steve Naroff79d12152009-07-16 15:41:00 +00007669 RHSType->isObjCObjectPointerType()) ||
Fariborz Jahanian255c0952009-01-13 23:34:40 +00007670 (Context.isObjCNSObjectType(RHSType) &&
Steve Naroff79d12152009-07-16 15:41:00 +00007671 LHSType->isObjCObjectPointerType())))
Fariborz Jahanian255c0952009-01-13 23:34:40 +00007672 ConvTy = Compatible;
Mike Stump4e1f26a2009-02-19 03:04:26 +00007673
John McCall7decc9e2010-11-18 06:31:45 +00007674 if (ConvTy == Compatible &&
Fariborz Jahaniane2a77762012-01-24 19:40:13 +00007675 LHSType->isObjCObjectType())
Fariborz Jahanian3c4225a2012-01-24 18:05:45 +00007676 Diag(Loc, diag::err_objc_object_assignment)
7677 << LHSType;
John McCall7decc9e2010-11-18 06:31:45 +00007678
Chris Lattnerea714382008-08-21 18:04:13 +00007679 // If the RHS is a unary plus or minus, check to see if they = and + are
7680 // right next to each other. If so, the user may have typo'd "x =+ 4"
7681 // instead of "x += 4".
Chris Lattnerea714382008-08-21 18:04:13 +00007682 if (ImplicitCastExpr *ICE = dyn_cast<ImplicitCastExpr>(RHSCheck))
7683 RHSCheck = ICE->getSubExpr();
7684 if (UnaryOperator *UO = dyn_cast<UnaryOperator>(RHSCheck)) {
John McCalle3027922010-08-25 11:45:40 +00007685 if ((UO->getOpcode() == UO_Plus ||
7686 UO->getOpcode() == UO_Minus) &&
Chris Lattner326f7572008-11-18 01:30:42 +00007687 Loc.isFileID() && UO->getOperatorLoc().isFileID() &&
Chris Lattnerea714382008-08-21 18:04:13 +00007688 // Only if the two operators are exactly adjacent.
Argyrios Kyrtzidise6e67de2011-09-19 20:40:19 +00007689 Loc.getLocWithOffset(1) == UO->getOperatorLoc() &&
Chris Lattner36c39c92009-03-08 06:51:10 +00007690 // And there is a space or other character before the subexpr of the
7691 // unary +/-. We don't want to warn on "x=-1".
Argyrios Kyrtzidise6e67de2011-09-19 20:40:19 +00007692 Loc.getLocWithOffset(2) != UO->getSubExpr()->getLocStart() &&
Chris Lattnered9f14c2009-03-09 07:11:10 +00007693 UO->getSubExpr()->getLocStart().isFileID()) {
Chris Lattner29e812b2008-11-20 06:06:08 +00007694 Diag(Loc, diag::warn_not_compound_assign)
John McCalle3027922010-08-25 11:45:40 +00007695 << (UO->getOpcode() == UO_Plus ? "+" : "-")
Chris Lattner29e812b2008-11-20 06:06:08 +00007696 << SourceRange(UO->getOperatorLoc(), UO->getOperatorLoc());
Chris Lattner36c39c92009-03-08 06:51:10 +00007697 }
Chris Lattnerea714382008-08-21 18:04:13 +00007698 }
John McCall31168b02011-06-15 23:02:42 +00007699
7700 if (ConvTy == Compatible) {
7701 if (LHSType.getObjCLifetime() == Qualifiers::OCL_Strong)
Richard Trieuda4f43a62011-09-07 01:33:52 +00007702 checkRetainCycles(LHSExpr, RHS.get());
David Blaikiebbafb8a2012-03-11 07:00:24 +00007703 else if (getLangOpts().ObjCAutoRefCount)
Richard Trieuda4f43a62011-09-07 01:33:52 +00007704 checkUnsafeExprAssigns(Loc, LHSExpr, RHS.get());
John McCall31168b02011-06-15 23:02:42 +00007705 }
Chris Lattnerea714382008-08-21 18:04:13 +00007706 } else {
7707 // Compound assignment "x += y"
Douglas Gregorc03a1082011-01-28 02:26:04 +00007708 ConvTy = CheckAssignmentConstraints(Loc, LHSType, RHSType);
Chris Lattnerea714382008-08-21 18:04:13 +00007709 }
Chris Lattner9bad62c2008-01-04 18:04:52 +00007710
Chris Lattner326f7572008-11-18 01:30:42 +00007711 if (DiagnoseAssignmentResult(ConvTy, Loc, LHSType, RHSType,
John Wiegley01296292011-04-08 18:41:53 +00007712 RHS.get(), AA_Assigning))
Chris Lattner9bad62c2008-01-04 18:04:52 +00007713 return QualType();
Mike Stump4e1f26a2009-02-19 03:04:26 +00007714
Richard Trieuda4f43a62011-09-07 01:33:52 +00007715 CheckForNullPointerDereference(*this, LHSExpr);
Kaelyn Uhrain2e7aa5a2011-08-05 23:18:04 +00007716
Steve Naroff98cf3e92007-06-06 18:38:38 +00007717 // C99 6.5.16p3: The type of an assignment expression is the type of the
7718 // left operand unless the left operand has qualified type, in which case
Mike Stump4e1f26a2009-02-19 03:04:26 +00007719 // it is the unqualified version of the type of the left operand.
Steve Naroff98cf3e92007-06-06 18:38:38 +00007720 // C99 6.5.16.1p2: In simple assignment, the value of the right operand
7721 // is converted to the type of the assignment expression (above).
Chris Lattnerf17bd422007-08-30 17:45:32 +00007722 // C++ 5.17p1: the type of the assignment expression is that of its left
Douglas Gregord2c2d172009-05-02 00:36:19 +00007723 // operand.
David Blaikiebbafb8a2012-03-11 07:00:24 +00007724 return (getLangOpts().CPlusPlus
John McCall01cbf2d2010-10-12 02:19:57 +00007725 ? LHSType : LHSType.getUnqualifiedType());
Steve Naroffae4143e2007-04-26 20:39:23 +00007726}
7727
Chris Lattner326f7572008-11-18 01:30:42 +00007728// C99 6.5.17
John Wiegley01296292011-04-08 18:41:53 +00007729static QualType CheckCommaOperands(Sema &S, ExprResult &LHS, ExprResult &RHS,
John McCall4bc41ae2010-11-18 19:01:18 +00007730 SourceLocation Loc) {
John McCall3aef3d82011-04-10 19:13:55 +00007731 LHS = S.CheckPlaceholderExpr(LHS.take());
7732 RHS = S.CheckPlaceholderExpr(RHS.take());
John Wiegley01296292011-04-08 18:41:53 +00007733 if (LHS.isInvalid() || RHS.isInvalid())
Douglas Gregor0124e9b2010-11-09 21:07:58 +00007734 return QualType();
7735
John McCall73d36182010-10-12 07:14:40 +00007736 // C's comma performs lvalue conversion (C99 6.3.2.1) on both its
7737 // operands, but not unary promotions.
7738 // C++'s comma does not do any conversions at all (C++ [expr.comma]p1).
Eli Friedmanba961a92009-03-23 00:24:07 +00007739
John McCall34376a62010-12-04 03:47:34 +00007740 // So we treat the LHS as a ignored value, and in C++ we allow the
7741 // containing site to determine what should be done with the RHS.
John Wiegley01296292011-04-08 18:41:53 +00007742 LHS = S.IgnoredValueConversions(LHS.take());
7743 if (LHS.isInvalid())
7744 return QualType();
John McCall34376a62010-12-04 03:47:34 +00007745
Eli Friedmanc11535c2012-05-24 00:47:05 +00007746 S.DiagnoseUnusedExprResult(LHS.get());
7747
David Blaikiebbafb8a2012-03-11 07:00:24 +00007748 if (!S.getLangOpts().CPlusPlus) {
John Wiegley01296292011-04-08 18:41:53 +00007749 RHS = S.DefaultFunctionArrayLvalueConversion(RHS.take());
7750 if (RHS.isInvalid())
7751 return QualType();
7752 if (!RHS.get()->getType()->isVoidType())
Richard Trieucfc491d2011-08-02 04:35:43 +00007753 S.RequireCompleteType(Loc, RHS.get()->getType(),
7754 diag::err_incomplete_type);
John McCall73d36182010-10-12 07:14:40 +00007755 }
Eli Friedmanba961a92009-03-23 00:24:07 +00007756
John Wiegley01296292011-04-08 18:41:53 +00007757 return RHS.get()->getType();
Steve Naroff95af0132007-03-30 23:47:58 +00007758}
7759
Steve Naroff7a5af782007-07-13 16:58:59 +00007760/// CheckIncrementDecrementOperand - unlike most "Check" methods, this routine
7761/// doesn't need to call UsualUnaryConversions or UsualArithmeticConversions.
John McCall4bc41ae2010-11-18 19:01:18 +00007762static QualType CheckIncrementDecrementOperand(Sema &S, Expr *Op,
7763 ExprValueKind &VK,
7764 SourceLocation OpLoc,
Richard Trieuba63ce62011-09-09 01:45:06 +00007765 bool IsInc, bool IsPrefix) {
Sebastian Redl8d2ccae2009-02-26 14:39:58 +00007766 if (Op->isTypeDependent())
John McCall4bc41ae2010-11-18 19:01:18 +00007767 return S.Context.DependentTy;
Sebastian Redl8d2ccae2009-02-26 14:39:58 +00007768
Chris Lattner6b0cf142008-11-21 07:05:48 +00007769 QualType ResType = Op->getType();
David Chisnallfa35df62012-01-16 17:27:18 +00007770 // Atomic types can be used for increment / decrement where the non-atomic
7771 // versions can, so ignore the _Atomic() specifier for the purpose of
7772 // checking.
7773 if (const AtomicType *ResAtomicType = ResType->getAs<AtomicType>())
7774 ResType = ResAtomicType->getValueType();
7775
Chris Lattner6b0cf142008-11-21 07:05:48 +00007776 assert(!ResType.isNull() && "no type for increment/decrement expression");
Steve Naroffd50c88e2007-04-05 21:15:20 +00007777
David Blaikiebbafb8a2012-03-11 07:00:24 +00007778 if (S.getLangOpts().CPlusPlus && ResType->isBooleanType()) {
Sebastian Redle10c2c32008-12-20 09:35:34 +00007779 // Decrement of bool is not allowed.
Richard Trieuba63ce62011-09-09 01:45:06 +00007780 if (!IsInc) {
John McCall4bc41ae2010-11-18 19:01:18 +00007781 S.Diag(OpLoc, diag::err_decrement_bool) << Op->getSourceRange();
Sebastian Redle10c2c32008-12-20 09:35:34 +00007782 return QualType();
7783 }
7784 // Increment of bool sets it to true, but is deprecated.
John McCall4bc41ae2010-11-18 19:01:18 +00007785 S.Diag(OpLoc, diag::warn_increment_bool) << Op->getSourceRange();
Sebastian Redle10c2c32008-12-20 09:35:34 +00007786 } else if (ResType->isRealType()) {
Chris Lattner6b0cf142008-11-21 07:05:48 +00007787 // OK!
John McCallf2538342012-07-31 05:14:30 +00007788 } else if (ResType->isPointerType()) {
Chris Lattner6b0cf142008-11-21 07:05:48 +00007789 // C99 6.5.2.4p2, 6.5.6p2
Chandler Carruthc9332212011-06-27 08:02:19 +00007790 if (!checkArithmeticOpPointerOperand(S, OpLoc, Op))
Douglas Gregordd430f72009-01-19 19:26:10 +00007791 return QualType();
John McCallf2538342012-07-31 05:14:30 +00007792 } else if (ResType->isObjCObjectPointerType()) {
7793 // On modern runtimes, ObjC pointer arithmetic is forbidden.
7794 // Otherwise, we just need a complete type.
7795 if (checkArithmeticIncompletePointerType(S, OpLoc, Op) ||
7796 checkArithmeticOnObjCPointer(S, OpLoc, Op))
7797 return QualType();
Eli Friedman090addd2010-01-03 00:20:48 +00007798 } else if (ResType->isAnyComplexType()) {
Chris Lattner6b0cf142008-11-21 07:05:48 +00007799 // C99 does not support ++/-- on complex types, we allow as an extension.
John McCall4bc41ae2010-11-18 19:01:18 +00007800 S.Diag(OpLoc, diag::ext_integer_increment_complex)
Chris Lattner1e5665e2008-11-24 06:25:27 +00007801 << ResType << Op->getSourceRange();
John McCall36226622010-10-12 02:09:17 +00007802 } else if (ResType->isPlaceholderType()) {
John McCall3aef3d82011-04-10 19:13:55 +00007803 ExprResult PR = S.CheckPlaceholderExpr(Op);
John McCall36226622010-10-12 02:09:17 +00007804 if (PR.isInvalid()) return QualType();
John McCall4bc41ae2010-11-18 19:01:18 +00007805 return CheckIncrementDecrementOperand(S, PR.take(), VK, OpLoc,
Richard Trieuba63ce62011-09-09 01:45:06 +00007806 IsInc, IsPrefix);
David Blaikiebbafb8a2012-03-11 07:00:24 +00007807 } else if (S.getLangOpts().AltiVec && ResType->isVectorType()) {
Anton Yartsev85129b82011-02-07 02:17:30 +00007808 // OK! ( C/C++ Language Extensions for CBEA(Version 2.6) 10.3 )
Chris Lattner6b0cf142008-11-21 07:05:48 +00007809 } else {
John McCall4bc41ae2010-11-18 19:01:18 +00007810 S.Diag(OpLoc, diag::err_typecheck_illegal_increment_decrement)
Richard Trieuba63ce62011-09-09 01:45:06 +00007811 << ResType << int(IsInc) << Op->getSourceRange();
Chris Lattner6b0cf142008-11-21 07:05:48 +00007812 return QualType();
Steve Naroff46ba1eb2007-04-03 23:13:13 +00007813 }
Mike Stump4e1f26a2009-02-19 03:04:26 +00007814 // At this point, we know we have a real, complex or pointer type.
Steve Naroff9e1e5512007-08-23 21:37:33 +00007815 // Now make sure the operand is a modifiable lvalue.
John McCall4bc41ae2010-11-18 19:01:18 +00007816 if (CheckForModifiableLvalue(Op, OpLoc, S))
Steve Naroff35d85152007-05-07 00:24:15 +00007817 return QualType();
Alexis Huntc46382e2010-04-28 23:02:27 +00007818 // In C++, a prefix increment is the same type as the operand. Otherwise
7819 // (in C or with postfix), the increment is the unqualified type of the
7820 // operand.
David Blaikiebbafb8a2012-03-11 07:00:24 +00007821 if (IsPrefix && S.getLangOpts().CPlusPlus) {
John McCall4bc41ae2010-11-18 19:01:18 +00007822 VK = VK_LValue;
7823 return ResType;
7824 } else {
7825 VK = VK_RValue;
7826 return ResType.getUnqualifiedType();
7827 }
Steve Naroff26c8ea52007-03-21 21:08:52 +00007828}
Fariborz Jahanian805b74e2010-09-14 23:02:38 +00007829
7830
Anders Carlsson806700f2008-02-01 07:15:58 +00007831/// getPrimaryDecl - Helper function for CheckAddressOfOperand().
Steve Naroff47500512007-04-19 23:00:49 +00007832/// This routine allows us to typecheck complex/recursive expressions
Daniel Dunbarb692ef42008-08-04 20:02:37 +00007833/// where the declaration is needed for type checking. We only need to
7834/// handle cases when the expression references a function designator
7835/// or is an lvalue. Here are some examples:
7836/// - &(x) => x
7837/// - &*****f => f for f a function designator.
7838/// - &s.xx => s
7839/// - &s.zz[1].yy -> s, if zz is an array
7840/// - *(x + 1) -> x, if x is an array
7841/// - &"123"[2] -> 0
7842/// - & __real__ x -> x
John McCallf3a88602011-02-03 08:15:49 +00007843static ValueDecl *getPrimaryDecl(Expr *E) {
Chris Lattner24d5bfe2008-04-02 04:24:33 +00007844 switch (E->getStmtClass()) {
Steve Naroff47500512007-04-19 23:00:49 +00007845 case Stmt::DeclRefExprClass:
Chris Lattner24d5bfe2008-04-02 04:24:33 +00007846 return cast<DeclRefExpr>(E)->getDecl();
Steve Naroff47500512007-04-19 23:00:49 +00007847 case Stmt::MemberExprClass:
Eli Friedman3a1e6922009-04-20 08:23:18 +00007848 // If this is an arrow operator, the address is an offset from
7849 // the base's value, so the object the base refers to is
7850 // irrelevant.
Chris Lattner24d5bfe2008-04-02 04:24:33 +00007851 if (cast<MemberExpr>(E)->isArrow())
Chris Lattner48d52842007-11-16 17:46:48 +00007852 return 0;
Eli Friedman3a1e6922009-04-20 08:23:18 +00007853 // Otherwise, the expression refers to a part of the base
Chris Lattner24d5bfe2008-04-02 04:24:33 +00007854 return getPrimaryDecl(cast<MemberExpr>(E)->getBase());
Anders Carlsson806700f2008-02-01 07:15:58 +00007855 case Stmt::ArraySubscriptExprClass: {
Mike Stump87c57ac2009-05-16 07:39:55 +00007856 // FIXME: This code shouldn't be necessary! We should catch the implicit
7857 // promotion of register arrays earlier.
Eli Friedman3a1e6922009-04-20 08:23:18 +00007858 Expr* Base = cast<ArraySubscriptExpr>(E)->getBase();
7859 if (ImplicitCastExpr* ICE = dyn_cast<ImplicitCastExpr>(Base)) {
7860 if (ICE->getSubExpr()->getType()->isArrayType())
7861 return getPrimaryDecl(ICE->getSubExpr());
7862 }
7863 return 0;
Anders Carlsson806700f2008-02-01 07:15:58 +00007864 }
Daniel Dunbarb692ef42008-08-04 20:02:37 +00007865 case Stmt::UnaryOperatorClass: {
7866 UnaryOperator *UO = cast<UnaryOperator>(E);
Mike Stump4e1f26a2009-02-19 03:04:26 +00007867
Daniel Dunbarb692ef42008-08-04 20:02:37 +00007868 switch(UO->getOpcode()) {
John McCalle3027922010-08-25 11:45:40 +00007869 case UO_Real:
7870 case UO_Imag:
7871 case UO_Extension:
Daniel Dunbarb692ef42008-08-04 20:02:37 +00007872 return getPrimaryDecl(UO->getSubExpr());
7873 default:
7874 return 0;
7875 }
7876 }
Steve Naroff47500512007-04-19 23:00:49 +00007877 case Stmt::ParenExprClass:
Chris Lattner24d5bfe2008-04-02 04:24:33 +00007878 return getPrimaryDecl(cast<ParenExpr>(E)->getSubExpr());
Chris Lattner48d52842007-11-16 17:46:48 +00007879 case Stmt::ImplicitCastExprClass:
Eli Friedman3a1e6922009-04-20 08:23:18 +00007880 // If the result of an implicit cast is an l-value, we care about
7881 // the sub-expression; otherwise, the result here doesn't matter.
Chris Lattner24d5bfe2008-04-02 04:24:33 +00007882 return getPrimaryDecl(cast<ImplicitCastExpr>(E)->getSubExpr());
Steve Naroff47500512007-04-19 23:00:49 +00007883 default:
7884 return 0;
7885 }
7886}
7887
Richard Trieu5f376f62011-09-07 21:46:33 +00007888namespace {
7889 enum {
7890 AO_Bit_Field = 0,
7891 AO_Vector_Element = 1,
7892 AO_Property_Expansion = 2,
7893 AO_Register_Variable = 3,
7894 AO_No_Error = 4
7895 };
7896}
Richard Trieu3fd7bb82011-09-02 00:47:55 +00007897/// \brief Diagnose invalid operand for address of operations.
7898///
7899/// \param Type The type of operand which cannot have its address taken.
Richard Trieu3fd7bb82011-09-02 00:47:55 +00007900static void diagnoseAddressOfInvalidType(Sema &S, SourceLocation Loc,
7901 Expr *E, unsigned Type) {
7902 S.Diag(Loc, diag::err_typecheck_address_of) << Type << E->getSourceRange();
7903}
7904
Steve Naroff47500512007-04-19 23:00:49 +00007905/// CheckAddressOfOperand - The operand of & must be either a function
Mike Stump4e1f26a2009-02-19 03:04:26 +00007906/// designator or an lvalue designating an object. If it is an lvalue, the
Steve Naroff47500512007-04-19 23:00:49 +00007907/// object cannot be declared with storage class register or be a bit field.
Mike Stump4e1f26a2009-02-19 03:04:26 +00007908/// Note: The usual conversions are *not* applied to the operand of the &
Steve Naroffa78fe7e2007-05-16 19:47:19 +00007909/// operator (C99 6.3.2.1p[2-4]), and its result is never an lvalue.
Mike Stump4e1f26a2009-02-19 03:04:26 +00007910/// In C++, the operand might be an overloaded function name, in which case
Douglas Gregorcd695e52008-11-10 20:40:00 +00007911/// we allow the '&' but retain the overloaded-function type.
John McCall526ab472011-10-25 17:37:35 +00007912static QualType CheckAddressOfOperand(Sema &S, ExprResult &OrigOp,
John McCall4bc41ae2010-11-18 19:01:18 +00007913 SourceLocation OpLoc) {
John McCall526ab472011-10-25 17:37:35 +00007914 if (const BuiltinType *PTy = OrigOp.get()->getType()->getAsPlaceholderType()){
7915 if (PTy->getKind() == BuiltinType::Overload) {
7916 if (!isa<OverloadExpr>(OrigOp.get()->IgnoreParens())) {
7917 S.Diag(OpLoc, diag::err_typecheck_invalid_lvalue_addrof)
7918 << OrigOp.get()->getSourceRange();
7919 return QualType();
7920 }
7921
7922 return S.Context.OverloadTy;
7923 }
7924
7925 if (PTy->getKind() == BuiltinType::UnknownAny)
7926 return S.Context.UnknownAnyTy;
7927
7928 if (PTy->getKind() == BuiltinType::BoundMember) {
7929 S.Diag(OpLoc, diag::err_invalid_form_pointer_member_function)
7930 << OrigOp.get()->getSourceRange();
Douglas Gregor668d3622011-10-09 19:10:41 +00007931 return QualType();
7932 }
John McCall526ab472011-10-25 17:37:35 +00007933
7934 OrigOp = S.CheckPlaceholderExpr(OrigOp.take());
7935 if (OrigOp.isInvalid()) return QualType();
John McCall0009fcc2011-04-26 20:42:42 +00007936 }
John McCall8d08b9b2010-08-27 09:08:28 +00007937
John McCall526ab472011-10-25 17:37:35 +00007938 if (OrigOp.get()->isTypeDependent())
7939 return S.Context.DependentTy;
7940
7941 assert(!OrigOp.get()->getType()->isPlaceholderType());
John McCall36226622010-10-12 02:09:17 +00007942
John McCall8d08b9b2010-08-27 09:08:28 +00007943 // Make sure to ignore parentheses in subsequent checks
John McCall526ab472011-10-25 17:37:35 +00007944 Expr *op = OrigOp.get()->IgnoreParens();
Douglas Gregor19b8c4f2008-12-17 22:52:20 +00007945
David Blaikiebbafb8a2012-03-11 07:00:24 +00007946 if (S.getLangOpts().C99) {
Steve Naroff826e91a2008-01-13 17:10:08 +00007947 // Implement C99-only parts of addressof rules.
7948 if (UnaryOperator* uOp = dyn_cast<UnaryOperator>(op)) {
John McCalle3027922010-08-25 11:45:40 +00007949 if (uOp->getOpcode() == UO_Deref)
Steve Naroff826e91a2008-01-13 17:10:08 +00007950 // Per C99 6.5.3.2, the address of a deref always returns a valid result
7951 // (assuming the deref expression is valid).
7952 return uOp->getSubExpr()->getType();
7953 }
7954 // Technically, there should be a check for array subscript
7955 // expressions here, but the result of one is always an lvalue anyway.
7956 }
John McCallf3a88602011-02-03 08:15:49 +00007957 ValueDecl *dcl = getPrimaryDecl(op);
John McCall086a4642010-11-24 05:12:34 +00007958 Expr::LValueClassification lval = op->ClassifyLValue(S.Context);
Richard Trieu5f376f62011-09-07 21:46:33 +00007959 unsigned AddressOfError = AO_No_Error;
Nuno Lopes17f345f2008-12-16 22:59:47 +00007960
Fariborz Jahanian071caef2011-03-26 19:48:30 +00007961 if (lval == Expr::LV_ClassTemporary) {
John McCall4bc41ae2010-11-18 19:01:18 +00007962 bool sfinae = S.isSFINAEContext();
7963 S.Diag(OpLoc, sfinae ? diag::err_typecheck_addrof_class_temporary
7964 : diag::ext_typecheck_addrof_class_temporary)
Douglas Gregorb154fdc2010-02-16 21:39:57 +00007965 << op->getType() << op->getSourceRange();
John McCall4bc41ae2010-11-18 19:01:18 +00007966 if (sfinae)
Douglas Gregorb154fdc2010-02-16 21:39:57 +00007967 return QualType();
John McCall8d08b9b2010-08-27 09:08:28 +00007968 } else if (isa<ObjCSelectorExpr>(op)) {
John McCall4bc41ae2010-11-18 19:01:18 +00007969 return S.Context.getPointerType(op->getType());
John McCall8d08b9b2010-08-27 09:08:28 +00007970 } else if (lval == Expr::LV_MemberFunction) {
7971 // If it's an instance method, make a member pointer.
7972 // The expression must have exactly the form &A::foo.
7973
7974 // If the underlying expression isn't a decl ref, give up.
7975 if (!isa<DeclRefExpr>(op)) {
John McCall4bc41ae2010-11-18 19:01:18 +00007976 S.Diag(OpLoc, diag::err_invalid_form_pointer_member_function)
John McCall526ab472011-10-25 17:37:35 +00007977 << OrigOp.get()->getSourceRange();
John McCall8d08b9b2010-08-27 09:08:28 +00007978 return QualType();
7979 }
7980 DeclRefExpr *DRE = cast<DeclRefExpr>(op);
7981 CXXMethodDecl *MD = cast<CXXMethodDecl>(DRE->getDecl());
7982
7983 // The id-expression was parenthesized.
John McCall526ab472011-10-25 17:37:35 +00007984 if (OrigOp.get() != DRE) {
John McCall4bc41ae2010-11-18 19:01:18 +00007985 S.Diag(OpLoc, diag::err_parens_pointer_member_function)
John McCall526ab472011-10-25 17:37:35 +00007986 << OrigOp.get()->getSourceRange();
John McCall8d08b9b2010-08-27 09:08:28 +00007987
7988 // The method was named without a qualifier.
7989 } else if (!DRE->getQualifier()) {
John McCall4bc41ae2010-11-18 19:01:18 +00007990 S.Diag(OpLoc, diag::err_unqualified_pointer_member_function)
John McCall8d08b9b2010-08-27 09:08:28 +00007991 << op->getSourceRange();
7992 }
7993
John McCall4bc41ae2010-11-18 19:01:18 +00007994 return S.Context.getMemberPointerType(op->getType(),
7995 S.Context.getTypeDeclType(MD->getParent()).getTypePtr());
John McCall8d08b9b2010-08-27 09:08:28 +00007996 } else if (lval != Expr::LV_Valid && lval != Expr::LV_IncompleteVoidType) {
Eli Friedmance7f9002009-05-16 23:27:50 +00007997 // C99 6.5.3.2p1
Eli Friedman3a1e6922009-04-20 08:23:18 +00007998 // The operand must be either an l-value or a function designator
Eli Friedmance7f9002009-05-16 23:27:50 +00007999 if (!op->getType()->isFunctionType()) {
John McCall526ab472011-10-25 17:37:35 +00008000 // Use a special diagnostic for loads from property references.
John McCallfe96e0b2011-11-06 09:01:30 +00008001 if (isa<PseudoObjectExpr>(op)) {
John McCall526ab472011-10-25 17:37:35 +00008002 AddressOfError = AO_Property_Expansion;
8003 } else {
8004 // FIXME: emit more specific diag...
8005 S.Diag(OpLoc, diag::err_typecheck_invalid_lvalue_addrof)
8006 << op->getSourceRange();
8007 return QualType();
8008 }
Steve Naroff35d85152007-05-07 00:24:15 +00008009 }
John McCall086a4642010-11-24 05:12:34 +00008010 } else if (op->getObjectKind() == OK_BitField) { // C99 6.5.3.2p1
Eli Friedman3a1e6922009-04-20 08:23:18 +00008011 // The operand cannot be a bit-field
Richard Trieu5f376f62011-09-07 21:46:33 +00008012 AddressOfError = AO_Bit_Field;
John McCall086a4642010-11-24 05:12:34 +00008013 } else if (op->getObjectKind() == OK_VectorComponent) {
Eli Friedman3a1e6922009-04-20 08:23:18 +00008014 // The operand cannot be an element of a vector
Richard Trieu5f376f62011-09-07 21:46:33 +00008015 AddressOfError = AO_Vector_Element;
Steve Naroffb96e4ab62008-02-29 23:30:25 +00008016 } else if (dcl) { // C99 6.5.3.2p1
Mike Stump4e1f26a2009-02-19 03:04:26 +00008017 // We have an lvalue with a decl. Make sure the decl is not declared
Steve Naroff47500512007-04-19 23:00:49 +00008018 // with the register storage-class specifier.
8019 if (const VarDecl *vd = dyn_cast<VarDecl>(dcl)) {
Fariborz Jahaniane0fd5a92010-08-24 22:21:48 +00008020 // in C++ it is not error to take address of a register
8021 // variable (c++03 7.1.1P3)
John McCall8e7d6562010-08-26 03:08:43 +00008022 if (vd->getStorageClass() == SC_Register &&
David Blaikiebbafb8a2012-03-11 07:00:24 +00008023 !S.getLangOpts().CPlusPlus) {
Richard Trieu5f376f62011-09-07 21:46:33 +00008024 AddressOfError = AO_Register_Variable;
Steve Naroff35d85152007-05-07 00:24:15 +00008025 }
John McCalld14a8642009-11-21 08:51:07 +00008026 } else if (isa<FunctionTemplateDecl>(dcl)) {
John McCall4bc41ae2010-11-18 19:01:18 +00008027 return S.Context.OverloadTy;
John McCallf3a88602011-02-03 08:15:49 +00008028 } else if (isa<FieldDecl>(dcl) || isa<IndirectFieldDecl>(dcl)) {
Douglas Gregor9aa8b552008-12-10 21:26:49 +00008029 // Okay: we can take the address of a field.
Sebastian Redl3d3f75a2009-02-03 20:19:35 +00008030 // Could be a pointer to member, though, if there is an explicit
8031 // scope qualifier for the class.
Douglas Gregor4bd90e52009-10-23 18:54:35 +00008032 if (isa<DeclRefExpr>(op) && cast<DeclRefExpr>(op)->getQualifier()) {
Sebastian Redl3d3f75a2009-02-03 20:19:35 +00008033 DeclContext *Ctx = dcl->getDeclContext();
Anders Carlsson0b675f52009-07-08 21:45:58 +00008034 if (Ctx && Ctx->isRecord()) {
John McCallf3a88602011-02-03 08:15:49 +00008035 if (dcl->getType()->isReferenceType()) {
John McCall4bc41ae2010-11-18 19:01:18 +00008036 S.Diag(OpLoc,
8037 diag::err_cannot_form_pointer_to_member_of_reference_type)
John McCallf3a88602011-02-03 08:15:49 +00008038 << dcl->getDeclName() << dcl->getType();
Anders Carlsson0b675f52009-07-08 21:45:58 +00008039 return QualType();
8040 }
Mike Stump11289f42009-09-09 15:08:12 +00008041
Argyrios Kyrtzidis8322b422011-01-31 07:04:29 +00008042 while (cast<RecordDecl>(Ctx)->isAnonymousStructOrUnion())
8043 Ctx = Ctx->getParent();
John McCall4bc41ae2010-11-18 19:01:18 +00008044 return S.Context.getMemberPointerType(op->getType(),
8045 S.Context.getTypeDeclType(cast<RecordDecl>(Ctx)).getTypePtr());
Anders Carlsson0b675f52009-07-08 21:45:58 +00008046 }
Sebastian Redl3d3f75a2009-02-03 20:19:35 +00008047 }
Eli Friedman755c0c92011-08-26 20:28:17 +00008048 } else if (!isa<FunctionDecl>(dcl) && !isa<NonTypeTemplateParmDecl>(dcl))
David Blaikie83d382b2011-09-23 05:06:16 +00008049 llvm_unreachable("Unknown/unexpected decl type");
Steve Naroff47500512007-04-19 23:00:49 +00008050 }
Sebastian Redl18f8ff62009-02-04 21:23:32 +00008051
Richard Trieu5f376f62011-09-07 21:46:33 +00008052 if (AddressOfError != AO_No_Error) {
8053 diagnoseAddressOfInvalidType(S, OpLoc, op, AddressOfError);
8054 return QualType();
8055 }
8056
Eli Friedmance7f9002009-05-16 23:27:50 +00008057 if (lval == Expr::LV_IncompleteVoidType) {
8058 // Taking the address of a void variable is technically illegal, but we
8059 // allow it in cases which are otherwise valid.
8060 // Example: "extern void x; void* y = &x;".
John McCall4bc41ae2010-11-18 19:01:18 +00008061 S.Diag(OpLoc, diag::ext_typecheck_addrof_void) << op->getSourceRange();
Eli Friedmance7f9002009-05-16 23:27:50 +00008062 }
8063
Steve Naroff47500512007-04-19 23:00:49 +00008064 // If the operand has type "type", the result has type "pointer to type".
Douglas Gregor0bdcb8a2010-07-29 16:05:45 +00008065 if (op->getType()->isObjCObjectType())
John McCall4bc41ae2010-11-18 19:01:18 +00008066 return S.Context.getObjCObjectPointerType(op->getType());
8067 return S.Context.getPointerType(op->getType());
Steve Naroff47500512007-04-19 23:00:49 +00008068}
8069
Chris Lattner9156f1b2010-07-05 19:17:26 +00008070/// CheckIndirectionOperand - Type check unary indirection (prefix '*').
John McCall4bc41ae2010-11-18 19:01:18 +00008071static QualType CheckIndirectionOperand(Sema &S, Expr *Op, ExprValueKind &VK,
8072 SourceLocation OpLoc) {
Sebastian Redl8d2ccae2009-02-26 14:39:58 +00008073 if (Op->isTypeDependent())
John McCall4bc41ae2010-11-18 19:01:18 +00008074 return S.Context.DependentTy;
Sebastian Redl8d2ccae2009-02-26 14:39:58 +00008075
John Wiegley01296292011-04-08 18:41:53 +00008076 ExprResult ConvResult = S.UsualUnaryConversions(Op);
8077 if (ConvResult.isInvalid())
8078 return QualType();
8079 Op = ConvResult.take();
Chris Lattner9156f1b2010-07-05 19:17:26 +00008080 QualType OpTy = Op->getType();
8081 QualType Result;
Argyrios Kyrtzidis69a2c922011-05-02 18:21:19 +00008082
8083 if (isa<CXXReinterpretCastExpr>(Op)) {
8084 QualType OpOrigType = Op->IgnoreParenCasts()->getType();
8085 S.CheckCompatibleReinterpretCast(OpOrigType, OpTy, /*IsDereference*/true,
8086 Op->getSourceRange());
8087 }
8088
Chris Lattner9156f1b2010-07-05 19:17:26 +00008089 // Note that per both C89 and C99, indirection is always legal, even if OpTy
8090 // is an incomplete type or void. It would be possible to warn about
8091 // dereferencing a void pointer, but it's completely well-defined, and such a
8092 // warning is unlikely to catch any mistakes.
8093 if (const PointerType *PT = OpTy->getAs<PointerType>())
8094 Result = PT->getPointeeType();
8095 else if (const ObjCObjectPointerType *OPT =
8096 OpTy->getAs<ObjCObjectPointerType>())
8097 Result = OPT->getPointeeType();
John McCall36226622010-10-12 02:09:17 +00008098 else {
John McCall3aef3d82011-04-10 19:13:55 +00008099 ExprResult PR = S.CheckPlaceholderExpr(Op);
John McCall36226622010-10-12 02:09:17 +00008100 if (PR.isInvalid()) return QualType();
John McCall4bc41ae2010-11-18 19:01:18 +00008101 if (PR.take() != Op)
8102 return CheckIndirectionOperand(S, PR.take(), VK, OpLoc);
John McCall36226622010-10-12 02:09:17 +00008103 }
Mike Stump4e1f26a2009-02-19 03:04:26 +00008104
Chris Lattner9156f1b2010-07-05 19:17:26 +00008105 if (Result.isNull()) {
John McCall4bc41ae2010-11-18 19:01:18 +00008106 S.Diag(OpLoc, diag::err_typecheck_indirection_requires_pointer)
Chris Lattner9156f1b2010-07-05 19:17:26 +00008107 << OpTy << Op->getSourceRange();
8108 return QualType();
8109 }
John McCall4bc41ae2010-11-18 19:01:18 +00008110
8111 // Dereferences are usually l-values...
8112 VK = VK_LValue;
8113
8114 // ...except that certain expressions are never l-values in C.
David Blaikiebbafb8a2012-03-11 07:00:24 +00008115 if (!S.getLangOpts().CPlusPlus && Result.isCForbiddenLValueType())
John McCall4bc41ae2010-11-18 19:01:18 +00008116 VK = VK_RValue;
Chris Lattner9156f1b2010-07-05 19:17:26 +00008117
8118 return Result;
Steve Naroff1926c832007-04-24 00:23:05 +00008119}
Steve Naroff218bc2b2007-05-04 21:54:46 +00008120
John McCalle3027922010-08-25 11:45:40 +00008121static inline BinaryOperatorKind ConvertTokenKindToBinaryOpcode(
Steve Naroff218bc2b2007-05-04 21:54:46 +00008122 tok::TokenKind Kind) {
John McCalle3027922010-08-25 11:45:40 +00008123 BinaryOperatorKind Opc;
Steve Naroff218bc2b2007-05-04 21:54:46 +00008124 switch (Kind) {
David Blaikie83d382b2011-09-23 05:06:16 +00008125 default: llvm_unreachable("Unknown binop!");
John McCalle3027922010-08-25 11:45:40 +00008126 case tok::periodstar: Opc = BO_PtrMemD; break;
8127 case tok::arrowstar: Opc = BO_PtrMemI; break;
8128 case tok::star: Opc = BO_Mul; break;
8129 case tok::slash: Opc = BO_Div; break;
8130 case tok::percent: Opc = BO_Rem; break;
8131 case tok::plus: Opc = BO_Add; break;
8132 case tok::minus: Opc = BO_Sub; break;
8133 case tok::lessless: Opc = BO_Shl; break;
8134 case tok::greatergreater: Opc = BO_Shr; break;
8135 case tok::lessequal: Opc = BO_LE; break;
8136 case tok::less: Opc = BO_LT; break;
8137 case tok::greaterequal: Opc = BO_GE; break;
8138 case tok::greater: Opc = BO_GT; break;
8139 case tok::exclaimequal: Opc = BO_NE; break;
8140 case tok::equalequal: Opc = BO_EQ; break;
8141 case tok::amp: Opc = BO_And; break;
8142 case tok::caret: Opc = BO_Xor; break;
8143 case tok::pipe: Opc = BO_Or; break;
8144 case tok::ampamp: Opc = BO_LAnd; break;
8145 case tok::pipepipe: Opc = BO_LOr; break;
8146 case tok::equal: Opc = BO_Assign; break;
8147 case tok::starequal: Opc = BO_MulAssign; break;
8148 case tok::slashequal: Opc = BO_DivAssign; break;
8149 case tok::percentequal: Opc = BO_RemAssign; break;
8150 case tok::plusequal: Opc = BO_AddAssign; break;
8151 case tok::minusequal: Opc = BO_SubAssign; break;
8152 case tok::lesslessequal: Opc = BO_ShlAssign; break;
8153 case tok::greatergreaterequal: Opc = BO_ShrAssign; break;
8154 case tok::ampequal: Opc = BO_AndAssign; break;
8155 case tok::caretequal: Opc = BO_XorAssign; break;
8156 case tok::pipeequal: Opc = BO_OrAssign; break;
8157 case tok::comma: Opc = BO_Comma; break;
Steve Naroff218bc2b2007-05-04 21:54:46 +00008158 }
8159 return Opc;
8160}
8161
John McCalle3027922010-08-25 11:45:40 +00008162static inline UnaryOperatorKind ConvertTokenKindToUnaryOpcode(
Steve Naroff35d85152007-05-07 00:24:15 +00008163 tok::TokenKind Kind) {
John McCalle3027922010-08-25 11:45:40 +00008164 UnaryOperatorKind Opc;
Steve Naroff35d85152007-05-07 00:24:15 +00008165 switch (Kind) {
David Blaikie83d382b2011-09-23 05:06:16 +00008166 default: llvm_unreachable("Unknown unary op!");
John McCalle3027922010-08-25 11:45:40 +00008167 case tok::plusplus: Opc = UO_PreInc; break;
8168 case tok::minusminus: Opc = UO_PreDec; break;
8169 case tok::amp: Opc = UO_AddrOf; break;
8170 case tok::star: Opc = UO_Deref; break;
8171 case tok::plus: Opc = UO_Plus; break;
8172 case tok::minus: Opc = UO_Minus; break;
8173 case tok::tilde: Opc = UO_Not; break;
8174 case tok::exclaim: Opc = UO_LNot; break;
8175 case tok::kw___real: Opc = UO_Real; break;
8176 case tok::kw___imag: Opc = UO_Imag; break;
8177 case tok::kw___extension__: Opc = UO_Extension; break;
Steve Naroff35d85152007-05-07 00:24:15 +00008178 }
8179 return Opc;
8180}
8181
Chandler Carruthe0cee6a2011-01-04 06:52:15 +00008182/// DiagnoseSelfAssignment - Emits a warning if a value is assigned to itself.
8183/// This warning is only emitted for builtin assignment operations. It is also
8184/// suppressed in the event of macro expansions.
Richard Trieuda4f43a62011-09-07 01:33:52 +00008185static void DiagnoseSelfAssignment(Sema &S, Expr *LHSExpr, Expr *RHSExpr,
Chandler Carruthe0cee6a2011-01-04 06:52:15 +00008186 SourceLocation OpLoc) {
8187 if (!S.ActiveTemplateInstantiations.empty())
8188 return;
8189 if (OpLoc.isInvalid() || OpLoc.isMacroID())
8190 return;
Richard Trieuda4f43a62011-09-07 01:33:52 +00008191 LHSExpr = LHSExpr->IgnoreParenImpCasts();
8192 RHSExpr = RHSExpr->IgnoreParenImpCasts();
8193 const DeclRefExpr *LHSDeclRef = dyn_cast<DeclRefExpr>(LHSExpr);
8194 const DeclRefExpr *RHSDeclRef = dyn_cast<DeclRefExpr>(RHSExpr);
8195 if (!LHSDeclRef || !RHSDeclRef ||
8196 LHSDeclRef->getLocation().isMacroID() ||
8197 RHSDeclRef->getLocation().isMacroID())
Chandler Carruthe0cee6a2011-01-04 06:52:15 +00008198 return;
Richard Trieuda4f43a62011-09-07 01:33:52 +00008199 const ValueDecl *LHSDecl =
8200 cast<ValueDecl>(LHSDeclRef->getDecl()->getCanonicalDecl());
8201 const ValueDecl *RHSDecl =
8202 cast<ValueDecl>(RHSDeclRef->getDecl()->getCanonicalDecl());
8203 if (LHSDecl != RHSDecl)
Chandler Carruthe0cee6a2011-01-04 06:52:15 +00008204 return;
Richard Trieuda4f43a62011-09-07 01:33:52 +00008205 if (LHSDecl->getType().isVolatileQualified())
Chandler Carruthe0cee6a2011-01-04 06:52:15 +00008206 return;
Richard Trieuda4f43a62011-09-07 01:33:52 +00008207 if (const ReferenceType *RefTy = LHSDecl->getType()->getAs<ReferenceType>())
Chandler Carruthe0cee6a2011-01-04 06:52:15 +00008208 if (RefTy->getPointeeType().isVolatileQualified())
8209 return;
8210
8211 S.Diag(OpLoc, diag::warn_self_assignment)
Richard Trieuda4f43a62011-09-07 01:33:52 +00008212 << LHSDeclRef->getType()
8213 << LHSExpr->getSourceRange() << RHSExpr->getSourceRange();
Chandler Carruthe0cee6a2011-01-04 06:52:15 +00008214}
8215
Douglas Gregor7d5fc7e2008-11-06 23:29:22 +00008216/// CreateBuiltinBinOp - Creates a new built-in binary operation with
8217/// operator @p Opc at location @c TokLoc. This routine only supports
8218/// built-in operations; ActOnBinOp handles overloaded operators.
John McCalldadc5752010-08-24 06:29:42 +00008219ExprResult Sema::CreateBuiltinBinOp(SourceLocation OpLoc,
Argyrios Kyrtzidis7a808c02011-01-05 20:09:36 +00008220 BinaryOperatorKind Opc,
Richard Trieu4a287fb2011-09-07 01:49:20 +00008221 Expr *LHSExpr, Expr *RHSExpr) {
David Blaikiebbafb8a2012-03-11 07:00:24 +00008222 if (getLangOpts().CPlusPlus0x && isa<InitListExpr>(RHSExpr)) {
Sebastian Redl67766732012-02-27 20:34:02 +00008223 // The syntax only allows initializer lists on the RHS of assignment,
8224 // so we don't need to worry about accepting invalid code for
8225 // non-assignment operators.
8226 // C++11 5.17p9:
8227 // The meaning of x = {v} [...] is that of x = T(v) [...]. The meaning
8228 // of x = {} is x = T().
8229 InitializationKind Kind =
8230 InitializationKind::CreateDirectList(RHSExpr->getLocStart());
8231 InitializedEntity Entity =
8232 InitializedEntity::InitializeTemporary(LHSExpr->getType());
8233 InitializationSequence InitSeq(*this, Entity, Kind, &RHSExpr, 1);
Benjamin Kramercc4c49d2012-08-23 23:38:35 +00008234 ExprResult Init = InitSeq.Perform(*this, Entity, Kind, RHSExpr);
Sebastian Redl67766732012-02-27 20:34:02 +00008235 if (Init.isInvalid())
8236 return Init;
8237 RHSExpr = Init.take();
8238 }
8239
Richard Trieu4a287fb2011-09-07 01:49:20 +00008240 ExprResult LHS = Owned(LHSExpr), RHS = Owned(RHSExpr);
Eli Friedman8b7b1b12009-03-28 01:22:36 +00008241 QualType ResultTy; // Result type of the binary operator.
Eli Friedman8b7b1b12009-03-28 01:22:36 +00008242 // The following two variables are used for compound assignment operators
8243 QualType CompLHSTy; // Type of LHS after promotions for computation
8244 QualType CompResultTy; // Type of computation result
John McCall7decc9e2010-11-18 06:31:45 +00008245 ExprValueKind VK = VK_RValue;
8246 ExprObjectKind OK = OK_Ordinary;
Douglas Gregor7d5fc7e2008-11-06 23:29:22 +00008247
8248 switch (Opc) {
John McCalle3027922010-08-25 11:45:40 +00008249 case BO_Assign:
Richard Trieu4a287fb2011-09-07 01:49:20 +00008250 ResultTy = CheckAssignmentOperands(LHS.get(), RHS, OpLoc, QualType());
David Blaikiebbafb8a2012-03-11 07:00:24 +00008251 if (getLangOpts().CPlusPlus &&
Richard Trieu4a287fb2011-09-07 01:49:20 +00008252 LHS.get()->getObjectKind() != OK_ObjCProperty) {
8253 VK = LHS.get()->getValueKind();
8254 OK = LHS.get()->getObjectKind();
John McCall7decc9e2010-11-18 06:31:45 +00008255 }
Chandler Carruthe0cee6a2011-01-04 06:52:15 +00008256 if (!ResultTy.isNull())
Richard Trieu4a287fb2011-09-07 01:49:20 +00008257 DiagnoseSelfAssignment(*this, LHS.get(), RHS.get(), OpLoc);
Douglas Gregor7d5fc7e2008-11-06 23:29:22 +00008258 break;
John McCalle3027922010-08-25 11:45:40 +00008259 case BO_PtrMemD:
8260 case BO_PtrMemI:
Richard Trieu4a287fb2011-09-07 01:49:20 +00008261 ResultTy = CheckPointerToMemberOperands(LHS, RHS, VK, OpLoc,
John McCalle3027922010-08-25 11:45:40 +00008262 Opc == BO_PtrMemI);
Sebastian Redl112a97662009-02-07 00:15:38 +00008263 break;
John McCalle3027922010-08-25 11:45:40 +00008264 case BO_Mul:
8265 case BO_Div:
Richard Trieu4a287fb2011-09-07 01:49:20 +00008266 ResultTy = CheckMultiplyDivideOperands(LHS, RHS, OpLoc, false,
John McCalle3027922010-08-25 11:45:40 +00008267 Opc == BO_Div);
Douglas Gregor7d5fc7e2008-11-06 23:29:22 +00008268 break;
John McCalle3027922010-08-25 11:45:40 +00008269 case BO_Rem:
Richard Trieu4a287fb2011-09-07 01:49:20 +00008270 ResultTy = CheckRemainderOperands(LHS, RHS, OpLoc);
Douglas Gregor7d5fc7e2008-11-06 23:29:22 +00008271 break;
John McCalle3027922010-08-25 11:45:40 +00008272 case BO_Add:
Nico Weberccec40d2012-03-02 22:01:22 +00008273 ResultTy = CheckAdditionOperands(LHS, RHS, OpLoc, Opc);
Douglas Gregor7d5fc7e2008-11-06 23:29:22 +00008274 break;
John McCalle3027922010-08-25 11:45:40 +00008275 case BO_Sub:
Richard Trieu4a287fb2011-09-07 01:49:20 +00008276 ResultTy = CheckSubtractionOperands(LHS, RHS, OpLoc);
Douglas Gregor7d5fc7e2008-11-06 23:29:22 +00008277 break;
John McCalle3027922010-08-25 11:45:40 +00008278 case BO_Shl:
8279 case BO_Shr:
Richard Trieu4a287fb2011-09-07 01:49:20 +00008280 ResultTy = CheckShiftOperands(LHS, RHS, OpLoc, Opc);
Douglas Gregor7d5fc7e2008-11-06 23:29:22 +00008281 break;
John McCalle3027922010-08-25 11:45:40 +00008282 case BO_LE:
8283 case BO_LT:
8284 case BO_GE:
8285 case BO_GT:
Richard Trieu4a287fb2011-09-07 01:49:20 +00008286 ResultTy = CheckCompareOperands(LHS, RHS, OpLoc, Opc, true);
Douglas Gregor7d5fc7e2008-11-06 23:29:22 +00008287 break;
John McCalle3027922010-08-25 11:45:40 +00008288 case BO_EQ:
8289 case BO_NE:
Richard Trieu4a287fb2011-09-07 01:49:20 +00008290 ResultTy = CheckCompareOperands(LHS, RHS, OpLoc, Opc, false);
Douglas Gregor7d5fc7e2008-11-06 23:29:22 +00008291 break;
John McCalle3027922010-08-25 11:45:40 +00008292 case BO_And:
8293 case BO_Xor:
8294 case BO_Or:
Richard Trieu4a287fb2011-09-07 01:49:20 +00008295 ResultTy = CheckBitwiseOperands(LHS, RHS, OpLoc);
Douglas Gregor7d5fc7e2008-11-06 23:29:22 +00008296 break;
John McCalle3027922010-08-25 11:45:40 +00008297 case BO_LAnd:
8298 case BO_LOr:
Richard Trieu4a287fb2011-09-07 01:49:20 +00008299 ResultTy = CheckLogicalOperands(LHS, RHS, OpLoc, Opc);
Douglas Gregor7d5fc7e2008-11-06 23:29:22 +00008300 break;
John McCalle3027922010-08-25 11:45:40 +00008301 case BO_MulAssign:
8302 case BO_DivAssign:
Richard Trieu4a287fb2011-09-07 01:49:20 +00008303 CompResultTy = CheckMultiplyDivideOperands(LHS, RHS, OpLoc, true,
John McCall7decc9e2010-11-18 06:31:45 +00008304 Opc == BO_DivAssign);
Eli Friedman8b7b1b12009-03-28 01:22:36 +00008305 CompLHSTy = CompResultTy;
Richard Trieu4a287fb2011-09-07 01:49:20 +00008306 if (!CompResultTy.isNull() && !LHS.isInvalid() && !RHS.isInvalid())
8307 ResultTy = CheckAssignmentOperands(LHS.get(), RHS, OpLoc, CompResultTy);
Douglas Gregor7d5fc7e2008-11-06 23:29:22 +00008308 break;
John McCalle3027922010-08-25 11:45:40 +00008309 case BO_RemAssign:
Richard Trieu4a287fb2011-09-07 01:49:20 +00008310 CompResultTy = CheckRemainderOperands(LHS, RHS, OpLoc, true);
Eli Friedman8b7b1b12009-03-28 01:22:36 +00008311 CompLHSTy = CompResultTy;
Richard Trieu4a287fb2011-09-07 01:49:20 +00008312 if (!CompResultTy.isNull() && !LHS.isInvalid() && !RHS.isInvalid())
8313 ResultTy = CheckAssignmentOperands(LHS.get(), RHS, OpLoc, CompResultTy);
Douglas Gregor7d5fc7e2008-11-06 23:29:22 +00008314 break;
John McCalle3027922010-08-25 11:45:40 +00008315 case BO_AddAssign:
Nico Weberccec40d2012-03-02 22:01:22 +00008316 CompResultTy = CheckAdditionOperands(LHS, RHS, OpLoc, Opc, &CompLHSTy);
Richard Trieu4a287fb2011-09-07 01:49:20 +00008317 if (!CompResultTy.isNull() && !LHS.isInvalid() && !RHS.isInvalid())
8318 ResultTy = CheckAssignmentOperands(LHS.get(), RHS, OpLoc, CompResultTy);
Douglas Gregor7d5fc7e2008-11-06 23:29:22 +00008319 break;
John McCalle3027922010-08-25 11:45:40 +00008320 case BO_SubAssign:
Richard Trieu4a287fb2011-09-07 01:49:20 +00008321 CompResultTy = CheckSubtractionOperands(LHS, RHS, OpLoc, &CompLHSTy);
8322 if (!CompResultTy.isNull() && !LHS.isInvalid() && !RHS.isInvalid())
8323 ResultTy = CheckAssignmentOperands(LHS.get(), RHS, OpLoc, CompResultTy);
Douglas Gregor7d5fc7e2008-11-06 23:29:22 +00008324 break;
John McCalle3027922010-08-25 11:45:40 +00008325 case BO_ShlAssign:
8326 case BO_ShrAssign:
Richard Trieu4a287fb2011-09-07 01:49:20 +00008327 CompResultTy = CheckShiftOperands(LHS, RHS, OpLoc, Opc, true);
Eli Friedman8b7b1b12009-03-28 01:22:36 +00008328 CompLHSTy = CompResultTy;
Richard Trieu4a287fb2011-09-07 01:49:20 +00008329 if (!CompResultTy.isNull() && !LHS.isInvalid() && !RHS.isInvalid())
8330 ResultTy = CheckAssignmentOperands(LHS.get(), RHS, OpLoc, CompResultTy);
Douglas Gregor7d5fc7e2008-11-06 23:29:22 +00008331 break;
John McCalle3027922010-08-25 11:45:40 +00008332 case BO_AndAssign:
8333 case BO_XorAssign:
8334 case BO_OrAssign:
Richard Trieu4a287fb2011-09-07 01:49:20 +00008335 CompResultTy = CheckBitwiseOperands(LHS, RHS, OpLoc, true);
Eli Friedman8b7b1b12009-03-28 01:22:36 +00008336 CompLHSTy = CompResultTy;
Richard Trieu4a287fb2011-09-07 01:49:20 +00008337 if (!CompResultTy.isNull() && !LHS.isInvalid() && !RHS.isInvalid())
8338 ResultTy = CheckAssignmentOperands(LHS.get(), RHS, OpLoc, CompResultTy);
Douglas Gregor7d5fc7e2008-11-06 23:29:22 +00008339 break;
John McCalle3027922010-08-25 11:45:40 +00008340 case BO_Comma:
Richard Trieu4a287fb2011-09-07 01:49:20 +00008341 ResultTy = CheckCommaOperands(*this, LHS, RHS, OpLoc);
David Blaikiebbafb8a2012-03-11 07:00:24 +00008342 if (getLangOpts().CPlusPlus && !RHS.isInvalid()) {
Richard Trieu4a287fb2011-09-07 01:49:20 +00008343 VK = RHS.get()->getValueKind();
8344 OK = RHS.get()->getObjectKind();
John McCall7decc9e2010-11-18 06:31:45 +00008345 }
Douglas Gregor7d5fc7e2008-11-06 23:29:22 +00008346 break;
8347 }
Richard Trieu4a287fb2011-09-07 01:49:20 +00008348 if (ResultTy.isNull() || LHS.isInvalid() || RHS.isInvalid())
Sebastian Redlb5d49352009-01-19 22:31:54 +00008349 return ExprError();
Kaelyn Uhrain2e7aa5a2011-08-05 23:18:04 +00008350
8351 // Check for array bounds violations for both sides of the BinaryOperator
Richard Trieu4a287fb2011-09-07 01:49:20 +00008352 CheckArrayAccess(LHS.get());
8353 CheckArrayAccess(RHS.get());
Kaelyn Uhrain2e7aa5a2011-08-05 23:18:04 +00008354
Eli Friedman8b7b1b12009-03-28 01:22:36 +00008355 if (CompResultTy.isNull())
Richard Trieu4a287fb2011-09-07 01:49:20 +00008356 return Owned(new (Context) BinaryOperator(LHS.take(), RHS.take(), Opc,
John Wiegley01296292011-04-08 18:41:53 +00008357 ResultTy, VK, OK, OpLoc));
David Blaikiebbafb8a2012-03-11 07:00:24 +00008358 if (getLangOpts().CPlusPlus && LHS.get()->getObjectKind() !=
Richard Trieucfc491d2011-08-02 04:35:43 +00008359 OK_ObjCProperty) {
John McCall7decc9e2010-11-18 06:31:45 +00008360 VK = VK_LValue;
Richard Trieu4a287fb2011-09-07 01:49:20 +00008361 OK = LHS.get()->getObjectKind();
John McCall7decc9e2010-11-18 06:31:45 +00008362 }
Richard Trieu4a287fb2011-09-07 01:49:20 +00008363 return Owned(new (Context) CompoundAssignOperator(LHS.take(), RHS.take(), Opc,
John Wiegley01296292011-04-08 18:41:53 +00008364 ResultTy, VK, OK, CompLHSTy,
John McCall7decc9e2010-11-18 06:31:45 +00008365 CompResultTy, OpLoc));
Douglas Gregor7d5fc7e2008-11-06 23:29:22 +00008366}
8367
Sebastian Redl44615072009-10-27 12:10:02 +00008368/// DiagnoseBitwisePrecedence - Emit a warning when bitwise and comparison
8369/// operators are mixed in a way that suggests that the programmer forgot that
8370/// comparison operators have higher precedence. The most typical example of
8371/// such code is "flags & 0x0020 != 0", which is equivalent to "flags & 1".
John McCalle3027922010-08-25 11:45:40 +00008372static void DiagnoseBitwisePrecedence(Sema &Self, BinaryOperatorKind Opc,
Richard Trieu4a287fb2011-09-07 01:49:20 +00008373 SourceLocation OpLoc, Expr *LHSExpr,
8374 Expr *RHSExpr) {
Sebastian Redl44615072009-10-27 12:10:02 +00008375 typedef BinaryOperator BinOp;
Richard Trieu4a287fb2011-09-07 01:49:20 +00008376 BinOp::Opcode LHSopc = static_cast<BinOp::Opcode>(-1),
8377 RHSopc = static_cast<BinOp::Opcode>(-1);
8378 if (BinOp *BO = dyn_cast<BinOp>(LHSExpr))
8379 LHSopc = BO->getOpcode();
8380 if (BinOp *BO = dyn_cast<BinOp>(RHSExpr))
8381 RHSopc = BO->getOpcode();
Sebastian Redl43028242009-10-26 15:24:15 +00008382
8383 // Subs are not binary operators.
Richard Trieu4a287fb2011-09-07 01:49:20 +00008384 if (LHSopc == -1 && RHSopc == -1)
Sebastian Redl43028242009-10-26 15:24:15 +00008385 return;
8386
8387 // Bitwise operations are sometimes used as eager logical ops.
8388 // Don't diagnose this.
Richard Trieu4a287fb2011-09-07 01:49:20 +00008389 if ((BinOp::isComparisonOp(LHSopc) || BinOp::isBitwiseOp(LHSopc)) &&
8390 (BinOp::isComparisonOp(RHSopc) || BinOp::isBitwiseOp(RHSopc)))
Sebastian Redl43028242009-10-26 15:24:15 +00008391 return;
8392
Richard Trieu4a287fb2011-09-07 01:49:20 +00008393 bool isLeftComp = BinOp::isComparisonOp(LHSopc);
8394 bool isRightComp = BinOp::isComparisonOp(RHSopc);
Richard Trieu73088052011-08-10 22:41:34 +00008395 if (!isLeftComp && !isRightComp) return;
8396
Richard Trieu4a287fb2011-09-07 01:49:20 +00008397 SourceRange DiagRange = isLeftComp ? SourceRange(LHSExpr->getLocStart(),
8398 OpLoc)
8399 : SourceRange(OpLoc, RHSExpr->getLocEnd());
8400 std::string OpStr = isLeftComp ? BinOp::getOpcodeStr(LHSopc)
8401 : BinOp::getOpcodeStr(RHSopc);
Richard Trieu73088052011-08-10 22:41:34 +00008402 SourceRange ParensRange = isLeftComp ?
Richard Trieu4a287fb2011-09-07 01:49:20 +00008403 SourceRange(cast<BinOp>(LHSExpr)->getRHS()->getLocStart(),
8404 RHSExpr->getLocEnd())
8405 : SourceRange(LHSExpr->getLocStart(),
8406 cast<BinOp>(RHSExpr)->getLHS()->getLocStart());
Richard Trieu73088052011-08-10 22:41:34 +00008407
8408 Self.Diag(OpLoc, diag::warn_precedence_bitwise_rel)
8409 << DiagRange << BinOp::getOpcodeStr(Opc) << OpStr;
8410 SuggestParentheses(Self, OpLoc,
8411 Self.PDiag(diag::note_precedence_bitwise_silence) << OpStr,
Nico Webercdfb1ae2012-06-03 07:07:00 +00008412 (isLeftComp ? LHSExpr : RHSExpr)->getSourceRange());
Richard Trieu73088052011-08-10 22:41:34 +00008413 SuggestParentheses(Self, OpLoc,
8414 Self.PDiag(diag::note_precedence_bitwise_first) << BinOp::getOpcodeStr(Opc),
8415 ParensRange);
Sebastian Redl43028242009-10-26 15:24:15 +00008416}
8417
Argyrios Kyrtzidis01bf7772011-06-20 18:41:26 +00008418/// \brief It accepts a '&' expr that is inside a '|' one.
8419/// Emit a diagnostic together with a fixit hint that wraps the '&' expression
8420/// in parentheses.
8421static void
8422EmitDiagnosticForBitwiseAndInBitwiseOr(Sema &Self, SourceLocation OpLoc,
8423 BinaryOperator *Bop) {
8424 assert(Bop->getOpcode() == BO_And);
8425 Self.Diag(Bop->getOperatorLoc(), diag::warn_bitwise_and_in_bitwise_or)
8426 << Bop->getSourceRange() << OpLoc;
8427 SuggestParentheses(Self, Bop->getOperatorLoc(),
8428 Self.PDiag(diag::note_bitwise_and_in_bitwise_or_silence),
8429 Bop->getSourceRange());
8430}
8431
Argyrios Kyrtzidis14a96622010-11-17 18:26:36 +00008432/// \brief It accepts a '&&' expr that is inside a '||' one.
8433/// Emit a diagnostic together with a fixit hint that wraps the '&&' expression
8434/// in parentheses.
8435static void
8436EmitDiagnosticForLogicalAndInLogicalOr(Sema &Self, SourceLocation OpLoc,
Argyrios Kyrtzidisad8b4d42011-04-22 19:16:27 +00008437 BinaryOperator *Bop) {
8438 assert(Bop->getOpcode() == BO_LAnd);
Chandler Carruthb00e8c02011-06-16 01:05:14 +00008439 Self.Diag(Bop->getOperatorLoc(), diag::warn_logical_and_in_logical_or)
8440 << Bop->getSourceRange() << OpLoc;
Argyrios Kyrtzidisad8b4d42011-04-22 19:16:27 +00008441 SuggestParentheses(Self, Bop->getOperatorLoc(),
Argyrios Kyrtzidis14a96622010-11-17 18:26:36 +00008442 Self.PDiag(diag::note_logical_and_in_logical_or_silence),
Chandler Carruthb00e8c02011-06-16 01:05:14 +00008443 Bop->getSourceRange());
Argyrios Kyrtzidis14a96622010-11-17 18:26:36 +00008444}
8445
8446/// \brief Returns true if the given expression can be evaluated as a constant
8447/// 'true'.
8448static bool EvaluatesAsTrue(Sema &S, Expr *E) {
8449 bool Res;
8450 return E->EvaluateAsBooleanCondition(Res, S.getASTContext()) && Res;
8451}
8452
Argyrios Kyrtzidis56e879d2010-11-17 19:18:19 +00008453/// \brief Returns true if the given expression can be evaluated as a constant
8454/// 'false'.
8455static bool EvaluatesAsFalse(Sema &S, Expr *E) {
8456 bool Res;
8457 return E->EvaluateAsBooleanCondition(Res, S.getASTContext()) && !Res;
8458}
8459
Argyrios Kyrtzidis14a96622010-11-17 18:26:36 +00008460/// \brief Look for '&&' in the left hand of a '||' expr.
8461static void DiagnoseLogicalAndInLogicalOrLHS(Sema &S, SourceLocation OpLoc,
Richard Trieuf9bd0f52011-09-07 02:02:10 +00008462 Expr *LHSExpr, Expr *RHSExpr) {
8463 if (BinaryOperator *Bop = dyn_cast<BinaryOperator>(LHSExpr)) {
Argyrios Kyrtzidisf89a56c2010-11-16 21:00:12 +00008464 if (Bop->getOpcode() == BO_LAnd) {
Argyrios Kyrtzidis56e879d2010-11-17 19:18:19 +00008465 // If it's "a && b || 0" don't warn since the precedence doesn't matter.
Richard Trieuf9bd0f52011-09-07 02:02:10 +00008466 if (EvaluatesAsFalse(S, RHSExpr))
Argyrios Kyrtzidis56e879d2010-11-17 19:18:19 +00008467 return;
Argyrios Kyrtzidis14a96622010-11-17 18:26:36 +00008468 // If it's "1 && a || b" don't warn since the precedence doesn't matter.
8469 if (!EvaluatesAsTrue(S, Bop->getLHS()))
8470 return EmitDiagnosticForLogicalAndInLogicalOr(S, OpLoc, Bop);
8471 } else if (Bop->getOpcode() == BO_LOr) {
8472 if (BinaryOperator *RBop = dyn_cast<BinaryOperator>(Bop->getRHS())) {
8473 // If it's "a || b && 1 || c" we didn't warn earlier for
8474 // "a || b && 1", but warn now.
8475 if (RBop->getOpcode() == BO_LAnd && EvaluatesAsTrue(S, RBop->getRHS()))
8476 return EmitDiagnosticForLogicalAndInLogicalOr(S, OpLoc, RBop);
8477 }
8478 }
8479 }
8480}
8481
8482/// \brief Look for '&&' in the right hand of a '||' expr.
8483static void DiagnoseLogicalAndInLogicalOrRHS(Sema &S, SourceLocation OpLoc,
Richard Trieuf9bd0f52011-09-07 02:02:10 +00008484 Expr *LHSExpr, Expr *RHSExpr) {
8485 if (BinaryOperator *Bop = dyn_cast<BinaryOperator>(RHSExpr)) {
Argyrios Kyrtzidis14a96622010-11-17 18:26:36 +00008486 if (Bop->getOpcode() == BO_LAnd) {
Argyrios Kyrtzidis56e879d2010-11-17 19:18:19 +00008487 // If it's "0 || a && b" don't warn since the precedence doesn't matter.
Richard Trieuf9bd0f52011-09-07 02:02:10 +00008488 if (EvaluatesAsFalse(S, LHSExpr))
Argyrios Kyrtzidis56e879d2010-11-17 19:18:19 +00008489 return;
Argyrios Kyrtzidis14a96622010-11-17 18:26:36 +00008490 // If it's "a || b && 1" don't warn since the precedence doesn't matter.
8491 if (!EvaluatesAsTrue(S, Bop->getRHS()))
8492 return EmitDiagnosticForLogicalAndInLogicalOr(S, OpLoc, Bop);
Argyrios Kyrtzidisf89a56c2010-11-16 21:00:12 +00008493 }
8494 }
8495}
8496
Argyrios Kyrtzidis01bf7772011-06-20 18:41:26 +00008497/// \brief Look for '&' in the left or right hand of a '|' expr.
8498static void DiagnoseBitwiseAndInBitwiseOr(Sema &S, SourceLocation OpLoc,
8499 Expr *OrArg) {
8500 if (BinaryOperator *Bop = dyn_cast<BinaryOperator>(OrArg)) {
8501 if (Bop->getOpcode() == BO_And)
8502 return EmitDiagnosticForBitwiseAndInBitwiseOr(S, OpLoc, Bop);
8503 }
8504}
8505
Sebastian Redl43028242009-10-26 15:24:15 +00008506/// DiagnoseBinOpPrecedence - Emit warnings for expressions with tricky
Argyrios Kyrtzidisf89a56c2010-11-16 21:00:12 +00008507/// precedence.
John McCalle3027922010-08-25 11:45:40 +00008508static void DiagnoseBinOpPrecedence(Sema &Self, BinaryOperatorKind Opc,
Richard Trieuf9bd0f52011-09-07 02:02:10 +00008509 SourceLocation OpLoc, Expr *LHSExpr,
8510 Expr *RHSExpr){
Argyrios Kyrtzidisf89a56c2010-11-16 21:00:12 +00008511 // Diagnose "arg1 'bitwise' arg2 'eq' arg3".
Sebastian Redl44615072009-10-27 12:10:02 +00008512 if (BinaryOperator::isBitwiseOp(Opc))
Richard Trieuf9bd0f52011-09-07 02:02:10 +00008513 DiagnoseBitwisePrecedence(Self, Opc, OpLoc, LHSExpr, RHSExpr);
Argyrios Kyrtzidis01bf7772011-06-20 18:41:26 +00008514
8515 // Diagnose "arg1 & arg2 | arg3"
8516 if (Opc == BO_Or && !OpLoc.isMacroID()/* Don't warn in macros. */) {
Richard Trieuf9bd0f52011-09-07 02:02:10 +00008517 DiagnoseBitwiseAndInBitwiseOr(Self, OpLoc, LHSExpr);
8518 DiagnoseBitwiseAndInBitwiseOr(Self, OpLoc, RHSExpr);
Argyrios Kyrtzidis01bf7772011-06-20 18:41:26 +00008519 }
Argyrios Kyrtzidisf89a56c2010-11-16 21:00:12 +00008520
Argyrios Kyrtzidis14a96622010-11-17 18:26:36 +00008521 // Warn about arg1 || arg2 && arg3, as GCC 4.3+ does.
8522 // We don't warn for 'assert(a || b && "bad")' since this is safe.
Argyrios Kyrtzidisb94e5a32010-11-17 18:54:22 +00008523 if (Opc == BO_LOr && !OpLoc.isMacroID()/* Don't warn in macros. */) {
Richard Trieuf9bd0f52011-09-07 02:02:10 +00008524 DiagnoseLogicalAndInLogicalOrLHS(Self, OpLoc, LHSExpr, RHSExpr);
8525 DiagnoseLogicalAndInLogicalOrRHS(Self, OpLoc, LHSExpr, RHSExpr);
Argyrios Kyrtzidisf89a56c2010-11-16 21:00:12 +00008526 }
Sebastian Redl43028242009-10-26 15:24:15 +00008527}
8528
Steve Naroff218bc2b2007-05-04 21:54:46 +00008529// Binary Operators. 'Tok' is the token for the operator.
John McCalldadc5752010-08-24 06:29:42 +00008530ExprResult Sema::ActOnBinOp(Scope *S, SourceLocation TokLoc,
John McCalle3027922010-08-25 11:45:40 +00008531 tok::TokenKind Kind,
Richard Trieuf9bd0f52011-09-07 02:02:10 +00008532 Expr *LHSExpr, Expr *RHSExpr) {
John McCalle3027922010-08-25 11:45:40 +00008533 BinaryOperatorKind Opc = ConvertTokenKindToBinaryOpcode(Kind);
Richard Trieuf9bd0f52011-09-07 02:02:10 +00008534 assert((LHSExpr != 0) && "ActOnBinOp(): missing left expression");
8535 assert((RHSExpr != 0) && "ActOnBinOp(): missing right expression");
Steve Naroff218bc2b2007-05-04 21:54:46 +00008536
Sebastian Redl43028242009-10-26 15:24:15 +00008537 // Emit warnings for tricky precedence issues, e.g. "bitfield & 0x4 == 0"
Richard Trieuf9bd0f52011-09-07 02:02:10 +00008538 DiagnoseBinOpPrecedence(*this, Opc, TokLoc, LHSExpr, RHSExpr);
Sebastian Redl43028242009-10-26 15:24:15 +00008539
Richard Trieuf9bd0f52011-09-07 02:02:10 +00008540 return BuildBinOp(S, TokLoc, Opc, LHSExpr, RHSExpr);
Douglas Gregor5287f092009-11-05 00:51:44 +00008541}
8542
John McCall526ab472011-10-25 17:37:35 +00008543/// Build an overloaded binary operator expression in the given scope.
8544static ExprResult BuildOverloadedBinOp(Sema &S, Scope *Sc, SourceLocation OpLoc,
8545 BinaryOperatorKind Opc,
8546 Expr *LHS, Expr *RHS) {
8547 // Find all of the overloaded operators visible from this
8548 // point. We perform both an operator-name lookup from the local
8549 // scope and an argument-dependent lookup based on the types of
8550 // the arguments.
8551 UnresolvedSet<16> Functions;
8552 OverloadedOperatorKind OverOp
8553 = BinaryOperator::getOverloadedOperator(Opc);
8554 if (Sc && OverOp != OO_None)
8555 S.LookupOverloadedOperatorName(OverOp, Sc, LHS->getType(),
8556 RHS->getType(), Functions);
8557
8558 // Build the (potentially-overloaded, potentially-dependent)
8559 // binary operation.
8560 return S.CreateOverloadedBinOp(OpLoc, Opc, Functions, LHS, RHS);
8561}
8562
John McCalldadc5752010-08-24 06:29:42 +00008563ExprResult Sema::BuildBinOp(Scope *S, SourceLocation OpLoc,
John McCalle3027922010-08-25 11:45:40 +00008564 BinaryOperatorKind Opc,
Richard Trieuf9bd0f52011-09-07 02:02:10 +00008565 Expr *LHSExpr, Expr *RHSExpr) {
John McCall9a43e122011-10-28 01:04:34 +00008566 // We want to end up calling one of checkPseudoObjectAssignment
8567 // (if the LHS is a pseudo-object), BuildOverloadedBinOp (if
8568 // both expressions are overloadable or either is type-dependent),
8569 // or CreateBuiltinBinOp (in any other case). We also want to get
8570 // any placeholder types out of the way.
8571
John McCall526ab472011-10-25 17:37:35 +00008572 // Handle pseudo-objects in the LHS.
8573 if (const BuiltinType *pty = LHSExpr->getType()->getAsPlaceholderType()) {
8574 // Assignments with a pseudo-object l-value need special analysis.
8575 if (pty->getKind() == BuiltinType::PseudoObject &&
8576 BinaryOperator::isAssignmentOp(Opc))
8577 return checkPseudoObjectAssignment(S, OpLoc, Opc, LHSExpr, RHSExpr);
8578
8579 // Don't resolve overloads if the other type is overloadable.
8580 if (pty->getKind() == BuiltinType::Overload) {
8581 // We can't actually test that if we still have a placeholder,
8582 // though. Fortunately, none of the exceptions we see in that
John McCall9a43e122011-10-28 01:04:34 +00008583 // code below are valid when the LHS is an overload set. Note
8584 // that an overload set can be dependently-typed, but it never
8585 // instantiates to having an overloadable type.
John McCall526ab472011-10-25 17:37:35 +00008586 ExprResult resolvedRHS = CheckPlaceholderExpr(RHSExpr);
8587 if (resolvedRHS.isInvalid()) return ExprError();
8588 RHSExpr = resolvedRHS.take();
8589
John McCall9a43e122011-10-28 01:04:34 +00008590 if (RHSExpr->isTypeDependent() ||
8591 RHSExpr->getType()->isOverloadableType())
John McCall526ab472011-10-25 17:37:35 +00008592 return BuildOverloadedBinOp(*this, S, OpLoc, Opc, LHSExpr, RHSExpr);
8593 }
8594
8595 ExprResult LHS = CheckPlaceholderExpr(LHSExpr);
8596 if (LHS.isInvalid()) return ExprError();
8597 LHSExpr = LHS.take();
8598 }
8599
8600 // Handle pseudo-objects in the RHS.
8601 if (const BuiltinType *pty = RHSExpr->getType()->getAsPlaceholderType()) {
8602 // An overload in the RHS can potentially be resolved by the type
8603 // being assigned to.
John McCall9a43e122011-10-28 01:04:34 +00008604 if (Opc == BO_Assign && pty->getKind() == BuiltinType::Overload) {
8605 if (LHSExpr->isTypeDependent() || RHSExpr->isTypeDependent())
8606 return BuildOverloadedBinOp(*this, S, OpLoc, Opc, LHSExpr, RHSExpr);
8607
Eli Friedman419b1ff2012-01-17 21:27:43 +00008608 if (LHSExpr->getType()->isOverloadableType())
8609 return BuildOverloadedBinOp(*this, S, OpLoc, Opc, LHSExpr, RHSExpr);
8610
John McCall526ab472011-10-25 17:37:35 +00008611 return CreateBuiltinBinOp(OpLoc, Opc, LHSExpr, RHSExpr);
John McCall9a43e122011-10-28 01:04:34 +00008612 }
John McCall526ab472011-10-25 17:37:35 +00008613
8614 // Don't resolve overloads if the other type is overloadable.
8615 if (pty->getKind() == BuiltinType::Overload &&
8616 LHSExpr->getType()->isOverloadableType())
8617 return BuildOverloadedBinOp(*this, S, OpLoc, Opc, LHSExpr, RHSExpr);
8618
8619 ExprResult resolvedRHS = CheckPlaceholderExpr(RHSExpr);
8620 if (!resolvedRHS.isUsable()) return ExprError();
8621 RHSExpr = resolvedRHS.take();
8622 }
8623
David Blaikiebbafb8a2012-03-11 07:00:24 +00008624 if (getLangOpts().CPlusPlus) {
John McCall9a43e122011-10-28 01:04:34 +00008625 // If either expression is type-dependent, always build an
8626 // overloaded op.
8627 if (LHSExpr->isTypeDependent() || RHSExpr->isTypeDependent())
8628 return BuildOverloadedBinOp(*this, S, OpLoc, Opc, LHSExpr, RHSExpr);
Kovarththanan Rajaratnamba2c6522010-03-13 10:17:05 +00008629
John McCall9a43e122011-10-28 01:04:34 +00008630 // Otherwise, build an overloaded op if either expression has an
8631 // overloadable type.
8632 if (LHSExpr->getType()->isOverloadableType() ||
8633 RHSExpr->getType()->isOverloadableType())
John McCall526ab472011-10-25 17:37:35 +00008634 return BuildOverloadedBinOp(*this, S, OpLoc, Opc, LHSExpr, RHSExpr);
Sebastian Redlb5d49352009-01-19 22:31:54 +00008635 }
Kovarththanan Rajaratnamba2c6522010-03-13 10:17:05 +00008636
Douglas Gregor7d5fc7e2008-11-06 23:29:22 +00008637 // Build a built-in binary operation.
Richard Trieuf9bd0f52011-09-07 02:02:10 +00008638 return CreateBuiltinBinOp(OpLoc, Opc, LHSExpr, RHSExpr);
Steve Naroff218bc2b2007-05-04 21:54:46 +00008639}
8640
John McCalldadc5752010-08-24 06:29:42 +00008641ExprResult Sema::CreateBuiltinUnaryOp(SourceLocation OpLoc,
Argyrios Kyrtzidis7a808c02011-01-05 20:09:36 +00008642 UnaryOperatorKind Opc,
John Wiegley01296292011-04-08 18:41:53 +00008643 Expr *InputExpr) {
8644 ExprResult Input = Owned(InputExpr);
John McCall7decc9e2010-11-18 06:31:45 +00008645 ExprValueKind VK = VK_RValue;
8646 ExprObjectKind OK = OK_Ordinary;
Steve Naroff35d85152007-05-07 00:24:15 +00008647 QualType resultType;
8648 switch (Opc) {
John McCalle3027922010-08-25 11:45:40 +00008649 case UO_PreInc:
8650 case UO_PreDec:
8651 case UO_PostInc:
8652 case UO_PostDec:
John Wiegley01296292011-04-08 18:41:53 +00008653 resultType = CheckIncrementDecrementOperand(*this, Input.get(), VK, OpLoc,
John McCalle3027922010-08-25 11:45:40 +00008654 Opc == UO_PreInc ||
8655 Opc == UO_PostInc,
8656 Opc == UO_PreInc ||
8657 Opc == UO_PreDec);
Steve Naroff35d85152007-05-07 00:24:15 +00008658 break;
John McCalle3027922010-08-25 11:45:40 +00008659 case UO_AddrOf:
John McCall526ab472011-10-25 17:37:35 +00008660 resultType = CheckAddressOfOperand(*this, Input, OpLoc);
Steve Naroff35d85152007-05-07 00:24:15 +00008661 break;
John McCall31996342011-04-07 08:22:57 +00008662 case UO_Deref: {
John Wiegley01296292011-04-08 18:41:53 +00008663 Input = DefaultFunctionArrayLvalueConversion(Input.take());
Eli Friedman34866c72012-08-31 00:14:07 +00008664 if (Input.isInvalid()) return ExprError();
John Wiegley01296292011-04-08 18:41:53 +00008665 resultType = CheckIndirectionOperand(*this, Input.get(), VK, OpLoc);
Steve Naroff35d85152007-05-07 00:24:15 +00008666 break;
John McCall31996342011-04-07 08:22:57 +00008667 }
John McCalle3027922010-08-25 11:45:40 +00008668 case UO_Plus:
8669 case UO_Minus:
John Wiegley01296292011-04-08 18:41:53 +00008670 Input = UsualUnaryConversions(Input.take());
8671 if (Input.isInvalid()) return ExprError();
8672 resultType = Input.get()->getType();
Sebastian Redl8d2ccae2009-02-26 14:39:58 +00008673 if (resultType->isDependentType())
8674 break;
Douglas Gregora3208f92010-06-22 23:41:02 +00008675 if (resultType->isArithmeticType() || // C99 6.5.3.3p1
8676 resultType->isVectorType())
Douglas Gregord08452f2008-11-19 15:42:04 +00008677 break;
David Blaikiebbafb8a2012-03-11 07:00:24 +00008678 else if (getLangOpts().CPlusPlus && // C++ [expr.unary.op]p6-7
Douglas Gregord08452f2008-11-19 15:42:04 +00008679 resultType->isEnumeralType())
8680 break;
David Blaikiebbafb8a2012-03-11 07:00:24 +00008681 else if (getLangOpts().CPlusPlus && // C++ [expr.unary.op]p6
John McCalle3027922010-08-25 11:45:40 +00008682 Opc == UO_Plus &&
Douglas Gregord08452f2008-11-19 15:42:04 +00008683 resultType->isPointerType())
8684 break;
8685
Sebastian Redlc215cfc2009-01-19 00:08:26 +00008686 return ExprError(Diag(OpLoc, diag::err_typecheck_unary_expr)
John Wiegley01296292011-04-08 18:41:53 +00008687 << resultType << Input.get()->getSourceRange());
8688
John McCalle3027922010-08-25 11:45:40 +00008689 case UO_Not: // bitwise complement
John Wiegley01296292011-04-08 18:41:53 +00008690 Input = UsualUnaryConversions(Input.take());
8691 if (Input.isInvalid()) return ExprError();
8692 resultType = Input.get()->getType();
Sebastian Redl8d2ccae2009-02-26 14:39:58 +00008693 if (resultType->isDependentType())
8694 break;
Chris Lattner0d707612008-07-25 23:52:49 +00008695 // C99 6.5.3.3p1. We allow complex int and float as a GCC extension.
8696 if (resultType->isComplexType() || resultType->isComplexIntegerType())
8697 // C99 does not support '~' for complex conjugation.
Chris Lattner29e812b2008-11-20 06:06:08 +00008698 Diag(OpLoc, diag::ext_integer_complement_complex)
John Wiegley01296292011-04-08 18:41:53 +00008699 << resultType << Input.get()->getSourceRange();
John McCall36226622010-10-12 02:09:17 +00008700 else if (resultType->hasIntegerRepresentation())
8701 break;
John McCall526ab472011-10-25 17:37:35 +00008702 else {
Sebastian Redlc215cfc2009-01-19 00:08:26 +00008703 return ExprError(Diag(OpLoc, diag::err_typecheck_unary_expr)
John Wiegley01296292011-04-08 18:41:53 +00008704 << resultType << Input.get()->getSourceRange());
John McCall36226622010-10-12 02:09:17 +00008705 }
Steve Naroff35d85152007-05-07 00:24:15 +00008706 break;
John Wiegley01296292011-04-08 18:41:53 +00008707
John McCalle3027922010-08-25 11:45:40 +00008708 case UO_LNot: // logical negation
Steve Naroff71b59a92007-06-04 22:22:31 +00008709 // Unlike +/-/~, integer promotions aren't done here (C99 6.5.3.3p5).
John Wiegley01296292011-04-08 18:41:53 +00008710 Input = DefaultFunctionArrayLvalueConversion(Input.take());
8711 if (Input.isInvalid()) return ExprError();
8712 resultType = Input.get()->getType();
Anton Korobeynikovf0c267e2011-10-14 23:23:15 +00008713
8714 // Though we still have to promote half FP to float...
8715 if (resultType->isHalfType()) {
8716 Input = ImpCastExprToType(Input.take(), Context.FloatTy, CK_FloatingCast).take();
8717 resultType = Context.FloatTy;
8718 }
8719
Sebastian Redl8d2ccae2009-02-26 14:39:58 +00008720 if (resultType->isDependentType())
8721 break;
Abramo Bagnara7ccce982011-04-07 09:26:19 +00008722 if (resultType->isScalarType()) {
8723 // C99 6.5.3.3p1: ok, fallthrough;
David Blaikiebbafb8a2012-03-11 07:00:24 +00008724 if (Context.getLangOpts().CPlusPlus) {
Abramo Bagnara7ccce982011-04-07 09:26:19 +00008725 // C++03 [expr.unary.op]p8, C++0x [expr.unary.op]p9:
8726 // operand contextually converted to bool.
John Wiegley01296292011-04-08 18:41:53 +00008727 Input = ImpCastExprToType(Input.take(), Context.BoolTy,
8728 ScalarTypeToBooleanCastKind(resultType));
Abramo Bagnara7ccce982011-04-07 09:26:19 +00008729 }
Tanya Lattner3dd33b22012-01-19 01:16:16 +00008730 } else if (resultType->isExtVectorType()) {
Tanya Lattner20248222012-01-16 21:02:28 +00008731 // Vector logical not returns the signed variant of the operand type.
8732 resultType = GetSignedVectorType(resultType);
8733 break;
John McCall36226622010-10-12 02:09:17 +00008734 } else {
Sebastian Redlc215cfc2009-01-19 00:08:26 +00008735 return ExprError(Diag(OpLoc, diag::err_typecheck_unary_expr)
John Wiegley01296292011-04-08 18:41:53 +00008736 << resultType << Input.get()->getSourceRange());
John McCall36226622010-10-12 02:09:17 +00008737 }
Douglas Gregordb8c6fd2010-09-20 17:13:33 +00008738
Chris Lattnerbe31ed82007-06-02 19:11:33 +00008739 // LNot always has type int. C99 6.5.3.3p5.
Sebastian Redlc215cfc2009-01-19 00:08:26 +00008740 // In C++, it's bool. C++ 5.3.1p8
Argyrios Kyrtzidis1bdd6882011-02-18 20:55:15 +00008741 resultType = Context.getLogicalOperationType();
Steve Naroff35d85152007-05-07 00:24:15 +00008742 break;
John McCalle3027922010-08-25 11:45:40 +00008743 case UO_Real:
8744 case UO_Imag:
John McCall4bc41ae2010-11-18 19:01:18 +00008745 resultType = CheckRealImagOperand(*this, Input, OpLoc, Opc == UO_Real);
Richard Smith0b6b8e42012-02-18 20:53:32 +00008746 // _Real maps ordinary l-values into ordinary l-values. _Imag maps ordinary
8747 // complex l-values to ordinary l-values and all other values to r-values.
John Wiegley01296292011-04-08 18:41:53 +00008748 if (Input.isInvalid()) return ExprError();
Richard Smith0b6b8e42012-02-18 20:53:32 +00008749 if (Opc == UO_Real || Input.get()->getType()->isAnyComplexType()) {
8750 if (Input.get()->getValueKind() != VK_RValue &&
8751 Input.get()->getObjectKind() == OK_Ordinary)
8752 VK = Input.get()->getValueKind();
David Blaikiebbafb8a2012-03-11 07:00:24 +00008753 } else if (!getLangOpts().CPlusPlus) {
Richard Smith0b6b8e42012-02-18 20:53:32 +00008754 // In C, a volatile scalar is read by __imag. In C++, it is not.
8755 Input = DefaultLvalueConversion(Input.take());
8756 }
Chris Lattner30b5dd02007-08-24 21:16:53 +00008757 break;
John McCalle3027922010-08-25 11:45:40 +00008758 case UO_Extension:
John Wiegley01296292011-04-08 18:41:53 +00008759 resultType = Input.get()->getType();
8760 VK = Input.get()->getValueKind();
8761 OK = Input.get()->getObjectKind();
Steve Naroff043d45d2007-05-15 02:32:35 +00008762 break;
Steve Naroff35d85152007-05-07 00:24:15 +00008763 }
John Wiegley01296292011-04-08 18:41:53 +00008764 if (resultType.isNull() || Input.isInvalid())
Sebastian Redlc215cfc2009-01-19 00:08:26 +00008765 return ExprError();
Douglas Gregor084d8552009-03-13 23:49:33 +00008766
Kaelyn Uhrain2e7aa5a2011-08-05 23:18:04 +00008767 // Check for array bounds violations in the operand of the UnaryOperator,
8768 // except for the '*' and '&' operators that have to be handled specially
8769 // by CheckArrayAccess (as there are special cases like &array[arraysize]
8770 // that are explicitly defined as valid by the standard).
8771 if (Opc != UO_AddrOf && Opc != UO_Deref)
8772 CheckArrayAccess(Input.get());
8773
John Wiegley01296292011-04-08 18:41:53 +00008774 return Owned(new (Context) UnaryOperator(Input.take(), Opc, resultType,
John McCall7decc9e2010-11-18 06:31:45 +00008775 VK, OK, OpLoc));
Steve Naroff35d85152007-05-07 00:24:15 +00008776}
Chris Lattnereefa10e2007-05-28 06:56:27 +00008777
Douglas Gregor72341032011-12-14 21:23:13 +00008778/// \brief Determine whether the given expression is a qualified member
8779/// access expression, of a form that could be turned into a pointer to member
8780/// with the address-of operator.
8781static bool isQualifiedMemberAccess(Expr *E) {
8782 if (DeclRefExpr *DRE = dyn_cast<DeclRefExpr>(E)) {
8783 if (!DRE->getQualifier())
8784 return false;
8785
8786 ValueDecl *VD = DRE->getDecl();
8787 if (!VD->isCXXClassMember())
8788 return false;
8789
8790 if (isa<FieldDecl>(VD) || isa<IndirectFieldDecl>(VD))
8791 return true;
8792 if (CXXMethodDecl *Method = dyn_cast<CXXMethodDecl>(VD))
8793 return Method->isInstance();
8794
8795 return false;
8796 }
8797
8798 if (UnresolvedLookupExpr *ULE = dyn_cast<UnresolvedLookupExpr>(E)) {
8799 if (!ULE->getQualifier())
8800 return false;
8801
8802 for (UnresolvedLookupExpr::decls_iterator D = ULE->decls_begin(),
8803 DEnd = ULE->decls_end();
8804 D != DEnd; ++D) {
8805 if (CXXMethodDecl *Method = dyn_cast<CXXMethodDecl>(*D)) {
8806 if (Method->isInstance())
8807 return true;
8808 } else {
8809 // Overload set does not contain methods.
8810 break;
8811 }
8812 }
8813
8814 return false;
8815 }
8816
8817 return false;
8818}
8819
John McCalldadc5752010-08-24 06:29:42 +00008820ExprResult Sema::BuildUnaryOp(Scope *S, SourceLocation OpLoc,
Richard Trieuba63ce62011-09-09 01:45:06 +00008821 UnaryOperatorKind Opc, Expr *Input) {
John McCall526ab472011-10-25 17:37:35 +00008822 // First things first: handle placeholders so that the
8823 // overloaded-operator check considers the right type.
8824 if (const BuiltinType *pty = Input->getType()->getAsPlaceholderType()) {
8825 // Increment and decrement of pseudo-object references.
8826 if (pty->getKind() == BuiltinType::PseudoObject &&
8827 UnaryOperator::isIncrementDecrementOp(Opc))
8828 return checkPseudoObjectIncDec(S, OpLoc, Opc, Input);
8829
8830 // extension is always a builtin operator.
8831 if (Opc == UO_Extension)
8832 return CreateBuiltinUnaryOp(OpLoc, Opc, Input);
8833
8834 // & gets special logic for several kinds of placeholder.
8835 // The builtin code knows what to do.
8836 if (Opc == UO_AddrOf &&
8837 (pty->getKind() == BuiltinType::Overload ||
8838 pty->getKind() == BuiltinType::UnknownAny ||
8839 pty->getKind() == BuiltinType::BoundMember))
8840 return CreateBuiltinUnaryOp(OpLoc, Opc, Input);
8841
8842 // Anything else needs to be handled now.
8843 ExprResult Result = CheckPlaceholderExpr(Input);
8844 if (Result.isInvalid()) return ExprError();
8845 Input = Result.take();
8846 }
8847
David Blaikiebbafb8a2012-03-11 07:00:24 +00008848 if (getLangOpts().CPlusPlus && Input->getType()->isOverloadableType() &&
Douglas Gregor72341032011-12-14 21:23:13 +00008849 UnaryOperator::getOverloadedOperator(Opc) != OO_None &&
8850 !(Opc == UO_AddrOf && isQualifiedMemberAccess(Input))) {
Douglas Gregor084d8552009-03-13 23:49:33 +00008851 // Find all of the overloaded operators visible from this
8852 // point. We perform both an operator-name lookup from the local
8853 // scope and an argument-dependent lookup based on the types of
8854 // the arguments.
John McCall4c4c1df2010-01-26 03:27:55 +00008855 UnresolvedSet<16> Functions;
Douglas Gregor084d8552009-03-13 23:49:33 +00008856 OverloadedOperatorKind OverOp = UnaryOperator::getOverloadedOperator(Opc);
John McCall4c4c1df2010-01-26 03:27:55 +00008857 if (S && OverOp != OO_None)
8858 LookupOverloadedOperatorName(OverOp, S, Input->getType(), QualType(),
8859 Functions);
Kovarththanan Rajaratnamba2c6522010-03-13 10:17:05 +00008860
John McCallb268a282010-08-23 23:25:46 +00008861 return CreateOverloadedUnaryOp(OpLoc, Opc, Functions, Input);
Douglas Gregor084d8552009-03-13 23:49:33 +00008862 }
Kovarththanan Rajaratnamba2c6522010-03-13 10:17:05 +00008863
John McCallb268a282010-08-23 23:25:46 +00008864 return CreateBuiltinUnaryOp(OpLoc, Opc, Input);
Douglas Gregor084d8552009-03-13 23:49:33 +00008865}
8866
Douglas Gregor5287f092009-11-05 00:51:44 +00008867// Unary Operators. 'Tok' is the token for the operator.
John McCalldadc5752010-08-24 06:29:42 +00008868ExprResult Sema::ActOnUnaryOp(Scope *S, SourceLocation OpLoc,
John McCall424cec92011-01-19 06:33:43 +00008869 tok::TokenKind Op, Expr *Input) {
John McCallb268a282010-08-23 23:25:46 +00008870 return BuildUnaryOp(S, OpLoc, ConvertTokenKindToUnaryOpcode(Op), Input);
Douglas Gregor5287f092009-11-05 00:51:44 +00008871}
8872
Steve Naroff66356bd2007-09-16 14:56:35 +00008873/// ActOnAddrLabel - Parse the GNU address of label extension: "&&foo".
Chris Lattnerc8e630e2011-02-17 07:39:24 +00008874ExprResult Sema::ActOnAddrLabel(SourceLocation OpLoc, SourceLocation LabLoc,
Chris Lattnercab02a62011-02-17 20:34:02 +00008875 LabelDecl *TheDecl) {
Chris Lattnerc8e630e2011-02-17 07:39:24 +00008876 TheDecl->setUsed();
Chris Lattnereefa10e2007-05-28 06:56:27 +00008877 // Create the AST node. The address of a label always has type 'void*'.
Chris Lattnerc8e630e2011-02-17 07:39:24 +00008878 return Owned(new (Context) AddrLabelExpr(OpLoc, LabLoc, TheDecl,
Sebastian Redl6d4256c2009-03-15 17:47:39 +00008879 Context.getPointerType(Context.VoidTy)));
Chris Lattnereefa10e2007-05-28 06:56:27 +00008880}
8881
John McCall31168b02011-06-15 23:02:42 +00008882/// Given the last statement in a statement-expression, check whether
8883/// the result is a producing expression (like a call to an
8884/// ns_returns_retained function) and, if so, rebuild it to hoist the
8885/// release out of the full-expression. Otherwise, return null.
8886/// Cannot fail.
Richard Trieuba63ce62011-09-09 01:45:06 +00008887static Expr *maybeRebuildARCConsumingStmt(Stmt *Statement) {
John McCall31168b02011-06-15 23:02:42 +00008888 // Should always be wrapped with one of these.
Richard Trieuba63ce62011-09-09 01:45:06 +00008889 ExprWithCleanups *cleanups = dyn_cast<ExprWithCleanups>(Statement);
John McCall31168b02011-06-15 23:02:42 +00008890 if (!cleanups) return 0;
8891
8892 ImplicitCastExpr *cast = dyn_cast<ImplicitCastExpr>(cleanups->getSubExpr());
John McCall2d637d22011-09-10 06:18:15 +00008893 if (!cast || cast->getCastKind() != CK_ARCConsumeObject)
John McCall31168b02011-06-15 23:02:42 +00008894 return 0;
8895
8896 // Splice out the cast. This shouldn't modify any interesting
8897 // features of the statement.
8898 Expr *producer = cast->getSubExpr();
8899 assert(producer->getType() == cast->getType());
8900 assert(producer->getValueKind() == cast->getValueKind());
8901 cleanups->setSubExpr(producer);
8902 return cleanups;
8903}
8904
John McCall3abee492012-04-04 01:27:53 +00008905void Sema::ActOnStartStmtExpr() {
8906 PushExpressionEvaluationContext(ExprEvalContexts.back().Context);
8907}
8908
8909void Sema::ActOnStmtExprError() {
John McCalled7b2782012-04-06 18:20:53 +00008910 // Note that function is also called by TreeTransform when leaving a
8911 // StmtExpr scope without rebuilding anything.
8912
John McCall3abee492012-04-04 01:27:53 +00008913 DiscardCleanupsInEvaluationContext();
8914 PopExpressionEvaluationContext();
8915}
8916
John McCalldadc5752010-08-24 06:29:42 +00008917ExprResult
John McCallb268a282010-08-23 23:25:46 +00008918Sema::ActOnStmtExpr(SourceLocation LPLoc, Stmt *SubStmt,
Sebastian Redl6d4256c2009-03-15 17:47:39 +00008919 SourceLocation RPLoc) { // "({..})"
Chris Lattner366727f2007-07-24 16:58:17 +00008920 assert(SubStmt && isa<CompoundStmt>(SubStmt) && "Invalid action invocation!");
8921 CompoundStmt *Compound = cast<CompoundStmt>(SubStmt);
8922
John McCall3abee492012-04-04 01:27:53 +00008923 if (hasAnyUnrecoverableErrorsInThisFunction())
8924 DiscardCleanupsInEvaluationContext();
8925 assert(!ExprNeedsCleanups && "cleanups within StmtExpr not correctly bound!");
8926 PopExpressionEvaluationContext();
8927
Douglas Gregor6cf3f3c2010-03-10 04:54:39 +00008928 bool isFileScope
8929 = (getCurFunctionOrMethodDecl() == 0) && (getCurBlock() == 0);
Chris Lattnera69b0762009-04-25 19:11:05 +00008930 if (isFileScope)
Sebastian Redl6d4256c2009-03-15 17:47:39 +00008931 return ExprError(Diag(LPLoc, diag::err_stmtexpr_file_scope));
Eli Friedman52cc0162009-01-24 23:09:00 +00008932
Chris Lattner366727f2007-07-24 16:58:17 +00008933 // FIXME: there are a variety of strange constraints to enforce here, for
8934 // example, it is not possible to goto into a stmt expression apparently.
8935 // More semantic analysis is needed.
Mike Stump4e1f26a2009-02-19 03:04:26 +00008936
Chris Lattner366727f2007-07-24 16:58:17 +00008937 // If there are sub stmts in the compound stmt, take the type of the last one
8938 // as the type of the stmtexpr.
8939 QualType Ty = Context.VoidTy;
Fariborz Jahanian56143ae2010-10-25 23:27:26 +00008940 bool StmtExprMayBindToTemp = false;
Chris Lattner944d3062008-07-26 19:51:01 +00008941 if (!Compound->body_empty()) {
8942 Stmt *LastStmt = Compound->body_back();
Fariborz Jahanian56143ae2010-10-25 23:27:26 +00008943 LabelStmt *LastLabelStmt = 0;
Chris Lattner944d3062008-07-26 19:51:01 +00008944 // If LastStmt is a label, skip down through into the body.
Fariborz Jahanian56143ae2010-10-25 23:27:26 +00008945 while (LabelStmt *Label = dyn_cast<LabelStmt>(LastStmt)) {
8946 LastLabelStmt = Label;
Chris Lattner944d3062008-07-26 19:51:01 +00008947 LastStmt = Label->getSubStmt();
Fariborz Jahanian56143ae2010-10-25 23:27:26 +00008948 }
John McCall31168b02011-06-15 23:02:42 +00008949
John Wiegley01296292011-04-08 18:41:53 +00008950 if (Expr *LastE = dyn_cast<Expr>(LastStmt)) {
John McCall34376a62010-12-04 03:47:34 +00008951 // Do function/array conversion on the last expression, but not
8952 // lvalue-to-rvalue. However, initialize an unqualified type.
John Wiegley01296292011-04-08 18:41:53 +00008953 ExprResult LastExpr = DefaultFunctionArrayConversion(LastE);
8954 if (LastExpr.isInvalid())
8955 return ExprError();
8956 Ty = LastExpr.get()->getType().getUnqualifiedType();
John McCall34376a62010-12-04 03:47:34 +00008957
John Wiegley01296292011-04-08 18:41:53 +00008958 if (!Ty->isDependentType() && !LastExpr.get()->isTypeDependent()) {
John McCall31168b02011-06-15 23:02:42 +00008959 // In ARC, if the final expression ends in a consume, splice
8960 // the consume out and bind it later. In the alternate case
8961 // (when dealing with a retainable type), the result
8962 // initialization will create a produce. In both cases the
8963 // result will be +1, and we'll need to balance that out with
8964 // a bind.
8965 if (Expr *rebuiltLastStmt
8966 = maybeRebuildARCConsumingStmt(LastExpr.get())) {
8967 LastExpr = rebuiltLastStmt;
8968 } else {
8969 LastExpr = PerformCopyInitialization(
Fariborz Jahanian56143ae2010-10-25 23:27:26 +00008970 InitializedEntity::InitializeResult(LPLoc,
8971 Ty,
8972 false),
8973 SourceLocation(),
John McCall31168b02011-06-15 23:02:42 +00008974 LastExpr);
8975 }
8976
John Wiegley01296292011-04-08 18:41:53 +00008977 if (LastExpr.isInvalid())
Fariborz Jahanian56143ae2010-10-25 23:27:26 +00008978 return ExprError();
John Wiegley01296292011-04-08 18:41:53 +00008979 if (LastExpr.get() != 0) {
Fariborz Jahanian56143ae2010-10-25 23:27:26 +00008980 if (!LastLabelStmt)
John Wiegley01296292011-04-08 18:41:53 +00008981 Compound->setLastStmt(LastExpr.take());
Fariborz Jahanian56143ae2010-10-25 23:27:26 +00008982 else
John Wiegley01296292011-04-08 18:41:53 +00008983 LastLabelStmt->setSubStmt(LastExpr.take());
Fariborz Jahanian56143ae2010-10-25 23:27:26 +00008984 StmtExprMayBindToTemp = true;
8985 }
8986 }
8987 }
Chris Lattner944d3062008-07-26 19:51:01 +00008988 }
Mike Stump4e1f26a2009-02-19 03:04:26 +00008989
Eli Friedmanba961a92009-03-23 00:24:07 +00008990 // FIXME: Check that expression type is complete/non-abstract; statement
8991 // expressions are not lvalues.
Fariborz Jahanian56143ae2010-10-25 23:27:26 +00008992 Expr *ResStmtExpr = new (Context) StmtExpr(Compound, Ty, LPLoc, RPLoc);
8993 if (StmtExprMayBindToTemp)
8994 return MaybeBindToTemporary(ResStmtExpr);
8995 return Owned(ResStmtExpr);
Chris Lattner366727f2007-07-24 16:58:17 +00008996}
Steve Naroff78864672007-08-01 22:05:33 +00008997
John McCalldadc5752010-08-24 06:29:42 +00008998ExprResult Sema::BuildBuiltinOffsetOf(SourceLocation BuiltinLoc,
John McCall36226622010-10-12 02:09:17 +00008999 TypeSourceInfo *TInfo,
9000 OffsetOfComponent *CompPtr,
9001 unsigned NumComponents,
9002 SourceLocation RParenLoc) {
Douglas Gregor882211c2010-04-28 22:16:22 +00009003 QualType ArgTy = TInfo->getType();
Sebastian Redl8d2ccae2009-02-26 14:39:58 +00009004 bool Dependent = ArgTy->isDependentType();
Abramo Bagnara1108e7b2010-05-20 10:00:11 +00009005 SourceRange TypeRange = TInfo->getTypeLoc().getLocalSourceRange();
Douglas Gregor882211c2010-04-28 22:16:22 +00009006
Chris Lattnerf17bd422007-08-30 17:45:32 +00009007 // We must have at least one component that refers to the type, and the first
9008 // one is known to be a field designator. Verify that the ArgTy represents
9009 // a struct/union/class.
Sebastian Redl8d2ccae2009-02-26 14:39:58 +00009010 if (!Dependent && !ArgTy->isRecordType())
Douglas Gregor882211c2010-04-28 22:16:22 +00009011 return ExprError(Diag(BuiltinLoc, diag::err_offsetof_record_type)
9012 << ArgTy << TypeRange);
9013
9014 // Type must be complete per C99 7.17p3 because a declaring a variable
9015 // with an incomplete type would be ill-formed.
9016 if (!Dependent
9017 && RequireCompleteType(BuiltinLoc, ArgTy,
Douglas Gregor7bfb2d02012-05-04 16:32:21 +00009018 diag::err_offsetof_incomplete_type, TypeRange))
Douglas Gregor882211c2010-04-28 22:16:22 +00009019 return ExprError();
9020
Chris Lattner78502cf2007-08-31 21:49:13 +00009021 // offsetof with non-identifier designators (e.g. "offsetof(x, a.b[c])") are a
9022 // GCC extension, diagnose them.
Eli Friedman988a16b2009-02-27 06:44:11 +00009023 // FIXME: This diagnostic isn't actually visible because the location is in
9024 // a system header!
Chris Lattner78502cf2007-08-31 21:49:13 +00009025 if (NumComponents != 1)
Chris Lattnerf490e152008-11-19 05:27:50 +00009026 Diag(BuiltinLoc, diag::ext_offsetof_extended_field_designator)
9027 << SourceRange(CompPtr[1].LocStart, CompPtr[NumComponents-1].LocEnd);
Douglas Gregor882211c2010-04-28 22:16:22 +00009028
9029 bool DidWarnAboutNonPOD = false;
9030 QualType CurrentType = ArgTy;
9031 typedef OffsetOfExpr::OffsetOfNode OffsetOfNode;
Chris Lattner0e62c1c2011-07-23 10:55:15 +00009032 SmallVector<OffsetOfNode, 4> Comps;
9033 SmallVector<Expr*, 4> Exprs;
Douglas Gregor882211c2010-04-28 22:16:22 +00009034 for (unsigned i = 0; i != NumComponents; ++i) {
9035 const OffsetOfComponent &OC = CompPtr[i];
9036 if (OC.isBrackets) {
9037 // Offset of an array sub-field. TODO: Should we allow vector elements?
9038 if (!CurrentType->isDependentType()) {
9039 const ArrayType *AT = Context.getAsArrayType(CurrentType);
9040 if(!AT)
9041 return ExprError(Diag(OC.LocEnd, diag::err_offsetof_array_type)
9042 << CurrentType);
9043 CurrentType = AT->getElementType();
9044 } else
9045 CurrentType = Context.DependentTy;
9046
Richard Smith9fcc5c32011-10-17 23:29:39 +00009047 ExprResult IdxRval = DefaultLvalueConversion(static_cast<Expr*>(OC.U.E));
9048 if (IdxRval.isInvalid())
9049 return ExprError();
9050 Expr *Idx = IdxRval.take();
9051
Douglas Gregor882211c2010-04-28 22:16:22 +00009052 // The expression must be an integral expression.
9053 // FIXME: An integral constant expression?
Douglas Gregor882211c2010-04-28 22:16:22 +00009054 if (!Idx->isTypeDependent() && !Idx->isValueDependent() &&
9055 !Idx->getType()->isIntegerType())
9056 return ExprError(Diag(Idx->getLocStart(),
9057 diag::err_typecheck_subscript_not_integer)
9058 << Idx->getSourceRange());
Richard Smitheda612882011-10-17 05:48:07 +00009059
Douglas Gregor882211c2010-04-28 22:16:22 +00009060 // Record this array index.
9061 Comps.push_back(OffsetOfNode(OC.LocStart, Exprs.size(), OC.LocEnd));
Richard Smith9fcc5c32011-10-17 23:29:39 +00009062 Exprs.push_back(Idx);
Douglas Gregor882211c2010-04-28 22:16:22 +00009063 continue;
9064 }
9065
9066 // Offset of a field.
9067 if (CurrentType->isDependentType()) {
9068 // We have the offset of a field, but we can't look into the dependent
9069 // type. Just record the identifier of the field.
9070 Comps.push_back(OffsetOfNode(OC.LocStart, OC.U.IdentInfo, OC.LocEnd));
9071 CurrentType = Context.DependentTy;
9072 continue;
9073 }
9074
9075 // We need to have a complete type to look into.
9076 if (RequireCompleteType(OC.LocStart, CurrentType,
9077 diag::err_offsetof_incomplete_type))
9078 return ExprError();
9079
9080 // Look for the designated field.
9081 const RecordType *RC = CurrentType->getAs<RecordType>();
9082 if (!RC)
9083 return ExprError(Diag(OC.LocEnd, diag::err_offsetof_record_type)
9084 << CurrentType);
9085 RecordDecl *RD = RC->getDecl();
9086
9087 // C++ [lib.support.types]p5:
9088 // The macro offsetof accepts a restricted set of type arguments in this
9089 // International Standard. type shall be a POD structure or a POD union
9090 // (clause 9).
Benjamin Kramer9e7876b2012-04-28 11:14:51 +00009091 // C++11 [support.types]p4:
9092 // If type is not a standard-layout class (Clause 9), the results are
9093 // undefined.
Douglas Gregor882211c2010-04-28 22:16:22 +00009094 if (CXXRecordDecl *CRD = dyn_cast<CXXRecordDecl>(RD)) {
Benjamin Kramer9e7876b2012-04-28 11:14:51 +00009095 bool IsSafe = LangOpts.CPlusPlus0x? CRD->isStandardLayout() : CRD->isPOD();
9096 unsigned DiagID =
9097 LangOpts.CPlusPlus0x? diag::warn_offsetof_non_standardlayout_type
9098 : diag::warn_offsetof_non_pod_type;
9099
9100 if (!IsSafe && !DidWarnAboutNonPOD &&
Ted Kremenek55ae3192011-02-23 01:51:43 +00009101 DiagRuntimeBehavior(BuiltinLoc, 0,
Benjamin Kramer9e7876b2012-04-28 11:14:51 +00009102 PDiag(DiagID)
Douglas Gregor882211c2010-04-28 22:16:22 +00009103 << SourceRange(CompPtr[0].LocStart, OC.LocEnd)
9104 << CurrentType))
9105 DidWarnAboutNonPOD = true;
9106 }
9107
9108 // Look for the field.
9109 LookupResult R(*this, OC.U.IdentInfo, OC.LocStart, LookupMemberName);
9110 LookupQualifiedName(R, RD);
9111 FieldDecl *MemberDecl = R.getAsSingle<FieldDecl>();
Francois Pichet783dd6e2010-11-21 06:08:52 +00009112 IndirectFieldDecl *IndirectMemberDecl = 0;
9113 if (!MemberDecl) {
Benjamin Kramer39593702010-11-21 14:11:41 +00009114 if ((IndirectMemberDecl = R.getAsSingle<IndirectFieldDecl>()))
Francois Pichet783dd6e2010-11-21 06:08:52 +00009115 MemberDecl = IndirectMemberDecl->getAnonField();
9116 }
9117
Douglas Gregor882211c2010-04-28 22:16:22 +00009118 if (!MemberDecl)
9119 return ExprError(Diag(BuiltinLoc, diag::err_no_member)
9120 << OC.U.IdentInfo << RD << SourceRange(OC.LocStart,
9121 OC.LocEnd));
9122
Douglas Gregor10982ea2010-04-28 22:36:06 +00009123 // C99 7.17p3:
9124 // (If the specified member is a bit-field, the behavior is undefined.)
9125 //
9126 // We diagnose this as an error.
Richard Smithcaf33902011-10-10 18:28:20 +00009127 if (MemberDecl->isBitField()) {
Douglas Gregor10982ea2010-04-28 22:36:06 +00009128 Diag(OC.LocEnd, diag::err_offsetof_bitfield)
9129 << MemberDecl->getDeclName()
9130 << SourceRange(BuiltinLoc, RParenLoc);
9131 Diag(MemberDecl->getLocation(), diag::note_bitfield_decl);
9132 return ExprError();
9133 }
Eli Friedman74ef7cf2010-08-05 10:11:36 +00009134
9135 RecordDecl *Parent = MemberDecl->getParent();
Francois Pichet783dd6e2010-11-21 06:08:52 +00009136 if (IndirectMemberDecl)
9137 Parent = cast<RecordDecl>(IndirectMemberDecl->getDeclContext());
Eli Friedman74ef7cf2010-08-05 10:11:36 +00009138
Douglas Gregord1702062010-04-29 00:18:15 +00009139 // If the member was found in a base class, introduce OffsetOfNodes for
9140 // the base class indirections.
9141 CXXBasePaths Paths(/*FindAmbiguities=*/true, /*RecordPaths=*/true,
9142 /*DetectVirtual=*/false);
Eli Friedman74ef7cf2010-08-05 10:11:36 +00009143 if (IsDerivedFrom(CurrentType, Context.getTypeDeclType(Parent), Paths)) {
Douglas Gregord1702062010-04-29 00:18:15 +00009144 CXXBasePath &Path = Paths.front();
9145 for (CXXBasePath::iterator B = Path.begin(), BEnd = Path.end();
9146 B != BEnd; ++B)
9147 Comps.push_back(OffsetOfNode(B->Base));
9148 }
Eli Friedman74ef7cf2010-08-05 10:11:36 +00009149
Francois Pichet783dd6e2010-11-21 06:08:52 +00009150 if (IndirectMemberDecl) {
9151 for (IndirectFieldDecl::chain_iterator FI =
9152 IndirectMemberDecl->chain_begin(),
9153 FEnd = IndirectMemberDecl->chain_end(); FI != FEnd; FI++) {
9154 assert(isa<FieldDecl>(*FI));
9155 Comps.push_back(OffsetOfNode(OC.LocStart,
9156 cast<FieldDecl>(*FI), OC.LocEnd));
9157 }
9158 } else
Douglas Gregor882211c2010-04-28 22:16:22 +00009159 Comps.push_back(OffsetOfNode(OC.LocStart, MemberDecl, OC.LocEnd));
Francois Pichet783dd6e2010-11-21 06:08:52 +00009160
Douglas Gregor882211c2010-04-28 22:16:22 +00009161 CurrentType = MemberDecl->getType().getNonReferenceType();
9162 }
9163
9164 return Owned(OffsetOfExpr::Create(Context, Context.getSizeType(), BuiltinLoc,
Benjamin Kramerc215e762012-08-24 11:54:20 +00009165 TInfo, Comps, Exprs, RParenLoc));
Douglas Gregor882211c2010-04-28 22:16:22 +00009166}
Mike Stump4e1f26a2009-02-19 03:04:26 +00009167
John McCalldadc5752010-08-24 06:29:42 +00009168ExprResult Sema::ActOnBuiltinOffsetOf(Scope *S,
John McCall36226622010-10-12 02:09:17 +00009169 SourceLocation BuiltinLoc,
9170 SourceLocation TypeLoc,
Richard Trieuba63ce62011-09-09 01:45:06 +00009171 ParsedType ParsedArgTy,
John McCall36226622010-10-12 02:09:17 +00009172 OffsetOfComponent *CompPtr,
9173 unsigned NumComponents,
Richard Trieuba63ce62011-09-09 01:45:06 +00009174 SourceLocation RParenLoc) {
John McCall36226622010-10-12 02:09:17 +00009175
Douglas Gregor882211c2010-04-28 22:16:22 +00009176 TypeSourceInfo *ArgTInfo;
Richard Trieuba63ce62011-09-09 01:45:06 +00009177 QualType ArgTy = GetTypeFromParser(ParsedArgTy, &ArgTInfo);
Douglas Gregor882211c2010-04-28 22:16:22 +00009178 if (ArgTy.isNull())
9179 return ExprError();
9180
Eli Friedman06dcfd92010-08-05 10:15:45 +00009181 if (!ArgTInfo)
9182 ArgTInfo = Context.getTrivialTypeSourceInfo(ArgTy, TypeLoc);
9183
9184 return BuildBuiltinOffsetOf(BuiltinLoc, ArgTInfo, CompPtr, NumComponents,
Richard Trieuba63ce62011-09-09 01:45:06 +00009185 RParenLoc);
Chris Lattnerf17bd422007-08-30 17:45:32 +00009186}
9187
9188
John McCalldadc5752010-08-24 06:29:42 +00009189ExprResult Sema::ActOnChooseExpr(SourceLocation BuiltinLoc,
John McCall36226622010-10-12 02:09:17 +00009190 Expr *CondExpr,
9191 Expr *LHSExpr, Expr *RHSExpr,
9192 SourceLocation RPLoc) {
Steve Naroff9efdabc2007-08-03 21:21:27 +00009193 assert((CondExpr && LHSExpr && RHSExpr) && "Missing type argument(s)");
9194
John McCall7decc9e2010-11-18 06:31:45 +00009195 ExprValueKind VK = VK_RValue;
9196 ExprObjectKind OK = OK_Ordinary;
Sebastian Redl8d2ccae2009-02-26 14:39:58 +00009197 QualType resType;
Douglas Gregor56751b52009-09-25 04:25:58 +00009198 bool ValueDependent = false;
Douglas Gregor0df91122009-05-19 22:43:30 +00009199 if (CondExpr->isTypeDependent() || CondExpr->isValueDependent()) {
Sebastian Redl8d2ccae2009-02-26 14:39:58 +00009200 resType = Context.DependentTy;
Douglas Gregor56751b52009-09-25 04:25:58 +00009201 ValueDependent = true;
Sebastian Redl8d2ccae2009-02-26 14:39:58 +00009202 } else {
9203 // The conditional expression is required to be a constant expression.
9204 llvm::APSInt condEval(32);
Douglas Gregore2b37442012-05-04 22:38:52 +00009205 ExprResult CondICE
9206 = VerifyIntegerConstantExpression(CondExpr, &condEval,
9207 diag::err_typecheck_choose_expr_requires_constant, false);
Richard Smithf4c51d92012-02-04 09:53:13 +00009208 if (CondICE.isInvalid())
9209 return ExprError();
9210 CondExpr = CondICE.take();
Steve Naroff9efdabc2007-08-03 21:21:27 +00009211
Sebastian Redl8d2ccae2009-02-26 14:39:58 +00009212 // If the condition is > zero, then the AST type is the same as the LSHExpr.
John McCall7decc9e2010-11-18 06:31:45 +00009213 Expr *ActiveExpr = condEval.getZExtValue() ? LHSExpr : RHSExpr;
9214
9215 resType = ActiveExpr->getType();
9216 ValueDependent = ActiveExpr->isValueDependent();
9217 VK = ActiveExpr->getValueKind();
9218 OK = ActiveExpr->getObjectKind();
Sebastian Redl8d2ccae2009-02-26 14:39:58 +00009219 }
9220
Sebastian Redl6d4256c2009-03-15 17:47:39 +00009221 return Owned(new (Context) ChooseExpr(BuiltinLoc, CondExpr, LHSExpr, RHSExpr,
John McCall7decc9e2010-11-18 06:31:45 +00009222 resType, VK, OK, RPLoc,
Douglas Gregor56751b52009-09-25 04:25:58 +00009223 resType->isDependentType(),
9224 ValueDependent));
Steve Naroff9efdabc2007-08-03 21:21:27 +00009225}
9226
Steve Naroffc540d662008-09-03 18:15:37 +00009227//===----------------------------------------------------------------------===//
9228// Clang Extensions.
9229//===----------------------------------------------------------------------===//
9230
9231/// ActOnBlockStart - This callback is invoked when a block literal is started.
Richard Trieuba63ce62011-09-09 01:45:06 +00009232void Sema::ActOnBlockStart(SourceLocation CaretLoc, Scope *CurScope) {
Douglas Gregor9a28e842010-03-01 23:15:13 +00009233 BlockDecl *Block = BlockDecl::Create(Context, CurContext, CaretLoc);
Richard Trieuba63ce62011-09-09 01:45:06 +00009234 PushBlockScope(CurScope, Block);
Douglas Gregor9a28e842010-03-01 23:15:13 +00009235 CurContext->addDecl(Block);
Richard Trieuba63ce62011-09-09 01:45:06 +00009236 if (CurScope)
9237 PushDeclContext(CurScope, Block);
Fariborz Jahanian1babe772010-07-09 18:44:02 +00009238 else
9239 CurContext = Block;
John McCallf1a3c2a2011-11-11 03:19:12 +00009240
Eli Friedman34b49062012-01-26 03:00:14 +00009241 getCurBlock()->HasImplicitReturnType = true;
9242
John McCallf1a3c2a2011-11-11 03:19:12 +00009243 // Enter a new evaluation context to insulate the block from any
9244 // cleanups from the enclosing full-expression.
9245 PushExpressionEvaluationContext(PotentiallyEvaluated);
Steve Naroff1d95e5a2008-10-10 01:28:17 +00009246}
9247
Douglas Gregor7efd007c2012-06-15 16:59:29 +00009248void Sema::ActOnBlockArguments(SourceLocation CaretLoc, Declarator &ParamInfo,
9249 Scope *CurScope) {
Mike Stumpf70bcf72009-05-07 18:43:07 +00009250 assert(ParamInfo.getIdentifier()==0 && "block-id should have no identifier!");
John McCall3882ace2011-01-05 12:14:39 +00009251 assert(ParamInfo.getContext() == Declarator::BlockLiteralContext);
Douglas Gregor9a28e842010-03-01 23:15:13 +00009252 BlockScopeInfo *CurBlock = getCurBlock();
Kovarththanan Rajaratnamba2c6522010-03-13 10:17:05 +00009253
John McCall8cb7bdf2010-06-04 23:28:52 +00009254 TypeSourceInfo *Sig = GetTypeForDeclarator(ParamInfo, CurScope);
John McCall8cb7bdf2010-06-04 23:28:52 +00009255 QualType T = Sig->getType();
Mike Stump82f071f2009-02-04 22:31:32 +00009256
Douglas Gregor7efd007c2012-06-15 16:59:29 +00009257 // FIXME: We should allow unexpanded parameter packs here, but that would,
9258 // in turn, make the block expression contain unexpanded parameter packs.
9259 if (DiagnoseUnexpandedParameterPack(CaretLoc, Sig, UPPC_Block)) {
9260 // Drop the parameters.
9261 FunctionProtoType::ExtProtoInfo EPI;
9262 EPI.HasTrailingReturn = false;
9263 EPI.TypeQuals |= DeclSpec::TQ_const;
9264 T = Context.getFunctionType(Context.DependentTy, /*Args=*/0, /*NumArgs=*/0,
9265 EPI);
9266 Sig = Context.getTrivialTypeSourceInfo(T);
9267 }
9268
John McCall3882ace2011-01-05 12:14:39 +00009269 // GetTypeForDeclarator always produces a function type for a block
9270 // literal signature. Furthermore, it is always a FunctionProtoType
9271 // unless the function was written with a typedef.
9272 assert(T->isFunctionType() &&
9273 "GetTypeForDeclarator made a non-function block signature");
9274
9275 // Look for an explicit signature in that function type.
9276 FunctionProtoTypeLoc ExplicitSignature;
9277
9278 TypeLoc tmp = Sig->getTypeLoc().IgnoreParens();
9279 if (isa<FunctionProtoTypeLoc>(tmp)) {
9280 ExplicitSignature = cast<FunctionProtoTypeLoc>(tmp);
9281
9282 // Check whether that explicit signature was synthesized by
9283 // GetTypeForDeclarator. If so, don't save that as part of the
9284 // written signature.
Abramo Bagnaraf2a79d92011-03-12 11:17:06 +00009285 if (ExplicitSignature.getLocalRangeBegin() ==
9286 ExplicitSignature.getLocalRangeEnd()) {
John McCall3882ace2011-01-05 12:14:39 +00009287 // This would be much cheaper if we stored TypeLocs instead of
9288 // TypeSourceInfos.
9289 TypeLoc Result = ExplicitSignature.getResultLoc();
9290 unsigned Size = Result.getFullDataSize();
9291 Sig = Context.CreateTypeSourceInfo(Result.getType(), Size);
9292 Sig->getTypeLoc().initializeFullCopy(Result, Size);
9293
9294 ExplicitSignature = FunctionProtoTypeLoc();
9295 }
John McCalla3ccba02010-06-04 11:21:44 +00009296 }
Mike Stump11289f42009-09-09 15:08:12 +00009297
John McCall3882ace2011-01-05 12:14:39 +00009298 CurBlock->TheDecl->setSignatureAsWritten(Sig);
9299 CurBlock->FunctionType = T;
9300
9301 const FunctionType *Fn = T->getAs<FunctionType>();
9302 QualType RetTy = Fn->getResultType();
9303 bool isVariadic =
9304 (isa<FunctionProtoType>(Fn) && cast<FunctionProtoType>(Fn)->isVariadic());
9305
John McCall8e346702010-06-04 19:02:56 +00009306 CurBlock->TheDecl->setIsVariadic(isVariadic);
Douglas Gregorb92a1562010-02-03 00:27:59 +00009307
John McCalla3ccba02010-06-04 11:21:44 +00009308 // Don't allow returning a objc interface by value.
9309 if (RetTy->isObjCObjectType()) {
Daniel Dunbar62ee6412012-03-09 18:35:03 +00009310 Diag(ParamInfo.getLocStart(),
John McCalla3ccba02010-06-04 11:21:44 +00009311 diag::err_object_cannot_be_passed_returned_by_value) << 0 << RetTy;
9312 return;
9313 }
Mike Stump4e1f26a2009-02-19 03:04:26 +00009314
John McCalla3ccba02010-06-04 11:21:44 +00009315 // Context.DependentTy is used as a placeholder for a missing block
John McCall8e346702010-06-04 19:02:56 +00009316 // return type. TODO: what should we do with declarators like:
9317 // ^ * { ... }
9318 // If the answer is "apply template argument deduction"....
Fariborz Jahaniandd5eb9d2011-12-03 17:47:53 +00009319 if (RetTy != Context.DependentTy) {
John McCalla3ccba02010-06-04 11:21:44 +00009320 CurBlock->ReturnType = RetTy;
Fariborz Jahaniandd5eb9d2011-12-03 17:47:53 +00009321 CurBlock->TheDecl->setBlockMissingReturnType(false);
Eli Friedman34b49062012-01-26 03:00:14 +00009322 CurBlock->HasImplicitReturnType = false;
Fariborz Jahaniandd5eb9d2011-12-03 17:47:53 +00009323 }
Mike Stump4e1f26a2009-02-19 03:04:26 +00009324
John McCalla3ccba02010-06-04 11:21:44 +00009325 // Push block parameters from the declarator if we had them.
Chris Lattner0e62c1c2011-07-23 10:55:15 +00009326 SmallVector<ParmVarDecl*, 8> Params;
John McCall3882ace2011-01-05 12:14:39 +00009327 if (ExplicitSignature) {
9328 for (unsigned I = 0, E = ExplicitSignature.getNumArgs(); I != E; ++I) {
9329 ParmVarDecl *Param = ExplicitSignature.getArg(I);
Fariborz Jahanian5ec502e2010-02-12 21:53:14 +00009330 if (Param->getIdentifier() == 0 &&
9331 !Param->isImplicit() &&
9332 !Param->isInvalidDecl() &&
David Blaikiebbafb8a2012-03-11 07:00:24 +00009333 !getLangOpts().CPlusPlus)
Fariborz Jahanian5ec502e2010-02-12 21:53:14 +00009334 Diag(Param->getLocation(), diag::err_parameter_name_omitted);
John McCall8e346702010-06-04 19:02:56 +00009335 Params.push_back(Param);
Fariborz Jahanian5ec502e2010-02-12 21:53:14 +00009336 }
John McCalla3ccba02010-06-04 11:21:44 +00009337
9338 // Fake up parameter variables if we have a typedef, like
9339 // ^ fntype { ... }
9340 } else if (const FunctionProtoType *Fn = T->getAs<FunctionProtoType>()) {
9341 for (FunctionProtoType::arg_type_iterator
9342 I = Fn->arg_type_begin(), E = Fn->arg_type_end(); I != E; ++I) {
9343 ParmVarDecl *Param =
9344 BuildParmVarDeclForTypedef(CurBlock->TheDecl,
Daniel Dunbar62ee6412012-03-09 18:35:03 +00009345 ParamInfo.getLocStart(),
John McCalla3ccba02010-06-04 11:21:44 +00009346 *I);
John McCall8e346702010-06-04 19:02:56 +00009347 Params.push_back(Param);
John McCalla3ccba02010-06-04 11:21:44 +00009348 }
Steve Naroffc540d662008-09-03 18:15:37 +00009349 }
John McCalla3ccba02010-06-04 11:21:44 +00009350
John McCall8e346702010-06-04 19:02:56 +00009351 // Set the parameters on the block decl.
Douglas Gregorb524d902010-11-01 18:37:59 +00009352 if (!Params.empty()) {
David Blaikie9c70e042011-09-21 18:16:56 +00009353 CurBlock->TheDecl->setParams(Params);
Douglas Gregorb524d902010-11-01 18:37:59 +00009354 CheckParmsForFunctionDef(CurBlock->TheDecl->param_begin(),
9355 CurBlock->TheDecl->param_end(),
9356 /*CheckParameterNames=*/false);
9357 }
9358
John McCalla3ccba02010-06-04 11:21:44 +00009359 // Finally we can process decl attributes.
Douglas Gregor758a8692009-06-17 21:51:59 +00009360 ProcessDeclAttributes(CurScope, CurBlock->TheDecl, ParamInfo);
John McCalldf8b37c2010-03-22 09:20:08 +00009361
John McCalla3ccba02010-06-04 11:21:44 +00009362 // Put the parameter variables in scope. We can bail out immediately
9363 // if we don't have any.
John McCall8e346702010-06-04 19:02:56 +00009364 if (Params.empty())
John McCalla3ccba02010-06-04 11:21:44 +00009365 return;
9366
Steve Naroff1d95e5a2008-10-10 01:28:17 +00009367 for (BlockDecl::param_iterator AI = CurBlock->TheDecl->param_begin(),
John McCallf7b2fb52010-01-22 00:28:27 +00009368 E = CurBlock->TheDecl->param_end(); AI != E; ++AI) {
9369 (*AI)->setOwningFunction(CurBlock->TheDecl);
9370
Steve Naroff1d95e5a2008-10-10 01:28:17 +00009371 // If this has an identifier, add it to the scope stack.
John McCalldf8b37c2010-03-22 09:20:08 +00009372 if ((*AI)->getIdentifier()) {
Argyrios Kyrtzidis1cb0de12010-12-15 18:44:22 +00009373 CheckShadow(CurBlock->TheScope, *AI);
John McCalldf8b37c2010-03-22 09:20:08 +00009374
Steve Naroff1d95e5a2008-10-10 01:28:17 +00009375 PushOnScopeChains(*AI, CurBlock->TheScope);
John McCalldf8b37c2010-03-22 09:20:08 +00009376 }
John McCallf7b2fb52010-01-22 00:28:27 +00009377 }
Steve Naroffc540d662008-09-03 18:15:37 +00009378}
9379
9380/// ActOnBlockError - If there is an error parsing a block, this callback
9381/// is invoked to pop the information about the block from the action impl.
9382void Sema::ActOnBlockError(SourceLocation CaretLoc, Scope *CurScope) {
John McCallf1a3c2a2011-11-11 03:19:12 +00009383 // Leave the expression-evaluation context.
9384 DiscardCleanupsInEvaluationContext();
9385 PopExpressionEvaluationContext();
9386
Steve Naroffc540d662008-09-03 18:15:37 +00009387 // Pop off CurBlock, handle nested blocks.
Chris Lattner41b86942009-04-21 22:38:46 +00009388 PopDeclContext();
Eli Friedman71c80552012-01-05 03:35:19 +00009389 PopFunctionScopeInfo();
Steve Naroffc540d662008-09-03 18:15:37 +00009390}
9391
9392/// ActOnBlockStmtExpr - This is called when the body of a block statement
9393/// literal was successfully completed. ^(int x){...}
John McCalldadc5752010-08-24 06:29:42 +00009394ExprResult Sema::ActOnBlockStmtExpr(SourceLocation CaretLoc,
Chris Lattner60f84492011-02-17 23:58:47 +00009395 Stmt *Body, Scope *CurScope) {
Chris Lattner9eac9312009-03-27 04:18:06 +00009396 // If blocks are disabled, emit an error.
9397 if (!LangOpts.Blocks)
9398 Diag(CaretLoc, diag::err_blocks_disable);
Mike Stump11289f42009-09-09 15:08:12 +00009399
John McCallf1a3c2a2011-11-11 03:19:12 +00009400 // Leave the expression-evaluation context.
John McCall85110b42012-03-08 22:00:17 +00009401 if (hasAnyUnrecoverableErrorsInThisFunction())
9402 DiscardCleanupsInEvaluationContext();
John McCallf1a3c2a2011-11-11 03:19:12 +00009403 assert(!ExprNeedsCleanups && "cleanups within block not correctly bound!");
9404 PopExpressionEvaluationContext();
9405
Douglas Gregor9a28e842010-03-01 23:15:13 +00009406 BlockScopeInfo *BSI = cast<BlockScopeInfo>(FunctionScopes.back());
Jordan Rosed39e5f12012-07-02 21:19:23 +00009407
9408 if (BSI->HasImplicitReturnType)
9409 deduceClosureReturnType(*BSI);
9410
Steve Naroff1d95e5a2008-10-10 01:28:17 +00009411 PopDeclContext();
9412
Steve Naroffc540d662008-09-03 18:15:37 +00009413 QualType RetTy = Context.VoidTy;
Fariborz Jahanian3fd73102009-06-19 23:37:08 +00009414 if (!BSI->ReturnType.isNull())
9415 RetTy = BSI->ReturnType;
Mike Stump4e1f26a2009-02-19 03:04:26 +00009416
Mike Stump3bf1ab42009-07-28 22:04:01 +00009417 bool NoReturn = BSI->TheDecl->getAttr<NoReturnAttr>();
Steve Naroffc540d662008-09-03 18:15:37 +00009418 QualType BlockTy;
John McCall8e346702010-06-04 19:02:56 +00009419
John McCallc63de662011-02-02 13:00:07 +00009420 // Set the captured variables on the block.
Eli Friedman20139d32012-01-11 02:36:31 +00009421 // FIXME: Share capture structure between BlockDecl and CapturingScopeInfo!
9422 SmallVector<BlockDecl::Capture, 4> Captures;
9423 for (unsigned i = 0, e = BSI->Captures.size(); i != e; i++) {
9424 CapturingScopeInfo::Capture &Cap = BSI->Captures[i];
9425 if (Cap.isThisCapture())
9426 continue;
Eli Friedman24af8502012-02-03 22:47:37 +00009427 BlockDecl::Capture NewCap(Cap.getVariable(), Cap.isBlockCapture(),
Eli Friedman20139d32012-01-11 02:36:31 +00009428 Cap.isNested(), Cap.getCopyExpr());
9429 Captures.push_back(NewCap);
9430 }
9431 BSI->TheDecl->setCaptures(Context, Captures.begin(), Captures.end(),
9432 BSI->CXXThisCaptureIndex != 0);
John McCallc63de662011-02-02 13:00:07 +00009433
John McCall8e346702010-06-04 19:02:56 +00009434 // If the user wrote a function type in some form, try to use that.
9435 if (!BSI->FunctionType.isNull()) {
9436 const FunctionType *FTy = BSI->FunctionType->getAs<FunctionType>();
9437
9438 FunctionType::ExtInfo Ext = FTy->getExtInfo();
9439 if (NoReturn && !Ext.getNoReturn()) Ext = Ext.withNoReturn(true);
9440
9441 // Turn protoless block types into nullary block types.
9442 if (isa<FunctionNoProtoType>(FTy)) {
John McCalldb40c7f2010-12-14 08:05:40 +00009443 FunctionProtoType::ExtProtoInfo EPI;
9444 EPI.ExtInfo = Ext;
9445 BlockTy = Context.getFunctionType(RetTy, 0, 0, EPI);
John McCall8e346702010-06-04 19:02:56 +00009446
9447 // Otherwise, if we don't need to change anything about the function type,
9448 // preserve its sugar structure.
9449 } else if (FTy->getResultType() == RetTy &&
9450 (!NoReturn || FTy->getNoReturnAttr())) {
9451 BlockTy = BSI->FunctionType;
9452
9453 // Otherwise, make the minimal modifications to the function type.
9454 } else {
9455 const FunctionProtoType *FPT = cast<FunctionProtoType>(FTy);
John McCalldb40c7f2010-12-14 08:05:40 +00009456 FunctionProtoType::ExtProtoInfo EPI = FPT->getExtProtoInfo();
9457 EPI.TypeQuals = 0; // FIXME: silently?
9458 EPI.ExtInfo = Ext;
John McCall8e346702010-06-04 19:02:56 +00009459 BlockTy = Context.getFunctionType(RetTy,
9460 FPT->arg_type_begin(),
9461 FPT->getNumArgs(),
John McCalldb40c7f2010-12-14 08:05:40 +00009462 EPI);
John McCall8e346702010-06-04 19:02:56 +00009463 }
9464
9465 // If we don't have a function type, just build one from nothing.
9466 } else {
John McCalldb40c7f2010-12-14 08:05:40 +00009467 FunctionProtoType::ExtProtoInfo EPI;
John McCall31168b02011-06-15 23:02:42 +00009468 EPI.ExtInfo = FunctionType::ExtInfo().withNoReturn(NoReturn);
John McCalldb40c7f2010-12-14 08:05:40 +00009469 BlockTy = Context.getFunctionType(RetTy, 0, 0, EPI);
John McCall8e346702010-06-04 19:02:56 +00009470 }
Mike Stump4e1f26a2009-02-19 03:04:26 +00009471
John McCall8e346702010-06-04 19:02:56 +00009472 DiagnoseUnusedParameters(BSI->TheDecl->param_begin(),
9473 BSI->TheDecl->param_end());
Steve Naroffc540d662008-09-03 18:15:37 +00009474 BlockTy = Context.getBlockPointerType(BlockTy);
Mike Stump4e1f26a2009-02-19 03:04:26 +00009475
Chris Lattner45542ea2009-04-19 05:28:12 +00009476 // If needed, diagnose invalid gotos and switches in the block.
John McCall31168b02011-06-15 23:02:42 +00009477 if (getCurFunction()->NeedsScopeChecking() &&
Douglas Gregor5d944db2012-08-17 05:12:08 +00009478 !hasAnyUnrecoverableErrorsInThisFunction() &&
9479 !PP.isCodeCompletionEnabled())
John McCallb268a282010-08-23 23:25:46 +00009480 DiagnoseInvalidJumps(cast<CompoundStmt>(Body));
Mike Stump11289f42009-09-09 15:08:12 +00009481
Chris Lattner60f84492011-02-17 23:58:47 +00009482 BSI->TheDecl->setBody(cast<CompoundStmt>(Body));
Kovarththanan Rajaratnamba2c6522010-03-13 10:17:05 +00009483
Jordan Rosed39e5f12012-07-02 21:19:23 +00009484 // Try to apply the named return value optimization. We have to check again
9485 // if we can do this, though, because blocks keep return statements around
9486 // to deduce an implicit return type.
9487 if (getLangOpts().CPlusPlus && RetTy->isRecordType() &&
9488 !BSI->TheDecl->isDependentContext())
9489 computeNRVO(Body, getCurBlock());
Douglas Gregor49695f02011-09-06 20:46:03 +00009490
Benjamin Kramera4fb8362011-07-12 14:11:05 +00009491 BlockExpr *Result = new (Context) BlockExpr(BSI->TheDecl, BlockTy);
9492 const AnalysisBasedWarnings::Policy &WP = AnalysisWarnings.getDefaultPolicy();
Eli Friedman71c80552012-01-05 03:35:19 +00009493 PopFunctionScopeInfo(&WP, Result->getBlockDecl(), Result);
Benjamin Kramera4fb8362011-07-12 14:11:05 +00009494
John McCall28fc7092011-11-10 05:35:25 +00009495 // If the block isn't obviously global, i.e. it captures anything at
John McCalld2393872012-04-13 01:08:17 +00009496 // all, then we need to do a few things in the surrounding context:
John McCall28fc7092011-11-10 05:35:25 +00009497 if (Result->getBlockDecl()->hasCaptures()) {
John McCalld2393872012-04-13 01:08:17 +00009498 // First, this expression has a new cleanup object.
John McCall28fc7092011-11-10 05:35:25 +00009499 ExprCleanupObjects.push_back(Result->getBlockDecl());
9500 ExprNeedsCleanups = true;
John McCalld2393872012-04-13 01:08:17 +00009501
9502 // It also gets a branch-protected scope if any of the captured
9503 // variables needs destruction.
9504 for (BlockDecl::capture_const_iterator
9505 ci = Result->getBlockDecl()->capture_begin(),
9506 ce = Result->getBlockDecl()->capture_end(); ci != ce; ++ci) {
9507 const VarDecl *var = ci->getVariable();
9508 if (var->getType().isDestructedType() != QualType::DK_none) {
9509 getCurFunction()->setHasBranchProtectedScope();
9510 break;
9511 }
9512 }
John McCall28fc7092011-11-10 05:35:25 +00009513 }
Fariborz Jahanian197c68c2012-03-06 18:41:35 +00009514
Douglas Gregor9a28e842010-03-01 23:15:13 +00009515 return Owned(Result);
Steve Naroffc540d662008-09-03 18:15:37 +00009516}
9517
John McCalldadc5752010-08-24 06:29:42 +00009518ExprResult Sema::ActOnVAArg(SourceLocation BuiltinLoc,
Richard Trieuba63ce62011-09-09 01:45:06 +00009519 Expr *E, ParsedType Ty,
Sebastian Redl6d4256c2009-03-15 17:47:39 +00009520 SourceLocation RPLoc) {
Abramo Bagnara27db2392010-08-10 10:06:15 +00009521 TypeSourceInfo *TInfo;
Richard Trieuba63ce62011-09-09 01:45:06 +00009522 GetTypeFromParser(Ty, &TInfo);
9523 return BuildVAArgExpr(BuiltinLoc, E, TInfo, RPLoc);
Abramo Bagnara27db2392010-08-10 10:06:15 +00009524}
9525
John McCalldadc5752010-08-24 06:29:42 +00009526ExprResult Sema::BuildVAArgExpr(SourceLocation BuiltinLoc,
John McCall7decc9e2010-11-18 06:31:45 +00009527 Expr *E, TypeSourceInfo *TInfo,
9528 SourceLocation RPLoc) {
Chris Lattner56382aa2009-04-05 15:49:53 +00009529 Expr *OrigExpr = E;
Mike Stump11289f42009-09-09 15:08:12 +00009530
Eli Friedman121ba0c2008-08-09 23:32:40 +00009531 // Get the va_list type
9532 QualType VaListType = Context.getBuiltinVaListType();
Eli Friedmane2cad652009-05-16 12:46:54 +00009533 if (VaListType->isArrayType()) {
9534 // Deal with implicit array decay; for example, on x86-64,
9535 // va_list is an array, but it's supposed to decay to
9536 // a pointer for va_arg.
Eli Friedman121ba0c2008-08-09 23:32:40 +00009537 VaListType = Context.getArrayDecayedType(VaListType);
Eli Friedmane2cad652009-05-16 12:46:54 +00009538 // Make sure the input expression also decays appropriately.
John Wiegley01296292011-04-08 18:41:53 +00009539 ExprResult Result = UsualUnaryConversions(E);
9540 if (Result.isInvalid())
9541 return ExprError();
9542 E = Result.take();
Eli Friedmane2cad652009-05-16 12:46:54 +00009543 } else {
9544 // Otherwise, the va_list argument must be an l-value because
9545 // it is modified by va_arg.
Mike Stump11289f42009-09-09 15:08:12 +00009546 if (!E->isTypeDependent() &&
Douglas Gregorad3150c2009-05-19 23:10:31 +00009547 CheckForModifiableLvalue(E, BuiltinLoc, *this))
Eli Friedmane2cad652009-05-16 12:46:54 +00009548 return ExprError();
9549 }
Eli Friedman121ba0c2008-08-09 23:32:40 +00009550
Douglas Gregorad3150c2009-05-19 23:10:31 +00009551 if (!E->isTypeDependent() &&
9552 !Context.hasSameType(VaListType, E->getType())) {
Sebastian Redl6d4256c2009-03-15 17:47:39 +00009553 return ExprError(Diag(E->getLocStart(),
9554 diag::err_first_argument_to_va_arg_not_of_type_va_list)
Chris Lattner56382aa2009-04-05 15:49:53 +00009555 << OrigExpr->getType() << E->getSourceRange());
Chris Lattner3f5cd772009-04-05 00:59:53 +00009556 }
Mike Stump4e1f26a2009-02-19 03:04:26 +00009557
David Majnemerc75d1a12011-06-14 05:17:32 +00009558 if (!TInfo->getType()->isDependentType()) {
9559 if (RequireCompleteType(TInfo->getTypeLoc().getBeginLoc(), TInfo->getType(),
Douglas Gregor7bfb2d02012-05-04 16:32:21 +00009560 diag::err_second_parameter_to_va_arg_incomplete,
9561 TInfo->getTypeLoc()))
David Majnemerc75d1a12011-06-14 05:17:32 +00009562 return ExprError();
David Majnemer254a5c02011-06-13 06:37:03 +00009563
David Majnemerc75d1a12011-06-14 05:17:32 +00009564 if (RequireNonAbstractType(TInfo->getTypeLoc().getBeginLoc(),
Douglas Gregorae298422012-05-04 17:09:59 +00009565 TInfo->getType(),
9566 diag::err_second_parameter_to_va_arg_abstract,
9567 TInfo->getTypeLoc()))
David Majnemerc75d1a12011-06-14 05:17:32 +00009568 return ExprError();
9569
Douglas Gregor7e1eb932011-07-30 06:45:27 +00009570 if (!TInfo->getType().isPODType(Context)) {
David Majnemerc75d1a12011-06-14 05:17:32 +00009571 Diag(TInfo->getTypeLoc().getBeginLoc(),
Douglas Gregor7e1eb932011-07-30 06:45:27 +00009572 TInfo->getType()->isObjCLifetimeType()
9573 ? diag::warn_second_parameter_to_va_arg_ownership_qualified
9574 : diag::warn_second_parameter_to_va_arg_not_pod)
David Majnemerc75d1a12011-06-14 05:17:32 +00009575 << TInfo->getType()
9576 << TInfo->getTypeLoc().getSourceRange();
Douglas Gregor7e1eb932011-07-30 06:45:27 +00009577 }
Eli Friedman6290ae42011-07-11 21:45:59 +00009578
9579 // Check for va_arg where arguments of the given type will be promoted
9580 // (i.e. this va_arg is guaranteed to have undefined behavior).
9581 QualType PromoteType;
9582 if (TInfo->getType()->isPromotableIntegerType()) {
9583 PromoteType = Context.getPromotedIntegerType(TInfo->getType());
9584 if (Context.typesAreCompatible(PromoteType, TInfo->getType()))
9585 PromoteType = QualType();
9586 }
9587 if (TInfo->getType()->isSpecificBuiltinType(BuiltinType::Float))
9588 PromoteType = Context.DoubleTy;
9589 if (!PromoteType.isNull())
9590 Diag(TInfo->getTypeLoc().getBeginLoc(),
9591 diag::warn_second_parameter_to_va_arg_never_compatible)
9592 << TInfo->getType()
9593 << PromoteType
9594 << TInfo->getTypeLoc().getSourceRange();
David Majnemerc75d1a12011-06-14 05:17:32 +00009595 }
Mike Stump4e1f26a2009-02-19 03:04:26 +00009596
Abramo Bagnara27db2392010-08-10 10:06:15 +00009597 QualType T = TInfo->getType().getNonLValueExprType(Context);
9598 return Owned(new (Context) VAArgExpr(BuiltinLoc, E, TInfo, RPLoc, T));
Anders Carlsson7e13ab82007-10-15 20:28:48 +00009599}
9600
John McCalldadc5752010-08-24 06:29:42 +00009601ExprResult Sema::ActOnGNUNullExpr(SourceLocation TokenLoc) {
Douglas Gregor3be4b122008-11-29 04:51:27 +00009602 // The type of __null will be int or long, depending on the size of
9603 // pointers on the target.
9604 QualType Ty;
Douglas Gregore8bbc122011-09-02 00:18:52 +00009605 unsigned pw = Context.getTargetInfo().getPointerWidth(0);
9606 if (pw == Context.getTargetInfo().getIntWidth())
Douglas Gregor3be4b122008-11-29 04:51:27 +00009607 Ty = Context.IntTy;
Douglas Gregore8bbc122011-09-02 00:18:52 +00009608 else if (pw == Context.getTargetInfo().getLongWidth())
Douglas Gregor3be4b122008-11-29 04:51:27 +00009609 Ty = Context.LongTy;
Douglas Gregore8bbc122011-09-02 00:18:52 +00009610 else if (pw == Context.getTargetInfo().getLongLongWidth())
NAKAMURA Takumi0d13fd32011-01-19 00:11:41 +00009611 Ty = Context.LongLongTy;
9612 else {
David Blaikie83d382b2011-09-23 05:06:16 +00009613 llvm_unreachable("I don't know size of pointer!");
NAKAMURA Takumi0d13fd32011-01-19 00:11:41 +00009614 }
Douglas Gregor3be4b122008-11-29 04:51:27 +00009615
Sebastian Redl6d4256c2009-03-15 17:47:39 +00009616 return Owned(new (Context) GNUNullExpr(Ty, TokenLoc));
Douglas Gregor3be4b122008-11-29 04:51:27 +00009617}
9618
Alexis Huntc46382e2010-04-28 23:02:27 +00009619static void MakeObjCStringLiteralFixItHint(Sema& SemaRef, QualType DstType,
Douglas Gregora771f462010-03-31 17:46:05 +00009620 Expr *SrcExpr, FixItHint &Hint) {
David Blaikiebbafb8a2012-03-11 07:00:24 +00009621 if (!SemaRef.getLangOpts().ObjC1)
Anders Carlssonace5d072009-11-10 04:46:30 +00009622 return;
Kovarththanan Rajaratnamba2c6522010-03-13 10:17:05 +00009623
Anders Carlssonace5d072009-11-10 04:46:30 +00009624 const ObjCObjectPointerType *PT = DstType->getAs<ObjCObjectPointerType>();
9625 if (!PT)
9626 return;
9627
9628 // Check if the destination is of type 'id'.
9629 if (!PT->isObjCIdType()) {
9630 // Check if the destination is the 'NSString' interface.
9631 const ObjCInterfaceDecl *ID = PT->getInterfaceDecl();
9632 if (!ID || !ID->getIdentifier()->isStr("NSString"))
9633 return;
9634 }
Kovarththanan Rajaratnamba2c6522010-03-13 10:17:05 +00009635
John McCallfe96e0b2011-11-06 09:01:30 +00009636 // Ignore any parens, implicit casts (should only be
9637 // array-to-pointer decays), and not-so-opaque values. The last is
9638 // important for making this trigger for property assignments.
9639 SrcExpr = SrcExpr->IgnoreParenImpCasts();
9640 if (OpaqueValueExpr *OV = dyn_cast<OpaqueValueExpr>(SrcExpr))
9641 if (OV->getSourceExpr())
9642 SrcExpr = OV->getSourceExpr()->IgnoreParenImpCasts();
9643
9644 StringLiteral *SL = dyn_cast<StringLiteral>(SrcExpr);
Douglas Gregorfb65e592011-07-27 05:40:30 +00009645 if (!SL || !SL->isAscii())
Anders Carlssonace5d072009-11-10 04:46:30 +00009646 return;
Kovarththanan Rajaratnamba2c6522010-03-13 10:17:05 +00009647
Douglas Gregora771f462010-03-31 17:46:05 +00009648 Hint = FixItHint::CreateInsertion(SL->getLocStart(), "@");
Anders Carlssonace5d072009-11-10 04:46:30 +00009649}
9650
Chris Lattner9bad62c2008-01-04 18:04:52 +00009651bool Sema::DiagnoseAssignmentResult(AssignConvertType ConvTy,
9652 SourceLocation Loc,
9653 QualType DstType, QualType SrcType,
Douglas Gregor4f4946a2010-04-22 00:20:18 +00009654 Expr *SrcExpr, AssignmentAction Action,
9655 bool *Complained) {
9656 if (Complained)
9657 *Complained = false;
9658
Chris Lattner9bad62c2008-01-04 18:04:52 +00009659 // Decode the result (notice that AST's are still created for extensions).
Douglas Gregor33823722011-06-11 01:09:30 +00009660 bool CheckInferredResultType = false;
Chris Lattner9bad62c2008-01-04 18:04:52 +00009661 bool isInvalid = false;
Eli Friedman381f4312012-02-29 20:59:56 +00009662 unsigned DiagKind = 0;
Douglas Gregora771f462010-03-31 17:46:05 +00009663 FixItHint Hint;
Anna Zaks3b402712011-07-28 19:51:27 +00009664 ConversionFixItGenerator ConvHints;
9665 bool MayHaveConvFixit = false;
Richard Trieucaff2472011-11-23 22:32:32 +00009666 bool MayHaveFunctionDiff = false;
Kovarththanan Rajaratnamba2c6522010-03-13 10:17:05 +00009667
Chris Lattner9bad62c2008-01-04 18:04:52 +00009668 switch (ConvTy) {
Fariborz Jahanian268fec12012-07-17 18:00:08 +00009669 case Compatible:
9670 DiagnoseAssignmentEnum(DstType, SrcType, SrcExpr);
9671 return false;
9672
Chris Lattner940cfeb2008-01-04 18:22:42 +00009673 case PointerToInt:
Chris Lattner9bad62c2008-01-04 18:04:52 +00009674 DiagKind = diag::ext_typecheck_convert_pointer_int;
Anna Zaks3b402712011-07-28 19:51:27 +00009675 ConvHints.tryToFixConversion(SrcExpr, SrcType, DstType, *this);
9676 MayHaveConvFixit = true;
Chris Lattner9bad62c2008-01-04 18:04:52 +00009677 break;
Chris Lattner940cfeb2008-01-04 18:22:42 +00009678 case IntToPointer:
9679 DiagKind = diag::ext_typecheck_convert_int_pointer;
Anna Zaks3b402712011-07-28 19:51:27 +00009680 ConvHints.tryToFixConversion(SrcExpr, SrcType, DstType, *this);
9681 MayHaveConvFixit = true;
Chris Lattner940cfeb2008-01-04 18:22:42 +00009682 break;
Chris Lattner9bad62c2008-01-04 18:04:52 +00009683 case IncompatiblePointer:
Douglas Gregora771f462010-03-31 17:46:05 +00009684 MakeObjCStringLiteralFixItHint(*this, DstType, SrcExpr, Hint);
Chris Lattner9bad62c2008-01-04 18:04:52 +00009685 DiagKind = diag::ext_typecheck_convert_incompatible_pointer;
Douglas Gregor33823722011-06-11 01:09:30 +00009686 CheckInferredResultType = DstType->isObjCObjectPointerType() &&
9687 SrcType->isObjCObjectPointerType();
Anna Zaks3b402712011-07-28 19:51:27 +00009688 if (Hint.isNull() && !CheckInferredResultType) {
9689 ConvHints.tryToFixConversion(SrcExpr, SrcType, DstType, *this);
9690 }
9691 MayHaveConvFixit = true;
Chris Lattner9bad62c2008-01-04 18:04:52 +00009692 break;
Eli Friedman80160bd2009-03-22 23:59:44 +00009693 case IncompatiblePointerSign:
9694 DiagKind = diag::ext_typecheck_convert_incompatible_pointer_sign;
9695 break;
Chris Lattner9bad62c2008-01-04 18:04:52 +00009696 case FunctionVoidPointer:
9697 DiagKind = diag::ext_typecheck_convert_pointer_void_func;
9698 break;
John McCall4fff8f62011-02-01 00:10:29 +00009699 case IncompatiblePointerDiscardsQualifiers: {
John McCall71de91c2011-02-01 23:28:01 +00009700 // Perform array-to-pointer decay if necessary.
9701 if (SrcType->isArrayType()) SrcType = Context.getArrayDecayedType(SrcType);
9702
John McCall4fff8f62011-02-01 00:10:29 +00009703 Qualifiers lhq = SrcType->getPointeeType().getQualifiers();
9704 Qualifiers rhq = DstType->getPointeeType().getQualifiers();
9705 if (lhq.getAddressSpace() != rhq.getAddressSpace()) {
9706 DiagKind = diag::err_typecheck_incompatible_address_space;
9707 break;
John McCall31168b02011-06-15 23:02:42 +00009708
9709
9710 } else if (lhq.getObjCLifetime() != rhq.getObjCLifetime()) {
Argyrios Kyrtzidiscff00d92011-06-24 00:08:59 +00009711 DiagKind = diag::err_typecheck_incompatible_ownership;
John McCall31168b02011-06-15 23:02:42 +00009712 break;
John McCall4fff8f62011-02-01 00:10:29 +00009713 }
9714
9715 llvm_unreachable("unknown error case for discarding qualifiers!");
9716 // fallthrough
9717 }
Chris Lattner9bad62c2008-01-04 18:04:52 +00009718 case CompatiblePointerDiscardsQualifiers:
Douglas Gregoraa1e21d2008-09-12 00:47:35 +00009719 // If the qualifiers lost were because we were applying the
9720 // (deprecated) C++ conversion from a string literal to a char*
9721 // (or wchar_t*), then there was no error (C++ 4.2p2). FIXME:
9722 // Ideally, this check would be performed in
John McCallaba90822011-01-31 23:13:11 +00009723 // checkPointerTypesForAssignment. However, that would require a
Douglas Gregoraa1e21d2008-09-12 00:47:35 +00009724 // bit of refactoring (so that the second argument is an
9725 // expression, rather than a type), which should be done as part
John McCallaba90822011-01-31 23:13:11 +00009726 // of a larger effort to fix checkPointerTypesForAssignment for
Douglas Gregoraa1e21d2008-09-12 00:47:35 +00009727 // C++ semantics.
David Blaikiebbafb8a2012-03-11 07:00:24 +00009728 if (getLangOpts().CPlusPlus &&
Douglas Gregoraa1e21d2008-09-12 00:47:35 +00009729 IsStringLiteralToNonConstPointerConversion(SrcExpr, DstType))
9730 return false;
Chris Lattner9bad62c2008-01-04 18:04:52 +00009731 DiagKind = diag::ext_typecheck_convert_discards_qualifiers;
9732 break;
Alexis Hunt6f3de502009-11-08 07:46:34 +00009733 case IncompatibleNestedPointerQualifiers:
Fariborz Jahanianb98dade2009-11-09 22:16:37 +00009734 DiagKind = diag::ext_nested_pointer_qualifier_mismatch;
Fariborz Jahaniand7aa9d82009-11-07 20:20:40 +00009735 break;
Steve Naroff081c7422008-09-04 15:10:53 +00009736 case IntToBlockPointer:
9737 DiagKind = diag::err_int_to_block_pointer;
9738 break;
9739 case IncompatibleBlockPointer:
Mike Stumpd79b5a82009-04-21 22:51:42 +00009740 DiagKind = diag::err_typecheck_convert_incompatible_block_pointer;
Steve Naroff081c7422008-09-04 15:10:53 +00009741 break;
Steve Naroff8afa9892008-10-14 22:18:38 +00009742 case IncompatibleObjCQualifiedId:
Mike Stump4e1f26a2009-02-19 03:04:26 +00009743 // FIXME: Diagnose the problem in ObjCQualifiedIdTypesAreCompatible, since
Steve Naroff8afa9892008-10-14 22:18:38 +00009744 // it can give a more specific diagnostic.
9745 DiagKind = diag::warn_incompatible_qualified_id;
9746 break;
Anders Carlssondb5a9b62009-01-30 23:17:46 +00009747 case IncompatibleVectors:
9748 DiagKind = diag::warn_incompatible_vectors;
9749 break;
Fariborz Jahanian6f472e82011-07-07 18:55:47 +00009750 case IncompatibleObjCWeakRef:
9751 DiagKind = diag::err_arc_weak_unavailable_assign;
9752 break;
Chris Lattner9bad62c2008-01-04 18:04:52 +00009753 case Incompatible:
9754 DiagKind = diag::err_typecheck_convert_incompatible;
Anna Zaks3b402712011-07-28 19:51:27 +00009755 ConvHints.tryToFixConversion(SrcExpr, SrcType, DstType, *this);
9756 MayHaveConvFixit = true;
Chris Lattner9bad62c2008-01-04 18:04:52 +00009757 isInvalid = true;
Richard Trieucaff2472011-11-23 22:32:32 +00009758 MayHaveFunctionDiff = true;
Chris Lattner9bad62c2008-01-04 18:04:52 +00009759 break;
9760 }
Mike Stump4e1f26a2009-02-19 03:04:26 +00009761
Douglas Gregorc68e1402010-04-09 00:35:39 +00009762 QualType FirstType, SecondType;
9763 switch (Action) {
9764 case AA_Assigning:
9765 case AA_Initializing:
9766 // The destination type comes first.
9767 FirstType = DstType;
9768 SecondType = SrcType;
9769 break;
Alexis Huntc46382e2010-04-28 23:02:27 +00009770
Douglas Gregorc68e1402010-04-09 00:35:39 +00009771 case AA_Returning:
9772 case AA_Passing:
9773 case AA_Converting:
9774 case AA_Sending:
9775 case AA_Casting:
9776 // The source type comes first.
9777 FirstType = SrcType;
9778 SecondType = DstType;
9779 break;
9780 }
Alexis Huntc46382e2010-04-28 23:02:27 +00009781
Anna Zaks3b402712011-07-28 19:51:27 +00009782 PartialDiagnostic FDiag = PDiag(DiagKind);
9783 FDiag << FirstType << SecondType << Action << SrcExpr->getSourceRange();
9784
9785 // If we can fix the conversion, suggest the FixIts.
9786 assert(ConvHints.isNull() || Hint.isNull());
9787 if (!ConvHints.isNull()) {
Benjamin Kramer490afa62012-01-14 21:05:10 +00009788 for (std::vector<FixItHint>::iterator HI = ConvHints.Hints.begin(),
9789 HE = ConvHints.Hints.end(); HI != HE; ++HI)
Anna Zaks3b402712011-07-28 19:51:27 +00009790 FDiag << *HI;
9791 } else {
9792 FDiag << Hint;
9793 }
9794 if (MayHaveConvFixit) { FDiag << (unsigned) (ConvHints.Kind); }
9795
Richard Trieucaff2472011-11-23 22:32:32 +00009796 if (MayHaveFunctionDiff)
9797 HandleFunctionTypeMismatch(FDiag, SecondType, FirstType);
9798
Anna Zaks3b402712011-07-28 19:51:27 +00009799 Diag(Loc, FDiag);
9800
Richard Trieucaff2472011-11-23 22:32:32 +00009801 if (SecondType == Context.OverloadTy)
9802 NoteAllOverloadCandidates(OverloadExpr::find(SrcExpr).Expression,
9803 FirstType);
9804
Douglas Gregor33823722011-06-11 01:09:30 +00009805 if (CheckInferredResultType)
9806 EmitRelatedResultTypeNote(SrcExpr);
9807
Douglas Gregor4f4946a2010-04-22 00:20:18 +00009808 if (Complained)
9809 *Complained = true;
Chris Lattner9bad62c2008-01-04 18:04:52 +00009810 return isInvalid;
9811}
Anders Carlssone54e8a12008-11-30 19:50:32 +00009812
Richard Smithf4c51d92012-02-04 09:53:13 +00009813ExprResult Sema::VerifyIntegerConstantExpression(Expr *E,
9814 llvm::APSInt *Result) {
Douglas Gregore2b37442012-05-04 22:38:52 +00009815 class SimpleICEDiagnoser : public VerifyICEDiagnoser {
9816 public:
9817 virtual void diagnoseNotICE(Sema &S, SourceLocation Loc, SourceRange SR) {
9818 S.Diag(Loc, diag::err_expr_not_ice) << S.LangOpts.CPlusPlus << SR;
9819 }
9820 } Diagnoser;
9821
9822 return VerifyIntegerConstantExpression(E, Result, Diagnoser);
9823}
9824
9825ExprResult Sema::VerifyIntegerConstantExpression(Expr *E,
9826 llvm::APSInt *Result,
9827 unsigned DiagID,
9828 bool AllowFold) {
9829 class IDDiagnoser : public VerifyICEDiagnoser {
9830 unsigned DiagID;
9831
9832 public:
9833 IDDiagnoser(unsigned DiagID)
9834 : VerifyICEDiagnoser(DiagID == 0), DiagID(DiagID) { }
9835
9836 virtual void diagnoseNotICE(Sema &S, SourceLocation Loc, SourceRange SR) {
9837 S.Diag(Loc, DiagID) << SR;
9838 }
9839 } Diagnoser(DiagID);
9840
9841 return VerifyIntegerConstantExpression(E, Result, Diagnoser, AllowFold);
9842}
9843
9844void Sema::VerifyICEDiagnoser::diagnoseFold(Sema &S, SourceLocation Loc,
9845 SourceRange SR) {
9846 S.Diag(Loc, diag::ext_expr_not_ice) << SR << S.LangOpts.CPlusPlus;
Richard Smithf4c51d92012-02-04 09:53:13 +00009847}
9848
Benjamin Kramer33adaae2012-04-18 14:22:41 +00009849ExprResult
9850Sema::VerifyIntegerConstantExpression(Expr *E, llvm::APSInt *Result,
Douglas Gregore2b37442012-05-04 22:38:52 +00009851 VerifyICEDiagnoser &Diagnoser,
9852 bool AllowFold) {
Daniel Dunbar62ee6412012-03-09 18:35:03 +00009853 SourceLocation DiagLoc = E->getLocStart();
Richard Smithf4c51d92012-02-04 09:53:13 +00009854
David Blaikiebbafb8a2012-03-11 07:00:24 +00009855 if (getLangOpts().CPlusPlus0x) {
Richard Smithf4c51d92012-02-04 09:53:13 +00009856 // C++11 [expr.const]p5:
9857 // If an expression of literal class type is used in a context where an
9858 // integral constant expression is required, then that class type shall
9859 // have a single non-explicit conversion function to an integral or
9860 // unscoped enumeration type
9861 ExprResult Converted;
Douglas Gregore2b37442012-05-04 22:38:52 +00009862 if (!Diagnoser.Suppress) {
9863 class CXX11ConvertDiagnoser : public ICEConvertDiagnoser {
9864 public:
9865 CXX11ConvertDiagnoser() : ICEConvertDiagnoser(false, true) { }
9866
9867 virtual DiagnosticBuilder diagnoseNotInt(Sema &S, SourceLocation Loc,
9868 QualType T) {
9869 return S.Diag(Loc, diag::err_ice_not_integral) << T;
9870 }
9871
9872 virtual DiagnosticBuilder diagnoseIncomplete(Sema &S,
9873 SourceLocation Loc,
9874 QualType T) {
9875 return S.Diag(Loc, diag::err_ice_incomplete_type) << T;
9876 }
9877
9878 virtual DiagnosticBuilder diagnoseExplicitConv(Sema &S,
9879 SourceLocation Loc,
9880 QualType T,
9881 QualType ConvTy) {
9882 return S.Diag(Loc, diag::err_ice_explicit_conversion) << T << ConvTy;
9883 }
9884
9885 virtual DiagnosticBuilder noteExplicitConv(Sema &S,
9886 CXXConversionDecl *Conv,
9887 QualType ConvTy) {
9888 return S.Diag(Conv->getLocation(), diag::note_ice_conversion_here)
9889 << ConvTy->isEnumeralType() << ConvTy;
9890 }
9891
9892 virtual DiagnosticBuilder diagnoseAmbiguous(Sema &S, SourceLocation Loc,
9893 QualType T) {
9894 return S.Diag(Loc, diag::err_ice_ambiguous_conversion) << T;
9895 }
9896
9897 virtual DiagnosticBuilder noteAmbiguous(Sema &S,
9898 CXXConversionDecl *Conv,
9899 QualType ConvTy) {
9900 return S.Diag(Conv->getLocation(), diag::note_ice_conversion_here)
9901 << ConvTy->isEnumeralType() << ConvTy;
9902 }
9903
9904 virtual DiagnosticBuilder diagnoseConversion(Sema &S,
9905 SourceLocation Loc,
9906 QualType T,
9907 QualType ConvTy) {
9908 return DiagnosticBuilder::getEmpty();
9909 }
9910 } ConvertDiagnoser;
9911
9912 Converted = ConvertToIntegralOrEnumerationType(DiagLoc, E,
9913 ConvertDiagnoser,
9914 /*AllowScopedEnumerations*/ false);
Richard Smithf4c51d92012-02-04 09:53:13 +00009915 } else {
9916 // The caller wants to silently enquire whether this is an ICE. Don't
9917 // produce any diagnostics if it isn't.
Douglas Gregore2b37442012-05-04 22:38:52 +00009918 class SilentICEConvertDiagnoser : public ICEConvertDiagnoser {
9919 public:
9920 SilentICEConvertDiagnoser() : ICEConvertDiagnoser(true, true) { }
9921
9922 virtual DiagnosticBuilder diagnoseNotInt(Sema &S, SourceLocation Loc,
9923 QualType T) {
9924 return DiagnosticBuilder::getEmpty();
9925 }
9926
9927 virtual DiagnosticBuilder diagnoseIncomplete(Sema &S,
9928 SourceLocation Loc,
9929 QualType T) {
9930 return DiagnosticBuilder::getEmpty();
9931 }
9932
9933 virtual DiagnosticBuilder diagnoseExplicitConv(Sema &S,
9934 SourceLocation Loc,
9935 QualType T,
9936 QualType ConvTy) {
9937 return DiagnosticBuilder::getEmpty();
9938 }
9939
9940 virtual DiagnosticBuilder noteExplicitConv(Sema &S,
9941 CXXConversionDecl *Conv,
9942 QualType ConvTy) {
9943 return DiagnosticBuilder::getEmpty();
9944 }
9945
9946 virtual DiagnosticBuilder diagnoseAmbiguous(Sema &S, SourceLocation Loc,
9947 QualType T) {
9948 return DiagnosticBuilder::getEmpty();
9949 }
9950
9951 virtual DiagnosticBuilder noteAmbiguous(Sema &S,
9952 CXXConversionDecl *Conv,
9953 QualType ConvTy) {
9954 return DiagnosticBuilder::getEmpty();
9955 }
9956
9957 virtual DiagnosticBuilder diagnoseConversion(Sema &S,
9958 SourceLocation Loc,
9959 QualType T,
9960 QualType ConvTy) {
9961 return DiagnosticBuilder::getEmpty();
9962 }
9963 } ConvertDiagnoser;
9964
9965 Converted = ConvertToIntegralOrEnumerationType(DiagLoc, E,
9966 ConvertDiagnoser, false);
Richard Smithf4c51d92012-02-04 09:53:13 +00009967 }
9968 if (Converted.isInvalid())
9969 return Converted;
9970 E = Converted.take();
9971 if (!E->getType()->isIntegralOrUnscopedEnumerationType())
9972 return ExprError();
9973 } else if (!E->getType()->isIntegralOrUnscopedEnumerationType()) {
9974 // An ICE must be of integral or unscoped enumeration type.
Douglas Gregore2b37442012-05-04 22:38:52 +00009975 if (!Diagnoser.Suppress)
9976 Diagnoser.diagnoseNotICE(*this, DiagLoc, E->getSourceRange());
Richard Smithf4c51d92012-02-04 09:53:13 +00009977 return ExprError();
9978 }
9979
Richard Smith902ca212011-12-14 23:32:26 +00009980 // Circumvent ICE checking in C++11 to avoid evaluating the expression twice
9981 // in the non-ICE case.
David Blaikiebbafb8a2012-03-11 07:00:24 +00009982 if (!getLangOpts().CPlusPlus0x && E->isIntegerConstantExpr(Context)) {
Richard Smithf4c51d92012-02-04 09:53:13 +00009983 if (Result)
9984 *Result = E->EvaluateKnownConstInt(Context);
9985 return Owned(E);
Eli Friedmanbb967cc2009-04-25 22:26:58 +00009986 }
9987
Anders Carlssone54e8a12008-11-30 19:50:32 +00009988 Expr::EvalResult EvalResult;
Richard Smith92b1ce02011-12-12 09:28:41 +00009989 llvm::SmallVector<PartialDiagnosticAt, 8> Notes;
9990 EvalResult.Diag = &Notes;
Anders Carlssone54e8a12008-11-30 19:50:32 +00009991
Richard Smith902ca212011-12-14 23:32:26 +00009992 // Try to evaluate the expression, and produce diagnostics explaining why it's
9993 // not a constant expression as a side-effect.
9994 bool Folded = E->EvaluateAsRValue(EvalResult, Context) &&
9995 EvalResult.Val.isInt() && !EvalResult.HasSideEffects;
9996
9997 // In C++11, we can rely on diagnostics being produced for any expression
9998 // which is not a constant expression. If no diagnostics were produced, then
9999 // this is a constant expression.
David Blaikiebbafb8a2012-03-11 07:00:24 +000010000 if (Folded && getLangOpts().CPlusPlus0x && Notes.empty()) {
Richard Smith902ca212011-12-14 23:32:26 +000010001 if (Result)
10002 *Result = EvalResult.Val.getInt();
Richard Smithf4c51d92012-02-04 09:53:13 +000010003 return Owned(E);
10004 }
10005
10006 // If our only note is the usual "invalid subexpression" note, just point
10007 // the caret at its location rather than producing an essentially
10008 // redundant note.
10009 if (Notes.size() == 1 && Notes[0].second.getDiagID() ==
10010 diag::note_invalid_subexpr_in_const_expr) {
10011 DiagLoc = Notes[0].first;
10012 Notes.clear();
Richard Smith902ca212011-12-14 23:32:26 +000010013 }
10014
10015 if (!Folded || !AllowFold) {
Douglas Gregore2b37442012-05-04 22:38:52 +000010016 if (!Diagnoser.Suppress) {
10017 Diagnoser.diagnoseNotICE(*this, DiagLoc, E->getSourceRange());
Richard Smith92b1ce02011-12-12 09:28:41 +000010018 for (unsigned I = 0, N = Notes.size(); I != N; ++I)
10019 Diag(Notes[I].first, Notes[I].second);
Anders Carlssone54e8a12008-11-30 19:50:32 +000010020 }
Mike Stump4e1f26a2009-02-19 03:04:26 +000010021
Richard Smithf4c51d92012-02-04 09:53:13 +000010022 return ExprError();
Anders Carlssone54e8a12008-11-30 19:50:32 +000010023 }
10024
Douglas Gregore2b37442012-05-04 22:38:52 +000010025 Diagnoser.diagnoseFold(*this, DiagLoc, E->getSourceRange());
Richard Smith2ec40612012-01-15 03:51:30 +000010026 for (unsigned I = 0, N = Notes.size(); I != N; ++I)
10027 Diag(Notes[I].first, Notes[I].second);
Mike Stump4e1f26a2009-02-19 03:04:26 +000010028
Anders Carlssone54e8a12008-11-30 19:50:32 +000010029 if (Result)
10030 *Result = EvalResult.Val.getInt();
Richard Smithf4c51d92012-02-04 09:53:13 +000010031 return Owned(E);
Anders Carlssone54e8a12008-11-30 19:50:32 +000010032}
Douglas Gregorc9c02ed2009-06-19 23:52:42 +000010033
Eli Friedman456f0182012-01-20 01:26:23 +000010034namespace {
10035 // Handle the case where we conclude a expression which we speculatively
10036 // considered to be unevaluated is actually evaluated.
10037 class TransformToPE : public TreeTransform<TransformToPE> {
10038 typedef TreeTransform<TransformToPE> BaseTransform;
10039
10040 public:
10041 TransformToPE(Sema &SemaRef) : BaseTransform(SemaRef) { }
10042
10043 // Make sure we redo semantic analysis
10044 bool AlwaysRebuild() { return true; }
10045
Eli Friedman5f0ca242012-02-06 23:29:57 +000010046 // Make sure we handle LabelStmts correctly.
10047 // FIXME: This does the right thing, but maybe we need a more general
10048 // fix to TreeTransform?
10049 StmtResult TransformLabelStmt(LabelStmt *S) {
10050 S->getDecl()->setStmt(0);
10051 return BaseTransform::TransformLabelStmt(S);
10052 }
10053
Eli Friedman456f0182012-01-20 01:26:23 +000010054 // We need to special-case DeclRefExprs referring to FieldDecls which
10055 // are not part of a member pointer formation; normal TreeTransforming
10056 // doesn't catch this case because of the way we represent them in the AST.
10057 // FIXME: This is a bit ugly; is it really the best way to handle this
10058 // case?
10059 //
10060 // Error on DeclRefExprs referring to FieldDecls.
10061 ExprResult TransformDeclRefExpr(DeclRefExpr *E) {
10062 if (isa<FieldDecl>(E->getDecl()) &&
David Blaikie131fcb42012-08-06 22:47:24 +000010063 !SemaRef.isUnevaluatedContext())
Eli Friedman456f0182012-01-20 01:26:23 +000010064 return SemaRef.Diag(E->getLocation(),
10065 diag::err_invalid_non_static_member_use)
10066 << E->getDecl() << E->getSourceRange();
10067
10068 return BaseTransform::TransformDeclRefExpr(E);
10069 }
10070
10071 // Exception: filter out member pointer formation
10072 ExprResult TransformUnaryOperator(UnaryOperator *E) {
10073 if (E->getOpcode() == UO_AddrOf && E->getType()->isMemberPointerType())
10074 return E;
10075
10076 return BaseTransform::TransformUnaryOperator(E);
10077 }
10078
Douglas Gregor89625492012-02-09 08:14:43 +000010079 ExprResult TransformLambdaExpr(LambdaExpr *E) {
10080 // Lambdas never need to be transformed.
10081 return E;
10082 }
Eli Friedman456f0182012-01-20 01:26:23 +000010083 };
Eli Friedmanfbc0dff2012-01-18 01:05:54 +000010084}
10085
Eli Friedman456f0182012-01-20 01:26:23 +000010086ExprResult Sema::TranformToPotentiallyEvaluated(Expr *E) {
Eli Friedmane4f22df2012-02-29 04:03:55 +000010087 assert(ExprEvalContexts.back().Context == Unevaluated &&
10088 "Should only transform unevaluated expressions");
Eli Friedman456f0182012-01-20 01:26:23 +000010089 ExprEvalContexts.back().Context =
10090 ExprEvalContexts[ExprEvalContexts.size()-2].Context;
10091 if (ExprEvalContexts.back().Context == Unevaluated)
10092 return E;
10093 return TransformToPE(*this).TransformExpr(E);
Eli Friedmanfbc0dff2012-01-18 01:05:54 +000010094}
10095
Douglas Gregorff790f12009-11-26 00:44:06 +000010096void
Douglas Gregor7fcbd902012-02-21 00:37:24 +000010097Sema::PushExpressionEvaluationContext(ExpressionEvaluationContext NewContext,
Richard Smithfd555f62012-02-22 02:04:18 +000010098 Decl *LambdaContextDecl,
10099 bool IsDecltype) {
Douglas Gregorff790f12009-11-26 00:44:06 +000010100 ExprEvalContexts.push_back(
John McCall31168b02011-06-15 23:02:42 +000010101 ExpressionEvaluationContextRecord(NewContext,
John McCall28fc7092011-11-10 05:35:25 +000010102 ExprCleanupObjects.size(),
Douglas Gregor7fcbd902012-02-21 00:37:24 +000010103 ExprNeedsCleanups,
Richard Smithfd555f62012-02-22 02:04:18 +000010104 LambdaContextDecl,
10105 IsDecltype));
John McCall31168b02011-06-15 23:02:42 +000010106 ExprNeedsCleanups = false;
Eli Friedman3bda6b12012-02-02 23:15:15 +000010107 if (!MaybeODRUseExprs.empty())
10108 std::swap(MaybeODRUseExprs, ExprEvalContexts.back().SavedMaybeODRUseExprs);
Douglas Gregor0b6a6242009-06-22 20:57:11 +000010109}
10110
Richard Trieucfc491d2011-08-02 04:35:43 +000010111void Sema::PopExpressionEvaluationContext() {
Eli Friedmanfa0df832012-02-02 03:46:19 +000010112 ExpressionEvaluationContextRecord& Rec = ExprEvalContexts.back();
Douglas Gregor0b6a6242009-06-22 20:57:11 +000010113
Douglas Gregor89625492012-02-09 08:14:43 +000010114 if (!Rec.Lambdas.empty()) {
10115 if (Rec.Context == Unevaluated) {
10116 // C++11 [expr.prim.lambda]p2:
10117 // A lambda-expression shall not appear in an unevaluated operand
10118 // (Clause 5).
10119 for (unsigned I = 0, N = Rec.Lambdas.size(); I != N; ++I)
10120 Diag(Rec.Lambdas[I]->getLocStart(),
10121 diag::err_lambda_unevaluated_operand);
10122 } else {
10123 // Mark the capture expressions odr-used. This was deferred
10124 // during lambda expression creation.
10125 for (unsigned I = 0, N = Rec.Lambdas.size(); I != N; ++I) {
10126 LambdaExpr *Lambda = Rec.Lambdas[I];
10127 for (LambdaExpr::capture_init_iterator
10128 C = Lambda->capture_init_begin(),
10129 CEnd = Lambda->capture_init_end();
10130 C != CEnd; ++C) {
10131 MarkDeclarationsReferencedInExpr(*C);
10132 }
10133 }
10134 }
10135 }
10136
Douglas Gregorff790f12009-11-26 00:44:06 +000010137 // When are coming out of an unevaluated context, clear out any
10138 // temporaries that we may have created as part of the evaluation of
10139 // the expression in that context: they aren't relevant because they
10140 // will never be constructed.
Richard Smith764d2fe2011-12-20 02:08:33 +000010141 if (Rec.Context == Unevaluated || Rec.Context == ConstantEvaluated) {
John McCall28fc7092011-11-10 05:35:25 +000010142 ExprCleanupObjects.erase(ExprCleanupObjects.begin() + Rec.NumCleanupObjects,
10143 ExprCleanupObjects.end());
John McCall31168b02011-06-15 23:02:42 +000010144 ExprNeedsCleanups = Rec.ParentNeedsCleanups;
Eli Friedman3bda6b12012-02-02 23:15:15 +000010145 CleanupVarDeclMarking();
10146 std::swap(MaybeODRUseExprs, Rec.SavedMaybeODRUseExprs);
John McCall31168b02011-06-15 23:02:42 +000010147 // Otherwise, merge the contexts together.
10148 } else {
10149 ExprNeedsCleanups |= Rec.ParentNeedsCleanups;
Eli Friedman3bda6b12012-02-02 23:15:15 +000010150 MaybeODRUseExprs.insert(Rec.SavedMaybeODRUseExprs.begin(),
10151 Rec.SavedMaybeODRUseExprs.end());
John McCall31168b02011-06-15 23:02:42 +000010152 }
Eli Friedmanfa0df832012-02-02 03:46:19 +000010153
10154 // Pop the current expression evaluation context off the stack.
10155 ExprEvalContexts.pop_back();
Douglas Gregor0b6a6242009-06-22 20:57:11 +000010156}
Douglas Gregorc9c02ed2009-06-19 23:52:42 +000010157
John McCall31168b02011-06-15 23:02:42 +000010158void Sema::DiscardCleanupsInEvaluationContext() {
John McCall28fc7092011-11-10 05:35:25 +000010159 ExprCleanupObjects.erase(
10160 ExprCleanupObjects.begin() + ExprEvalContexts.back().NumCleanupObjects,
10161 ExprCleanupObjects.end());
John McCall31168b02011-06-15 23:02:42 +000010162 ExprNeedsCleanups = false;
Eli Friedman3bda6b12012-02-02 23:15:15 +000010163 MaybeODRUseExprs.clear();
John McCall31168b02011-06-15 23:02:42 +000010164}
10165
Eli Friedmane0afc982012-01-21 01:01:51 +000010166ExprResult Sema::HandleExprEvaluationContextForTypeof(Expr *E) {
10167 if (!E->getType()->isVariablyModifiedType())
10168 return E;
10169 return TranformToPotentiallyEvaluated(E);
10170}
10171
Benjamin Kramerbf8da9d2012-02-06 11:13:08 +000010172static bool IsPotentiallyEvaluatedContext(Sema &SemaRef) {
Douglas Gregorc9c02ed2009-06-19 23:52:42 +000010173 // Do not mark anything as "used" within a dependent context; wait for
10174 // an instantiation.
Eli Friedmanfa0df832012-02-02 03:46:19 +000010175 if (SemaRef.CurContext->isDependentContext())
10176 return false;
Mike Stump11289f42009-09-09 15:08:12 +000010177
Eli Friedmanfa0df832012-02-02 03:46:19 +000010178 switch (SemaRef.ExprEvalContexts.back().Context) {
10179 case Sema::Unevaluated:
Douglas Gregor0b6a6242009-06-22 20:57:11 +000010180 // We are in an expression that is not potentially evaluated; do nothing.
Eli Friedman02b58512012-01-21 04:44:06 +000010181 // (Depending on how you read the standard, we actually do need to do
10182 // something here for null pointer constants, but the standard's
10183 // definition of a null pointer constant is completely crazy.)
Eli Friedmanfa0df832012-02-02 03:46:19 +000010184 return false;
Mike Stump11289f42009-09-09 15:08:12 +000010185
Eli Friedmanfa0df832012-02-02 03:46:19 +000010186 case Sema::ConstantEvaluated:
10187 case Sema::PotentiallyEvaluated:
Eli Friedman02b58512012-01-21 04:44:06 +000010188 // We are in a potentially evaluated expression (or a constant-expression
10189 // in C++03); we need to do implicit template instantiation, implicitly
10190 // define class members, and mark most declarations as used.
Eli Friedmanfa0df832012-02-02 03:46:19 +000010191 return true;
Mike Stump11289f42009-09-09 15:08:12 +000010192
Eli Friedmanfa0df832012-02-02 03:46:19 +000010193 case Sema::PotentiallyEvaluatedIfUsed:
Douglas Gregor8a01b2a2010-09-11 20:24:53 +000010194 // Referenced declarations will only be used if the construct in the
10195 // containing expression is used.
Eli Friedmanfa0df832012-02-02 03:46:19 +000010196 return false;
Douglas Gregor0b6a6242009-06-22 20:57:11 +000010197 }
Matt Beaumont-Gay248bc722012-02-02 18:35:35 +000010198 llvm_unreachable("Invalid context");
Eli Friedmanfa0df832012-02-02 03:46:19 +000010199}
10200
10201/// \brief Mark a function referenced, and check whether it is odr-used
10202/// (C++ [basic.def.odr]p2, C99 6.9p3)
10203void Sema::MarkFunctionReferenced(SourceLocation Loc, FunctionDecl *Func) {
10204 assert(Func && "No function?");
10205
10206 Func->setReferenced();
10207
Richard Smith4a941e22012-02-14 22:25:15 +000010208 // Don't mark this function as used multiple times, unless it's a constexpr
10209 // function which we need to instantiate.
10210 if (Func->isUsed(false) &&
10211 !(Func->isConstexpr() && !Func->getBody() &&
10212 Func->isImplicitlyInstantiable()))
Eli Friedmanfa0df832012-02-02 03:46:19 +000010213 return;
10214
10215 if (!IsPotentiallyEvaluatedContext(*this))
10216 return;
Mike Stump11289f42009-09-09 15:08:12 +000010217
Douglas Gregorc9c02ed2009-06-19 23:52:42 +000010218 // Note that this declaration has been used.
Eli Friedmanfa0df832012-02-02 03:46:19 +000010219 if (CXXConstructorDecl *Constructor = dyn_cast<CXXConstructorDecl>(Func)) {
Richard Smith273c4e92012-02-26 07:51:39 +000010220 if (Constructor->isDefaulted() && !Constructor->isDeleted()) {
Sebastian Redl22653ba2011-08-30 19:58:05 +000010221 if (Constructor->isDefaultConstructor()) {
10222 if (Constructor->isTrivial())
10223 return;
10224 if (!Constructor->isUsed(false))
10225 DefineImplicitDefaultConstructor(Loc, Constructor);
10226 } else if (Constructor->isCopyConstructor()) {
10227 if (!Constructor->isUsed(false))
10228 DefineImplicitCopyConstructor(Loc, Constructor);
10229 } else if (Constructor->isMoveConstructor()) {
10230 if (!Constructor->isUsed(false))
10231 DefineImplicitMoveConstructor(Loc, Constructor);
10232 }
Fariborz Jahanian477d2422009-06-22 23:34:40 +000010233 }
Kovarththanan Rajaratnamba2c6522010-03-13 10:17:05 +000010234
Douglas Gregor88d292c2010-05-13 16:44:06 +000010235 MarkVTableUsed(Loc, Constructor->getParent());
Eli Friedmanfa0df832012-02-02 03:46:19 +000010236 } else if (CXXDestructorDecl *Destructor =
10237 dyn_cast<CXXDestructorDecl>(Func)) {
Richard Smith273c4e92012-02-26 07:51:39 +000010238 if (Destructor->isDefaulted() && !Destructor->isDeleted() &&
10239 !Destructor->isUsed(false))
Fariborz Jahanian24a175b2009-06-26 23:49:16 +000010240 DefineImplicitDestructor(Loc, Destructor);
Douglas Gregor88d292c2010-05-13 16:44:06 +000010241 if (Destructor->isVirtual())
10242 MarkVTableUsed(Loc, Destructor->getParent());
Eli Friedmanfa0df832012-02-02 03:46:19 +000010243 } else if (CXXMethodDecl *MethodDecl = dyn_cast<CXXMethodDecl>(Func)) {
Richard Smith273c4e92012-02-26 07:51:39 +000010244 if (MethodDecl->isDefaulted() && !MethodDecl->isDeleted() &&
10245 MethodDecl->isOverloadedOperator() &&
Fariborz Jahanian41f79272009-06-25 21:45:19 +000010246 MethodDecl->getOverloadedOperator() == OO_Equal) {
Sebastian Redl22653ba2011-08-30 19:58:05 +000010247 if (!MethodDecl->isUsed(false)) {
10248 if (MethodDecl->isCopyAssignmentOperator())
10249 DefineImplicitCopyAssignment(Loc, MethodDecl);
10250 else
10251 DefineImplicitMoveAssignment(Loc, MethodDecl);
10252 }
Douglas Gregord3b672c2012-02-16 01:06:16 +000010253 } else if (isa<CXXConversionDecl>(MethodDecl) &&
10254 MethodDecl->getParent()->isLambda()) {
10255 CXXConversionDecl *Conversion = cast<CXXConversionDecl>(MethodDecl);
10256 if (Conversion->isLambdaToBlockPointerConversion())
10257 DefineImplicitLambdaToBlockPointerConversion(Loc, Conversion);
10258 else
10259 DefineImplicitLambdaToFunctionPointerConversion(Loc, Conversion);
Douglas Gregor88d292c2010-05-13 16:44:06 +000010260 } else if (MethodDecl->isVirtual())
10261 MarkVTableUsed(Loc, MethodDecl->getParent());
Fariborz Jahanian41f79272009-06-25 21:45:19 +000010262 }
John McCall83779672011-02-19 02:53:41 +000010263
Eli Friedmanfa0df832012-02-02 03:46:19 +000010264 // Recursive functions should be marked when used from another function.
10265 // FIXME: Is this really right?
10266 if (CurContext == Func) return;
Kovarththanan Rajaratnamba2c6522010-03-13 10:17:05 +000010267
Richard Smithd3b5c9082012-07-27 04:22:15 +000010268 // Resolve the exception specification for any function which is
Richard Smithf623c962012-04-17 00:58:00 +000010269 // used: CodeGen will need it.
Richard Smithd3729422012-04-19 00:08:28 +000010270 const FunctionProtoType *FPT = Func->getType()->getAs<FunctionProtoType>();
Richard Smithd3b5c9082012-07-27 04:22:15 +000010271 if (FPT && isUnresolvedExceptionSpec(FPT->getExceptionSpecType()))
10272 ResolveExceptionSpec(Loc, FPT);
Richard Smithf623c962012-04-17 00:58:00 +000010273
Eli Friedmanfa0df832012-02-02 03:46:19 +000010274 // Implicit instantiation of function templates and member functions of
10275 // class templates.
10276 if (Func->isImplicitlyInstantiable()) {
10277 bool AlreadyInstantiated = false;
Richard Smith4a941e22012-02-14 22:25:15 +000010278 SourceLocation PointOfInstantiation = Loc;
Eli Friedmanfa0df832012-02-02 03:46:19 +000010279 if (FunctionTemplateSpecializationInfo *SpecInfo
10280 = Func->getTemplateSpecializationInfo()) {
10281 if (SpecInfo->getPointOfInstantiation().isInvalid())
10282 SpecInfo->setPointOfInstantiation(Loc);
10283 else if (SpecInfo->getTemplateSpecializationKind()
Richard Smith4a941e22012-02-14 22:25:15 +000010284 == TSK_ImplicitInstantiation) {
Eli Friedmanfa0df832012-02-02 03:46:19 +000010285 AlreadyInstantiated = true;
Richard Smith4a941e22012-02-14 22:25:15 +000010286 PointOfInstantiation = SpecInfo->getPointOfInstantiation();
10287 }
Eli Friedmanfa0df832012-02-02 03:46:19 +000010288 } else if (MemberSpecializationInfo *MSInfo
10289 = Func->getMemberSpecializationInfo()) {
10290 if (MSInfo->getPointOfInstantiation().isInvalid())
Douglas Gregor06db9f52009-10-12 20:18:28 +000010291 MSInfo->setPointOfInstantiation(Loc);
Eli Friedmanfa0df832012-02-02 03:46:19 +000010292 else if (MSInfo->getTemplateSpecializationKind()
Richard Smith4a941e22012-02-14 22:25:15 +000010293 == TSK_ImplicitInstantiation) {
Eli Friedmanfa0df832012-02-02 03:46:19 +000010294 AlreadyInstantiated = true;
Richard Smith4a941e22012-02-14 22:25:15 +000010295 PointOfInstantiation = MSInfo->getPointOfInstantiation();
10296 }
Douglas Gregor06db9f52009-10-12 20:18:28 +000010297 }
Mike Stump11289f42009-09-09 15:08:12 +000010298
Richard Smith4a941e22012-02-14 22:25:15 +000010299 if (!AlreadyInstantiated || Func->isConstexpr()) {
Eli Friedmanfa0df832012-02-02 03:46:19 +000010300 if (isa<CXXRecordDecl>(Func->getDeclContext()) &&
10301 cast<CXXRecordDecl>(Func->getDeclContext())->isLocalClass())
Richard Smith4a941e22012-02-14 22:25:15 +000010302 PendingLocalImplicitInstantiations.push_back(
10303 std::make_pair(Func, PointOfInstantiation));
10304 else if (Func->isConstexpr())
Eli Friedmanfa0df832012-02-02 03:46:19 +000010305 // Do not defer instantiations of constexpr functions, to avoid the
10306 // expression evaluator needing to call back into Sema if it sees a
10307 // call to such a function.
Richard Smith4a941e22012-02-14 22:25:15 +000010308 InstantiateFunctionDefinition(PointOfInstantiation, Func);
Argyrios Kyrtzidise5dc5b32012-02-10 20:10:44 +000010309 else {
Richard Smith4a941e22012-02-14 22:25:15 +000010310 PendingInstantiations.push_back(std::make_pair(Func,
10311 PointOfInstantiation));
Argyrios Kyrtzidise5dc5b32012-02-10 20:10:44 +000010312 // Notify the consumer that a function was implicitly instantiated.
10313 Consumer.HandleCXXImplicitFunctionInstantiation(Func);
10314 }
John McCall83779672011-02-19 02:53:41 +000010315 }
Eli Friedmanfa0df832012-02-02 03:46:19 +000010316 } else {
10317 // Walk redefinitions, as some of them may be instantiable.
10318 for (FunctionDecl::redecl_iterator i(Func->redecls_begin()),
10319 e(Func->redecls_end()); i != e; ++i) {
10320 if (!i->isUsed(false) && i->isImplicitlyInstantiable())
10321 MarkFunctionReferenced(Loc, *i);
10322 }
Sam Weinigbae69142009-09-11 03:29:30 +000010323 }
Eli Friedmanfa0df832012-02-02 03:46:19 +000010324
10325 // Keep track of used but undefined functions.
10326 if (!Func->isPure() && !Func->hasBody() &&
10327 Func->getLinkage() != ExternalLinkage) {
10328 SourceLocation &old = UndefinedInternals[Func->getCanonicalDecl()];
10329 if (old.isInvalid()) old = Loc;
10330 }
10331
10332 Func->setUsed(true);
10333}
10334
Eli Friedman9bb33f52012-02-03 02:04:35 +000010335static void
10336diagnoseUncapturableValueReference(Sema &S, SourceLocation loc,
10337 VarDecl *var, DeclContext *DC) {
Eli Friedmandd053f62012-02-07 00:15:00 +000010338 DeclContext *VarDC = var->getDeclContext();
10339
Eli Friedman9bb33f52012-02-03 02:04:35 +000010340 // If the parameter still belongs to the translation unit, then
10341 // we're actually just using one parameter in the declaration of
10342 // the next.
10343 if (isa<ParmVarDecl>(var) &&
Eli Friedmandd053f62012-02-07 00:15:00 +000010344 isa<TranslationUnitDecl>(VarDC))
Eli Friedman9bb33f52012-02-03 02:04:35 +000010345 return;
10346
Eli Friedmandd053f62012-02-07 00:15:00 +000010347 // For C code, don't diagnose about capture if we're not actually in code
10348 // right now; it's impossible to write a non-constant expression outside of
10349 // function context, so we'll get other (more useful) diagnostics later.
10350 //
10351 // For C++, things get a bit more nasty... it would be nice to suppress this
10352 // diagnostic for certain cases like using a local variable in an array bound
10353 // for a member of a local class, but the correct predicate is not obvious.
David Blaikiebbafb8a2012-03-11 07:00:24 +000010354 if (!S.getLangOpts().CPlusPlus && !S.CurContext->isFunctionOrMethod())
Eli Friedman9bb33f52012-02-03 02:04:35 +000010355 return;
10356
Eli Friedmandd053f62012-02-07 00:15:00 +000010357 if (isa<CXXMethodDecl>(VarDC) &&
10358 cast<CXXRecordDecl>(VarDC->getParent())->isLambda()) {
10359 S.Diag(loc, diag::err_reference_to_local_var_in_enclosing_lambda)
10360 << var->getIdentifier();
10361 } else if (FunctionDecl *fn = dyn_cast<FunctionDecl>(VarDC)) {
10362 S.Diag(loc, diag::err_reference_to_local_var_in_enclosing_function)
10363 << var->getIdentifier() << fn->getDeclName();
10364 } else if (isa<BlockDecl>(VarDC)) {
10365 S.Diag(loc, diag::err_reference_to_local_var_in_enclosing_block)
10366 << var->getIdentifier();
10367 } else {
10368 // FIXME: Is there any other context where a local variable can be
10369 // declared?
10370 S.Diag(loc, diag::err_reference_to_local_var_in_enclosing_context)
10371 << var->getIdentifier();
10372 }
Eli Friedman9bb33f52012-02-03 02:04:35 +000010373
Eli Friedman9bb33f52012-02-03 02:04:35 +000010374 S.Diag(var->getLocation(), diag::note_local_variable_declared_here)
10375 << var->getIdentifier();
Eli Friedmandd053f62012-02-07 00:15:00 +000010376
10377 // FIXME: Add additional diagnostic info about class etc. which prevents
10378 // capture.
Eli Friedman9bb33f52012-02-03 02:04:35 +000010379}
10380
Douglas Gregor81495f32012-02-12 18:42:33 +000010381/// \brief Capture the given variable in the given lambda expression.
10382static ExprResult captureInLambda(Sema &S, LambdaScopeInfo *LSI,
Douglas Gregorfdf598e2012-02-18 09:37:24 +000010383 VarDecl *Var, QualType FieldType,
10384 QualType DeclRefType,
Douglas Gregora8182f92012-05-16 17:01:33 +000010385 SourceLocation Loc,
10386 bool RefersToEnclosingLocal) {
Douglas Gregor81495f32012-02-12 18:42:33 +000010387 CXXRecordDecl *Lambda = LSI->Lambda;
Douglas Gregor81495f32012-02-12 18:42:33 +000010388
Douglas Gregorabecb9c2012-02-09 01:56:40 +000010389 // Build the non-static data member.
10390 FieldDecl *Field
10391 = FieldDecl::Create(S.Context, Lambda, Loc, Loc, 0, FieldType,
10392 S.Context.getTrivialTypeSourceInfo(FieldType, Loc),
Richard Smith2b013182012-06-10 03:12:00 +000010393 0, false, ICIS_NoInit);
Douglas Gregorabecb9c2012-02-09 01:56:40 +000010394 Field->setImplicit(true);
10395 Field->setAccess(AS_private);
Douglas Gregor3d23f7882012-02-09 02:12:34 +000010396 Lambda->addDecl(Field);
Douglas Gregorabecb9c2012-02-09 01:56:40 +000010397
10398 // C++11 [expr.prim.lambda]p21:
10399 // When the lambda-expression is evaluated, the entities that
10400 // are captured by copy are used to direct-initialize each
10401 // corresponding non-static data member of the resulting closure
10402 // object. (For array members, the array elements are
10403 // direct-initialized in increasing subscript order.) These
10404 // initializations are performed in the (unspecified) order in
10405 // which the non-static data members are declared.
Douglas Gregorabecb9c2012-02-09 01:56:40 +000010406
Douglas Gregor89625492012-02-09 08:14:43 +000010407 // Introduce a new evaluation context for the initialization, so
10408 // that temporaries introduced as part of the capture are retained
10409 // to be re-"exported" from the lambda expression itself.
Douglas Gregorabecb9c2012-02-09 01:56:40 +000010410 S.PushExpressionEvaluationContext(Sema::PotentiallyEvaluated);
10411
Douglas Gregorf02455e2012-02-10 09:26:04 +000010412 // C++ [expr.prim.labda]p12:
10413 // An entity captured by a lambda-expression is odr-used (3.2) in
10414 // the scope containing the lambda-expression.
Douglas Gregora8182f92012-05-16 17:01:33 +000010415 Expr *Ref = new (S.Context) DeclRefExpr(Var, RefersToEnclosingLocal,
10416 DeclRefType, VK_LValue, Loc);
Eli Friedman23b1be92012-03-01 21:32:56 +000010417 Var->setReferenced(true);
Douglas Gregorf02455e2012-02-10 09:26:04 +000010418 Var->setUsed(true);
Douglas Gregor199cec72012-02-09 02:45:47 +000010419
10420 // When the field has array type, create index variables for each
10421 // dimension of the array. We use these index variables to subscript
10422 // the source array, and other clients (e.g., CodeGen) will perform
10423 // the necessary iteration with these index variables.
10424 SmallVector<VarDecl *, 4> IndexVariables;
Douglas Gregor199cec72012-02-09 02:45:47 +000010425 QualType BaseType = FieldType;
10426 QualType SizeType = S.Context.getSizeType();
Douglas Gregor54fcea62012-02-13 16:35:30 +000010427 LSI->ArrayIndexStarts.push_back(LSI->ArrayIndexVars.size());
Douglas Gregor199cec72012-02-09 02:45:47 +000010428 while (const ConstantArrayType *Array
10429 = S.Context.getAsConstantArrayType(BaseType)) {
Douglas Gregor199cec72012-02-09 02:45:47 +000010430 // Create the iteration variable for this array index.
10431 IdentifierInfo *IterationVarName = 0;
10432 {
10433 SmallString<8> Str;
10434 llvm::raw_svector_ostream OS(Str);
10435 OS << "__i" << IndexVariables.size();
10436 IterationVarName = &S.Context.Idents.get(OS.str());
10437 }
10438 VarDecl *IterationVar
10439 = VarDecl::Create(S.Context, S.CurContext, Loc, Loc,
10440 IterationVarName, SizeType,
10441 S.Context.getTrivialTypeSourceInfo(SizeType, Loc),
10442 SC_None, SC_None);
10443 IndexVariables.push_back(IterationVar);
Douglas Gregor54fcea62012-02-13 16:35:30 +000010444 LSI->ArrayIndexVars.push_back(IterationVar);
10445
Douglas Gregor199cec72012-02-09 02:45:47 +000010446 // Create a reference to the iteration variable.
10447 ExprResult IterationVarRef
10448 = S.BuildDeclRefExpr(IterationVar, SizeType, VK_LValue, Loc);
10449 assert(!IterationVarRef.isInvalid() &&
10450 "Reference to invented variable cannot fail!");
10451 IterationVarRef = S.DefaultLvalueConversion(IterationVarRef.take());
10452 assert(!IterationVarRef.isInvalid() &&
10453 "Conversion of invented variable cannot fail!");
10454
10455 // Subscript the array with this iteration variable.
10456 ExprResult Subscript = S.CreateBuiltinArraySubscriptExpr(
10457 Ref, Loc, IterationVarRef.take(), Loc);
10458 if (Subscript.isInvalid()) {
10459 S.CleanupVarDeclMarking();
10460 S.DiscardCleanupsInEvaluationContext();
10461 S.PopExpressionEvaluationContext();
10462 return ExprError();
10463 }
10464
10465 Ref = Subscript.take();
10466 BaseType = Array->getElementType();
10467 }
10468
10469 // Construct the entity that we will be initializing. For an array, this
10470 // will be first element in the array, which may require several levels
10471 // of array-subscript entities.
10472 SmallVector<InitializedEntity, 4> Entities;
10473 Entities.reserve(1 + IndexVariables.size());
Douglas Gregor19666fb2012-02-15 16:57:26 +000010474 Entities.push_back(
10475 InitializedEntity::InitializeLambdaCapture(Var, Field, Loc));
Douglas Gregor199cec72012-02-09 02:45:47 +000010476 for (unsigned I = 0, N = IndexVariables.size(); I != N; ++I)
10477 Entities.push_back(InitializedEntity::InitializeElement(S.Context,
10478 0,
10479 Entities.back()));
10480
Douglas Gregorabecb9c2012-02-09 01:56:40 +000010481 InitializationKind InitKind
10482 = InitializationKind::CreateDirect(Loc, Loc, Loc);
Douglas Gregor199cec72012-02-09 02:45:47 +000010483 InitializationSequence Init(S, Entities.back(), InitKind, &Ref, 1);
Douglas Gregorabecb9c2012-02-09 01:56:40 +000010484 ExprResult Result(true);
Douglas Gregor199cec72012-02-09 02:45:47 +000010485 if (!Init.Diagnose(S, Entities.back(), InitKind, &Ref, 1))
Benjamin Kramercc4c49d2012-08-23 23:38:35 +000010486 Result = Init.Perform(S, Entities.back(), InitKind, Ref);
Douglas Gregorabecb9c2012-02-09 01:56:40 +000010487
10488 // If this initialization requires any cleanups (e.g., due to a
10489 // default argument to a copy constructor), note that for the
10490 // lambda.
10491 if (S.ExprNeedsCleanups)
10492 LSI->ExprNeedsCleanups = true;
10493
10494 // Exit the expression evaluation context used for the capture.
10495 S.CleanupVarDeclMarking();
10496 S.DiscardCleanupsInEvaluationContext();
10497 S.PopExpressionEvaluationContext();
10498 return Result;
Douglas Gregor199cec72012-02-09 02:45:47 +000010499}
Douglas Gregorabecb9c2012-02-09 01:56:40 +000010500
Douglas Gregorfdf598e2012-02-18 09:37:24 +000010501bool Sema::tryCaptureVariable(VarDecl *Var, SourceLocation Loc,
10502 TryCaptureKind Kind, SourceLocation EllipsisLoc,
10503 bool BuildAndDiagnose,
10504 QualType &CaptureType,
10505 QualType &DeclRefType) {
10506 bool Nested = false;
Douglas Gregor81495f32012-02-12 18:42:33 +000010507
Eli Friedman24af8502012-02-03 22:47:37 +000010508 DeclContext *DC = CurContext;
Douglas Gregorfdf598e2012-02-18 09:37:24 +000010509 if (Var->getDeclContext() == DC) return true;
10510 if (!Var->hasLocalStorage()) return true;
Eli Friedman9bb33f52012-02-03 02:04:35 +000010511
Douglas Gregor81495f32012-02-12 18:42:33 +000010512 bool HasBlocksAttr = Var->hasAttr<BlocksAttr>();
Eli Friedman9bb33f52012-02-03 02:04:35 +000010513
Douglas Gregorfdf598e2012-02-18 09:37:24 +000010514 // Walk up the stack to determine whether we can capture the variable,
10515 // performing the "simple" checks that don't depend on type. We stop when
10516 // we've either hit the declared scope of the variable or find an existing
10517 // capture of that variable.
10518 CaptureType = Var->getType();
10519 DeclRefType = CaptureType.getNonReferenceType();
10520 bool Explicit = (Kind != TryCapture_Implicit);
10521 unsigned FunctionScopesIndex = FunctionScopes.size() - 1;
Eli Friedman9bb33f52012-02-03 02:04:35 +000010522 do {
Eli Friedman24af8502012-02-03 22:47:37 +000010523 // Only block literals and lambda expressions can capture; other
Eli Friedman9bb33f52012-02-03 02:04:35 +000010524 // scopes don't work.
Eli Friedman24af8502012-02-03 22:47:37 +000010525 DeclContext *ParentDC;
10526 if (isa<BlockDecl>(DC))
10527 ParentDC = DC->getParent();
10528 else if (isa<CXXMethodDecl>(DC) &&
Douglas Gregor81495f32012-02-12 18:42:33 +000010529 cast<CXXMethodDecl>(DC)->getOverloadedOperator() == OO_Call &&
Eli Friedman24af8502012-02-03 22:47:37 +000010530 cast<CXXRecordDecl>(DC->getParent())->isLambda())
10531 ParentDC = DC->getParent()->getParent();
Douglas Gregor81495f32012-02-12 18:42:33 +000010532 else {
Douglas Gregorfdf598e2012-02-18 09:37:24 +000010533 if (BuildAndDiagnose)
Douglas Gregor81495f32012-02-12 18:42:33 +000010534 diagnoseUncapturableValueReference(*this, Loc, Var, DC);
Douglas Gregorfdf598e2012-02-18 09:37:24 +000010535 return true;
Douglas Gregor81495f32012-02-12 18:42:33 +000010536 }
Eli Friedman9bb33f52012-02-03 02:04:35 +000010537
Eli Friedman24af8502012-02-03 22:47:37 +000010538 CapturingScopeInfo *CSI =
Douglas Gregor81495f32012-02-12 18:42:33 +000010539 cast<CapturingScopeInfo>(FunctionScopes[FunctionScopesIndex]);
Eli Friedman9bb33f52012-02-03 02:04:35 +000010540
Eli Friedman24af8502012-02-03 22:47:37 +000010541 // Check whether we've already captured it.
Douglas Gregor81495f32012-02-12 18:42:33 +000010542 if (CSI->CaptureMap.count(Var)) {
Douglas Gregorfdf598e2012-02-18 09:37:24 +000010543 // If we found a capture, any subcaptures are nested.
Eli Friedman9bb33f52012-02-03 02:04:35 +000010544 Nested = true;
Douglas Gregorfdf598e2012-02-18 09:37:24 +000010545
10546 // Retrieve the capture type for this variable.
10547 CaptureType = CSI->getCapture(Var).getCaptureType();
10548
10549 // Compute the type of an expression that refers to this variable.
10550 DeclRefType = CaptureType.getNonReferenceType();
10551
10552 const CapturingScopeInfo::Capture &Cap = CSI->getCapture(Var);
10553 if (Cap.isCopyCapture() &&
10554 !(isa<LambdaScopeInfo>(CSI) && cast<LambdaScopeInfo>(CSI)->Mutable))
10555 DeclRefType.addConst();
Eli Friedman9bb33f52012-02-03 02:04:35 +000010556 break;
10557 }
10558
Douglas Gregor81495f32012-02-12 18:42:33 +000010559 bool IsBlock = isa<BlockScopeInfo>(CSI);
Douglas Gregorfdf598e2012-02-18 09:37:24 +000010560 bool IsLambda = !IsBlock;
Eli Friedman24af8502012-02-03 22:47:37 +000010561
10562 // Lambdas are not allowed to capture unnamed variables
10563 // (e.g. anonymous unions).
10564 // FIXME: The C++11 rule don't actually state this explicitly, but I'm
10565 // assuming that's the intent.
Douglas Gregor81495f32012-02-12 18:42:33 +000010566 if (IsLambda && !Var->getDeclName()) {
Douglas Gregorfdf598e2012-02-18 09:37:24 +000010567 if (BuildAndDiagnose) {
Douglas Gregor81495f32012-02-12 18:42:33 +000010568 Diag(Loc, diag::err_lambda_capture_anonymous_var);
10569 Diag(Var->getLocation(), diag::note_declared_at);
10570 }
Douglas Gregorfdf598e2012-02-18 09:37:24 +000010571 return true;
Eli Friedman24af8502012-02-03 22:47:37 +000010572 }
10573
10574 // Prohibit variably-modified types; they're difficult to deal with.
Douglas Gregorfdf598e2012-02-18 09:37:24 +000010575 if (Var->getType()->isVariablyModifiedType()) {
10576 if (BuildAndDiagnose) {
Douglas Gregor81495f32012-02-12 18:42:33 +000010577 if (IsBlock)
10578 Diag(Loc, diag::err_ref_vm_type);
10579 else
10580 Diag(Loc, diag::err_lambda_capture_vm_type) << Var->getDeclName();
10581 Diag(Var->getLocation(), diag::note_previous_decl)
10582 << Var->getDeclName();
10583 }
Douglas Gregorfdf598e2012-02-18 09:37:24 +000010584 return true;
Eli Friedman9bb33f52012-02-03 02:04:35 +000010585 }
10586
Eli Friedman24af8502012-02-03 22:47:37 +000010587 // Lambdas are not allowed to capture __block variables; they don't
10588 // support the expected semantics.
Douglas Gregor81495f32012-02-12 18:42:33 +000010589 if (IsLambda && HasBlocksAttr) {
Douglas Gregorfdf598e2012-02-18 09:37:24 +000010590 if (BuildAndDiagnose) {
Douglas Gregor81495f32012-02-12 18:42:33 +000010591 Diag(Loc, diag::err_lambda_capture_block)
10592 << Var->getDeclName();
10593 Diag(Var->getLocation(), diag::note_previous_decl)
10594 << Var->getDeclName();
10595 }
Douglas Gregorfdf598e2012-02-18 09:37:24 +000010596 return true;
Eli Friedman24af8502012-02-03 22:47:37 +000010597 }
10598
Douglas Gregor81495f32012-02-12 18:42:33 +000010599 if (CSI->ImpCaptureStyle == CapturingScopeInfo::ImpCap_None && !Explicit) {
10600 // No capture-default
Douglas Gregorfdf598e2012-02-18 09:37:24 +000010601 if (BuildAndDiagnose) {
Douglas Gregor81495f32012-02-12 18:42:33 +000010602 Diag(Loc, diag::err_lambda_impcap) << Var->getDeclName();
10603 Diag(Var->getLocation(), diag::note_previous_decl)
10604 << Var->getDeclName();
10605 Diag(cast<LambdaScopeInfo>(CSI)->Lambda->getLocStart(),
10606 diag::note_lambda_decl);
10607 }
Douglas Gregorfdf598e2012-02-18 09:37:24 +000010608 return true;
Douglas Gregor81495f32012-02-12 18:42:33 +000010609 }
10610
10611 FunctionScopesIndex--;
10612 DC = ParentDC;
10613 Explicit = false;
10614 } while (!Var->getDeclContext()->Equals(DC));
10615
Douglas Gregorfdf598e2012-02-18 09:37:24 +000010616 // Walk back down the scope stack, computing the type of the capture at
10617 // each step, checking type-specific requirements, and adding captures if
10618 // requested.
10619 for (unsigned I = ++FunctionScopesIndex, N = FunctionScopes.size(); I != N;
10620 ++I) {
10621 CapturingScopeInfo *CSI = cast<CapturingScopeInfo>(FunctionScopes[I]);
Douglas Gregor812d8f62012-02-18 05:51:20 +000010622
Douglas Gregorfdf598e2012-02-18 09:37:24 +000010623 // Compute the type of the capture and of a reference to the capture within
10624 // this scope.
10625 if (isa<BlockScopeInfo>(CSI)) {
10626 Expr *CopyExpr = 0;
10627 bool ByRef = false;
10628
10629 // Blocks are not allowed to capture arrays.
10630 if (CaptureType->isArrayType()) {
10631 if (BuildAndDiagnose) {
10632 Diag(Loc, diag::err_ref_array_type);
10633 Diag(Var->getLocation(), diag::note_previous_decl)
10634 << Var->getDeclName();
10635 }
10636 return true;
10637 }
10638
John McCall67cd5e02012-03-30 05:23:48 +000010639 // Forbid the block-capture of autoreleasing variables.
10640 if (CaptureType.getObjCLifetime() == Qualifiers::OCL_Autoreleasing) {
10641 if (BuildAndDiagnose) {
10642 Diag(Loc, diag::err_arc_autoreleasing_capture)
10643 << /*block*/ 0;
10644 Diag(Var->getLocation(), diag::note_previous_decl)
10645 << Var->getDeclName();
10646 }
10647 return true;
10648 }
10649
Douglas Gregorfdf598e2012-02-18 09:37:24 +000010650 if (HasBlocksAttr || CaptureType->isReferenceType()) {
10651 // Block capture by reference does not change the capture or
10652 // declaration reference types.
10653 ByRef = true;
10654 } else {
10655 // Block capture by copy introduces 'const'.
10656 CaptureType = CaptureType.getNonReferenceType().withConst();
10657 DeclRefType = CaptureType;
10658
David Blaikiebbafb8a2012-03-11 07:00:24 +000010659 if (getLangOpts().CPlusPlus && BuildAndDiagnose) {
Douglas Gregorfdf598e2012-02-18 09:37:24 +000010660 if (const RecordType *Record = DeclRefType->getAs<RecordType>()) {
10661 // The capture logic needs the destructor, so make sure we mark it.
10662 // Usually this is unnecessary because most local variables have
10663 // their destructors marked at declaration time, but parameters are
10664 // an exception because it's technically only the call site that
10665 // actually requires the destructor.
10666 if (isa<ParmVarDecl>(Var))
10667 FinalizeVarWithDestructor(Var, Record);
10668
10669 // According to the blocks spec, the capture of a variable from
10670 // the stack requires a const copy constructor. This is not true
10671 // of the copy/move done to move a __block variable to the heap.
John McCall113bee02012-03-10 09:33:50 +000010672 Expr *DeclRef = new (Context) DeclRefExpr(Var, false,
Douglas Gregorfdf598e2012-02-18 09:37:24 +000010673 DeclRefType.withConst(),
10674 VK_LValue, Loc);
10675 ExprResult Result
10676 = PerformCopyInitialization(
10677 InitializedEntity::InitializeBlock(Var->getLocation(),
10678 CaptureType, false),
10679 Loc, Owned(DeclRef));
10680
10681 // Build a full-expression copy expression if initialization
10682 // succeeded and used a non-trivial constructor. Recover from
10683 // errors by pretending that the copy isn't necessary.
10684 if (!Result.isInvalid() &&
10685 !cast<CXXConstructExpr>(Result.get())->getConstructor()
10686 ->isTrivial()) {
10687 Result = MaybeCreateExprWithCleanups(Result);
10688 CopyExpr = Result.take();
10689 }
10690 }
10691 }
10692 }
10693
10694 // Actually capture the variable.
10695 if (BuildAndDiagnose)
10696 CSI->addCapture(Var, HasBlocksAttr, ByRef, Nested, Loc,
10697 SourceLocation(), CaptureType, CopyExpr);
10698 Nested = true;
10699 continue;
10700 }
Douglas Gregor812d8f62012-02-18 05:51:20 +000010701
Douglas Gregorfdf598e2012-02-18 09:37:24 +000010702 LambdaScopeInfo *LSI = cast<LambdaScopeInfo>(CSI);
10703
10704 // Determine whether we are capturing by reference or by value.
10705 bool ByRef = false;
10706 if (I == N - 1 && Kind != TryCapture_Implicit) {
10707 ByRef = (Kind == TryCapture_ExplicitByRef);
Eli Friedman24af8502012-02-03 22:47:37 +000010708 } else {
Douglas Gregorfdf598e2012-02-18 09:37:24 +000010709 ByRef = (LSI->ImpCaptureStyle == LambdaScopeInfo::ImpCap_LambdaByref);
Eli Friedman24af8502012-02-03 22:47:37 +000010710 }
Douglas Gregorfdf598e2012-02-18 09:37:24 +000010711
10712 // Compute the type of the field that will capture this variable.
10713 if (ByRef) {
10714 // C++11 [expr.prim.lambda]p15:
10715 // An entity is captured by reference if it is implicitly or
10716 // explicitly captured but not captured by copy. It is
10717 // unspecified whether additional unnamed non-static data
10718 // members are declared in the closure type for entities
10719 // captured by reference.
10720 //
10721 // FIXME: It is not clear whether we want to build an lvalue reference
10722 // to the DeclRefType or to CaptureType.getNonReferenceType(). GCC appears
10723 // to do the former, while EDG does the latter. Core issue 1249 will
10724 // clarify, but for now we follow GCC because it's a more permissive and
10725 // easily defensible position.
10726 CaptureType = Context.getLValueReferenceType(DeclRefType);
10727 } else {
10728 // C++11 [expr.prim.lambda]p14:
10729 // For each entity captured by copy, an unnamed non-static
10730 // data member is declared in the closure type. The
10731 // declaration order of these members is unspecified. The type
10732 // of such a data member is the type of the corresponding
10733 // captured entity if the entity is not a reference to an
10734 // object, or the referenced type otherwise. [Note: If the
10735 // captured entity is a reference to a function, the
10736 // corresponding data member is also a reference to a
10737 // function. - end note ]
10738 if (const ReferenceType *RefType = CaptureType->getAs<ReferenceType>()){
10739 if (!RefType->getPointeeType()->isFunctionType())
10740 CaptureType = RefType->getPointeeType();
Eli Friedman9bb33f52012-02-03 02:04:35 +000010741 }
John McCall67cd5e02012-03-30 05:23:48 +000010742
10743 // Forbid the lambda copy-capture of autoreleasing variables.
10744 if (CaptureType.getObjCLifetime() == Qualifiers::OCL_Autoreleasing) {
10745 if (BuildAndDiagnose) {
10746 Diag(Loc, diag::err_arc_autoreleasing_capture) << /*lambda*/ 1;
10747 Diag(Var->getLocation(), diag::note_previous_decl)
10748 << Var->getDeclName();
10749 }
10750 return true;
10751 }
Eli Friedman9bb33f52012-02-03 02:04:35 +000010752 }
10753
Douglas Gregorfdf598e2012-02-18 09:37:24 +000010754 // Capture this variable in the lambda.
10755 Expr *CopyExpr = 0;
10756 if (BuildAndDiagnose) {
10757 ExprResult Result = captureInLambda(*this, LSI, Var, CaptureType,
Douglas Gregora8182f92012-05-16 17:01:33 +000010758 DeclRefType, Loc,
10759 I == N-1);
Douglas Gregorfdf598e2012-02-18 09:37:24 +000010760 if (!Result.isInvalid())
10761 CopyExpr = Result.take();
10762 }
10763
10764 // Compute the type of a reference to this captured variable.
10765 if (ByRef)
10766 DeclRefType = CaptureType.getNonReferenceType();
10767 else {
10768 // C++ [expr.prim.lambda]p5:
10769 // The closure type for a lambda-expression has a public inline
10770 // function call operator [...]. This function call operator is
10771 // declared const (9.3.1) if and only if the lambda-expression’s
10772 // parameter-declaration-clause is not followed by mutable.
10773 DeclRefType = CaptureType.getNonReferenceType();
10774 if (!LSI->Mutable && !CaptureType->isReferenceType())
10775 DeclRefType.addConst();
10776 }
10777
10778 // Add the capture.
10779 if (BuildAndDiagnose)
10780 CSI->addCapture(Var, /*IsBlock=*/false, ByRef, Nested, Loc,
10781 EllipsisLoc, CaptureType, CopyExpr);
Eli Friedman9bb33f52012-02-03 02:04:35 +000010782 Nested = true;
10783 }
Douglas Gregorfdf598e2012-02-18 09:37:24 +000010784
10785 return false;
10786}
10787
10788bool Sema::tryCaptureVariable(VarDecl *Var, SourceLocation Loc,
10789 TryCaptureKind Kind, SourceLocation EllipsisLoc) {
10790 QualType CaptureType;
10791 QualType DeclRefType;
10792 return tryCaptureVariable(Var, Loc, Kind, EllipsisLoc,
10793 /*BuildAndDiagnose=*/true, CaptureType,
10794 DeclRefType);
10795}
10796
10797QualType Sema::getCapturedDeclRefType(VarDecl *Var, SourceLocation Loc) {
10798 QualType CaptureType;
10799 QualType DeclRefType;
10800
10801 // Determine whether we can capture this variable.
10802 if (tryCaptureVariable(Var, Loc, TryCapture_Implicit, SourceLocation(),
10803 /*BuildAndDiagnose=*/false, CaptureType, DeclRefType))
10804 return QualType();
10805
10806 return DeclRefType;
Eli Friedman9bb33f52012-02-03 02:04:35 +000010807}
10808
Eli Friedman3bda6b12012-02-02 23:15:15 +000010809static void MarkVarDeclODRUsed(Sema &SemaRef, VarDecl *Var,
10810 SourceLocation Loc) {
10811 // Keep track of used but undefined variables.
Eli Friedman130bbd02012-02-04 00:54:05 +000010812 // FIXME: We shouldn't suppress this warning for static data members.
Daniel Dunbar9d355812012-03-09 01:51:51 +000010813 if (Var->hasDefinition(SemaRef.Context) == VarDecl::DeclarationOnly &&
Eli Friedman130bbd02012-02-04 00:54:05 +000010814 Var->getLinkage() != ExternalLinkage &&
10815 !(Var->isStaticDataMember() && Var->hasInit())) {
Eli Friedman3bda6b12012-02-02 23:15:15 +000010816 SourceLocation &old = SemaRef.UndefinedInternals[Var->getCanonicalDecl()];
10817 if (old.isInvalid()) old = Loc;
10818 }
10819
Douglas Gregorfdf598e2012-02-18 09:37:24 +000010820 SemaRef.tryCaptureVariable(Var, Loc);
Eli Friedman9bb33f52012-02-03 02:04:35 +000010821
Eli Friedman3bda6b12012-02-02 23:15:15 +000010822 Var->setUsed(true);
10823}
10824
10825void Sema::UpdateMarkingForLValueToRValue(Expr *E) {
10826 // Per C++11 [basic.def.odr], a variable is odr-used "unless it is
10827 // an object that satisfies the requirements for appearing in a
10828 // constant expression (5.19) and the lvalue-to-rvalue conversion (4.1)
10829 // is immediately applied." This function handles the lvalue-to-rvalue
10830 // conversion part.
10831 MaybeODRUseExprs.erase(E->IgnoreParens());
10832}
10833
Eli Friedmanc6237c62012-02-29 03:16:56 +000010834ExprResult Sema::ActOnConstantExpression(ExprResult Res) {
10835 if (!Res.isUsable())
10836 return Res;
10837
10838 // If a constant-expression is a reference to a variable where we delay
10839 // deciding whether it is an odr-use, just assume we will apply the
10840 // lvalue-to-rvalue conversion. In the one case where this doesn't happen
10841 // (a non-type template argument), we have special handling anyway.
10842 UpdateMarkingForLValueToRValue(Res.get());
10843 return Res;
10844}
10845
Eli Friedman3bda6b12012-02-02 23:15:15 +000010846void Sema::CleanupVarDeclMarking() {
10847 for (llvm::SmallPtrSetIterator<Expr*> i = MaybeODRUseExprs.begin(),
10848 e = MaybeODRUseExprs.end();
10849 i != e; ++i) {
10850 VarDecl *Var;
10851 SourceLocation Loc;
John McCall113bee02012-03-10 09:33:50 +000010852 if (DeclRefExpr *DRE = dyn_cast<DeclRefExpr>(*i)) {
Eli Friedman3bda6b12012-02-02 23:15:15 +000010853 Var = cast<VarDecl>(DRE->getDecl());
10854 Loc = DRE->getLocation();
10855 } else if (MemberExpr *ME = dyn_cast<MemberExpr>(*i)) {
10856 Var = cast<VarDecl>(ME->getMemberDecl());
10857 Loc = ME->getMemberLoc();
10858 } else {
10859 llvm_unreachable("Unexpcted expression");
10860 }
10861
10862 MarkVarDeclODRUsed(*this, Var, Loc);
10863 }
10864
10865 MaybeODRUseExprs.clear();
10866}
10867
10868// Mark a VarDecl referenced, and perform the necessary handling to compute
10869// odr-uses.
10870static void DoMarkVarDeclReferenced(Sema &SemaRef, SourceLocation Loc,
10871 VarDecl *Var, Expr *E) {
Eli Friedmanfa0df832012-02-02 03:46:19 +000010872 Var->setReferenced();
10873
Eli Friedman3bda6b12012-02-02 23:15:15 +000010874 if (!IsPotentiallyEvaluatedContext(SemaRef))
Eli Friedmanfa0df832012-02-02 03:46:19 +000010875 return;
10876
10877 // Implicit instantiation of static data members of class templates.
Richard Smithd3cf2382012-02-15 02:42:50 +000010878 if (Var->isStaticDataMember() && Var->getInstantiatedFromStaticDataMember()) {
Eli Friedmanfa0df832012-02-02 03:46:19 +000010879 MemberSpecializationInfo *MSInfo = Var->getMemberSpecializationInfo();
10880 assert(MSInfo && "Missing member specialization information?");
Richard Smithd3cf2382012-02-15 02:42:50 +000010881 bool AlreadyInstantiated = !MSInfo->getPointOfInstantiation().isInvalid();
10882 if (MSInfo->getTemplateSpecializationKind() == TSK_ImplicitInstantiation &&
Daniel Dunbar9d355812012-03-09 01:51:51 +000010883 (!AlreadyInstantiated ||
10884 Var->isUsableInConstantExpressions(SemaRef.Context))) {
Richard Smithd3cf2382012-02-15 02:42:50 +000010885 if (!AlreadyInstantiated) {
10886 // This is a modification of an existing AST node. Notify listeners.
10887 if (ASTMutationListener *L = SemaRef.getASTMutationListener())
10888 L->StaticDataMemberInstantiated(Var);
10889 MSInfo->setPointOfInstantiation(Loc);
10890 }
10891 SourceLocation PointOfInstantiation = MSInfo->getPointOfInstantiation();
Daniel Dunbar9d355812012-03-09 01:51:51 +000010892 if (Var->isUsableInConstantExpressions(SemaRef.Context))
Eli Friedmanfa0df832012-02-02 03:46:19 +000010893 // Do not defer instantiations of variables which could be used in a
10894 // constant expression.
Richard Smithd3cf2382012-02-15 02:42:50 +000010895 SemaRef.InstantiateStaticDataMemberDefinition(PointOfInstantiation,Var);
Eli Friedmanfa0df832012-02-02 03:46:19 +000010896 else
Richard Smithd3cf2382012-02-15 02:42:50 +000010897 SemaRef.PendingInstantiations.push_back(
10898 std::make_pair(Var, PointOfInstantiation));
Eli Friedmanfa0df832012-02-02 03:46:19 +000010899 }
10900 }
10901
Eli Friedman3bda6b12012-02-02 23:15:15 +000010902 // Per C++11 [basic.def.odr], a variable is odr-used "unless it is
10903 // an object that satisfies the requirements for appearing in a
10904 // constant expression (5.19) and the lvalue-to-rvalue conversion (4.1)
10905 // is immediately applied." We check the first part here, and
10906 // Sema::UpdateMarkingForLValueToRValue deals with the second part.
10907 // Note that we use the C++11 definition everywhere because nothing in
Richard Smith35ecb362012-03-02 04:14:40 +000010908 // C++03 depends on whether we get the C++03 version correct. This does not
10909 // apply to references, since they are not objects.
Eli Friedman3bda6b12012-02-02 23:15:15 +000010910 const VarDecl *DefVD;
Richard Smith35ecb362012-03-02 04:14:40 +000010911 if (E && !isa<ParmVarDecl>(Var) && !Var->getType()->isReferenceType() &&
Daniel Dunbar9d355812012-03-09 01:51:51 +000010912 Var->isUsableInConstantExpressions(SemaRef.Context) &&
Eli Friedman3bda6b12012-02-02 23:15:15 +000010913 Var->getAnyInitializer(DefVD) && DefVD->checkInitIsICE())
10914 SemaRef.MaybeODRUseExprs.insert(E);
10915 else
10916 MarkVarDeclODRUsed(SemaRef, Var, Loc);
10917}
Eli Friedmanfa0df832012-02-02 03:46:19 +000010918
Eli Friedman3bda6b12012-02-02 23:15:15 +000010919/// \brief Mark a variable referenced, and check whether it is odr-used
10920/// (C++ [basic.def.odr]p2, C99 6.9p3). Note that this should not be
10921/// used directly for normal expressions referring to VarDecl.
10922void Sema::MarkVariableReferenced(SourceLocation Loc, VarDecl *Var) {
10923 DoMarkVarDeclReferenced(*this, Loc, Var, 0);
Eli Friedmanfa0df832012-02-02 03:46:19 +000010924}
10925
10926static void MarkExprReferenced(Sema &SemaRef, SourceLocation Loc,
10927 Decl *D, Expr *E) {
Eli Friedman3bda6b12012-02-02 23:15:15 +000010928 if (VarDecl *Var = dyn_cast<VarDecl>(D)) {
10929 DoMarkVarDeclReferenced(SemaRef, Loc, Var, E);
10930 return;
10931 }
10932
Eli Friedmanfa0df832012-02-02 03:46:19 +000010933 SemaRef.MarkAnyDeclReferenced(Loc, D);
Rafael Espindola49e860b2012-06-26 17:45:31 +000010934
10935 // If this is a call to a method via a cast, also mark the method in the
10936 // derived class used in case codegen can devirtualize the call.
10937 const MemberExpr *ME = dyn_cast<MemberExpr>(E);
10938 if (!ME)
10939 return;
10940 CXXMethodDecl *MD = dyn_cast<CXXMethodDecl>(ME->getMemberDecl());
10941 if (!MD)
10942 return;
10943 const Expr *Base = ME->getBase();
Rafael Espindolab7f5a9c2012-06-27 18:18:05 +000010944 const CXXRecordDecl *MostDerivedClassDecl = Base->getBestDynamicClassType();
Rafael Espindola49e860b2012-06-26 17:45:31 +000010945 if (!MostDerivedClassDecl)
10946 return;
10947 CXXMethodDecl *DM = MD->getCorrespondingMethodInClass(MostDerivedClassDecl);
Rafael Espindolaa245edc2012-06-27 17:44:39 +000010948 if (!DM)
10949 return;
Rafael Espindola49e860b2012-06-26 17:45:31 +000010950 SemaRef.MarkAnyDeclReferenced(Loc, DM);
Douglas Gregord3b672c2012-02-16 01:06:16 +000010951}
Eli Friedmanfa0df832012-02-02 03:46:19 +000010952
Eli Friedmanfa0df832012-02-02 03:46:19 +000010953/// \brief Perform reference-marking and odr-use handling for a DeclRefExpr.
10954void Sema::MarkDeclRefReferenced(DeclRefExpr *E) {
10955 MarkExprReferenced(*this, E->getLocation(), E->getDecl(), E);
10956}
10957
10958/// \brief Perform reference-marking and odr-use handling for a MemberExpr.
10959void Sema::MarkMemberReferenced(MemberExpr *E) {
10960 MarkExprReferenced(*this, E->getMemberLoc(), E->getMemberDecl(), E);
10961}
10962
Douglas Gregorf02455e2012-02-10 09:26:04 +000010963/// \brief Perform marking for a reference to an arbitrary declaration. It
Eli Friedmanfa0df832012-02-02 03:46:19 +000010964/// marks the declaration referenced, and performs odr-use checking for functions
10965/// and variables. This method should not be used when building an normal
10966/// expression which refers to a variable.
10967void Sema::MarkAnyDeclReferenced(SourceLocation Loc, Decl *D) {
10968 if (VarDecl *VD = dyn_cast<VarDecl>(D))
10969 MarkVariableReferenced(Loc, VD);
10970 else if (FunctionDecl *FD = dyn_cast<FunctionDecl>(D))
10971 MarkFunctionReferenced(Loc, FD);
10972 else
10973 D->setReferenced();
Douglas Gregorc9c02ed2009-06-19 23:52:42 +000010974}
Anders Carlsson7f84ed92009-10-09 23:51:55 +000010975
Douglas Gregor5597ab42010-05-07 23:12:07 +000010976namespace {
Chandler Carruthaf80f662010-06-09 08:17:30 +000010977 // Mark all of the declarations referenced
Douglas Gregor5597ab42010-05-07 23:12:07 +000010978 // FIXME: Not fully implemented yet! We need to have a better understanding
Chandler Carruthaf80f662010-06-09 08:17:30 +000010979 // of when we're entering
Douglas Gregor5597ab42010-05-07 23:12:07 +000010980 class MarkReferencedDecls : public RecursiveASTVisitor<MarkReferencedDecls> {
10981 Sema &S;
10982 SourceLocation Loc;
Chandler Carruthaf80f662010-06-09 08:17:30 +000010983
Douglas Gregor5597ab42010-05-07 23:12:07 +000010984 public:
10985 typedef RecursiveASTVisitor<MarkReferencedDecls> Inherited;
Chandler Carruthaf80f662010-06-09 08:17:30 +000010986
Douglas Gregor5597ab42010-05-07 23:12:07 +000010987 MarkReferencedDecls(Sema &S, SourceLocation Loc) : S(S), Loc(Loc) { }
Chandler Carruthaf80f662010-06-09 08:17:30 +000010988
10989 bool TraverseTemplateArgument(const TemplateArgument &Arg);
10990 bool TraverseRecordType(RecordType *T);
Douglas Gregor5597ab42010-05-07 23:12:07 +000010991 };
10992}
10993
Chandler Carruthaf80f662010-06-09 08:17:30 +000010994bool MarkReferencedDecls::TraverseTemplateArgument(
10995 const TemplateArgument &Arg) {
Douglas Gregor5597ab42010-05-07 23:12:07 +000010996 if (Arg.getKind() == TemplateArgument::Declaration) {
Douglas Gregor31f55dc2012-04-06 22:40:38 +000010997 if (Decl *D = Arg.getAsDecl())
10998 S.MarkAnyDeclReferenced(Loc, D);
Douglas Gregor5597ab42010-05-07 23:12:07 +000010999 }
Chandler Carruthaf80f662010-06-09 08:17:30 +000011000
11001 return Inherited::TraverseTemplateArgument(Arg);
Douglas Gregor5597ab42010-05-07 23:12:07 +000011002}
11003
Chandler Carruthaf80f662010-06-09 08:17:30 +000011004bool MarkReferencedDecls::TraverseRecordType(RecordType *T) {
Douglas Gregor5597ab42010-05-07 23:12:07 +000011005 if (ClassTemplateSpecializationDecl *Spec
11006 = dyn_cast<ClassTemplateSpecializationDecl>(T->getDecl())) {
11007 const TemplateArgumentList &Args = Spec->getTemplateArgs();
Douglas Gregor1ccc8412010-11-07 23:05:16 +000011008 return TraverseTemplateArguments(Args.data(), Args.size());
Douglas Gregor5597ab42010-05-07 23:12:07 +000011009 }
11010
Chandler Carruthc65667c2010-06-10 10:31:57 +000011011 return true;
Douglas Gregor5597ab42010-05-07 23:12:07 +000011012}
11013
11014void Sema::MarkDeclarationsReferencedInType(SourceLocation Loc, QualType T) {
11015 MarkReferencedDecls Marker(*this, Loc);
Chandler Carruthaf80f662010-06-09 08:17:30 +000011016 Marker.TraverseType(Context.getCanonicalType(T));
Douglas Gregor5597ab42010-05-07 23:12:07 +000011017}
11018
Douglas Gregor8a01b2a2010-09-11 20:24:53 +000011019namespace {
11020 /// \brief Helper class that marks all of the declarations referenced by
11021 /// potentially-evaluated subexpressions as "referenced".
11022 class EvaluatedExprMarker : public EvaluatedExprVisitor<EvaluatedExprMarker> {
11023 Sema &S;
Douglas Gregor680e9e02012-02-21 19:11:17 +000011024 bool SkipLocalVariables;
Douglas Gregor8a01b2a2010-09-11 20:24:53 +000011025
11026 public:
11027 typedef EvaluatedExprVisitor<EvaluatedExprMarker> Inherited;
11028
Douglas Gregor680e9e02012-02-21 19:11:17 +000011029 EvaluatedExprMarker(Sema &S, bool SkipLocalVariables)
11030 : Inherited(S.Context), S(S), SkipLocalVariables(SkipLocalVariables) { }
Douglas Gregor8a01b2a2010-09-11 20:24:53 +000011031
11032 void VisitDeclRefExpr(DeclRefExpr *E) {
Douglas Gregor680e9e02012-02-21 19:11:17 +000011033 // If we were asked not to visit local variables, don't.
11034 if (SkipLocalVariables) {
11035 if (VarDecl *VD = dyn_cast<VarDecl>(E->getDecl()))
11036 if (VD->hasLocalStorage())
11037 return;
11038 }
11039
Eli Friedmanfa0df832012-02-02 03:46:19 +000011040 S.MarkDeclRefReferenced(E);
Douglas Gregor8a01b2a2010-09-11 20:24:53 +000011041 }
11042
11043 void VisitMemberExpr(MemberExpr *E) {
Eli Friedmanfa0df832012-02-02 03:46:19 +000011044 S.MarkMemberReferenced(E);
Douglas Gregor32b3de52010-09-11 23:32:50 +000011045 Inherited::VisitMemberExpr(E);
Douglas Gregor8a01b2a2010-09-11 20:24:53 +000011046 }
11047
John McCall28fc7092011-11-10 05:35:25 +000011048 void VisitCXXBindTemporaryExpr(CXXBindTemporaryExpr *E) {
Eli Friedmanfa0df832012-02-02 03:46:19 +000011049 S.MarkFunctionReferenced(E->getLocStart(),
John McCall28fc7092011-11-10 05:35:25 +000011050 const_cast<CXXDestructorDecl*>(E->getTemporary()->getDestructor()));
11051 Visit(E->getSubExpr());
11052 }
11053
Douglas Gregor8a01b2a2010-09-11 20:24:53 +000011054 void VisitCXXNewExpr(CXXNewExpr *E) {
Douglas Gregor8a01b2a2010-09-11 20:24:53 +000011055 if (E->getOperatorNew())
Eli Friedmanfa0df832012-02-02 03:46:19 +000011056 S.MarkFunctionReferenced(E->getLocStart(), E->getOperatorNew());
Douglas Gregor8a01b2a2010-09-11 20:24:53 +000011057 if (E->getOperatorDelete())
Eli Friedmanfa0df832012-02-02 03:46:19 +000011058 S.MarkFunctionReferenced(E->getLocStart(), E->getOperatorDelete());
Douglas Gregor32b3de52010-09-11 23:32:50 +000011059 Inherited::VisitCXXNewExpr(E);
Douglas Gregor8a01b2a2010-09-11 20:24:53 +000011060 }
Sebastian Redl6047f072012-02-16 12:22:20 +000011061
Douglas Gregor8a01b2a2010-09-11 20:24:53 +000011062 void VisitCXXDeleteExpr(CXXDeleteExpr *E) {
11063 if (E->getOperatorDelete())
Eli Friedmanfa0df832012-02-02 03:46:19 +000011064 S.MarkFunctionReferenced(E->getLocStart(), E->getOperatorDelete());
Douglas Gregor6ed2fee2010-09-14 22:55:20 +000011065 QualType Destroyed = S.Context.getBaseElementType(E->getDestroyedType());
11066 if (const RecordType *DestroyedRec = Destroyed->getAs<RecordType>()) {
11067 CXXRecordDecl *Record = cast<CXXRecordDecl>(DestroyedRec->getDecl());
Eli Friedmanfa0df832012-02-02 03:46:19 +000011068 S.MarkFunctionReferenced(E->getLocStart(),
Douglas Gregor6ed2fee2010-09-14 22:55:20 +000011069 S.LookupDestructor(Record));
11070 }
11071
Douglas Gregor32b3de52010-09-11 23:32:50 +000011072 Inherited::VisitCXXDeleteExpr(E);
Douglas Gregor8a01b2a2010-09-11 20:24:53 +000011073 }
11074
11075 void VisitCXXConstructExpr(CXXConstructExpr *E) {
Eli Friedmanfa0df832012-02-02 03:46:19 +000011076 S.MarkFunctionReferenced(E->getLocStart(), E->getConstructor());
Douglas Gregor32b3de52010-09-11 23:32:50 +000011077 Inherited::VisitCXXConstructExpr(E);
Douglas Gregor8a01b2a2010-09-11 20:24:53 +000011078 }
11079
Douglas Gregorf0873f42010-10-19 17:17:35 +000011080 void VisitCXXDefaultArgExpr(CXXDefaultArgExpr *E) {
11081 Visit(E->getExpr());
11082 }
Eli Friedman3bda6b12012-02-02 23:15:15 +000011083
11084 void VisitImplicitCastExpr(ImplicitCastExpr *E) {
11085 Inherited::VisitImplicitCastExpr(E);
11086
11087 if (E->getCastKind() == CK_LValueToRValue)
11088 S.UpdateMarkingForLValueToRValue(E->getSubExpr());
11089 }
Douglas Gregor8a01b2a2010-09-11 20:24:53 +000011090 };
11091}
11092
11093/// \brief Mark any declarations that appear within this expression or any
11094/// potentially-evaluated subexpressions as "referenced".
Douglas Gregor680e9e02012-02-21 19:11:17 +000011095///
11096/// \param SkipLocalVariables If true, don't mark local variables as
11097/// 'referenced'.
11098void Sema::MarkDeclarationsReferencedInExpr(Expr *E,
11099 bool SkipLocalVariables) {
11100 EvaluatedExprMarker(*this, SkipLocalVariables).Visit(E);
Douglas Gregor8a01b2a2010-09-11 20:24:53 +000011101}
11102
Douglas Gregorda8cdbc2009-12-22 01:01:55 +000011103/// \brief Emit a diagnostic that describes an effect on the run-time behavior
11104/// of the program being compiled.
11105///
11106/// This routine emits the given diagnostic when the code currently being
Kovarththanan Rajaratnamba2c6522010-03-13 10:17:05 +000011107/// type-checked is "potentially evaluated", meaning that there is a
Douglas Gregorda8cdbc2009-12-22 01:01:55 +000011108/// possibility that the code will actually be executable. Code in sizeof()
11109/// expressions, code used only during overload resolution, etc., are not
11110/// potentially evaluated. This routine will suppress such diagnostics or,
11111/// in the absolutely nutty case of potentially potentially evaluated
Kovarththanan Rajaratnamba2c6522010-03-13 10:17:05 +000011112/// expressions (C++ typeid), queue the diagnostic to potentially emit it
Douglas Gregorda8cdbc2009-12-22 01:01:55 +000011113/// later.
Kovarththanan Rajaratnamba2c6522010-03-13 10:17:05 +000011114///
Douglas Gregorda8cdbc2009-12-22 01:01:55 +000011115/// This routine should be used for all diagnostics that describe the run-time
11116/// behavior of a program, such as passing a non-POD value through an ellipsis.
11117/// Failure to do so will likely result in spurious diagnostics or failures
11118/// during overload resolution or within sizeof/alignof/typeof/typeid.
Richard Trieuba63ce62011-09-09 01:45:06 +000011119bool Sema::DiagRuntimeBehavior(SourceLocation Loc, const Stmt *Statement,
Douglas Gregorda8cdbc2009-12-22 01:01:55 +000011120 const PartialDiagnostic &PD) {
John McCall31168b02011-06-15 23:02:42 +000011121 switch (ExprEvalContexts.back().Context) {
Douglas Gregorda8cdbc2009-12-22 01:01:55 +000011122 case Unevaluated:
11123 // The argument will never be evaluated, so don't complain.
11124 break;
Kovarththanan Rajaratnamba2c6522010-03-13 10:17:05 +000011125
Richard Smith764d2fe2011-12-20 02:08:33 +000011126 case ConstantEvaluated:
11127 // Relevant diagnostics should be produced by constant evaluation.
11128 break;
11129
Douglas Gregorda8cdbc2009-12-22 01:01:55 +000011130 case PotentiallyEvaluated:
Douglas Gregor8a01b2a2010-09-11 20:24:53 +000011131 case PotentiallyEvaluatedIfUsed:
Richard Trieuba63ce62011-09-09 01:45:06 +000011132 if (Statement && getCurFunctionOrMethodDecl()) {
Ted Kremenek3427fac2011-02-23 01:52:04 +000011133 FunctionScopes.back()->PossiblyUnreachableDiags.
Richard Trieuba63ce62011-09-09 01:45:06 +000011134 push_back(sema::PossiblyUnreachableDiag(PD, Loc, Statement));
Ted Kremenek3427fac2011-02-23 01:52:04 +000011135 }
11136 else
11137 Diag(Loc, PD);
11138
Douglas Gregorda8cdbc2009-12-22 01:01:55 +000011139 return true;
Douglas Gregorda8cdbc2009-12-22 01:01:55 +000011140 }
11141
11142 return false;
11143}
11144
Anders Carlsson7f84ed92009-10-09 23:51:55 +000011145bool Sema::CheckCallReturnType(QualType ReturnType, SourceLocation Loc,
11146 CallExpr *CE, FunctionDecl *FD) {
11147 if (ReturnType->isVoidType() || !ReturnType->isIncompleteType())
11148 return false;
11149
Richard Smithfd555f62012-02-22 02:04:18 +000011150 // If we're inside a decltype's expression, don't check for a valid return
11151 // type or construct temporaries until we know whether this is the last call.
11152 if (ExprEvalContexts.back().IsDecltype) {
11153 ExprEvalContexts.back().DelayedDecltypeCalls.push_back(CE);
11154 return false;
11155 }
11156
Douglas Gregora6c5abb2012-05-04 16:48:41 +000011157 class CallReturnIncompleteDiagnoser : public TypeDiagnoser {
Douglas Gregor7bfb2d02012-05-04 16:32:21 +000011158 FunctionDecl *FD;
11159 CallExpr *CE;
11160
11161 public:
11162 CallReturnIncompleteDiagnoser(FunctionDecl *FD, CallExpr *CE)
11163 : FD(FD), CE(CE) { }
11164
11165 virtual void diagnose(Sema &S, SourceLocation Loc, QualType T) {
11166 if (!FD) {
11167 S.Diag(Loc, diag::err_call_incomplete_return)
11168 << T << CE->getSourceRange();
11169 return;
11170 }
11171
11172 S.Diag(Loc, diag::err_call_function_incomplete_return)
11173 << CE->getSourceRange() << FD->getDeclName() << T;
11174 S.Diag(FD->getLocation(),
11175 diag::note_function_with_incomplete_return_type_declared_here)
11176 << FD->getDeclName();
11177 }
11178 } Diagnoser(FD, CE);
11179
11180 if (RequireCompleteType(Loc, ReturnType, Diagnoser))
Anders Carlsson7f84ed92009-10-09 23:51:55 +000011181 return true;
11182
11183 return false;
11184}
11185
Douglas Gregor2d4f64f2011-01-19 16:50:08 +000011186// Diagnose the s/=/==/ and s/\|=/!=/ typos. Note that adding parentheses
John McCalld5707ab2009-10-12 21:59:07 +000011187// will prevent this condition from triggering, which is what we want.
11188void Sema::DiagnoseAssignmentAsCondition(Expr *E) {
11189 SourceLocation Loc;
11190
John McCall0506e4a2009-11-11 02:41:58 +000011191 unsigned diagnostic = diag::warn_condition_is_assignment;
Douglas Gregor2d4f64f2011-01-19 16:50:08 +000011192 bool IsOrAssign = false;
John McCall0506e4a2009-11-11 02:41:58 +000011193
Chandler Carruthf87d6c02011-08-16 22:30:10 +000011194 if (BinaryOperator *Op = dyn_cast<BinaryOperator>(E)) {
Douglas Gregor2d4f64f2011-01-19 16:50:08 +000011195 if (Op->getOpcode() != BO_Assign && Op->getOpcode() != BO_OrAssign)
John McCalld5707ab2009-10-12 21:59:07 +000011196 return;
11197
Douglas Gregor2d4f64f2011-01-19 16:50:08 +000011198 IsOrAssign = Op->getOpcode() == BO_OrAssign;
11199
John McCallb0e419e2009-11-12 00:06:05 +000011200 // Greylist some idioms by putting them into a warning subcategory.
11201 if (ObjCMessageExpr *ME
11202 = dyn_cast<ObjCMessageExpr>(Op->getRHS()->IgnoreParenCasts())) {
11203 Selector Sel = ME->getSelector();
11204
John McCallb0e419e2009-11-12 00:06:05 +000011205 // self = [<foo> init...]
Douglas Gregor486b74e2011-09-27 16:10:05 +000011206 if (isSelfExpr(Op->getLHS()) && Sel.getNameForSlot(0).startswith("init"))
John McCallb0e419e2009-11-12 00:06:05 +000011207 diagnostic = diag::warn_condition_is_idiomatic_assignment;
11208
11209 // <foo> = [<bar> nextObject]
Douglas Gregoraf2a6ae2011-02-18 22:29:55 +000011210 else if (Sel.isUnarySelector() && Sel.getNameForSlot(0) == "nextObject")
John McCallb0e419e2009-11-12 00:06:05 +000011211 diagnostic = diag::warn_condition_is_idiomatic_assignment;
11212 }
John McCall0506e4a2009-11-11 02:41:58 +000011213
John McCalld5707ab2009-10-12 21:59:07 +000011214 Loc = Op->getOperatorLoc();
Chandler Carruthf87d6c02011-08-16 22:30:10 +000011215 } else if (CXXOperatorCallExpr *Op = dyn_cast<CXXOperatorCallExpr>(E)) {
Douglas Gregor2d4f64f2011-01-19 16:50:08 +000011216 if (Op->getOperator() != OO_Equal && Op->getOperator() != OO_PipeEqual)
John McCalld5707ab2009-10-12 21:59:07 +000011217 return;
11218
Douglas Gregor2d4f64f2011-01-19 16:50:08 +000011219 IsOrAssign = Op->getOperator() == OO_PipeEqual;
John McCalld5707ab2009-10-12 21:59:07 +000011220 Loc = Op->getOperatorLoc();
Fariborz Jahanianf07bcc52012-08-29 17:17:11 +000011221 } else if (PseudoObjectExpr *POE = dyn_cast<PseudoObjectExpr>(E))
11222 return DiagnoseAssignmentAsCondition(POE->getSyntacticForm());
11223 else {
John McCalld5707ab2009-10-12 21:59:07 +000011224 // Not an assignment.
11225 return;
11226 }
11227
Douglas Gregor2bf2d3d2010-04-14 16:09:52 +000011228 Diag(Loc, diagnostic) << E->getSourceRange();
Douglas Gregor2d4f64f2011-01-19 16:50:08 +000011229
Daniel Dunbar62ee6412012-03-09 18:35:03 +000011230 SourceLocation Open = E->getLocStart();
Argyrios Kyrtzidise1b97c42011-04-25 23:01:29 +000011231 SourceLocation Close = PP.getLocForEndOfToken(E->getSourceRange().getEnd());
11232 Diag(Loc, diag::note_condition_assign_silence)
11233 << FixItHint::CreateInsertion(Open, "(")
11234 << FixItHint::CreateInsertion(Close, ")");
11235
Douglas Gregor2d4f64f2011-01-19 16:50:08 +000011236 if (IsOrAssign)
11237 Diag(Loc, diag::note_condition_or_assign_to_comparison)
11238 << FixItHint::CreateReplacement(Loc, "!=");
11239 else
11240 Diag(Loc, diag::note_condition_assign_to_comparison)
11241 << FixItHint::CreateReplacement(Loc, "==");
John McCalld5707ab2009-10-12 21:59:07 +000011242}
11243
Argyrios Kyrtzidis8b6ec682011-02-01 18:24:22 +000011244/// \brief Redundant parentheses over an equality comparison can indicate
11245/// that the user intended an assignment used as condition.
Richard Trieuba63ce62011-09-09 01:45:06 +000011246void Sema::DiagnoseEqualityWithExtraParens(ParenExpr *ParenE) {
Argyrios Kyrtzidisf4f82782011-02-01 22:23:56 +000011247 // Don't warn if the parens came from a macro.
Richard Trieuba63ce62011-09-09 01:45:06 +000011248 SourceLocation parenLoc = ParenE->getLocStart();
Argyrios Kyrtzidisf4f82782011-02-01 22:23:56 +000011249 if (parenLoc.isInvalid() || parenLoc.isMacroID())
11250 return;
Argyrios Kyrtzidisba699d62011-03-28 23:52:04 +000011251 // Don't warn for dependent expressions.
Richard Trieuba63ce62011-09-09 01:45:06 +000011252 if (ParenE->isTypeDependent())
Argyrios Kyrtzidisba699d62011-03-28 23:52:04 +000011253 return;
Argyrios Kyrtzidisf4f82782011-02-01 22:23:56 +000011254
Richard Trieuba63ce62011-09-09 01:45:06 +000011255 Expr *E = ParenE->IgnoreParens();
Argyrios Kyrtzidis8b6ec682011-02-01 18:24:22 +000011256
11257 if (BinaryOperator *opE = dyn_cast<BinaryOperator>(E))
Argyrios Kyrtzidis582dd682011-02-01 19:32:59 +000011258 if (opE->getOpcode() == BO_EQ &&
11259 opE->getLHS()->IgnoreParenImpCasts()->isModifiableLvalue(Context)
11260 == Expr::MLV_Valid) {
Argyrios Kyrtzidis8b6ec682011-02-01 18:24:22 +000011261 SourceLocation Loc = opE->getOperatorLoc();
Ted Kremenekc358d9f2011-02-01 22:36:09 +000011262
Ted Kremenekae022092011-02-02 02:20:30 +000011263 Diag(Loc, diag::warn_equality_with_extra_parens) << E->getSourceRange();
Daniel Dunbar62ee6412012-03-09 18:35:03 +000011264 SourceRange ParenERange = ParenE->getSourceRange();
Ted Kremenekae022092011-02-02 02:20:30 +000011265 Diag(Loc, diag::note_equality_comparison_silence)
Daniel Dunbar62ee6412012-03-09 18:35:03 +000011266 << FixItHint::CreateRemoval(ParenERange.getBegin())
11267 << FixItHint::CreateRemoval(ParenERange.getEnd());
Argyrios Kyrtzidise1b97c42011-04-25 23:01:29 +000011268 Diag(Loc, diag::note_equality_comparison_to_assign)
11269 << FixItHint::CreateReplacement(Loc, "=");
Argyrios Kyrtzidis8b6ec682011-02-01 18:24:22 +000011270 }
11271}
11272
John Wiegley01296292011-04-08 18:41:53 +000011273ExprResult Sema::CheckBooleanCondition(Expr *E, SourceLocation Loc) {
John McCalld5707ab2009-10-12 21:59:07 +000011274 DiagnoseAssignmentAsCondition(E);
Argyrios Kyrtzidis8b6ec682011-02-01 18:24:22 +000011275 if (ParenExpr *parenE = dyn_cast<ParenExpr>(E))
11276 DiagnoseEqualityWithExtraParens(parenE);
John McCalld5707ab2009-10-12 21:59:07 +000011277
John McCall0009fcc2011-04-26 20:42:42 +000011278 ExprResult result = CheckPlaceholderExpr(E);
11279 if (result.isInvalid()) return ExprError();
11280 E = result.take();
Argyrios Kyrtzidisca766292010-11-01 18:49:26 +000011281
John McCall0009fcc2011-04-26 20:42:42 +000011282 if (!E->isTypeDependent()) {
David Blaikiebbafb8a2012-03-11 07:00:24 +000011283 if (getLangOpts().CPlusPlus)
John McCall34376a62010-12-04 03:47:34 +000011284 return CheckCXXBooleanCondition(E); // C++ 6.4p4
11285
John Wiegley01296292011-04-08 18:41:53 +000011286 ExprResult ERes = DefaultFunctionArrayLvalueConversion(E);
11287 if (ERes.isInvalid())
11288 return ExprError();
11289 E = ERes.take();
John McCall29cb2fd2010-12-04 06:09:13 +000011290
11291 QualType T = E->getType();
John Wiegley01296292011-04-08 18:41:53 +000011292 if (!T->isScalarType()) { // C99 6.8.4.1p1
11293 Diag(Loc, diag::err_typecheck_statement_requires_scalar)
11294 << T << E->getSourceRange();
11295 return ExprError();
11296 }
John McCalld5707ab2009-10-12 21:59:07 +000011297 }
11298
John Wiegley01296292011-04-08 18:41:53 +000011299 return Owned(E);
John McCalld5707ab2009-10-12 21:59:07 +000011300}
Douglas Gregore60e41a2010-05-06 17:25:47 +000011301
John McCalldadc5752010-08-24 06:29:42 +000011302ExprResult Sema::ActOnBooleanCondition(Scope *S, SourceLocation Loc,
Richard Trieuba63ce62011-09-09 01:45:06 +000011303 Expr *SubExpr) {
11304 if (!SubExpr)
Douglas Gregore60e41a2010-05-06 17:25:47 +000011305 return ExprError();
John Wiegley01296292011-04-08 18:41:53 +000011306
Richard Trieuba63ce62011-09-09 01:45:06 +000011307 return CheckBooleanCondition(SubExpr, Loc);
Douglas Gregore60e41a2010-05-06 17:25:47 +000011308}
John McCall36e7fe32010-10-12 00:20:44 +000011309
John McCall31996342011-04-07 08:22:57 +000011310namespace {
John McCall2979fe02011-04-12 00:42:48 +000011311 /// A visitor for rebuilding a call to an __unknown_any expression
11312 /// to have an appropriate type.
11313 struct RebuildUnknownAnyFunction
11314 : StmtVisitor<RebuildUnknownAnyFunction, ExprResult> {
11315
11316 Sema &S;
11317
11318 RebuildUnknownAnyFunction(Sema &S) : S(S) {}
11319
11320 ExprResult VisitStmt(Stmt *S) {
11321 llvm_unreachable("unexpected statement!");
John McCall2979fe02011-04-12 00:42:48 +000011322 }
11323
Richard Trieu10162ab2011-09-09 03:59:41 +000011324 ExprResult VisitExpr(Expr *E) {
11325 S.Diag(E->getExprLoc(), diag::err_unsupported_unknown_any_call)
11326 << E->getSourceRange();
John McCall2979fe02011-04-12 00:42:48 +000011327 return ExprError();
11328 }
11329
11330 /// Rebuild an expression which simply semantically wraps another
11331 /// expression which it shares the type and value kind of.
Richard Trieu10162ab2011-09-09 03:59:41 +000011332 template <class T> ExprResult rebuildSugarExpr(T *E) {
11333 ExprResult SubResult = Visit(E->getSubExpr());
11334 if (SubResult.isInvalid()) return ExprError();
John McCall2979fe02011-04-12 00:42:48 +000011335
Richard Trieu10162ab2011-09-09 03:59:41 +000011336 Expr *SubExpr = SubResult.take();
11337 E->setSubExpr(SubExpr);
11338 E->setType(SubExpr->getType());
11339 E->setValueKind(SubExpr->getValueKind());
11340 assert(E->getObjectKind() == OK_Ordinary);
11341 return E;
John McCall2979fe02011-04-12 00:42:48 +000011342 }
11343
Richard Trieu10162ab2011-09-09 03:59:41 +000011344 ExprResult VisitParenExpr(ParenExpr *E) {
11345 return rebuildSugarExpr(E);
John McCall2979fe02011-04-12 00:42:48 +000011346 }
11347
Richard Trieu10162ab2011-09-09 03:59:41 +000011348 ExprResult VisitUnaryExtension(UnaryOperator *E) {
11349 return rebuildSugarExpr(E);
John McCall2979fe02011-04-12 00:42:48 +000011350 }
11351
Richard Trieu10162ab2011-09-09 03:59:41 +000011352 ExprResult VisitUnaryAddrOf(UnaryOperator *E) {
11353 ExprResult SubResult = Visit(E->getSubExpr());
11354 if (SubResult.isInvalid()) return ExprError();
John McCall2979fe02011-04-12 00:42:48 +000011355
Richard Trieu10162ab2011-09-09 03:59:41 +000011356 Expr *SubExpr = SubResult.take();
11357 E->setSubExpr(SubExpr);
11358 E->setType(S.Context.getPointerType(SubExpr->getType()));
11359 assert(E->getValueKind() == VK_RValue);
11360 assert(E->getObjectKind() == OK_Ordinary);
11361 return E;
John McCall2979fe02011-04-12 00:42:48 +000011362 }
11363
Richard Trieu10162ab2011-09-09 03:59:41 +000011364 ExprResult resolveDecl(Expr *E, ValueDecl *VD) {
11365 if (!isa<FunctionDecl>(VD)) return VisitExpr(E);
John McCall2979fe02011-04-12 00:42:48 +000011366
Richard Trieu10162ab2011-09-09 03:59:41 +000011367 E->setType(VD->getType());
John McCall2979fe02011-04-12 00:42:48 +000011368
Richard Trieu10162ab2011-09-09 03:59:41 +000011369 assert(E->getValueKind() == VK_RValue);
David Blaikiebbafb8a2012-03-11 07:00:24 +000011370 if (S.getLangOpts().CPlusPlus &&
Richard Trieu10162ab2011-09-09 03:59:41 +000011371 !(isa<CXXMethodDecl>(VD) &&
11372 cast<CXXMethodDecl>(VD)->isInstance()))
11373 E->setValueKind(VK_LValue);
John McCall2979fe02011-04-12 00:42:48 +000011374
Richard Trieu10162ab2011-09-09 03:59:41 +000011375 return E;
John McCall2979fe02011-04-12 00:42:48 +000011376 }
11377
Richard Trieu10162ab2011-09-09 03:59:41 +000011378 ExprResult VisitMemberExpr(MemberExpr *E) {
11379 return resolveDecl(E, E->getMemberDecl());
John McCall2979fe02011-04-12 00:42:48 +000011380 }
11381
Richard Trieu10162ab2011-09-09 03:59:41 +000011382 ExprResult VisitDeclRefExpr(DeclRefExpr *E) {
11383 return resolveDecl(E, E->getDecl());
John McCall2979fe02011-04-12 00:42:48 +000011384 }
11385 };
11386}
11387
11388/// Given a function expression of unknown-any type, try to rebuild it
11389/// to have a function type.
Richard Trieu10162ab2011-09-09 03:59:41 +000011390static ExprResult rebuildUnknownAnyFunction(Sema &S, Expr *FunctionExpr) {
11391 ExprResult Result = RebuildUnknownAnyFunction(S).Visit(FunctionExpr);
11392 if (Result.isInvalid()) return ExprError();
11393 return S.DefaultFunctionArrayConversion(Result.take());
John McCall2979fe02011-04-12 00:42:48 +000011394}
11395
11396namespace {
John McCall2d2e8702011-04-11 07:02:50 +000011397 /// A visitor for rebuilding an expression of type __unknown_anytype
11398 /// into one which resolves the type directly on the referring
11399 /// expression. Strict preservation of the original source
11400 /// structure is not a goal.
John McCall31996342011-04-07 08:22:57 +000011401 struct RebuildUnknownAnyExpr
John McCall39439732011-04-09 22:50:59 +000011402 : StmtVisitor<RebuildUnknownAnyExpr, ExprResult> {
John McCall31996342011-04-07 08:22:57 +000011403
11404 Sema &S;
11405
11406 /// The current destination type.
11407 QualType DestType;
11408
Richard Trieu10162ab2011-09-09 03:59:41 +000011409 RebuildUnknownAnyExpr(Sema &S, QualType CastType)
11410 : S(S), DestType(CastType) {}
John McCall31996342011-04-07 08:22:57 +000011411
John McCall39439732011-04-09 22:50:59 +000011412 ExprResult VisitStmt(Stmt *S) {
John McCall2d2e8702011-04-11 07:02:50 +000011413 llvm_unreachable("unexpected statement!");
John McCall31996342011-04-07 08:22:57 +000011414 }
11415
Richard Trieu10162ab2011-09-09 03:59:41 +000011416 ExprResult VisitExpr(Expr *E) {
11417 S.Diag(E->getExprLoc(), diag::err_unsupported_unknown_any_expr)
11418 << E->getSourceRange();
John McCall2d2e8702011-04-11 07:02:50 +000011419 return ExprError();
John McCall31996342011-04-07 08:22:57 +000011420 }
11421
Richard Trieu10162ab2011-09-09 03:59:41 +000011422 ExprResult VisitCallExpr(CallExpr *E);
11423 ExprResult VisitObjCMessageExpr(ObjCMessageExpr *E);
John McCall2d2e8702011-04-11 07:02:50 +000011424
John McCall39439732011-04-09 22:50:59 +000011425 /// Rebuild an expression which simply semantically wraps another
11426 /// expression which it shares the type and value kind of.
Richard Trieu10162ab2011-09-09 03:59:41 +000011427 template <class T> ExprResult rebuildSugarExpr(T *E) {
11428 ExprResult SubResult = Visit(E->getSubExpr());
11429 if (SubResult.isInvalid()) return ExprError();
11430 Expr *SubExpr = SubResult.take();
11431 E->setSubExpr(SubExpr);
11432 E->setType(SubExpr->getType());
11433 E->setValueKind(SubExpr->getValueKind());
11434 assert(E->getObjectKind() == OK_Ordinary);
11435 return E;
John McCall39439732011-04-09 22:50:59 +000011436 }
John McCall31996342011-04-07 08:22:57 +000011437
Richard Trieu10162ab2011-09-09 03:59:41 +000011438 ExprResult VisitParenExpr(ParenExpr *E) {
11439 return rebuildSugarExpr(E);
John McCall39439732011-04-09 22:50:59 +000011440 }
11441
Richard Trieu10162ab2011-09-09 03:59:41 +000011442 ExprResult VisitUnaryExtension(UnaryOperator *E) {
11443 return rebuildSugarExpr(E);
John McCall39439732011-04-09 22:50:59 +000011444 }
11445
Richard Trieu10162ab2011-09-09 03:59:41 +000011446 ExprResult VisitUnaryAddrOf(UnaryOperator *E) {
11447 const PointerType *Ptr = DestType->getAs<PointerType>();
11448 if (!Ptr) {
11449 S.Diag(E->getOperatorLoc(), diag::err_unknown_any_addrof)
11450 << E->getSourceRange();
John McCall2979fe02011-04-12 00:42:48 +000011451 return ExprError();
11452 }
Richard Trieu10162ab2011-09-09 03:59:41 +000011453 assert(E->getValueKind() == VK_RValue);
11454 assert(E->getObjectKind() == OK_Ordinary);
11455 E->setType(DestType);
John McCall2979fe02011-04-12 00:42:48 +000011456
11457 // Build the sub-expression as if it were an object of the pointee type.
Richard Trieu10162ab2011-09-09 03:59:41 +000011458 DestType = Ptr->getPointeeType();
11459 ExprResult SubResult = Visit(E->getSubExpr());
11460 if (SubResult.isInvalid()) return ExprError();
11461 E->setSubExpr(SubResult.take());
11462 return E;
John McCall2979fe02011-04-12 00:42:48 +000011463 }
11464
Richard Trieu10162ab2011-09-09 03:59:41 +000011465 ExprResult VisitImplicitCastExpr(ImplicitCastExpr *E);
John McCall39439732011-04-09 22:50:59 +000011466
Richard Trieu10162ab2011-09-09 03:59:41 +000011467 ExprResult resolveDecl(Expr *E, ValueDecl *VD);
John McCall39439732011-04-09 22:50:59 +000011468
Richard Trieu10162ab2011-09-09 03:59:41 +000011469 ExprResult VisitMemberExpr(MemberExpr *E) {
11470 return resolveDecl(E, E->getMemberDecl());
John McCall2979fe02011-04-12 00:42:48 +000011471 }
John McCall39439732011-04-09 22:50:59 +000011472
Richard Trieu10162ab2011-09-09 03:59:41 +000011473 ExprResult VisitDeclRefExpr(DeclRefExpr *E) {
11474 return resolveDecl(E, E->getDecl());
John McCall31996342011-04-07 08:22:57 +000011475 }
11476 };
11477}
11478
John McCall2d2e8702011-04-11 07:02:50 +000011479/// Rebuilds a call expression which yielded __unknown_anytype.
Richard Trieu10162ab2011-09-09 03:59:41 +000011480ExprResult RebuildUnknownAnyExpr::VisitCallExpr(CallExpr *E) {
11481 Expr *CalleeExpr = E->getCallee();
John McCall2d2e8702011-04-11 07:02:50 +000011482
11483 enum FnKind {
John McCall4adb38c2011-04-27 00:36:17 +000011484 FK_MemberFunction,
John McCall2d2e8702011-04-11 07:02:50 +000011485 FK_FunctionPointer,
11486 FK_BlockPointer
11487 };
11488
Richard Trieu10162ab2011-09-09 03:59:41 +000011489 FnKind Kind;
11490 QualType CalleeType = CalleeExpr->getType();
11491 if (CalleeType == S.Context.BoundMemberTy) {
11492 assert(isa<CXXMemberCallExpr>(E) || isa<CXXOperatorCallExpr>(E));
11493 Kind = FK_MemberFunction;
11494 CalleeType = Expr::findBoundMemberType(CalleeExpr);
11495 } else if (const PointerType *Ptr = CalleeType->getAs<PointerType>()) {
11496 CalleeType = Ptr->getPointeeType();
11497 Kind = FK_FunctionPointer;
John McCall2d2e8702011-04-11 07:02:50 +000011498 } else {
Richard Trieu10162ab2011-09-09 03:59:41 +000011499 CalleeType = CalleeType->castAs<BlockPointerType>()->getPointeeType();
11500 Kind = FK_BlockPointer;
John McCall2d2e8702011-04-11 07:02:50 +000011501 }
Richard Trieu10162ab2011-09-09 03:59:41 +000011502 const FunctionType *FnType = CalleeType->castAs<FunctionType>();
John McCall2d2e8702011-04-11 07:02:50 +000011503
11504 // Verify that this is a legal result type of a function.
11505 if (DestType->isArrayType() || DestType->isFunctionType()) {
11506 unsigned diagID = diag::err_func_returning_array_function;
Richard Trieu10162ab2011-09-09 03:59:41 +000011507 if (Kind == FK_BlockPointer)
John McCall2d2e8702011-04-11 07:02:50 +000011508 diagID = diag::err_block_returning_array_function;
11509
Richard Trieu10162ab2011-09-09 03:59:41 +000011510 S.Diag(E->getExprLoc(), diagID)
John McCall2d2e8702011-04-11 07:02:50 +000011511 << DestType->isFunctionType() << DestType;
11512 return ExprError();
11513 }
11514
11515 // Otherwise, go ahead and set DestType as the call's result.
Richard Trieu10162ab2011-09-09 03:59:41 +000011516 E->setType(DestType.getNonLValueExprType(S.Context));
11517 E->setValueKind(Expr::getValueKindForType(DestType));
11518 assert(E->getObjectKind() == OK_Ordinary);
John McCall2d2e8702011-04-11 07:02:50 +000011519
11520 // Rebuild the function type, replacing the result type with DestType.
Richard Trieu10162ab2011-09-09 03:59:41 +000011521 if (const FunctionProtoType *Proto = dyn_cast<FunctionProtoType>(FnType))
John McCall2d2e8702011-04-11 07:02:50 +000011522 DestType = S.Context.getFunctionType(DestType,
Richard Trieu10162ab2011-09-09 03:59:41 +000011523 Proto->arg_type_begin(),
11524 Proto->getNumArgs(),
11525 Proto->getExtProtoInfo());
John McCall2d2e8702011-04-11 07:02:50 +000011526 else
11527 DestType = S.Context.getFunctionNoProtoType(DestType,
Richard Trieu10162ab2011-09-09 03:59:41 +000011528 FnType->getExtInfo());
John McCall2d2e8702011-04-11 07:02:50 +000011529
11530 // Rebuild the appropriate pointer-to-function type.
Richard Trieu10162ab2011-09-09 03:59:41 +000011531 switch (Kind) {
John McCall4adb38c2011-04-27 00:36:17 +000011532 case FK_MemberFunction:
John McCall2d2e8702011-04-11 07:02:50 +000011533 // Nothing to do.
11534 break;
11535
11536 case FK_FunctionPointer:
11537 DestType = S.Context.getPointerType(DestType);
11538 break;
11539
11540 case FK_BlockPointer:
11541 DestType = S.Context.getBlockPointerType(DestType);
11542 break;
11543 }
11544
11545 // Finally, we can recurse.
Richard Trieu10162ab2011-09-09 03:59:41 +000011546 ExprResult CalleeResult = Visit(CalleeExpr);
11547 if (!CalleeResult.isUsable()) return ExprError();
11548 E->setCallee(CalleeResult.take());
John McCall2d2e8702011-04-11 07:02:50 +000011549
11550 // Bind a temporary if necessary.
Richard Trieu10162ab2011-09-09 03:59:41 +000011551 return S.MaybeBindToTemporary(E);
John McCall2d2e8702011-04-11 07:02:50 +000011552}
11553
Richard Trieu10162ab2011-09-09 03:59:41 +000011554ExprResult RebuildUnknownAnyExpr::VisitObjCMessageExpr(ObjCMessageExpr *E) {
John McCall2979fe02011-04-12 00:42:48 +000011555 // Verify that this is a legal result type of a call.
11556 if (DestType->isArrayType() || DestType->isFunctionType()) {
Richard Trieu10162ab2011-09-09 03:59:41 +000011557 S.Diag(E->getExprLoc(), diag::err_func_returning_array_function)
John McCall2979fe02011-04-12 00:42:48 +000011558 << DestType->isFunctionType() << DestType;
11559 return ExprError();
John McCall2d2e8702011-04-11 07:02:50 +000011560 }
11561
John McCall3f4138c2011-07-13 17:56:40 +000011562 // Rewrite the method result type if available.
Richard Trieu10162ab2011-09-09 03:59:41 +000011563 if (ObjCMethodDecl *Method = E->getMethodDecl()) {
11564 assert(Method->getResultType() == S.Context.UnknownAnyTy);
11565 Method->setResultType(DestType);
John McCall3f4138c2011-07-13 17:56:40 +000011566 }
John McCall2979fe02011-04-12 00:42:48 +000011567
John McCall2d2e8702011-04-11 07:02:50 +000011568 // Change the type of the message.
Richard Trieu10162ab2011-09-09 03:59:41 +000011569 E->setType(DestType.getNonReferenceType());
11570 E->setValueKind(Expr::getValueKindForType(DestType));
John McCall2d2e8702011-04-11 07:02:50 +000011571
Richard Trieu10162ab2011-09-09 03:59:41 +000011572 return S.MaybeBindToTemporary(E);
John McCall2d2e8702011-04-11 07:02:50 +000011573}
11574
Richard Trieu10162ab2011-09-09 03:59:41 +000011575ExprResult RebuildUnknownAnyExpr::VisitImplicitCastExpr(ImplicitCastExpr *E) {
John McCall2979fe02011-04-12 00:42:48 +000011576 // The only case we should ever see here is a function-to-pointer decay.
Sean Callanan2db103c2012-03-06 23:12:57 +000011577 if (E->getCastKind() == CK_FunctionToPointerDecay) {
Sean Callanan12495112012-03-06 21:34:12 +000011578 assert(E->getValueKind() == VK_RValue);
11579 assert(E->getObjectKind() == OK_Ordinary);
11580
11581 E->setType(DestType);
11582
11583 // Rebuild the sub-expression as the pointee (function) type.
11584 DestType = DestType->castAs<PointerType>()->getPointeeType();
11585
11586 ExprResult Result = Visit(E->getSubExpr());
11587 if (!Result.isUsable()) return ExprError();
11588
11589 E->setSubExpr(Result.take());
11590 return S.Owned(E);
Sean Callanan2db103c2012-03-06 23:12:57 +000011591 } else if (E->getCastKind() == CK_LValueToRValue) {
Sean Callanan12495112012-03-06 21:34:12 +000011592 assert(E->getValueKind() == VK_RValue);
11593 assert(E->getObjectKind() == OK_Ordinary);
John McCall2d2e8702011-04-11 07:02:50 +000011594
Sean Callanan12495112012-03-06 21:34:12 +000011595 assert(isa<BlockPointerType>(E->getType()));
John McCall2979fe02011-04-12 00:42:48 +000011596
Sean Callanan12495112012-03-06 21:34:12 +000011597 E->setType(DestType);
John McCall2d2e8702011-04-11 07:02:50 +000011598
Sean Callanan12495112012-03-06 21:34:12 +000011599 // The sub-expression has to be a lvalue reference, so rebuild it as such.
11600 DestType = S.Context.getLValueReferenceType(DestType);
John McCall2d2e8702011-04-11 07:02:50 +000011601
Sean Callanan12495112012-03-06 21:34:12 +000011602 ExprResult Result = Visit(E->getSubExpr());
11603 if (!Result.isUsable()) return ExprError();
11604
11605 E->setSubExpr(Result.take());
11606 return S.Owned(E);
Sean Callanan2db103c2012-03-06 23:12:57 +000011607 } else {
Sean Callanan12495112012-03-06 21:34:12 +000011608 llvm_unreachable("Unhandled cast type!");
11609 }
John McCall2d2e8702011-04-11 07:02:50 +000011610}
11611
Richard Trieu10162ab2011-09-09 03:59:41 +000011612ExprResult RebuildUnknownAnyExpr::resolveDecl(Expr *E, ValueDecl *VD) {
11613 ExprValueKind ValueKind = VK_LValue;
11614 QualType Type = DestType;
John McCall2d2e8702011-04-11 07:02:50 +000011615
11616 // We know how to make this work for certain kinds of decls:
11617
11618 // - functions
Richard Trieu10162ab2011-09-09 03:59:41 +000011619 if (FunctionDecl *FD = dyn_cast<FunctionDecl>(VD)) {
11620 if (const PointerType *Ptr = Type->getAs<PointerType>()) {
11621 DestType = Ptr->getPointeeType();
11622 ExprResult Result = resolveDecl(E, VD);
11623 if (Result.isInvalid()) return ExprError();
11624 return S.ImpCastExprToType(Result.take(), Type,
John McCall9a877fe2011-08-10 04:12:23 +000011625 CK_FunctionToPointerDecay, VK_RValue);
11626 }
11627
Richard Trieu10162ab2011-09-09 03:59:41 +000011628 if (!Type->isFunctionType()) {
11629 S.Diag(E->getExprLoc(), diag::err_unknown_any_function)
11630 << VD << E->getSourceRange();
John McCall9a877fe2011-08-10 04:12:23 +000011631 return ExprError();
11632 }
John McCall2d2e8702011-04-11 07:02:50 +000011633
Richard Trieu10162ab2011-09-09 03:59:41 +000011634 if (CXXMethodDecl *MD = dyn_cast<CXXMethodDecl>(FD))
11635 if (MD->isInstance()) {
11636 ValueKind = VK_RValue;
11637 Type = S.Context.BoundMemberTy;
John McCall4adb38c2011-04-27 00:36:17 +000011638 }
11639
John McCall2d2e8702011-04-11 07:02:50 +000011640 // Function references aren't l-values in C.
David Blaikiebbafb8a2012-03-11 07:00:24 +000011641 if (!S.getLangOpts().CPlusPlus)
Richard Trieu10162ab2011-09-09 03:59:41 +000011642 ValueKind = VK_RValue;
John McCall2d2e8702011-04-11 07:02:50 +000011643
11644 // - variables
Richard Trieu10162ab2011-09-09 03:59:41 +000011645 } else if (isa<VarDecl>(VD)) {
11646 if (const ReferenceType *RefTy = Type->getAs<ReferenceType>()) {
11647 Type = RefTy->getPointeeType();
11648 } else if (Type->isFunctionType()) {
11649 S.Diag(E->getExprLoc(), diag::err_unknown_any_var_function_type)
11650 << VD << E->getSourceRange();
John McCall2979fe02011-04-12 00:42:48 +000011651 return ExprError();
John McCall2d2e8702011-04-11 07:02:50 +000011652 }
11653
11654 // - nothing else
11655 } else {
Richard Trieu10162ab2011-09-09 03:59:41 +000011656 S.Diag(E->getExprLoc(), diag::err_unsupported_unknown_any_decl)
11657 << VD << E->getSourceRange();
John McCall2d2e8702011-04-11 07:02:50 +000011658 return ExprError();
11659 }
11660
Richard Trieu10162ab2011-09-09 03:59:41 +000011661 VD->setType(DestType);
11662 E->setType(Type);
11663 E->setValueKind(ValueKind);
11664 return S.Owned(E);
John McCall2d2e8702011-04-11 07:02:50 +000011665}
11666
John McCall31996342011-04-07 08:22:57 +000011667/// Check a cast of an unknown-any type. We intentionally only
11668/// trigger this for C-style casts.
Richard Trieuba63ce62011-09-09 01:45:06 +000011669ExprResult Sema::checkUnknownAnyCast(SourceRange TypeRange, QualType CastType,
11670 Expr *CastExpr, CastKind &CastKind,
11671 ExprValueKind &VK, CXXCastPath &Path) {
John McCall31996342011-04-07 08:22:57 +000011672 // Rewrite the casted expression from scratch.
Richard Trieuba63ce62011-09-09 01:45:06 +000011673 ExprResult result = RebuildUnknownAnyExpr(*this, CastType).Visit(CastExpr);
John McCall39439732011-04-09 22:50:59 +000011674 if (!result.isUsable()) return ExprError();
John McCall31996342011-04-07 08:22:57 +000011675
Richard Trieuba63ce62011-09-09 01:45:06 +000011676 CastExpr = result.take();
11677 VK = CastExpr->getValueKind();
11678 CastKind = CK_NoOp;
John McCall39439732011-04-09 22:50:59 +000011679
Richard Trieuba63ce62011-09-09 01:45:06 +000011680 return CastExpr;
John McCall31996342011-04-07 08:22:57 +000011681}
11682
Douglas Gregord8fb1e32011-12-01 01:37:36 +000011683ExprResult Sema::forceUnknownAnyToType(Expr *E, QualType ToType) {
11684 return RebuildUnknownAnyExpr(*this, ToType).Visit(E);
11685}
11686
Richard Trieuba63ce62011-09-09 01:45:06 +000011687static ExprResult diagnoseUnknownAnyExpr(Sema &S, Expr *E) {
11688 Expr *orig = E;
John McCall2d2e8702011-04-11 07:02:50 +000011689 unsigned diagID = diag::err_uncasted_use_of_unknown_any;
John McCall31996342011-04-07 08:22:57 +000011690 while (true) {
Richard Trieuba63ce62011-09-09 01:45:06 +000011691 E = E->IgnoreParenImpCasts();
11692 if (CallExpr *call = dyn_cast<CallExpr>(E)) {
11693 E = call->getCallee();
John McCall2d2e8702011-04-11 07:02:50 +000011694 diagID = diag::err_uncasted_call_of_unknown_any;
11695 } else {
John McCall31996342011-04-07 08:22:57 +000011696 break;
John McCall2d2e8702011-04-11 07:02:50 +000011697 }
John McCall31996342011-04-07 08:22:57 +000011698 }
11699
John McCall2d2e8702011-04-11 07:02:50 +000011700 SourceLocation loc;
11701 NamedDecl *d;
Richard Trieuba63ce62011-09-09 01:45:06 +000011702 if (DeclRefExpr *ref = dyn_cast<DeclRefExpr>(E)) {
John McCall2d2e8702011-04-11 07:02:50 +000011703 loc = ref->getLocation();
11704 d = ref->getDecl();
Richard Trieuba63ce62011-09-09 01:45:06 +000011705 } else if (MemberExpr *mem = dyn_cast<MemberExpr>(E)) {
John McCall2d2e8702011-04-11 07:02:50 +000011706 loc = mem->getMemberLoc();
11707 d = mem->getMemberDecl();
Richard Trieuba63ce62011-09-09 01:45:06 +000011708 } else if (ObjCMessageExpr *msg = dyn_cast<ObjCMessageExpr>(E)) {
John McCall2d2e8702011-04-11 07:02:50 +000011709 diagID = diag::err_uncasted_call_of_unknown_any;
Argyrios Kyrtzidisa6011e22011-10-03 06:36:51 +000011710 loc = msg->getSelectorStartLoc();
John McCall2d2e8702011-04-11 07:02:50 +000011711 d = msg->getMethodDecl();
John McCallfa6f5d62011-08-31 20:57:36 +000011712 if (!d) {
11713 S.Diag(loc, diag::err_uncasted_send_to_unknown_any_method)
11714 << static_cast<unsigned>(msg->isClassMessage()) << msg->getSelector()
11715 << orig->getSourceRange();
11716 return ExprError();
11717 }
John McCall2d2e8702011-04-11 07:02:50 +000011718 } else {
Richard Trieuba63ce62011-09-09 01:45:06 +000011719 S.Diag(E->getExprLoc(), diag::err_unsupported_unknown_any_expr)
11720 << E->getSourceRange();
John McCall2d2e8702011-04-11 07:02:50 +000011721 return ExprError();
11722 }
11723
11724 S.Diag(loc, diagID) << d << orig->getSourceRange();
John McCall31996342011-04-07 08:22:57 +000011725
11726 // Never recoverable.
11727 return ExprError();
11728}
11729
John McCall36e7fe32010-10-12 00:20:44 +000011730/// Check for operands with placeholder types and complain if found.
11731/// Returns true if there was an error and no recovery was possible.
John McCall3aef3d82011-04-10 19:13:55 +000011732ExprResult Sema::CheckPlaceholderExpr(Expr *E) {
John McCall4124c492011-10-17 18:40:02 +000011733 const BuiltinType *placeholderType = E->getType()->getAsPlaceholderType();
11734 if (!placeholderType) return Owned(E);
11735
11736 switch (placeholderType->getKind()) {
John McCall36e7fe32010-10-12 00:20:44 +000011737
John McCall31996342011-04-07 08:22:57 +000011738 // Overloaded expressions.
John McCall4124c492011-10-17 18:40:02 +000011739 case BuiltinType::Overload: {
John McCall50a2c2c2011-10-11 23:14:30 +000011740 // Try to resolve a single function template specialization.
11741 // This is obligatory.
11742 ExprResult result = Owned(E);
11743 if (ResolveAndFixSingleFunctionTemplateSpecialization(result, false)) {
11744 return result;
11745
11746 // If that failed, try to recover with a call.
11747 } else {
11748 tryToRecoverWithCall(result, PDiag(diag::err_ovl_unresolvable),
11749 /*complain*/ true);
11750 return result;
11751 }
11752 }
John McCall31996342011-04-07 08:22:57 +000011753
John McCall0009fcc2011-04-26 20:42:42 +000011754 // Bound member functions.
John McCall4124c492011-10-17 18:40:02 +000011755 case BuiltinType::BoundMember: {
John McCall50a2c2c2011-10-11 23:14:30 +000011756 ExprResult result = Owned(E);
11757 tryToRecoverWithCall(result, PDiag(diag::err_bound_member_function),
11758 /*complain*/ true);
11759 return result;
John McCall4124c492011-10-17 18:40:02 +000011760 }
11761
11762 // ARC unbridged casts.
11763 case BuiltinType::ARCUnbridgedCast: {
11764 Expr *realCast = stripARCUnbridgedCast(E);
11765 diagnoseARCUnbridgedCast(realCast);
11766 return Owned(realCast);
11767 }
John McCall0009fcc2011-04-26 20:42:42 +000011768
John McCall31996342011-04-07 08:22:57 +000011769 // Expressions of unknown type.
John McCall4124c492011-10-17 18:40:02 +000011770 case BuiltinType::UnknownAny:
John McCall31996342011-04-07 08:22:57 +000011771 return diagnoseUnknownAnyExpr(*this, E);
11772
John McCall526ab472011-10-25 17:37:35 +000011773 // Pseudo-objects.
11774 case BuiltinType::PseudoObject:
11775 return checkPseudoObjectRValue(E);
11776
Eli Friedman34866c72012-08-31 00:14:07 +000011777 case BuiltinType::BuiltinFn:
11778 Diag(E->getLocStart(), diag::err_builtin_fn_use);
11779 return ExprError();
11780
John McCalle314e272011-10-18 21:02:43 +000011781 // Everything else should be impossible.
11782#define BUILTIN_TYPE(Id, SingletonId) \
11783 case BuiltinType::Id:
11784#define PLACEHOLDER_TYPE(Id, SingletonId)
11785#include "clang/AST/BuiltinTypes.def"
John McCall4124c492011-10-17 18:40:02 +000011786 break;
11787 }
11788
11789 llvm_unreachable("invalid placeholder type!");
John McCall36e7fe32010-10-12 00:20:44 +000011790}
Richard Trieu2c850c02011-04-21 21:44:26 +000011791
Richard Trieuba63ce62011-09-09 01:45:06 +000011792bool Sema::CheckCaseExpression(Expr *E) {
11793 if (E->isTypeDependent())
Richard Trieu2c850c02011-04-21 21:44:26 +000011794 return true;
Richard Trieuba63ce62011-09-09 01:45:06 +000011795 if (E->isValueDependent() || E->isIntegerConstantExpr(Context))
11796 return E->getType()->isIntegralOrEnumerationType();
Richard Trieu2c850c02011-04-21 21:44:26 +000011797 return false;
11798}
Ted Kremeneke65b0862012-03-06 20:05:56 +000011799
11800/// ActOnObjCBoolLiteral - Parse {__objc_yes,__objc_no} literals.
11801ExprResult
11802Sema::ActOnObjCBoolLiteral(SourceLocation OpLoc, tok::TokenKind Kind) {
11803 assert((Kind == tok::kw___objc_yes || Kind == tok::kw___objc_no) &&
11804 "Unknown Objective-C Boolean value!");
Fariborz Jahanianf2578572012-08-30 18:49:41 +000011805 QualType BoolT = Context.ObjCBuiltinBoolTy;
11806 if (!Context.getBOOLDecl()) {
11807 LookupResult Result(*this, &Context.Idents.get("BOOL"), SourceLocation(),
11808 Sema::LookupOrdinaryName);
11809 if (LookupName(Result, getCurScope())) {
11810 NamedDecl *ND = Result.getFoundDecl();
11811 if (TypedefDecl *TD = dyn_cast<TypedefDecl>(ND))
11812 Context.setBOOLDecl(TD);
11813 }
11814 }
11815 if (Context.getBOOLDecl())
11816 BoolT = Context.getBOOLType();
Ted Kremeneke65b0862012-03-06 20:05:56 +000011817 return Owned(new (Context) ObjCBoolLiteralExpr(Kind == tok::kw___objc_yes,
Fariborz Jahanianf2578572012-08-30 18:49:41 +000011818 BoolT, OpLoc));
Ted Kremeneke65b0862012-03-06 20:05:56 +000011819}