blob: c687f1929316da41d6c4876ec7341153a2d1ea6b [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"
Chandler Carruth3a022472012-12-04 09:13:33 +000015#include "TreeTransform.h"
Argyrios Kyrtzidise5dc5b32012-02-10 20:10:44 +000016#include "clang/AST/ASTConsumer.h"
Chandler Carruth3a022472012-12-04 09:13:33 +000017#include "clang/AST/ASTContext.h"
Sebastian Redl2ac2c722011-04-29 08:19:30 +000018#include "clang/AST/ASTMutationListener.h"
Douglas Gregord1702062010-04-29 00:18:15 +000019#include "clang/AST/CXXInheritance.h"
Daniel Dunbar6e8aa532008-08-11 05:35:13 +000020#include "clang/AST/DeclObjC.h"
Anders Carlsson029fc692009-08-26 22:59:12 +000021#include "clang/AST/DeclTemplate.h"
Douglas Gregor8a01b2a2010-09-11 20:24:53 +000022#include "clang/AST/EvaluatedExprVisitor.h"
Douglas Gregor882211c2010-04-28 22:16:22 +000023#include "clang/AST/Expr.h"
Chris Lattneraa9c7ae2008-04-08 04:40:51 +000024#include "clang/AST/ExprCXX.h"
Steve Naroff021ca182008-05-29 21:12:08 +000025#include "clang/AST/ExprObjC.h"
Douglas Gregor5597ab42010-05-07 23:12:07 +000026#include "clang/AST/RecursiveASTVisitor.h"
Douglas Gregor882211c2010-04-28 22:16:22 +000027#include "clang/AST/TypeLoc.h"
Anders Carlsson029fc692009-08-26 22:59:12 +000028#include "clang/Basic/PartialDiagnostic.h"
Steve Narofff2fb89e2007-03-13 20:29:44 +000029#include "clang/Basic/SourceManager.h"
Chris Lattner5b183d82006-11-10 05:03:26 +000030#include "clang/Basic/TargetInfo.h"
Anders Carlsson029fc692009-08-26 22:59:12 +000031#include "clang/Lex/LiteralSupport.h"
32#include "clang/Lex/Preprocessor.h"
Chandler Carruth3a022472012-12-04 09:13:33 +000033#include "clang/Sema/AnalysisBasedWarnings.h"
John McCall8b0666c2010-08-20 18:27:03 +000034#include "clang/Sema/DeclSpec.h"
Chandler Carruth3a022472012-12-04 09:13:33 +000035#include "clang/Sema/DelayedDiagnostic.h"
John McCall8b0666c2010-08-20 18:27:03 +000036#include "clang/Sema/Designator.h"
Chandler Carruth3a022472012-12-04 09:13:33 +000037#include "clang/Sema/Initialization.h"
38#include "clang/Sema/Lookup.h"
39#include "clang/Sema/ParsedTemplate.h"
John McCall8b0666c2010-08-20 18:27:03 +000040#include "clang/Sema/Scope.h"
John McCallaab3e412010-08-25 08:40:02 +000041#include "clang/Sema/ScopeInfo.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"
Chris Lattner5b183d82006-11-10 05:03:26 +000044using namespace clang;
John McCallaab3e412010-08-25 08:40:02 +000045using namespace sema;
Chris Lattner5b183d82006-11-10 05:03:26 +000046
Sebastian Redlb49c46c2011-09-24 17:48:00 +000047/// \brief Determine whether the use of this declaration is valid, without
48/// emitting diagnostics.
49bool Sema::CanUseDecl(NamedDecl *D) {
50 // See if this is an auto-typed variable whose initializer we are parsing.
51 if (ParsingInitForAutoVars.count(D))
52 return false;
53
54 // See if this is a deleted function.
55 if (FunctionDecl *FD = dyn_cast<FunctionDecl>(D)) {
56 if (FD->isDeleted())
57 return false;
Richard Smith2a7d4812013-05-04 07:00:32 +000058
59 // If the function has a deduced return type, and we can't deduce it,
60 // then we can't use it either.
61 if (getLangOpts().CPlusPlus1y && FD->getResultType()->isUndeducedType() &&
62 DeduceReturnType(FD, SourceLocation(), /*Diagnose*/false))
63 return false;
Sebastian Redlb49c46c2011-09-24 17:48:00 +000064 }
Sebastian Redl5999aec2011-10-16 18:19:16 +000065
66 // See if this function is unavailable.
67 if (D->getAvailability() == AR_Unavailable &&
68 cast<Decl>(CurContext)->getAvailability() != AR_Unavailable)
69 return false;
70
Sebastian Redlb49c46c2011-09-24 17:48:00 +000071 return true;
72}
David Chisnall9f57c292009-08-17 16:35:33 +000073
Fariborz Jahanian66c93f42012-09-06 16:43:18 +000074static void DiagnoseUnusedOfDecl(Sema &S, NamedDecl *D, SourceLocation Loc) {
75 // Warn if this is used but marked unused.
76 if (D->hasAttr<UnusedAttr>()) {
Fariborz Jahanian979780f2012-09-06 18:38:58 +000077 const Decl *DC = cast<Decl>(S.getCurObjCLexicalContext());
Fariborz Jahanian66c93f42012-09-06 16:43:18 +000078 if (!DC->hasAttr<UnusedAttr>())
79 S.Diag(Loc, diag::warn_used_but_marked_unused) << D->getDeclName();
80 }
81}
82
Ted Kremenek6eb25622012-02-10 02:45:47 +000083static AvailabilityResult DiagnoseAvailabilityOfDecl(Sema &S,
Fariborz Jahanian6b854c52011-09-29 22:45:21 +000084 NamedDecl *D, SourceLocation Loc,
85 const ObjCInterfaceDecl *UnknownObjCClass) {
86 // See if this declaration is unavailable or deprecated.
87 std::string Message;
88 AvailabilityResult Result = D->getAvailability(&Message);
Fariborz Jahanian25d09c22011-11-28 19:45:58 +000089 if (const EnumConstantDecl *ECD = dyn_cast<EnumConstantDecl>(D))
90 if (Result == AR_Available) {
91 const DeclContext *DC = ECD->getDeclContext();
92 if (const EnumDecl *TheEnumDecl = dyn_cast<EnumDecl>(DC))
93 Result = TheEnumDecl->getAvailability(&Message);
94 }
Jordan Rose2bd991a2012-10-10 16:42:54 +000095
Fariborz Jahanian974c9482012-09-21 20:46:37 +000096 const ObjCPropertyDecl *ObjCPDecl = 0;
Jordan Rose2bd991a2012-10-10 16:42:54 +000097 if (Result == AR_Deprecated || Result == AR_Unavailable) {
98 if (const ObjCMethodDecl *MD = dyn_cast<ObjCMethodDecl>(D)) {
99 if (const ObjCPropertyDecl *PD = MD->findPropertyDecl()) {
100 AvailabilityResult PDeclResult = PD->getAvailability(0);
101 if (PDeclResult == Result)
102 ObjCPDecl = PD;
103 }
Fariborz Jahanian974c9482012-09-21 20:46:37 +0000104 }
Jordan Rose2bd991a2012-10-10 16:42:54 +0000105 }
Fariborz Jahanian25d09c22011-11-28 19:45:58 +0000106
Fariborz Jahanian6b854c52011-09-29 22:45:21 +0000107 switch (Result) {
108 case AR_Available:
109 case AR_NotYetIntroduced:
110 break;
111
112 case AR_Deprecated:
Fariborz Jahanian974c9482012-09-21 20:46:37 +0000113 S.EmitDeprecationWarning(D, Message, Loc, UnknownObjCClass, ObjCPDecl);
Fariborz Jahanian6b854c52011-09-29 22:45:21 +0000114 break;
115
116 case AR_Unavailable:
Ted Kremenek6eb25622012-02-10 02:45:47 +0000117 if (S.getCurContextAvailability() != AR_Unavailable) {
Fariborz Jahanian6b854c52011-09-29 22:45:21 +0000118 if (Message.empty()) {
Fariborz Jahanian974c9482012-09-21 20:46:37 +0000119 if (!UnknownObjCClass) {
Ted Kremenek6eb25622012-02-10 02:45:47 +0000120 S.Diag(Loc, diag::err_unavailable) << D->getDeclName();
Fariborz Jahanian974c9482012-09-21 20:46:37 +0000121 if (ObjCPDecl)
122 S.Diag(ObjCPDecl->getLocation(), diag::note_property_attribute)
123 << ObjCPDecl->getDeclName() << 1;
124 }
Fariborz Jahanian6b854c52011-09-29 22:45:21 +0000125 else
Ted Kremenek6eb25622012-02-10 02:45:47 +0000126 S.Diag(Loc, diag::warn_unavailable_fwdclass_message)
Fariborz Jahanian6b854c52011-09-29 22:45:21 +0000127 << D->getDeclName();
128 }
Fariborz Jahanian974c9482012-09-21 20:46:37 +0000129 else
Ted Kremenek6eb25622012-02-10 02:45:47 +0000130 S.Diag(Loc, diag::err_unavailable_message)
Fariborz Jahanian6b854c52011-09-29 22:45:21 +0000131 << D->getDeclName() << Message;
Fariborz Jahanian974c9482012-09-21 20:46:37 +0000132 S.Diag(D->getLocation(), diag::note_unavailable_here)
133 << isa<FunctionDecl>(D) << false;
134 if (ObjCPDecl)
135 S.Diag(ObjCPDecl->getLocation(), diag::note_property_attribute)
136 << ObjCPDecl->getDeclName() << 1;
Fariborz Jahanian6b854c52011-09-29 22:45:21 +0000137 }
138 break;
139 }
140 return Result;
141}
142
Eli Friedmanebea0f22013-07-18 23:29:14 +0000143/// \brief Emit a note explaining that this function is deleted.
Richard Smith852265f2012-03-30 20:53:28 +0000144void Sema::NoteDeletedFunction(FunctionDecl *Decl) {
Eli Friedmanebea0f22013-07-18 23:29:14 +0000145 assert(Decl->isDeleted());
146
Richard Smith852265f2012-03-30 20:53:28 +0000147 CXXMethodDecl *Method = dyn_cast<CXXMethodDecl>(Decl);
148
Eli Friedmanebea0f22013-07-18 23:29:14 +0000149 if (Method && Method->isDeleted() && Method->isDefaulted()) {
Richard Smith6f1e2c62012-04-02 20:59:25 +0000150 // If the method was explicitly defaulted, point at that declaration.
151 if (!Method->isImplicit())
152 Diag(Decl->getLocation(), diag::note_implicitly_deleted);
153
154 // Try to diagnose why this special member function was implicitly
155 // deleted. This might fail, if that reason no longer applies.
Richard Smith852265f2012-03-30 20:53:28 +0000156 CXXSpecialMember CSM = getSpecialMember(Method);
Richard Smith6f1e2c62012-04-02 20:59:25 +0000157 if (CSM != CXXInvalid)
158 ShouldDeleteSpecialMember(Method, CSM, /*Diagnose=*/true);
159
160 return;
Richard Smith852265f2012-03-30 20:53:28 +0000161 }
162
Eli Friedmanebea0f22013-07-18 23:29:14 +0000163 if (CXXConstructorDecl *CD = dyn_cast<CXXConstructorDecl>(Decl)) {
164 if (CXXConstructorDecl *BaseCD =
165 const_cast<CXXConstructorDecl*>(CD->getInheritedConstructor())) {
166 Diag(Decl->getLocation(), diag::note_inherited_deleted_here);
167 if (BaseCD->isDeleted()) {
168 NoteDeletedFunction(BaseCD);
169 } else {
170 // FIXME: An explanation of why exactly it can't be inherited
171 // would be nice.
172 Diag(BaseCD->getLocation(), diag::note_cannot_inherit);
173 }
174 return;
175 }
176 }
177
Richard Smith852265f2012-03-30 20:53:28 +0000178 Diag(Decl->getLocation(), diag::note_unavailable_here)
Eli Friedmanebea0f22013-07-18 23:29:14 +0000179 << 1 << true;
Richard Smith852265f2012-03-30 20:53:28 +0000180}
181
Jordan Rose28cd12f2012-06-18 22:09:19 +0000182/// \brief Determine whether a FunctionDecl was ever declared with an
183/// explicit storage class.
184static bool hasAnyExplicitStorageClass(const FunctionDecl *D) {
185 for (FunctionDecl::redecl_iterator I = D->redecls_begin(),
186 E = D->redecls_end();
187 I != E; ++I) {
Rafael Espindola6ae7e502013-04-03 19:27:57 +0000188 if (I->getStorageClass() != SC_None)
Jordan Rose28cd12f2012-06-18 22:09:19 +0000189 return true;
190 }
191 return false;
192}
193
194/// \brief Check whether we're in an extern inline function and referring to a
Jordan Rosede9e9762012-06-20 18:50:06 +0000195/// variable or function with internal linkage (C11 6.7.4p3).
Jordan Rose28cd12f2012-06-18 22:09:19 +0000196///
Jordan Rose28cd12f2012-06-18 22:09:19 +0000197/// This is only a warning because we used to silently accept this code, but
Jordan Rosede9e9762012-06-20 18:50:06 +0000198/// in many cases it will not behave correctly. This is not enabled in C++ mode
199/// because the restriction language is a bit weaker (C++11 [basic.def.odr]p6)
200/// and so while there may still be user mistakes, most of the time we can't
201/// prove that there are errors.
Jordan Rose28cd12f2012-06-18 22:09:19 +0000202static void diagnoseUseOfInternalDeclInInlineFunction(Sema &S,
203 const NamedDecl *D,
204 SourceLocation Loc) {
Jordan Rosede9e9762012-06-20 18:50:06 +0000205 // This is disabled under C++; there are too many ways for this to fire in
206 // contexts where the warning is a false positive, or where it is technically
207 // correct but benign.
208 if (S.getLangOpts().CPlusPlus)
209 return;
Jordan Rose28cd12f2012-06-18 22:09:19 +0000210
211 // Check if this is an inlined function or method.
212 FunctionDecl *Current = S.getCurFunctionDecl();
213 if (!Current)
214 return;
215 if (!Current->isInlined())
216 return;
Rafael Espindola3ae00052013-05-13 00:12:11 +0000217 if (!Current->isExternallyVisible())
Jordan Rose28cd12f2012-06-18 22:09:19 +0000218 return;
Rafael Espindola3ae00052013-05-13 00:12:11 +0000219
Jordan Rose28cd12f2012-06-18 22:09:19 +0000220 // Check if the decl has internal linkage.
Rafael Espindola3ae00052013-05-13 00:12:11 +0000221 if (D->getFormalLinkage() != InternalLinkage)
Jordan Rose28cd12f2012-06-18 22:09:19 +0000222 return;
Jordan Rose28cd12f2012-06-18 22:09:19 +0000223
Jordan Rose815fe262012-06-21 05:54:50 +0000224 // Downgrade from ExtWarn to Extension if
225 // (1) the supposedly external inline function is in the main file,
226 // and probably won't be included anywhere else.
227 // (2) the thing we're referencing is a pure function.
228 // (3) the thing we're referencing is another inline function.
229 // This last can give us false negatives, but it's better than warning on
230 // wrappers for simple C library functions.
231 const FunctionDecl *UsedFn = dyn_cast<FunctionDecl>(D);
232 bool DowngradeWarning = S.getSourceManager().isFromMainFile(Loc);
233 if (!DowngradeWarning && UsedFn)
234 DowngradeWarning = UsedFn->isInlined() || UsedFn->hasAttr<ConstAttr>();
235
236 S.Diag(Loc, DowngradeWarning ? diag::ext_internal_in_extern_inline
237 : diag::warn_internal_in_extern_inline)
238 << /*IsVar=*/!UsedFn << D;
Jordan Rose28cd12f2012-06-18 22:09:19 +0000239
John McCallc87d9722013-04-02 02:48:58 +0000240 S.MaybeSuggestAddingStaticToDecl(Current);
Jordan Rose28cd12f2012-06-18 22:09:19 +0000241
242 S.Diag(D->getCanonicalDecl()->getLocation(),
243 diag::note_internal_decl_declared_here)
244 << D;
245}
246
John McCallc87d9722013-04-02 02:48:58 +0000247void Sema::MaybeSuggestAddingStaticToDecl(const FunctionDecl *Cur) {
248 const FunctionDecl *First = Cur->getFirstDeclaration();
249
250 // Suggest "static" on the function, if possible.
251 if (!hasAnyExplicitStorageClass(First)) {
252 SourceLocation DeclBegin = First->getSourceRange().getBegin();
253 Diag(DeclBegin, diag::note_convert_inline_to_static)
254 << Cur << FixItHint::CreateInsertion(DeclBegin, "static ");
255 }
256}
257
Douglas Gregor171c45a2009-02-18 21:56:37 +0000258/// \brief Determine whether the use of this declaration is valid, and
259/// emit any corresponding diagnostics.
260///
261/// This routine diagnoses various problems with referencing
262/// declarations that can occur when using a declaration. For example,
263/// it might warn if a deprecated or unavailable declaration is being
264/// used, or produce an error (and return true) if a C++0x deleted
265/// function is being used.
266///
267/// \returns true if there was an error (this declaration cannot be
268/// referenced), false otherwise.
Chris Lattnerb7df3c62009-10-25 22:31:57 +0000269///
Fariborz Jahanian7d6e11a2010-12-21 00:44:01 +0000270bool Sema::DiagnoseUseOfDecl(NamedDecl *D, SourceLocation Loc,
Fariborz Jahanian6b854c52011-09-29 22:45:21 +0000271 const ObjCInterfaceDecl *UnknownObjCClass) {
David Blaikiebbafb8a2012-03-11 07:00:24 +0000272 if (getLangOpts().CPlusPlus && isa<FunctionDecl>(D)) {
Douglas Gregor5bb5e4a2010-10-12 23:32:35 +0000273 // If there were any diagnostics suppressed by template argument deduction,
274 // emit them now.
Craig Topper79be4cd2013-07-05 04:33:53 +0000275 SuppressedDiagnosticsMap::iterator
Douglas Gregor5bb5e4a2010-10-12 23:32:35 +0000276 Pos = SuppressedDiagnostics.find(D->getCanonicalDecl());
277 if (Pos != SuppressedDiagnostics.end()) {
Chris Lattner0e62c1c2011-07-23 10:55:15 +0000278 SmallVectorImpl<PartialDiagnosticAt> &Suppressed = Pos->second;
Douglas Gregor5bb5e4a2010-10-12 23:32:35 +0000279 for (unsigned I = 0, N = Suppressed.size(); I != N; ++I)
280 Diag(Suppressed[I].first, Suppressed[I].second);
281
282 // Clear out the list of suppressed diagnostics, so that we don't emit
Douglas Gregor20b2ebd2011-03-23 00:50:03 +0000283 // them again for this specialization. However, we don't obsolete this
Douglas Gregor5bb5e4a2010-10-12 23:32:35 +0000284 // entry from the table, because we want to avoid ever emitting these
285 // diagnostics again.
286 Suppressed.clear();
287 }
288 }
289
Richard Smith30482bc2011-02-20 03:19:35 +0000290 // See if this is an auto-typed variable whose initializer we are parsing.
Richard Smithb2bc2e62011-02-21 20:05:19 +0000291 if (ParsingInitForAutoVars.count(D)) {
292 Diag(Loc, diag::err_auto_variable_cannot_appear_in_own_initializer)
293 << D->getDeclName();
294 return true;
Richard Smith30482bc2011-02-20 03:19:35 +0000295 }
296
Douglas Gregor171c45a2009-02-18 21:56:37 +0000297 // See if this is a deleted function.
Douglas Gregorde681d42009-02-24 04:26:15 +0000298 if (FunctionDecl *FD = dyn_cast<FunctionDecl>(D)) {
Douglas Gregor171c45a2009-02-18 21:56:37 +0000299 if (FD->isDeleted()) {
300 Diag(Loc, diag::err_deleted_function_use);
Richard Smith852265f2012-03-30 20:53:28 +0000301 NoteDeletedFunction(FD);
Douglas Gregor171c45a2009-02-18 21:56:37 +0000302 return true;
303 }
Richard Smith2a7d4812013-05-04 07:00:32 +0000304
305 // If the function has a deduced return type, and we can't deduce it,
306 // then we can't use it either.
307 if (getLangOpts().CPlusPlus1y && FD->getResultType()->isUndeducedType() &&
308 DeduceReturnType(FD, Loc))
309 return true;
Douglas Gregorde681d42009-02-24 04:26:15 +0000310 }
Ted Kremenek6eb25622012-02-10 02:45:47 +0000311 DiagnoseAvailabilityOfDecl(*this, D, Loc, UnknownObjCClass);
Douglas Gregor20b2ebd2011-03-23 00:50:03 +0000312
Fariborz Jahanian66c93f42012-09-06 16:43:18 +0000313 DiagnoseUnusedOfDecl(*this, D, Loc);
Jordan Rose2684c682012-06-15 18:19:48 +0000314
Jordan Rose28cd12f2012-06-18 22:09:19 +0000315 diagnoseUseOfInternalDeclInInlineFunction(*this, D, Loc);
Jordan Rose2684c682012-06-15 18:19:48 +0000316
Douglas Gregor171c45a2009-02-18 21:56:37 +0000317 return false;
Chris Lattner4bf74fd2009-02-15 22:43:40 +0000318}
319
Douglas Gregor20b2ebd2011-03-23 00:50:03 +0000320/// \brief Retrieve the message suffix that should be added to a
321/// diagnostic complaining about the given function being deleted or
322/// unavailable.
323std::string Sema::getDeletedOrUnavailableSuffix(const FunctionDecl *FD) {
Douglas Gregor20b2ebd2011-03-23 00:50:03 +0000324 std::string Message;
325 if (FD->getAvailability(&Message))
326 return ": " + Message;
327
328 return std::string();
329}
330
John McCallb46f2872011-09-09 07:56:05 +0000331/// DiagnoseSentinelCalls - This routine checks whether a call or
332/// message-send is to a declaration with the sentinel attribute, and
333/// if so, it checks that the requirements of the sentinel are
334/// satisfied.
Fariborz Jahanian027b8862009-05-13 18:09:35 +0000335void Sema::DiagnoseSentinelCalls(NamedDecl *D, SourceLocation Loc,
Dmitri Gribenko9c785c22013-05-09 21:02:07 +0000336 ArrayRef<Expr *> Args) {
Argyrios Kyrtzidisb4b64ca2009-06-30 02:34:44 +0000337 const SentinelAttr *attr = D->getAttr<SentinelAttr>();
Mike Stump11289f42009-09-09 15:08:12 +0000338 if (!attr)
Fariborz Jahanian9e877212009-05-13 23:20:50 +0000339 return;
Douglas Gregorc298ffc2010-04-22 16:44:27 +0000340
John McCallb46f2872011-09-09 07:56:05 +0000341 // The number of formal parameters of the declaration.
342 unsigned numFormalParams;
Mike Stump11289f42009-09-09 15:08:12 +0000343
John McCallb46f2872011-09-09 07:56:05 +0000344 // The kind of declaration. This is also an index into a %select in
345 // the diagnostic.
346 enum CalleeType { CT_Function, CT_Method, CT_Block } calleeType;
347
Fariborz Jahanian4a528032009-05-14 18:00:00 +0000348 if (ObjCMethodDecl *MD = dyn_cast<ObjCMethodDecl>(D)) {
John McCallb46f2872011-09-09 07:56:05 +0000349 numFormalParams = MD->param_size();
350 calleeType = CT_Method;
Mike Stump12b8ce12009-08-04 21:02:39 +0000351 } else if (FunctionDecl *FD = dyn_cast<FunctionDecl>(D)) {
John McCallb46f2872011-09-09 07:56:05 +0000352 numFormalParams = FD->param_size();
353 calleeType = CT_Function;
354 } else if (isa<VarDecl>(D)) {
355 QualType type = cast<ValueDecl>(D)->getType();
356 const FunctionType *fn = 0;
357 if (const PointerType *ptr = type->getAs<PointerType>()) {
358 fn = ptr->getPointeeType()->getAs<FunctionType>();
359 if (!fn) return;
360 calleeType = CT_Function;
361 } else if (const BlockPointerType *ptr = type->getAs<BlockPointerType>()) {
362 fn = ptr->getPointeeType()->castAs<FunctionType>();
363 calleeType = CT_Block;
364 } else {
Fariborz Jahanian0aa5c452009-05-15 20:33:25 +0000365 return;
John McCallb46f2872011-09-09 07:56:05 +0000366 }
Fariborz Jahanian4a528032009-05-14 18:00:00 +0000367
John McCallb46f2872011-09-09 07:56:05 +0000368 if (const FunctionProtoType *proto = dyn_cast<FunctionProtoType>(fn)) {
369 numFormalParams = proto->getNumArgs();
370 } else {
371 numFormalParams = 0;
372 }
373 } else {
Fariborz Jahanian9e877212009-05-13 23:20:50 +0000374 return;
375 }
John McCallb46f2872011-09-09 07:56:05 +0000376
377 // "nullPos" is the number of formal parameters at the end which
378 // effectively count as part of the variadic arguments. This is
379 // useful if you would prefer to not have *any* formal parameters,
380 // but the language forces you to have at least one.
381 unsigned nullPos = attr->getNullPos();
382 assert((nullPos == 0 || nullPos == 1) && "invalid null position on sentinel");
383 numFormalParams = (nullPos > numFormalParams ? 0 : numFormalParams - nullPos);
384
385 // The number of arguments which should follow the sentinel.
386 unsigned numArgsAfterSentinel = attr->getSentinel();
387
388 // If there aren't enough arguments for all the formal parameters,
389 // the sentinel, and the args after the sentinel, complain.
Dmitri Gribenko9c785c22013-05-09 21:02:07 +0000390 if (Args.size() < numFormalParams + numArgsAfterSentinel + 1) {
Fariborz Jahanian9e877212009-05-13 23:20:50 +0000391 Diag(Loc, diag::warn_not_enough_argument) << D->getDeclName();
Joerg Sonnenbergerffc6d492013-06-26 21:31:47 +0000392 Diag(D->getLocation(), diag::note_sentinel_here) << int(calleeType);
Fariborz Jahanian9e877212009-05-13 23:20:50 +0000393 return;
394 }
John McCallb46f2872011-09-09 07:56:05 +0000395
396 // Otherwise, find the sentinel expression.
Dmitri Gribenko9c785c22013-05-09 21:02:07 +0000397 Expr *sentinelExpr = Args[Args.size() - numArgsAfterSentinel - 1];
John McCall7ddbcf42010-05-06 23:53:00 +0000398 if (!sentinelExpr) return;
John McCall7ddbcf42010-05-06 23:53:00 +0000399 if (sentinelExpr->isValueDependent()) return;
Argyrios Kyrtzidis2e809ce2012-02-03 05:58:16 +0000400 if (Context.isSentinelNullExpr(sentinelExpr)) return;
John McCall7ddbcf42010-05-06 23:53:00 +0000401
John McCallb46f2872011-09-09 07:56:05 +0000402 // Pick a reasonable string to insert. Optimistically use 'nil' or
403 // 'NULL' if those are actually defined in the context. Only use
404 // 'nil' for ObjC methods, where it's much more likely that the
405 // variadic arguments form a list of object pointers.
406 SourceLocation MissingNilLoc
Douglas Gregor5ff4e982011-07-30 08:57:03 +0000407 = PP.getLocForEndOfToken(sentinelExpr->getLocEnd());
408 std::string NullValue;
John McCallb46f2872011-09-09 07:56:05 +0000409 if (calleeType == CT_Method &&
410 PP.getIdentifierInfo("nil")->hasMacroDefinition())
Douglas Gregor5ff4e982011-07-30 08:57:03 +0000411 NullValue = "nil";
412 else if (PP.getIdentifierInfo("NULL")->hasMacroDefinition())
413 NullValue = "NULL";
Douglas Gregor5ff4e982011-07-30 08:57:03 +0000414 else
John McCallb46f2872011-09-09 07:56:05 +0000415 NullValue = "(void*) 0";
Eli Friedman9ab36372011-09-27 23:46:37 +0000416
417 if (MissingNilLoc.isInvalid())
Joerg Sonnenbergerffc6d492013-06-26 21:31:47 +0000418 Diag(Loc, diag::warn_missing_sentinel) << int(calleeType);
Eli Friedman9ab36372011-09-27 23:46:37 +0000419 else
420 Diag(MissingNilLoc, diag::warn_missing_sentinel)
Joerg Sonnenbergerffc6d492013-06-26 21:31:47 +0000421 << int(calleeType)
Eli Friedman9ab36372011-09-27 23:46:37 +0000422 << FixItHint::CreateInsertion(MissingNilLoc, ", " + NullValue);
Joerg Sonnenbergerffc6d492013-06-26 21:31:47 +0000423 Diag(D->getLocation(), diag::note_sentinel_here) << int(calleeType);
Fariborz Jahanian027b8862009-05-13 18:09:35 +0000424}
425
Richard Trieuba63ce62011-09-09 01:45:06 +0000426SourceRange Sema::getExprRange(Expr *E) const {
427 return E ? E->getSourceRange() : SourceRange();
Douglas Gregor87f95b02009-02-26 21:00:50 +0000428}
429
Chris Lattner513165e2008-07-25 21:10:04 +0000430//===----------------------------------------------------------------------===//
431// Standard Promotions and Conversions
432//===----------------------------------------------------------------------===//
433
Chris Lattner513165e2008-07-25 21:10:04 +0000434/// DefaultFunctionArrayConversion (C99 6.3.2.1p3, C99 6.3.2.1p4).
John Wiegley01296292011-04-08 18:41:53 +0000435ExprResult Sema::DefaultFunctionArrayConversion(Expr *E) {
John McCall50a2c2c2011-10-11 23:14:30 +0000436 // Handle any placeholder expressions which made it here.
437 if (E->getType()->isPlaceholderType()) {
438 ExprResult result = CheckPlaceholderExpr(E);
439 if (result.isInvalid()) return ExprError();
440 E = result.take();
441 }
442
Chris Lattner513165e2008-07-25 21:10:04 +0000443 QualType Ty = E->getType();
444 assert(!Ty.isNull() && "DefaultFunctionArrayConversion - missing type");
445
Chris Lattner513165e2008-07-25 21:10:04 +0000446 if (Ty->isFunctionType())
John Wiegley01296292011-04-08 18:41:53 +0000447 E = ImpCastExprToType(E, Context.getPointerType(Ty),
448 CK_FunctionToPointerDecay).take();
Chris Lattner61f60a02008-07-25 21:33:13 +0000449 else if (Ty->isArrayType()) {
450 // In C90 mode, arrays only promote to pointers if the array expression is
451 // an lvalue. The relevant legalese is C90 6.2.2.1p3: "an lvalue that has
452 // type 'array of type' is converted to an expression that has type 'pointer
453 // to type'...". In C99 this was changed to: C99 6.3.2.1p3: "an expression
454 // that has type 'array of type' ...". The relevant change is "an lvalue"
455 // (C90) to "an expression" (C99).
Argyrios Kyrtzidis9321c742008-09-11 04:25:59 +0000456 //
457 // C++ 4.2p1:
458 // An lvalue or rvalue of type "array of N T" or "array of unknown bound of
459 // T" can be converted to an rvalue of type "pointer to T".
460 //
David Blaikiebbafb8a2012-03-11 07:00:24 +0000461 if (getLangOpts().C99 || getLangOpts().CPlusPlus || E->isLValue())
John Wiegley01296292011-04-08 18:41:53 +0000462 E = ImpCastExprToType(E, Context.getArrayDecayedType(Ty),
463 CK_ArrayToPointerDecay).take();
Chris Lattner61f60a02008-07-25 21:33:13 +0000464 }
John Wiegley01296292011-04-08 18:41:53 +0000465 return Owned(E);
Chris Lattner513165e2008-07-25 21:10:04 +0000466}
467
Argyrios Kyrtzidisa9b630e2011-04-26 17:41:22 +0000468static void CheckForNullPointerDereference(Sema &S, Expr *E) {
469 // Check to see if we are dereferencing a null pointer. If so,
470 // and if not volatile-qualified, this is undefined behavior that the
471 // optimizer will delete, so warn about it. People sometimes try to use this
472 // to get a deterministic trap and are surprised by clang's behavior. This
473 // only handles the pattern "*null", which is a very syntactic check.
474 if (UnaryOperator *UO = dyn_cast<UnaryOperator>(E->IgnoreParenCasts()))
475 if (UO->getOpcode() == UO_Deref &&
476 UO->getSubExpr()->IgnoreParenCasts()->
477 isNullPointerConstant(S.Context, Expr::NPC_ValueDependentIsNotNull) &&
478 !UO->getType().isVolatileQualified()) {
479 S.DiagRuntimeBehavior(UO->getOperatorLoc(), UO,
480 S.PDiag(diag::warn_indirection_through_null)
481 << UO->getSubExpr()->getSourceRange());
482 S.DiagRuntimeBehavior(UO->getOperatorLoc(), UO,
483 S.PDiag(diag::note_indirection_through_null));
484 }
485}
486
Fariborz Jahanian3b602ce2013-03-28 23:39:11 +0000487static void DiagnoseDirectIsaAccess(Sema &S, const ObjCIvarRefExpr *OIRE,
Fariborz Jahanianf12ff4df2013-04-02 18:57:54 +0000488 SourceLocation AssignLoc,
489 const Expr* RHS) {
Fariborz Jahanian3b602ce2013-03-28 23:39:11 +0000490 const ObjCIvarDecl *IV = OIRE->getDecl();
491 if (!IV)
492 return;
493
494 DeclarationName MemberName = IV->getDeclName();
495 IdentifierInfo *Member = MemberName.getAsIdentifierInfo();
496 if (!Member || !Member->isStr("isa"))
497 return;
498
499 const Expr *Base = OIRE->getBase();
500 QualType BaseType = Base->getType();
501 if (OIRE->isArrow())
502 BaseType = BaseType->getPointeeType();
503 if (const ObjCObjectType *OTy = BaseType->getAs<ObjCObjectType>())
504 if (ObjCInterfaceDecl *IDecl = OTy->getInterface()) {
505 ObjCInterfaceDecl *ClassDeclared = 0;
506 ObjCIvarDecl *IV = IDecl->lookupInstanceVariable(Member, ClassDeclared);
507 if (!ClassDeclared->getSuperClass()
508 && (*ClassDeclared->ivar_begin()) == IV) {
Fariborz Jahanianf12ff4df2013-04-02 18:57:54 +0000509 if (RHS) {
510 NamedDecl *ObjectSetClass =
511 S.LookupSingleName(S.TUScope,
512 &S.Context.Idents.get("object_setClass"),
513 SourceLocation(), S.LookupOrdinaryName);
514 if (ObjectSetClass) {
515 SourceLocation RHSLocEnd = S.PP.getLocForEndOfToken(RHS->getLocEnd());
516 S.Diag(OIRE->getExprLoc(), diag::warn_objc_isa_assign) <<
517 FixItHint::CreateInsertion(OIRE->getLocStart(), "object_setClass(") <<
518 FixItHint::CreateReplacement(SourceRange(OIRE->getOpLoc(),
519 AssignLoc), ",") <<
520 FixItHint::CreateInsertion(RHSLocEnd, ")");
521 }
522 else
523 S.Diag(OIRE->getLocation(), diag::warn_objc_isa_assign);
524 } else {
525 NamedDecl *ObjectGetClass =
526 S.LookupSingleName(S.TUScope,
527 &S.Context.Idents.get("object_getClass"),
528 SourceLocation(), S.LookupOrdinaryName);
529 if (ObjectGetClass)
530 S.Diag(OIRE->getExprLoc(), diag::warn_objc_isa_use) <<
531 FixItHint::CreateInsertion(OIRE->getLocStart(), "object_getClass(") <<
532 FixItHint::CreateReplacement(
533 SourceRange(OIRE->getOpLoc(),
534 OIRE->getLocEnd()), ")");
535 else
536 S.Diag(OIRE->getLocation(), diag::warn_objc_isa_use);
537 }
Fariborz Jahanian3b602ce2013-03-28 23:39:11 +0000538 S.Diag(IV->getLocation(), diag::note_ivar_decl);
539 }
540 }
541}
542
John Wiegley01296292011-04-08 18:41:53 +0000543ExprResult Sema::DefaultLvalueConversion(Expr *E) {
John McCall50a2c2c2011-10-11 23:14:30 +0000544 // Handle any placeholder expressions which made it here.
545 if (E->getType()->isPlaceholderType()) {
546 ExprResult result = CheckPlaceholderExpr(E);
547 if (result.isInvalid()) return ExprError();
548 E = result.take();
549 }
550
John McCallf3735e02010-12-01 04:43:34 +0000551 // C++ [conv.lval]p1:
552 // A glvalue of a non-function, non-array type T can be
553 // converted to a prvalue.
John Wiegley01296292011-04-08 18:41:53 +0000554 if (!E->isGLValue()) return Owned(E);
Kaelyn Uhrain2e7aa5a2011-08-05 23:18:04 +0000555
John McCall27584242010-12-06 20:48:59 +0000556 QualType T = E->getType();
557 assert(!T.isNull() && "r-value conversion on typeless expression?");
John McCall34376a62010-12-04 03:47:34 +0000558
John McCall27584242010-12-06 20:48:59 +0000559 // We don't want to throw lvalue-to-rvalue casts on top of
560 // expressions of certain types in C++.
David Blaikiebbafb8a2012-03-11 07:00:24 +0000561 if (getLangOpts().CPlusPlus &&
John McCall27584242010-12-06 20:48:59 +0000562 (E->getType() == Context.OverloadTy ||
563 T->isDependentType() ||
564 T->isRecordType()))
John Wiegley01296292011-04-08 18:41:53 +0000565 return Owned(E);
John McCall27584242010-12-06 20:48:59 +0000566
567 // The C standard is actually really unclear on this point, and
568 // DR106 tells us what the result should be but not why. It's
569 // generally best to say that void types just doesn't undergo
570 // lvalue-to-rvalue at all. Note that expressions of unqualified
571 // 'void' type are never l-values, but qualified void can be.
572 if (T->isVoidType())
John Wiegley01296292011-04-08 18:41:53 +0000573 return Owned(E);
John McCall27584242010-12-06 20:48:59 +0000574
John McCall6ced97a2013-02-12 01:29:43 +0000575 // OpenCL usually rejects direct accesses to values of 'half' type.
576 if (getLangOpts().OpenCL && !getOpenCLOptions().cl_khr_fp16 &&
577 T->isHalfType()) {
578 Diag(E->getExprLoc(), diag::err_opencl_half_load_store)
579 << 0 << T;
580 return ExprError();
581 }
582
Argyrios Kyrtzidisa9b630e2011-04-26 17:41:22 +0000583 CheckForNullPointerDereference(*this, E);
Fariborz Jahanian06bb7f72013-03-28 19:50:55 +0000584 if (const ObjCIsaExpr *OISA = dyn_cast<ObjCIsaExpr>(E->IgnoreParenCasts())) {
585 NamedDecl *ObjectGetClass = LookupSingleName(TUScope,
586 &Context.Idents.get("object_getClass"),
587 SourceLocation(), LookupOrdinaryName);
588 if (ObjectGetClass)
589 Diag(E->getExprLoc(), diag::warn_objc_isa_use) <<
590 FixItHint::CreateInsertion(OISA->getLocStart(), "object_getClass(") <<
591 FixItHint::CreateReplacement(
592 SourceRange(OISA->getOpLoc(), OISA->getIsaMemberLoc()), ")");
593 else
594 Diag(E->getExprLoc(), diag::warn_objc_isa_use);
595 }
Fariborz Jahanian3b602ce2013-03-28 23:39:11 +0000596 else if (const ObjCIvarRefExpr *OIRE =
597 dyn_cast<ObjCIvarRefExpr>(E->IgnoreParenCasts()))
Fariborz Jahanianf12ff4df2013-04-02 18:57:54 +0000598 DiagnoseDirectIsaAccess(*this, OIRE, SourceLocation(), /* Expr*/0);
Fariborz Jahanian3b602ce2013-03-28 23:39:11 +0000599
John McCall27584242010-12-06 20:48:59 +0000600 // C++ [conv.lval]p1:
601 // [...] If T is a non-class type, the type of the prvalue is the
602 // cv-unqualified version of T. Otherwise, the type of the
603 // rvalue is T.
604 //
605 // C99 6.3.2.1p2:
606 // If the lvalue has qualified type, the value has the unqualified
607 // version of the type of the lvalue; otherwise, the value has the
Anton Korobeynikovf0c267e2011-10-14 23:23:15 +0000608 // type of the lvalue.
John McCall27584242010-12-06 20:48:59 +0000609 if (T.hasQualifiers())
610 T = T.getUnqualifiedType();
Anton Korobeynikovf0c267e2011-10-14 23:23:15 +0000611
Eli Friedman3bda6b12012-02-02 23:15:15 +0000612 UpdateMarkingForLValueToRValue(E);
Fariborz Jahanianfbd19742012-11-27 23:02:53 +0000613
614 // Loading a __weak object implicitly retains the value, so we need a cleanup to
615 // balance that.
616 if (getLangOpts().ObjCAutoRefCount &&
617 E->getType().getObjCLifetime() == Qualifiers::OCL_Weak)
618 ExprNeedsCleanups = true;
Eli Friedman3bda6b12012-02-02 23:15:15 +0000619
Anton Korobeynikovf0c267e2011-10-14 23:23:15 +0000620 ExprResult Res = Owned(ImplicitCastExpr::Create(Context, T, CK_LValueToRValue,
621 E, 0, VK_RValue));
622
Douglas Gregorc79862f2012-04-12 17:51:55 +0000623 // C11 6.3.2.1p2:
624 // ... if the lvalue has atomic type, the value has the non-atomic version
625 // of the type of the lvalue ...
626 if (const AtomicType *Atomic = T->getAs<AtomicType>()) {
627 T = Atomic->getValueType().getUnqualifiedType();
628 Res = Owned(ImplicitCastExpr::Create(Context, T, CK_AtomicToNonAtomic,
629 Res.get(), 0, VK_RValue));
630 }
631
Anton Korobeynikovf0c267e2011-10-14 23:23:15 +0000632 return Res;
John McCall27584242010-12-06 20:48:59 +0000633}
634
John Wiegley01296292011-04-08 18:41:53 +0000635ExprResult Sema::DefaultFunctionArrayLvalueConversion(Expr *E) {
636 ExprResult Res = DefaultFunctionArrayConversion(E);
637 if (Res.isInvalid())
638 return ExprError();
639 Res = DefaultLvalueConversion(Res.take());
640 if (Res.isInvalid())
641 return ExprError();
Benjamin Kramer62b95d82012-08-23 21:35:17 +0000642 return Res;
Douglas Gregorb92a1562010-02-03 00:27:59 +0000643}
644
645
Chris Lattner513165e2008-07-25 21:10:04 +0000646/// UsualUnaryConversions - Performs various conversions that are common to most
Mike Stump11289f42009-09-09 15:08:12 +0000647/// operators (C99 6.3). The conversions of array and function types are
Chris Lattner57540c52011-04-15 05:22:18 +0000648/// sometimes suppressed. For example, the array->pointer conversion doesn't
Chris Lattner513165e2008-07-25 21:10:04 +0000649/// apply if the array is an argument to the sizeof or address (&) operators.
650/// In these instances, this routine should *not* be called.
John Wiegley01296292011-04-08 18:41:53 +0000651ExprResult Sema::UsualUnaryConversions(Expr *E) {
John McCallf3735e02010-12-01 04:43:34 +0000652 // First, convert to an r-value.
John Wiegley01296292011-04-08 18:41:53 +0000653 ExprResult Res = DefaultFunctionArrayLvalueConversion(E);
654 if (Res.isInvalid())
Fariborz Jahanian47ef4662013-03-06 00:37:40 +0000655 return ExprError();
John Wiegley01296292011-04-08 18:41:53 +0000656 E = Res.take();
Anton Korobeynikovf0c267e2011-10-14 23:23:15 +0000657
John McCallf3735e02010-12-01 04:43:34 +0000658 QualType Ty = E->getType();
Chris Lattner513165e2008-07-25 21:10:04 +0000659 assert(!Ty.isNull() && "UsualUnaryConversions - missing type");
Anton Korobeynikovf0c267e2011-10-14 23:23:15 +0000660
Joey Goulydd7f4562013-01-23 11:56:20 +0000661 // Half FP have to be promoted to float unless it is natively supported
662 if (Ty->isHalfType() && !getLangOpts().NativeHalfType)
Anton Korobeynikovf0c267e2011-10-14 23:23:15 +0000663 return ImpCastExprToType(Res.take(), Context.FloatTy, CK_FloatingCast);
664
John McCallf3735e02010-12-01 04:43:34 +0000665 // Try to perform integral promotions if the object has a theoretically
666 // promotable type.
667 if (Ty->isIntegralOrUnscopedEnumerationType()) {
668 // C99 6.3.1.1p2:
669 //
670 // The following may be used in an expression wherever an int or
671 // unsigned int may be used:
672 // - an object or expression with an integer type whose integer
673 // conversion rank is less than or equal to the rank of int
674 // and unsigned int.
675 // - A bit-field of type _Bool, int, signed int, or unsigned int.
676 //
677 // If an int can represent all values of the original type, the
678 // value is converted to an int; otherwise, it is converted to an
679 // unsigned int. These are called the integer promotions. All
680 // other types are unchanged by the integer promotions.
Anton Korobeynikovf0c267e2011-10-14 23:23:15 +0000681
John McCallf3735e02010-12-01 04:43:34 +0000682 QualType PTy = Context.isPromotableBitField(E);
683 if (!PTy.isNull()) {
John Wiegley01296292011-04-08 18:41:53 +0000684 E = ImpCastExprToType(E, PTy, CK_IntegralCast).take();
685 return Owned(E);
John McCallf3735e02010-12-01 04:43:34 +0000686 }
687 if (Ty->isPromotableIntegerType()) {
688 QualType PT = Context.getPromotedIntegerType(Ty);
John Wiegley01296292011-04-08 18:41:53 +0000689 E = ImpCastExprToType(E, PT, CK_IntegralCast).take();
690 return Owned(E);
John McCallf3735e02010-12-01 04:43:34 +0000691 }
Eli Friedman629ffb92009-08-20 04:21:42 +0000692 }
John Wiegley01296292011-04-08 18:41:53 +0000693 return Owned(E);
Chris Lattner513165e2008-07-25 21:10:04 +0000694}
695
Chris Lattner2ce500f2008-07-25 22:25:12 +0000696/// DefaultArgumentPromotion (C99 6.5.2.2p6). Used for function calls that
Tim Northoverda165072013-01-30 09:46:55 +0000697/// do not have a prototype. Arguments that have type float or __fp16
698/// are promoted to double. All other argument types are converted by
699/// UsualUnaryConversions().
John Wiegley01296292011-04-08 18:41:53 +0000700ExprResult Sema::DefaultArgumentPromotion(Expr *E) {
701 QualType Ty = E->getType();
Chris Lattner2ce500f2008-07-25 22:25:12 +0000702 assert(!Ty.isNull() && "DefaultArgumentPromotion - missing type");
Mike Stump11289f42009-09-09 15:08:12 +0000703
John Wiegley01296292011-04-08 18:41:53 +0000704 ExprResult Res = UsualUnaryConversions(E);
705 if (Res.isInvalid())
Fariborz Jahanian47ef4662013-03-06 00:37:40 +0000706 return ExprError();
John Wiegley01296292011-04-08 18:41:53 +0000707 E = Res.take();
John McCall9bc26772010-12-06 18:36:11 +0000708
Tim Northoverda165072013-01-30 09:46:55 +0000709 // If this is a 'float' or '__fp16' (CVR qualified or typedef) promote to
710 // double.
711 const BuiltinType *BTy = Ty->getAs<BuiltinType>();
712 if (BTy && (BTy->getKind() == BuiltinType::Half ||
713 BTy->getKind() == BuiltinType::Float))
John Wiegley01296292011-04-08 18:41:53 +0000714 E = ImpCastExprToType(E, Context.DoubleTy, CK_FloatingCast).take();
715
John McCall4bb057d2011-08-27 22:06:17 +0000716 // C++ performs lvalue-to-rvalue conversion as a default argument
John McCall0562caa2011-08-29 23:55:37 +0000717 // promotion, even on class types, but note:
718 // C++11 [conv.lval]p2:
719 // When an lvalue-to-rvalue conversion occurs in an unevaluated
720 // operand or a subexpression thereof the value contained in the
721 // referenced object is not accessed. Otherwise, if the glvalue
722 // has a class type, the conversion copy-initializes a temporary
723 // of type T from the glvalue and the result of the conversion
724 // is a prvalue for the temporary.
Eli Friedman05e28012012-01-17 02:13:45 +0000725 // FIXME: add some way to gate this entire thing for correctness in
726 // potentially potentially evaluated contexts.
David Blaikie131fcb42012-08-06 22:47:24 +0000727 if (getLangOpts().CPlusPlus && E->isGLValue() && !isUnevaluatedContext()) {
Eli Friedman05e28012012-01-17 02:13:45 +0000728 ExprResult Temp = PerformCopyInitialization(
729 InitializedEntity::InitializeTemporary(E->getType()),
730 E->getExprLoc(),
731 Owned(E));
732 if (Temp.isInvalid())
733 return ExprError();
734 E = Temp.get();
John McCall29ad95b2011-08-27 01:09:30 +0000735 }
736
John Wiegley01296292011-04-08 18:41:53 +0000737 return Owned(E);
Chris Lattner2ce500f2008-07-25 22:25:12 +0000738}
739
Richard Smith55ce3522012-06-25 20:30:08 +0000740/// Determine the degree of POD-ness for an expression.
741/// Incomplete types are considered POD, since this check can be performed
742/// when we're in an unevaluated context.
743Sema::VarArgKind Sema::isValidVarArgType(const QualType &Ty) {
Jordan Rose3e0ec582012-07-19 18:10:23 +0000744 if (Ty->isIncompleteType()) {
745 if (Ty->isObjCObjectType())
746 return VAK_Invalid;
Richard Smith55ce3522012-06-25 20:30:08 +0000747 return VAK_Valid;
Jordan Rose3e0ec582012-07-19 18:10:23 +0000748 }
749
750 if (Ty.isCXX98PODType(Context))
751 return VAK_Valid;
752
Richard Smith16488472012-11-16 00:53:38 +0000753 // C++11 [expr.call]p7:
754 // Passing a potentially-evaluated argument of class type (Clause 9)
Richard Smith55ce3522012-06-25 20:30:08 +0000755 // having a non-trivial copy constructor, a non-trivial move constructor,
Richard Smith16488472012-11-16 00:53:38 +0000756 // or a non-trivial destructor, with no corresponding parameter,
Richard Smith55ce3522012-06-25 20:30:08 +0000757 // is conditionally-supported with implementation-defined semantics.
Richard Smith2bf7fdb2013-01-02 11:42:31 +0000758 if (getLangOpts().CPlusPlus11 && !Ty->isDependentType())
Richard Smith55ce3522012-06-25 20:30:08 +0000759 if (CXXRecordDecl *Record = Ty->getAsCXXRecordDecl())
Richard Smith16488472012-11-16 00:53:38 +0000760 if (!Record->hasNonTrivialCopyConstructor() &&
761 !Record->hasNonTrivialMoveConstructor() &&
762 !Record->hasNonTrivialDestructor())
Richard Smith55ce3522012-06-25 20:30:08 +0000763 return VAK_ValidInCXX11;
764
765 if (getLangOpts().ObjCAutoRefCount && Ty->isObjCLifetimeType())
766 return VAK_Valid;
767 return VAK_Invalid;
768}
769
770bool Sema::variadicArgumentPODCheck(const Expr *E, VariadicCallType CT) {
771 // Don't allow one to pass an Objective-C interface to a vararg.
772 const QualType & Ty = E->getType();
773
774 // Complain about passing non-POD types through varargs.
775 switch (isValidVarArgType(Ty)) {
776 case VAK_Valid:
777 break;
778 case VAK_ValidInCXX11:
779 DiagRuntimeBehavior(E->getLocStart(), 0,
780 PDiag(diag::warn_cxx98_compat_pass_non_pod_arg_to_vararg)
781 << E->getType() << CT);
782 break;
Jordan Rose3e0ec582012-07-19 18:10:23 +0000783 case VAK_Invalid: {
784 if (Ty->isObjCObjectType())
785 return DiagRuntimeBehavior(E->getLocStart(), 0,
786 PDiag(diag::err_cannot_pass_objc_interface_to_vararg)
787 << Ty << CT);
788
Richard Smith55ce3522012-06-25 20:30:08 +0000789 return DiagRuntimeBehavior(E->getLocStart(), 0,
790 PDiag(diag::warn_cannot_pass_non_pod_arg_to_vararg)
Richard Smith2bf7fdb2013-01-02 11:42:31 +0000791 << getLangOpts().CPlusPlus11 << Ty << CT);
Richard Smith55ce3522012-06-25 20:30:08 +0000792 }
Jordan Rose3e0ec582012-07-19 18:10:23 +0000793 }
Richard Smith55ce3522012-06-25 20:30:08 +0000794 // c++ rules are enforced elsewhere.
795 return false;
796}
797
Chris Lattnera8a7d0f2009-04-12 08:11:20 +0000798/// DefaultVariadicArgumentPromotion - Like DefaultArgumentPromotion, but
Jordan Rose3e0ec582012-07-19 18:10:23 +0000799/// will create a trap if the resulting type is not a POD type.
John Wiegley01296292011-04-08 18:41:53 +0000800ExprResult Sema::DefaultVariadicArgumentPromotion(Expr *E, VariadicCallType CT,
John McCall31168b02011-06-15 23:02:42 +0000801 FunctionDecl *FDecl) {
Richard Smith7659b122012-06-27 20:29:39 +0000802 if (const BuiltinType *PlaceholderTy = E->getType()->getAsPlaceholderType()) {
John McCall4124c492011-10-17 18:40:02 +0000803 // Strip the unbridged-cast placeholder expression off, if applicable.
804 if (PlaceholderTy->getKind() == BuiltinType::ARCUnbridgedCast &&
805 (CT == VariadicMethod ||
806 (FDecl && FDecl->hasAttr<CFAuditedTransferAttr>()))) {
807 E = stripARCUnbridgedCast(E);
808
809 // Otherwise, do normal placeholder checking.
810 } else {
811 ExprResult ExprRes = CheckPlaceholderExpr(E);
812 if (ExprRes.isInvalid())
813 return ExprError();
814 E = ExprRes.take();
815 }
816 }
Douglas Gregorcbd446d2011-06-17 00:15:10 +0000817
John McCall4124c492011-10-17 18:40:02 +0000818 ExprResult ExprRes = DefaultArgumentPromotion(E);
John Wiegley01296292011-04-08 18:41:53 +0000819 if (ExprRes.isInvalid())
820 return ExprError();
821 E = ExprRes.take();
Mike Stump11289f42009-09-09 15:08:12 +0000822
Richard Smith55ce3522012-06-25 20:30:08 +0000823 // Diagnostics regarding non-POD argument types are
824 // emitted along with format string checking in Sema::CheckFunctionCall().
Richard Smith56471fd2012-06-27 20:23:58 +0000825 if (isValidVarArgType(E->getType()) == VAK_Invalid) {
Richard Smith55ce3522012-06-25 20:30:08 +0000826 // Turn this into a trap.
827 CXXScopeSpec SS;
828 SourceLocation TemplateKWLoc;
829 UnqualifiedId Name;
830 Name.setIdentifier(PP.getIdentifierInfo("__builtin_trap"),
831 E->getLocStart());
832 ExprResult TrapFn = ActOnIdExpression(TUScope, SS, TemplateKWLoc,
833 Name, true, false);
834 if (TrapFn.isInvalid())
835 return ExprError();
John McCall31168b02011-06-15 23:02:42 +0000836
Richard Smith55ce3522012-06-25 20:30:08 +0000837 ExprResult Call = ActOnCallExpr(TUScope, TrapFn.get(),
Dmitri Gribenko78852e92013-05-05 20:40:26 +0000838 E->getLocStart(), None,
Richard Smith55ce3522012-06-25 20:30:08 +0000839 E->getLocEnd());
840 if (Call.isInvalid())
841 return ExprError();
Douglas Gregor347e0f22011-05-21 19:26:31 +0000842
Richard Smith55ce3522012-06-25 20:30:08 +0000843 ExprResult Comma = ActOnBinOp(TUScope, E->getLocStart(), tok::comma,
844 Call.get(), E);
845 if (Comma.isInvalid())
846 return ExprError();
847 return Comma.get();
Douglas Gregor253cadf2011-05-21 16:27:21 +0000848 }
Richard Smith55ce3522012-06-25 20:30:08 +0000849
David Blaikiebbafb8a2012-03-11 07:00:24 +0000850 if (!getLangOpts().CPlusPlus &&
Fariborz Jahanian3854a552012-03-01 23:42:00 +0000851 RequireCompleteType(E->getExprLoc(), E->getType(),
Fariborz Jahanianbf482812012-03-02 17:05:03 +0000852 diag::err_call_incomplete_argument))
Fariborz Jahanian3854a552012-03-01 23:42:00 +0000853 return ExprError();
Richard Smith55ce3522012-06-25 20:30:08 +0000854
John Wiegley01296292011-04-08 18:41:53 +0000855 return Owned(E);
Anders Carlssona7d069d2009-01-16 16:48:51 +0000856}
857
Richard Trieu7aa58f12011-09-02 20:58:51 +0000858/// \brief Converts an integer to complex float type. Helper function of
859/// UsualArithmeticConversions()
860///
861/// \return false if the integer expression is an integer type and is
862/// successfully converted to the complex type.
Richard Trieuba63ce62011-09-09 01:45:06 +0000863static bool handleIntegerToComplexFloatConversion(Sema &S, ExprResult &IntExpr,
864 ExprResult &ComplexExpr,
865 QualType IntTy,
866 QualType ComplexTy,
867 bool SkipCast) {
868 if (IntTy->isComplexType() || IntTy->isRealFloatingType()) return true;
869 if (SkipCast) return false;
870 if (IntTy->isIntegerType()) {
871 QualType fpTy = cast<ComplexType>(ComplexTy)->getElementType();
872 IntExpr = S.ImpCastExprToType(IntExpr.take(), fpTy, CK_IntegralToFloating);
873 IntExpr = S.ImpCastExprToType(IntExpr.take(), ComplexTy,
Richard Trieu7aa58f12011-09-02 20:58:51 +0000874 CK_FloatingRealToComplex);
875 } else {
Richard Trieuba63ce62011-09-09 01:45:06 +0000876 assert(IntTy->isComplexIntegerType());
877 IntExpr = S.ImpCastExprToType(IntExpr.take(), ComplexTy,
Richard Trieu7aa58f12011-09-02 20:58:51 +0000878 CK_IntegralComplexToFloatingComplex);
879 }
880 return false;
881}
882
883/// \brief Takes two complex float types and converts them to the same type.
884/// Helper function of UsualArithmeticConversions()
885static QualType
Richard Trieu5065cdd2011-09-06 18:25:09 +0000886handleComplexFloatToComplexFloatConverstion(Sema &S, ExprResult &LHS,
887 ExprResult &RHS, QualType LHSType,
888 QualType RHSType,
Richard Trieuba63ce62011-09-09 01:45:06 +0000889 bool IsCompAssign) {
Richard Trieu5065cdd2011-09-06 18:25:09 +0000890 int order = S.Context.getFloatingTypeOrder(LHSType, RHSType);
Richard Trieu7aa58f12011-09-02 20:58:51 +0000891
892 if (order < 0) {
893 // _Complex float -> _Complex double
Richard Trieuba63ce62011-09-09 01:45:06 +0000894 if (!IsCompAssign)
Richard Trieu5065cdd2011-09-06 18:25:09 +0000895 LHS = S.ImpCastExprToType(LHS.take(), RHSType, CK_FloatingComplexCast);
896 return RHSType;
Richard Trieu7aa58f12011-09-02 20:58:51 +0000897 }
898 if (order > 0)
899 // _Complex float -> _Complex double
Richard Trieu5065cdd2011-09-06 18:25:09 +0000900 RHS = S.ImpCastExprToType(RHS.take(), LHSType, CK_FloatingComplexCast);
901 return LHSType;
Richard Trieu7aa58f12011-09-02 20:58:51 +0000902}
903
904/// \brief Converts otherExpr to complex float and promotes complexExpr if
905/// necessary. Helper function of UsualArithmeticConversions()
906static QualType handleOtherComplexFloatConversion(Sema &S,
Richard Trieuba63ce62011-09-09 01:45:06 +0000907 ExprResult &ComplexExpr,
908 ExprResult &OtherExpr,
909 QualType ComplexTy,
910 QualType OtherTy,
911 bool ConvertComplexExpr,
912 bool ConvertOtherExpr) {
913 int order = S.Context.getFloatingTypeOrder(ComplexTy, OtherTy);
Richard Trieu7aa58f12011-09-02 20:58:51 +0000914
915 // If just the complexExpr is complex, the otherExpr needs to be converted,
916 // and the complexExpr might need to be promoted.
917 if (order > 0) { // complexExpr is wider
918 // float -> _Complex double
Richard Trieuba63ce62011-09-09 01:45:06 +0000919 if (ConvertOtherExpr) {
920 QualType fp = cast<ComplexType>(ComplexTy)->getElementType();
921 OtherExpr = S.ImpCastExprToType(OtherExpr.take(), fp, CK_FloatingCast);
922 OtherExpr = S.ImpCastExprToType(OtherExpr.take(), ComplexTy,
Richard Trieu7aa58f12011-09-02 20:58:51 +0000923 CK_FloatingRealToComplex);
924 }
Richard Trieuba63ce62011-09-09 01:45:06 +0000925 return ComplexTy;
Richard Trieu7aa58f12011-09-02 20:58:51 +0000926 }
927
928 // otherTy is at least as wide. Find its corresponding complex type.
Richard Trieuba63ce62011-09-09 01:45:06 +0000929 QualType result = (order == 0 ? ComplexTy :
930 S.Context.getComplexType(OtherTy));
Richard Trieu7aa58f12011-09-02 20:58:51 +0000931
932 // double -> _Complex double
Richard Trieuba63ce62011-09-09 01:45:06 +0000933 if (ConvertOtherExpr)
934 OtherExpr = S.ImpCastExprToType(OtherExpr.take(), result,
Richard Trieu7aa58f12011-09-02 20:58:51 +0000935 CK_FloatingRealToComplex);
936
937 // _Complex float -> _Complex double
Richard Trieuba63ce62011-09-09 01:45:06 +0000938 if (ConvertComplexExpr && order < 0)
939 ComplexExpr = S.ImpCastExprToType(ComplexExpr.take(), result,
Richard Trieu7aa58f12011-09-02 20:58:51 +0000940 CK_FloatingComplexCast);
941
942 return result;
943}
944
945/// \brief Handle arithmetic conversion with complex types. Helper function of
946/// UsualArithmeticConversions()
Richard Trieu5065cdd2011-09-06 18:25:09 +0000947static QualType handleComplexFloatConversion(Sema &S, ExprResult &LHS,
948 ExprResult &RHS, QualType LHSType,
949 QualType RHSType,
Richard Trieuba63ce62011-09-09 01:45:06 +0000950 bool IsCompAssign) {
Richard Trieu7aa58f12011-09-02 20:58:51 +0000951 // if we have an integer operand, the result is the complex type.
Richard Trieu5065cdd2011-09-06 18:25:09 +0000952 if (!handleIntegerToComplexFloatConversion(S, RHS, LHS, RHSType, LHSType,
Richard Trieu7aa58f12011-09-02 20:58:51 +0000953 /*skipCast*/false))
Richard Trieu5065cdd2011-09-06 18:25:09 +0000954 return LHSType;
955 if (!handleIntegerToComplexFloatConversion(S, LHS, RHS, LHSType, RHSType,
Richard Trieuba63ce62011-09-09 01:45:06 +0000956 /*skipCast*/IsCompAssign))
Richard Trieu5065cdd2011-09-06 18:25:09 +0000957 return RHSType;
Richard Trieu7aa58f12011-09-02 20:58:51 +0000958
959 // This handles complex/complex, complex/float, or float/complex.
960 // When both operands are complex, the shorter operand is converted to the
961 // type of the longer, and that is the type of the result. This corresponds
962 // to what is done when combining two real floating-point operands.
963 // The fun begins when size promotion occur across type domains.
964 // From H&S 6.3.4: When one operand is complex and the other is a real
965 // floating-point type, the less precise type is converted, within it's
966 // real or complex domain, to the precision of the other type. For example,
967 // when combining a "long double" with a "double _Complex", the
968 // "double _Complex" is promoted to "long double _Complex".
969
Richard Trieu5065cdd2011-09-06 18:25:09 +0000970 bool LHSComplexFloat = LHSType->isComplexType();
971 bool RHSComplexFloat = RHSType->isComplexType();
Richard Trieu7aa58f12011-09-02 20:58:51 +0000972
973 // If both are complex, just cast to the more precise type.
974 if (LHSComplexFloat && RHSComplexFloat)
Richard Trieu5065cdd2011-09-06 18:25:09 +0000975 return handleComplexFloatToComplexFloatConverstion(S, LHS, RHS,
976 LHSType, RHSType,
Richard Trieuba63ce62011-09-09 01:45:06 +0000977 IsCompAssign);
Richard Trieu7aa58f12011-09-02 20:58:51 +0000978
979 // If only one operand is complex, promote it if necessary and convert the
980 // other operand to complex.
981 if (LHSComplexFloat)
982 return handleOtherComplexFloatConversion(
Richard Trieuba63ce62011-09-09 01:45:06 +0000983 S, LHS, RHS, LHSType, RHSType, /*convertComplexExpr*/!IsCompAssign,
Richard Trieu7aa58f12011-09-02 20:58:51 +0000984 /*convertOtherExpr*/ true);
985
986 assert(RHSComplexFloat);
987 return handleOtherComplexFloatConversion(
Richard Trieu5065cdd2011-09-06 18:25:09 +0000988 S, RHS, LHS, RHSType, LHSType, /*convertComplexExpr*/true,
Richard Trieuba63ce62011-09-09 01:45:06 +0000989 /*convertOtherExpr*/ !IsCompAssign);
Richard Trieu7aa58f12011-09-02 20:58:51 +0000990}
991
992/// \brief Hande arithmetic conversion from integer to float. Helper function
993/// of UsualArithmeticConversions()
Richard Trieuba63ce62011-09-09 01:45:06 +0000994static QualType handleIntToFloatConversion(Sema &S, ExprResult &FloatExpr,
995 ExprResult &IntExpr,
996 QualType FloatTy, QualType IntTy,
997 bool ConvertFloat, bool ConvertInt) {
998 if (IntTy->isIntegerType()) {
999 if (ConvertInt)
Richard Trieu7aa58f12011-09-02 20:58:51 +00001000 // Convert intExpr to the lhs floating point type.
Richard Trieuba63ce62011-09-09 01:45:06 +00001001 IntExpr = S.ImpCastExprToType(IntExpr.take(), FloatTy,
Richard Trieu7aa58f12011-09-02 20:58:51 +00001002 CK_IntegralToFloating);
Richard Trieuba63ce62011-09-09 01:45:06 +00001003 return FloatTy;
Richard Trieu7aa58f12011-09-02 20:58:51 +00001004 }
1005
1006 // Convert both sides to the appropriate complex float.
Richard Trieuba63ce62011-09-09 01:45:06 +00001007 assert(IntTy->isComplexIntegerType());
1008 QualType result = S.Context.getComplexType(FloatTy);
Richard Trieu7aa58f12011-09-02 20:58:51 +00001009
1010 // _Complex int -> _Complex float
Richard Trieuba63ce62011-09-09 01:45:06 +00001011 if (ConvertInt)
1012 IntExpr = S.ImpCastExprToType(IntExpr.take(), result,
Richard Trieu7aa58f12011-09-02 20:58:51 +00001013 CK_IntegralComplexToFloatingComplex);
1014
1015 // float -> _Complex float
Richard Trieuba63ce62011-09-09 01:45:06 +00001016 if (ConvertFloat)
1017 FloatExpr = S.ImpCastExprToType(FloatExpr.take(), result,
Richard Trieu7aa58f12011-09-02 20:58:51 +00001018 CK_FloatingRealToComplex);
1019
1020 return result;
1021}
1022
1023/// \brief Handle arithmethic conversion with floating point types. Helper
1024/// function of UsualArithmeticConversions()
Richard Trieucfe3f212011-09-06 18:38:41 +00001025static QualType handleFloatConversion(Sema &S, ExprResult &LHS,
1026 ExprResult &RHS, QualType LHSType,
Richard Trieuba63ce62011-09-09 01:45:06 +00001027 QualType RHSType, bool IsCompAssign) {
Richard Trieucfe3f212011-09-06 18:38:41 +00001028 bool LHSFloat = LHSType->isRealFloatingType();
1029 bool RHSFloat = RHSType->isRealFloatingType();
Richard Trieu7aa58f12011-09-02 20:58:51 +00001030
1031 // If we have two real floating types, convert the smaller operand
1032 // to the bigger result.
1033 if (LHSFloat && RHSFloat) {
Richard Trieucfe3f212011-09-06 18:38:41 +00001034 int order = S.Context.getFloatingTypeOrder(LHSType, RHSType);
Richard Trieu7aa58f12011-09-02 20:58:51 +00001035 if (order > 0) {
Richard Trieucfe3f212011-09-06 18:38:41 +00001036 RHS = S.ImpCastExprToType(RHS.take(), LHSType, CK_FloatingCast);
1037 return LHSType;
Richard Trieu7aa58f12011-09-02 20:58:51 +00001038 }
1039
1040 assert(order < 0 && "illegal float comparison");
Richard Trieuba63ce62011-09-09 01:45:06 +00001041 if (!IsCompAssign)
Richard Trieucfe3f212011-09-06 18:38:41 +00001042 LHS = S.ImpCastExprToType(LHS.take(), RHSType, CK_FloatingCast);
1043 return RHSType;
Richard Trieu7aa58f12011-09-02 20:58:51 +00001044 }
1045
1046 if (LHSFloat)
Richard Trieucfe3f212011-09-06 18:38:41 +00001047 return handleIntToFloatConversion(S, LHS, RHS, LHSType, RHSType,
Richard Trieuba63ce62011-09-09 01:45:06 +00001048 /*convertFloat=*/!IsCompAssign,
Richard Trieu7aa58f12011-09-02 20:58:51 +00001049 /*convertInt=*/ true);
1050 assert(RHSFloat);
Richard Trieucfe3f212011-09-06 18:38:41 +00001051 return handleIntToFloatConversion(S, RHS, LHS, RHSType, LHSType,
Richard Trieu7aa58f12011-09-02 20:58:51 +00001052 /*convertInt=*/ true,
Richard Trieuba63ce62011-09-09 01:45:06 +00001053 /*convertFloat=*/!IsCompAssign);
Richard Trieu7aa58f12011-09-02 20:58:51 +00001054}
1055
Bill Schmidteb03ae22013-02-01 15:34:29 +00001056typedef ExprResult PerformCastFn(Sema &S, Expr *operand, QualType toType);
Richard Trieu7aa58f12011-09-02 20:58:51 +00001057
Bill Schmidteb03ae22013-02-01 15:34:29 +00001058namespace {
1059/// These helper callbacks are placed in an anonymous namespace to
1060/// permit their use as function template parameters.
1061ExprResult doIntegralCast(Sema &S, Expr *op, QualType toType) {
1062 return S.ImpCastExprToType(op, toType, CK_IntegralCast);
1063}
Richard Trieu7aa58f12011-09-02 20:58:51 +00001064
Bill Schmidteb03ae22013-02-01 15:34:29 +00001065ExprResult doComplexIntegralCast(Sema &S, Expr *op, QualType toType) {
1066 return S.ImpCastExprToType(op, S.Context.getComplexType(toType),
1067 CK_IntegralComplexCast);
1068}
Richard Trieu7aa58f12011-09-02 20:58:51 +00001069}
1070
1071/// \brief Handle integer arithmetic conversions. Helper function of
1072/// UsualArithmeticConversions()
Bill Schmidteb03ae22013-02-01 15:34:29 +00001073template <PerformCastFn doLHSCast, PerformCastFn doRHSCast>
Richard Trieu9a52fbb2011-09-06 19:52:52 +00001074static QualType handleIntegerConversion(Sema &S, ExprResult &LHS,
1075 ExprResult &RHS, QualType LHSType,
Richard Trieuba63ce62011-09-09 01:45:06 +00001076 QualType RHSType, bool IsCompAssign) {
Richard Trieu7aa58f12011-09-02 20:58:51 +00001077 // The rules for this case are in C99 6.3.1.8
Richard Trieu9a52fbb2011-09-06 19:52:52 +00001078 int order = S.Context.getIntegerTypeOrder(LHSType, RHSType);
1079 bool LHSSigned = LHSType->hasSignedIntegerRepresentation();
1080 bool RHSSigned = RHSType->hasSignedIntegerRepresentation();
1081 if (LHSSigned == RHSSigned) {
Richard Trieu7aa58f12011-09-02 20:58:51 +00001082 // Same signedness; use the higher-ranked type
1083 if (order >= 0) {
Bill Schmidteb03ae22013-02-01 15:34:29 +00001084 RHS = (*doRHSCast)(S, RHS.take(), LHSType);
Richard Trieu9a52fbb2011-09-06 19:52:52 +00001085 return LHSType;
Richard Trieuba63ce62011-09-09 01:45:06 +00001086 } else if (!IsCompAssign)
Bill Schmidteb03ae22013-02-01 15:34:29 +00001087 LHS = (*doLHSCast)(S, LHS.take(), RHSType);
Richard Trieu9a52fbb2011-09-06 19:52:52 +00001088 return RHSType;
1089 } else if (order != (LHSSigned ? 1 : -1)) {
Richard Trieu7aa58f12011-09-02 20:58:51 +00001090 // The unsigned type has greater than or equal rank to the
1091 // signed type, so use the unsigned type
Richard Trieu9a52fbb2011-09-06 19:52:52 +00001092 if (RHSSigned) {
Bill Schmidteb03ae22013-02-01 15:34:29 +00001093 RHS = (*doRHSCast)(S, RHS.take(), LHSType);
Richard Trieu9a52fbb2011-09-06 19:52:52 +00001094 return LHSType;
Richard Trieuba63ce62011-09-09 01:45:06 +00001095 } else if (!IsCompAssign)
Bill Schmidteb03ae22013-02-01 15:34:29 +00001096 LHS = (*doLHSCast)(S, LHS.take(), RHSType);
Richard Trieu9a52fbb2011-09-06 19:52:52 +00001097 return RHSType;
1098 } else if (S.Context.getIntWidth(LHSType) != S.Context.getIntWidth(RHSType)) {
Richard Trieu7aa58f12011-09-02 20:58:51 +00001099 // The two types are different widths; if we are here, that
1100 // means the signed type is larger than the unsigned type, so
1101 // use the signed type.
Richard Trieu9a52fbb2011-09-06 19:52:52 +00001102 if (LHSSigned) {
Bill Schmidteb03ae22013-02-01 15:34:29 +00001103 RHS = (*doRHSCast)(S, RHS.take(), LHSType);
Richard Trieu9a52fbb2011-09-06 19:52:52 +00001104 return LHSType;
Richard Trieuba63ce62011-09-09 01:45:06 +00001105 } else if (!IsCompAssign)
Bill Schmidteb03ae22013-02-01 15:34:29 +00001106 LHS = (*doLHSCast)(S, LHS.take(), RHSType);
Richard Trieu9a52fbb2011-09-06 19:52:52 +00001107 return RHSType;
Richard Trieu7aa58f12011-09-02 20:58:51 +00001108 } else {
1109 // The signed type is higher-ranked than the unsigned type,
1110 // but isn't actually any bigger (like unsigned int and long
1111 // on most 32-bit systems). Use the unsigned type corresponding
1112 // to the signed type.
1113 QualType result =
Richard Trieu9a52fbb2011-09-06 19:52:52 +00001114 S.Context.getCorrespondingUnsignedType(LHSSigned ? LHSType : RHSType);
Bill Schmidteb03ae22013-02-01 15:34:29 +00001115 RHS = (*doRHSCast)(S, RHS.take(), result);
Richard Trieuba63ce62011-09-09 01:45:06 +00001116 if (!IsCompAssign)
Bill Schmidteb03ae22013-02-01 15:34:29 +00001117 LHS = (*doLHSCast)(S, LHS.take(), result);
Richard Trieu7aa58f12011-09-02 20:58:51 +00001118 return result;
1119 }
1120}
1121
Bill Schmidteb03ae22013-02-01 15:34:29 +00001122/// \brief Handle conversions with GCC complex int extension. Helper function
1123/// of UsualArithmeticConversions()
1124static QualType handleComplexIntConversion(Sema &S, ExprResult &LHS,
1125 ExprResult &RHS, QualType LHSType,
1126 QualType RHSType,
1127 bool IsCompAssign) {
1128 const ComplexType *LHSComplexInt = LHSType->getAsComplexIntegerType();
1129 const ComplexType *RHSComplexInt = RHSType->getAsComplexIntegerType();
1130
1131 if (LHSComplexInt && RHSComplexInt) {
1132 QualType LHSEltType = LHSComplexInt->getElementType();
1133 QualType RHSEltType = RHSComplexInt->getElementType();
1134 QualType ScalarType =
1135 handleIntegerConversion<doComplexIntegralCast, doComplexIntegralCast>
1136 (S, LHS, RHS, LHSEltType, RHSEltType, IsCompAssign);
1137
1138 return S.Context.getComplexType(ScalarType);
1139 }
1140
1141 if (LHSComplexInt) {
1142 QualType LHSEltType = LHSComplexInt->getElementType();
1143 QualType ScalarType =
1144 handleIntegerConversion<doComplexIntegralCast, doIntegralCast>
1145 (S, LHS, RHS, LHSEltType, RHSType, IsCompAssign);
1146 QualType ComplexType = S.Context.getComplexType(ScalarType);
1147 RHS = S.ImpCastExprToType(RHS.take(), ComplexType,
1148 CK_IntegralRealToComplex);
1149
1150 return ComplexType;
1151 }
1152
1153 assert(RHSComplexInt);
1154
1155 QualType RHSEltType = RHSComplexInt->getElementType();
1156 QualType ScalarType =
1157 handleIntegerConversion<doIntegralCast, doComplexIntegralCast>
1158 (S, LHS, RHS, LHSType, RHSEltType, IsCompAssign);
1159 QualType ComplexType = S.Context.getComplexType(ScalarType);
1160
1161 if (!IsCompAssign)
1162 LHS = S.ImpCastExprToType(LHS.take(), ComplexType,
1163 CK_IntegralRealToComplex);
1164 return ComplexType;
1165}
1166
Chris Lattner513165e2008-07-25 21:10:04 +00001167/// UsualArithmeticConversions - Performs various conversions that are common to
1168/// binary operators (C99 6.3.1.8). If both operands aren't arithmetic, this
Mike Stump11289f42009-09-09 15:08:12 +00001169/// routine returns the first non-arithmetic type found. The client is
Chris Lattner513165e2008-07-25 21:10:04 +00001170/// responsible for emitting appropriate error diagnostics.
Richard Trieu9a52fbb2011-09-06 19:52:52 +00001171QualType Sema::UsualArithmeticConversions(ExprResult &LHS, ExprResult &RHS,
Richard Trieuba63ce62011-09-09 01:45:06 +00001172 bool IsCompAssign) {
1173 if (!IsCompAssign) {
Richard Trieu9a52fbb2011-09-06 19:52:52 +00001174 LHS = UsualUnaryConversions(LHS.take());
1175 if (LHS.isInvalid())
John Wiegley01296292011-04-08 18:41:53 +00001176 return QualType();
1177 }
Eli Friedman8b7b1b12009-03-28 01:22:36 +00001178
Richard Trieu9a52fbb2011-09-06 19:52:52 +00001179 RHS = UsualUnaryConversions(RHS.take());
1180 if (RHS.isInvalid())
John Wiegley01296292011-04-08 18:41:53 +00001181 return QualType();
Douglas Gregora11693b2008-11-12 17:17:38 +00001182
Mike Stump11289f42009-09-09 15:08:12 +00001183 // For conversion purposes, we ignore any qualifiers.
Chris Lattner513165e2008-07-25 21:10:04 +00001184 // For example, "const float" and "float" are equivalent.
Richard Trieu9a52fbb2011-09-06 19:52:52 +00001185 QualType LHSType =
1186 Context.getCanonicalType(LHS.get()->getType()).getUnqualifiedType();
1187 QualType RHSType =
1188 Context.getCanonicalType(RHS.get()->getType()).getUnqualifiedType();
Douglas Gregora11693b2008-11-12 17:17:38 +00001189
Eli Friedman93ee5ca2012-06-16 02:19:17 +00001190 // For conversion purposes, we ignore any atomic qualifier on the LHS.
1191 if (const AtomicType *AtomicLHS = LHSType->getAs<AtomicType>())
1192 LHSType = AtomicLHS->getValueType();
1193
Douglas Gregora11693b2008-11-12 17:17:38 +00001194 // If both types are identical, no conversion is needed.
Richard Trieu9a52fbb2011-09-06 19:52:52 +00001195 if (LHSType == RHSType)
1196 return LHSType;
Douglas Gregora11693b2008-11-12 17:17:38 +00001197
1198 // If either side is a non-arithmetic type (e.g. a pointer), we are done.
1199 // The caller can deal with this (e.g. pointer + int).
Richard Trieu9a52fbb2011-09-06 19:52:52 +00001200 if (!LHSType->isArithmeticType() || !RHSType->isArithmeticType())
Eli Friedman93ee5ca2012-06-16 02:19:17 +00001201 return QualType();
Douglas Gregora11693b2008-11-12 17:17:38 +00001202
John McCalld005ac92010-11-13 08:17:45 +00001203 // Apply unary and bitfield promotions to the LHS's type.
Richard Trieu9a52fbb2011-09-06 19:52:52 +00001204 QualType LHSUnpromotedType = LHSType;
1205 if (LHSType->isPromotableIntegerType())
1206 LHSType = Context.getPromotedIntegerType(LHSType);
1207 QualType LHSBitfieldPromoteTy = Context.isPromotableBitField(LHS.get());
Douglas Gregord2c2d172009-05-02 00:36:19 +00001208 if (!LHSBitfieldPromoteTy.isNull())
Richard Trieu9a52fbb2011-09-06 19:52:52 +00001209 LHSType = LHSBitfieldPromoteTy;
Richard Trieuba63ce62011-09-09 01:45:06 +00001210 if (LHSType != LHSUnpromotedType && !IsCompAssign)
Richard Trieu9a52fbb2011-09-06 19:52:52 +00001211 LHS = ImpCastExprToType(LHS.take(), LHSType, CK_IntegralCast);
Douglas Gregord2c2d172009-05-02 00:36:19 +00001212
John McCalld005ac92010-11-13 08:17:45 +00001213 // If both types are identical, no conversion is needed.
Richard Trieu9a52fbb2011-09-06 19:52:52 +00001214 if (LHSType == RHSType)
1215 return LHSType;
John McCalld005ac92010-11-13 08:17:45 +00001216
1217 // At this point, we have two different arithmetic types.
1218
1219 // Handle complex types first (C99 6.3.1.8p1).
Richard Trieu9a52fbb2011-09-06 19:52:52 +00001220 if (LHSType->isComplexType() || RHSType->isComplexType())
1221 return handleComplexFloatConversion(*this, LHS, RHS, LHSType, RHSType,
Richard Trieuba63ce62011-09-09 01:45:06 +00001222 IsCompAssign);
John McCalld005ac92010-11-13 08:17:45 +00001223
1224 // Now handle "real" floating types (i.e. float, double, long double).
Richard Trieu9a52fbb2011-09-06 19:52:52 +00001225 if (LHSType->isRealFloatingType() || RHSType->isRealFloatingType())
1226 return handleFloatConversion(*this, LHS, RHS, LHSType, RHSType,
Richard Trieuba63ce62011-09-09 01:45:06 +00001227 IsCompAssign);
John McCalld005ac92010-11-13 08:17:45 +00001228
1229 // Handle GCC complex int extension.
Richard Trieu9a52fbb2011-09-06 19:52:52 +00001230 if (LHSType->isComplexIntegerType() || RHSType->isComplexIntegerType())
Benjamin Kramer499c68b2011-09-06 19:57:14 +00001231 return handleComplexIntConversion(*this, LHS, RHS, LHSType, RHSType,
Richard Trieuba63ce62011-09-09 01:45:06 +00001232 IsCompAssign);
John McCalld005ac92010-11-13 08:17:45 +00001233
1234 // Finally, we have two differing integer types.
Bill Schmidteb03ae22013-02-01 15:34:29 +00001235 return handleIntegerConversion<doIntegralCast, doIntegralCast>
1236 (*this, LHS, RHS, LHSType, RHSType, IsCompAssign);
Douglas Gregora11693b2008-11-12 17:17:38 +00001237}
1238
Bill Schmidteb03ae22013-02-01 15:34:29 +00001239
Chris Lattner513165e2008-07-25 21:10:04 +00001240//===----------------------------------------------------------------------===//
1241// Semantic Analysis for various Expression Types
1242//===----------------------------------------------------------------------===//
1243
1244
Peter Collingbourne91147592011-04-15 00:35:48 +00001245ExprResult
1246Sema::ActOnGenericSelectionExpr(SourceLocation KeyLoc,
1247 SourceLocation DefaultLoc,
1248 SourceLocation RParenLoc,
1249 Expr *ControllingExpr,
Dmitri Gribenko82360372013-05-10 13:06:58 +00001250 ArrayRef<ParsedType> ArgTypes,
1251 ArrayRef<Expr *> ArgExprs) {
Richard Trieuba63ce62011-09-09 01:45:06 +00001252 unsigned NumAssocs = ArgTypes.size();
1253 assert(NumAssocs == ArgExprs.size());
Peter Collingbourne91147592011-04-15 00:35:48 +00001254
Peter Collingbourne91147592011-04-15 00:35:48 +00001255 TypeSourceInfo **Types = new TypeSourceInfo*[NumAssocs];
1256 for (unsigned i = 0; i < NumAssocs; ++i) {
Dmitri Gribenko82360372013-05-10 13:06:58 +00001257 if (ArgTypes[i])
1258 (void) GetTypeFromParser(ArgTypes[i], &Types[i]);
Peter Collingbourne91147592011-04-15 00:35:48 +00001259 else
1260 Types[i] = 0;
1261 }
1262
1263 ExprResult ER = CreateGenericSelectionExpr(KeyLoc, DefaultLoc, RParenLoc,
Dmitri Gribenko82360372013-05-10 13:06:58 +00001264 ControllingExpr,
1265 llvm::makeArrayRef(Types, NumAssocs),
1266 ArgExprs);
Benjamin Kramer34623762011-04-15 11:21:57 +00001267 delete [] Types;
Peter Collingbourne91147592011-04-15 00:35:48 +00001268 return ER;
1269}
1270
1271ExprResult
1272Sema::CreateGenericSelectionExpr(SourceLocation KeyLoc,
1273 SourceLocation DefaultLoc,
1274 SourceLocation RParenLoc,
1275 Expr *ControllingExpr,
Dmitri Gribenko82360372013-05-10 13:06:58 +00001276 ArrayRef<TypeSourceInfo *> Types,
1277 ArrayRef<Expr *> Exprs) {
1278 unsigned NumAssocs = Types.size();
1279 assert(NumAssocs == Exprs.size());
John McCall587b3482013-02-12 02:08:12 +00001280 if (ControllingExpr->getType()->isPlaceholderType()) {
1281 ExprResult result = CheckPlaceholderExpr(ControllingExpr);
1282 if (result.isInvalid()) return ExprError();
1283 ControllingExpr = result.take();
1284 }
1285
Peter Collingbourne91147592011-04-15 00:35:48 +00001286 bool TypeErrorFound = false,
1287 IsResultDependent = ControllingExpr->isTypeDependent(),
1288 ContainsUnexpandedParameterPack
1289 = ControllingExpr->containsUnexpandedParameterPack();
1290
1291 for (unsigned i = 0; i < NumAssocs; ++i) {
1292 if (Exprs[i]->containsUnexpandedParameterPack())
1293 ContainsUnexpandedParameterPack = true;
1294
1295 if (Types[i]) {
1296 if (Types[i]->getType()->containsUnexpandedParameterPack())
1297 ContainsUnexpandedParameterPack = true;
1298
1299 if (Types[i]->getType()->isDependentType()) {
1300 IsResultDependent = true;
1301 } else {
Benjamin Kramere56f3932011-12-23 17:00:35 +00001302 // C11 6.5.1.1p2 "The type name in a generic association shall specify a
Peter Collingbourne91147592011-04-15 00:35:48 +00001303 // complete object type other than a variably modified type."
1304 unsigned D = 0;
1305 if (Types[i]->getType()->isIncompleteType())
1306 D = diag::err_assoc_type_incomplete;
1307 else if (!Types[i]->getType()->isObjectType())
1308 D = diag::err_assoc_type_nonobject;
1309 else if (Types[i]->getType()->isVariablyModifiedType())
1310 D = diag::err_assoc_type_variably_modified;
1311
1312 if (D != 0) {
1313 Diag(Types[i]->getTypeLoc().getBeginLoc(), D)
1314 << Types[i]->getTypeLoc().getSourceRange()
1315 << Types[i]->getType();
1316 TypeErrorFound = true;
1317 }
1318
Benjamin Kramere56f3932011-12-23 17:00:35 +00001319 // C11 6.5.1.1p2 "No two generic associations in the same generic
Peter Collingbourne91147592011-04-15 00:35:48 +00001320 // selection shall specify compatible types."
1321 for (unsigned j = i+1; j < NumAssocs; ++j)
1322 if (Types[j] && !Types[j]->getType()->isDependentType() &&
1323 Context.typesAreCompatible(Types[i]->getType(),
1324 Types[j]->getType())) {
1325 Diag(Types[j]->getTypeLoc().getBeginLoc(),
1326 diag::err_assoc_compatible_types)
1327 << Types[j]->getTypeLoc().getSourceRange()
1328 << Types[j]->getType()
1329 << Types[i]->getType();
1330 Diag(Types[i]->getTypeLoc().getBeginLoc(),
1331 diag::note_compat_assoc)
1332 << Types[i]->getTypeLoc().getSourceRange()
1333 << Types[i]->getType();
1334 TypeErrorFound = true;
1335 }
1336 }
1337 }
1338 }
1339 if (TypeErrorFound)
1340 return ExprError();
1341
1342 // If we determined that the generic selection is result-dependent, don't
1343 // try to compute the result expression.
1344 if (IsResultDependent)
1345 return Owned(new (Context) GenericSelectionExpr(
1346 Context, KeyLoc, ControllingExpr,
Dmitri Gribenko82360372013-05-10 13:06:58 +00001347 Types, Exprs,
Benjamin Kramerc215e762012-08-24 11:54:20 +00001348 DefaultLoc, RParenLoc, ContainsUnexpandedParameterPack));
Peter Collingbourne91147592011-04-15 00:35:48 +00001349
Chris Lattner0e62c1c2011-07-23 10:55:15 +00001350 SmallVector<unsigned, 1> CompatIndices;
Peter Collingbourne91147592011-04-15 00:35:48 +00001351 unsigned DefaultIndex = -1U;
1352 for (unsigned i = 0; i < NumAssocs; ++i) {
1353 if (!Types[i])
1354 DefaultIndex = i;
1355 else if (Context.typesAreCompatible(ControllingExpr->getType(),
1356 Types[i]->getType()))
1357 CompatIndices.push_back(i);
1358 }
1359
Benjamin Kramere56f3932011-12-23 17:00:35 +00001360 // C11 6.5.1.1p2 "The controlling expression of a generic selection shall have
Peter Collingbourne91147592011-04-15 00:35:48 +00001361 // type compatible with at most one of the types named in its generic
1362 // association list."
1363 if (CompatIndices.size() > 1) {
1364 // We strip parens here because the controlling expression is typically
1365 // parenthesized in macro definitions.
1366 ControllingExpr = ControllingExpr->IgnoreParens();
1367 Diag(ControllingExpr->getLocStart(), diag::err_generic_sel_multi_match)
1368 << ControllingExpr->getSourceRange() << ControllingExpr->getType()
1369 << (unsigned) CompatIndices.size();
Craig Topper2341c0d2013-07-04 03:08:24 +00001370 for (SmallVectorImpl<unsigned>::iterator I = CompatIndices.begin(),
Peter Collingbourne91147592011-04-15 00:35:48 +00001371 E = CompatIndices.end(); I != E; ++I) {
1372 Diag(Types[*I]->getTypeLoc().getBeginLoc(),
1373 diag::note_compat_assoc)
1374 << Types[*I]->getTypeLoc().getSourceRange()
1375 << Types[*I]->getType();
1376 }
1377 return ExprError();
1378 }
1379
Benjamin Kramere56f3932011-12-23 17:00:35 +00001380 // C11 6.5.1.1p2 "If a generic selection has no default generic association,
Peter Collingbourne91147592011-04-15 00:35:48 +00001381 // its controlling expression shall have type compatible with exactly one of
1382 // the types named in its generic association list."
1383 if (DefaultIndex == -1U && CompatIndices.size() == 0) {
1384 // We strip parens here because the controlling expression is typically
1385 // parenthesized in macro definitions.
1386 ControllingExpr = ControllingExpr->IgnoreParens();
1387 Diag(ControllingExpr->getLocStart(), diag::err_generic_sel_no_match)
1388 << ControllingExpr->getSourceRange() << ControllingExpr->getType();
1389 return ExprError();
1390 }
1391
Benjamin Kramere56f3932011-12-23 17:00:35 +00001392 // C11 6.5.1.1p3 "If a generic selection has a generic association with a
Peter Collingbourne91147592011-04-15 00:35:48 +00001393 // type name that is compatible with the type of the controlling expression,
1394 // then the result expression of the generic selection is the expression
1395 // in that generic association. Otherwise, the result expression of the
1396 // generic selection is the expression in the default generic association."
1397 unsigned ResultIndex =
1398 CompatIndices.size() ? CompatIndices[0] : DefaultIndex;
1399
1400 return Owned(new (Context) GenericSelectionExpr(
1401 Context, KeyLoc, ControllingExpr,
Dmitri Gribenko82360372013-05-10 13:06:58 +00001402 Types, Exprs,
Benjamin Kramerc215e762012-08-24 11:54:20 +00001403 DefaultLoc, RParenLoc, ContainsUnexpandedParameterPack,
Peter Collingbourne91147592011-04-15 00:35:48 +00001404 ResultIndex));
1405}
1406
Richard Smith75b67d62012-03-08 01:34:56 +00001407/// getUDSuffixLoc - Create a SourceLocation for a ud-suffix, given the
1408/// location of the token and the offset of the ud-suffix within it.
1409static SourceLocation getUDSuffixLoc(Sema &S, SourceLocation TokLoc,
1410 unsigned Offset) {
1411 return Lexer::AdvanceToTokenCharacter(TokLoc, Offset, S.getSourceManager(),
David Blaikiebbafb8a2012-03-11 07:00:24 +00001412 S.getLangOpts());
Richard Smith75b67d62012-03-08 01:34:56 +00001413}
1414
Richard Smithbcc22fc2012-03-09 08:00:36 +00001415/// BuildCookedLiteralOperatorCall - A user-defined literal was found. Look up
1416/// the corresponding cooked (non-raw) literal operator, and build a call to it.
1417static ExprResult BuildCookedLiteralOperatorCall(Sema &S, Scope *Scope,
1418 IdentifierInfo *UDSuffix,
1419 SourceLocation UDSuffixLoc,
1420 ArrayRef<Expr*> Args,
1421 SourceLocation LitEndLoc) {
1422 assert(Args.size() <= 2 && "too many arguments for literal operator");
1423
1424 QualType ArgTy[2];
1425 for (unsigned ArgIdx = 0; ArgIdx != Args.size(); ++ArgIdx) {
1426 ArgTy[ArgIdx] = Args[ArgIdx]->getType();
1427 if (ArgTy[ArgIdx]->isArrayType())
1428 ArgTy[ArgIdx] = S.Context.getArrayDecayedType(ArgTy[ArgIdx]);
1429 }
1430
1431 DeclarationName OpName =
1432 S.Context.DeclarationNames.getCXXLiteralOperatorName(UDSuffix);
1433 DeclarationNameInfo OpNameInfo(OpName, UDSuffixLoc);
1434 OpNameInfo.setCXXLiteralOperatorNameLoc(UDSuffixLoc);
1435
1436 LookupResult R(S, OpName, UDSuffixLoc, Sema::LookupOrdinaryName);
1437 if (S.LookupLiteralOperator(Scope, R, llvm::makeArrayRef(ArgTy, Args.size()),
1438 /*AllowRawAndTemplate*/false) == Sema::LOLR_Error)
1439 return ExprError();
1440
1441 return S.BuildLiteralOperatorCall(R, OpNameInfo, Args, LitEndLoc);
1442}
1443
Steve Naroff83895f72007-09-16 03:34:24 +00001444/// ActOnStringLiteral - The specified tokens were lexed as pasted string
Chris Lattner5b183d82006-11-10 05:03:26 +00001445/// fragments (e.g. "foo" "bar" L"baz"). The result string has to handle string
1446/// concatenation ([C99 5.1.1.2, translation phase #6]), so it may come from
1447/// multiple tokens. However, the common case is that StringToks points to one
1448/// string.
Sebastian Redlffbcf962009-01-18 18:53:16 +00001449///
John McCalldadc5752010-08-24 06:29:42 +00001450ExprResult
Richard Smithbcc22fc2012-03-09 08:00:36 +00001451Sema::ActOnStringLiteral(const Token *StringToks, unsigned NumStringToks,
1452 Scope *UDLScope) {
Chris Lattner5b183d82006-11-10 05:03:26 +00001453 assert(NumStringToks && "Must have at least one string!");
1454
Chris Lattner8a24e582009-01-16 18:51:42 +00001455 StringLiteralParser Literal(StringToks, NumStringToks, PP);
Steve Naroff4f88b312007-03-13 22:37:02 +00001456 if (Literal.hadError)
Sebastian Redlffbcf962009-01-18 18:53:16 +00001457 return ExprError();
Chris Lattner5b183d82006-11-10 05:03:26 +00001458
Chris Lattner0e62c1c2011-07-23 10:55:15 +00001459 SmallVector<SourceLocation, 4> StringTokLocs;
Chris Lattner5b183d82006-11-10 05:03:26 +00001460 for (unsigned i = 0; i != NumStringToks; ++i)
1461 StringTokLocs.push_back(StringToks[i].getLocation());
Chris Lattner36fc8792008-02-11 00:02:17 +00001462
Chris Lattner36fc8792008-02-11 00:02:17 +00001463 QualType StrTy = Context.CharTy;
Douglas Gregorfb65e592011-07-27 05:40:30 +00001464 if (Literal.isWide())
Hans Wennborg0d81e012013-05-10 10:08:40 +00001465 StrTy = Context.getWideCharType();
Douglas Gregorfb65e592011-07-27 05:40:30 +00001466 else if (Literal.isUTF16())
1467 StrTy = Context.Char16Ty;
1468 else if (Literal.isUTF32())
1469 StrTy = Context.Char32Ty;
Eli Friedmanfcec6302011-11-01 02:23:42 +00001470 else if (Literal.isPascal())
Anders Carlsson6b06e182011-04-06 18:42:48 +00001471 StrTy = Context.UnsignedCharTy;
Douglas Gregoraa1e21d2008-09-12 00:47:35 +00001472
Douglas Gregorfb65e592011-07-27 05:40:30 +00001473 StringLiteral::StringKind Kind = StringLiteral::Ascii;
1474 if (Literal.isWide())
1475 Kind = StringLiteral::Wide;
1476 else if (Literal.isUTF8())
1477 Kind = StringLiteral::UTF8;
1478 else if (Literal.isUTF16())
1479 Kind = StringLiteral::UTF16;
1480 else if (Literal.isUTF32())
1481 Kind = StringLiteral::UTF32;
1482
Douglas Gregoraa1e21d2008-09-12 00:47:35 +00001483 // A C++ string literal has a const-qualified element type (C++ 2.13.4p1).
David Blaikiebbafb8a2012-03-11 07:00:24 +00001484 if (getLangOpts().CPlusPlus || getLangOpts().ConstStrings)
Douglas Gregoraa1e21d2008-09-12 00:47:35 +00001485 StrTy.addConst();
Sebastian Redlffbcf962009-01-18 18:53:16 +00001486
Chris Lattner36fc8792008-02-11 00:02:17 +00001487 // Get an array type for the string, according to C99 6.4.5. This includes
1488 // the nul terminator character as well as the string length for pascal
1489 // strings.
1490 StrTy = Context.getConstantArrayType(StrTy,
Chris Lattnerd42c29f2009-02-26 23:01:51 +00001491 llvm::APInt(32, Literal.GetNumStringChars()+1),
Chris Lattner36fc8792008-02-11 00:02:17 +00001492 ArrayType::Normal, 0);
Mike Stump11289f42009-09-09 15:08:12 +00001493
Chris Lattner5b183d82006-11-10 05:03:26 +00001494 // Pass &StringTokLocs[0], StringTokLocs.size() to factory!
Richard Smithc67fdd42012-03-07 08:35:16 +00001495 StringLiteral *Lit = StringLiteral::Create(Context, Literal.GetString(),
1496 Kind, Literal.Pascal, StrTy,
1497 &StringTokLocs[0],
1498 StringTokLocs.size());
1499 if (Literal.getUDSuffix().empty())
1500 return Owned(Lit);
1501
1502 // We're building a user-defined literal.
1503 IdentifierInfo *UDSuffix = &Context.Idents.get(Literal.getUDSuffix());
Richard Smith75b67d62012-03-08 01:34:56 +00001504 SourceLocation UDSuffixLoc =
1505 getUDSuffixLoc(*this, StringTokLocs[Literal.getUDSuffixToken()],
1506 Literal.getUDSuffixOffset());
Richard Smithc67fdd42012-03-07 08:35:16 +00001507
Richard Smithbcc22fc2012-03-09 08:00:36 +00001508 // Make sure we're allowed user-defined literals here.
1509 if (!UDLScope)
1510 return ExprError(Diag(UDSuffixLoc, diag::err_invalid_string_udl));
1511
Richard Smithc67fdd42012-03-07 08:35:16 +00001512 // C++11 [lex.ext]p5: The literal L is treated as a call of the form
1513 // operator "" X (str, len)
1514 QualType SizeType = Context.getSizeType();
1515 llvm::APInt Len(Context.getIntWidth(SizeType), Literal.GetNumStringChars());
1516 IntegerLiteral *LenArg = IntegerLiteral::Create(Context, Len, SizeType,
1517 StringTokLocs[0]);
1518 Expr *Args[] = { Lit, LenArg };
Richard Smithbcc22fc2012-03-09 08:00:36 +00001519 return BuildCookedLiteralOperatorCall(*this, UDLScope, UDSuffix, UDSuffixLoc,
1520 Args, StringTokLocs.back());
Chris Lattner5b183d82006-11-10 05:03:26 +00001521}
1522
John McCalldadc5752010-08-24 06:29:42 +00001523ExprResult
John McCall7decc9e2010-11-18 06:31:45 +00001524Sema::BuildDeclRefExpr(ValueDecl *D, QualType Ty, ExprValueKind VK,
John McCallf4cd4f92011-02-09 01:13:10 +00001525 SourceLocation Loc,
1526 const CXXScopeSpec *SS) {
Abramo Bagnarad6d2f182010-08-11 22:01:17 +00001527 DeclarationNameInfo NameInfo(D->getDeclName(), Loc);
John McCall7decc9e2010-11-18 06:31:45 +00001528 return BuildDeclRefExpr(D, Ty, VK, NameInfo, SS);
Abramo Bagnarad6d2f182010-08-11 22:01:17 +00001529}
1530
John McCallf4cd4f92011-02-09 01:13:10 +00001531/// BuildDeclRefExpr - Build an expression that references a
1532/// declaration that does not require a closure capture.
John McCalldadc5752010-08-24 06:29:42 +00001533ExprResult
John McCallf4cd4f92011-02-09 01:13:10 +00001534Sema::BuildDeclRefExpr(ValueDecl *D, QualType Ty, ExprValueKind VK,
Abramo Bagnarad6d2f182010-08-11 22:01:17 +00001535 const DeclarationNameInfo &NameInfo,
Daniel Jasper689ae012013-03-22 10:01:35 +00001536 const CXXScopeSpec *SS, NamedDecl *FoundD) {
David Blaikiebbafb8a2012-03-11 07:00:24 +00001537 if (getLangOpts().CUDA)
Peter Collingbourne7277fe82011-10-02 23:49:40 +00001538 if (const FunctionDecl *Caller = dyn_cast<FunctionDecl>(CurContext))
1539 if (const FunctionDecl *Callee = dyn_cast<FunctionDecl>(D)) {
1540 CUDAFunctionTarget CallerTarget = IdentifyCUDATarget(Caller),
1541 CalleeTarget = IdentifyCUDATarget(Callee);
1542 if (CheckCUDATarget(CallerTarget, CalleeTarget)) {
1543 Diag(NameInfo.getLoc(), diag::err_ref_bad_target)
1544 << CalleeTarget << D->getIdentifier() << CallerTarget;
1545 Diag(D->getLocation(), diag::note_previous_decl)
1546 << D->getIdentifier();
1547 return ExprError();
1548 }
1549 }
1550
John McCall113bee02012-03-10 09:33:50 +00001551 bool refersToEnclosingScope =
1552 (CurContext != D->getDeclContext() &&
1553 D->getDeclContext()->isFunctionOrMethod());
1554
Eli Friedmanfa0df832012-02-02 03:46:19 +00001555 DeclRefExpr *E = DeclRefExpr::Create(Context,
1556 SS ? SS->getWithLocInContext(Context)
1557 : NestedNameSpecifierLoc(),
John McCall113bee02012-03-10 09:33:50 +00001558 SourceLocation(),
1559 D, refersToEnclosingScope,
Daniel Jasper689ae012013-03-22 10:01:35 +00001560 NameInfo, Ty, VK, FoundD);
Mike Stump11289f42009-09-09 15:08:12 +00001561
Eli Friedmanfa0df832012-02-02 03:46:19 +00001562 MarkDeclRefReferenced(E);
John McCall086a4642010-11-24 05:12:34 +00001563
Jordan Rose657b5f42012-09-28 22:21:35 +00001564 if (getLangOpts().ObjCARCWeak && isa<VarDecl>(D) &&
1565 Ty.getObjCLifetime() == Qualifiers::OCL_Weak) {
1566 DiagnosticsEngine::Level Level =
1567 Diags.getDiagnosticLevel(diag::warn_arc_repeated_use_of_weak,
1568 E->getLocStart());
1569 if (Level != DiagnosticsEngine::Ignored)
Fariborz Jahanian6f829e32013-05-21 21:20:26 +00001570 recordUseOfEvaluatedWeak(E);
Jordan Rose657b5f42012-09-28 22:21:35 +00001571 }
1572
John McCall086a4642010-11-24 05:12:34 +00001573 // Just in case we're building an illegal pointer-to-member.
Richard Smithcaf33902011-10-10 18:28:20 +00001574 FieldDecl *FD = dyn_cast<FieldDecl>(D);
1575 if (FD && FD->isBitField())
John McCall086a4642010-11-24 05:12:34 +00001576 E->setObjectKind(OK_BitField);
1577
1578 return Owned(E);
Douglas Gregorc7acfdf2009-01-06 05:10:23 +00001579}
1580
Abramo Bagnarad6d2f182010-08-11 22:01:17 +00001581/// Decomposes the given name into a DeclarationNameInfo, its location, and
John McCall10eae182009-11-30 22:42:35 +00001582/// possibly a list of template arguments.
1583///
1584/// If this produces template arguments, it is permitted to call
1585/// DecomposeTemplateName.
1586///
1587/// This actually loses a lot of source location information for
1588/// non-standard name kinds; we should consider preserving that in
1589/// some way.
Richard Trieucfc491d2011-08-02 04:35:43 +00001590void
1591Sema::DecomposeUnqualifiedId(const UnqualifiedId &Id,
1592 TemplateArgumentListInfo &Buffer,
1593 DeclarationNameInfo &NameInfo,
1594 const TemplateArgumentListInfo *&TemplateArgs) {
John McCall10eae182009-11-30 22:42:35 +00001595 if (Id.getKind() == UnqualifiedId::IK_TemplateId) {
1596 Buffer.setLAngleLoc(Id.TemplateId->LAngleLoc);
1597 Buffer.setRAngleLoc(Id.TemplateId->RAngleLoc);
1598
Benjamin Kramercc4c49d2012-08-23 23:38:35 +00001599 ASTTemplateArgsPtr TemplateArgsPtr(Id.TemplateId->getTemplateArgs(),
John McCall10eae182009-11-30 22:42:35 +00001600 Id.TemplateId->NumArgs);
Douglas Gregor5476205b2011-06-23 00:49:38 +00001601 translateTemplateArguments(TemplateArgsPtr, Buffer);
John McCall10eae182009-11-30 22:42:35 +00001602
John McCall3e56fd42010-08-23 07:28:44 +00001603 TemplateName TName = Id.TemplateId->Template.get();
Abramo Bagnarad6d2f182010-08-11 22:01:17 +00001604 SourceLocation TNameLoc = Id.TemplateId->TemplateNameLoc;
Douglas Gregor5476205b2011-06-23 00:49:38 +00001605 NameInfo = Context.getNameForTemplate(TName, TNameLoc);
John McCall10eae182009-11-30 22:42:35 +00001606 TemplateArgs = &Buffer;
1607 } else {
Douglas Gregor5476205b2011-06-23 00:49:38 +00001608 NameInfo = GetNameFromUnqualifiedId(Id);
John McCall10eae182009-11-30 22:42:35 +00001609 TemplateArgs = 0;
1610 }
1611}
1612
John McCalld681c392009-12-16 08:11:27 +00001613/// Diagnose an empty lookup.
1614///
1615/// \return false if new lookup candidates were found
Nick Lewyckyc96c37f2010-07-06 19:51:49 +00001616bool Sema::DiagnoseEmptyLookup(Scope *S, CXXScopeSpec &SS, LookupResult &R,
Kaelyn Uhrain79d01c12012-01-18 05:58:54 +00001617 CorrectionCandidateCallback &CCC,
Kaelyn Uhrain42830922011-08-05 00:09:52 +00001618 TemplateArgumentListInfo *ExplicitTemplateArgs,
Ahmed Charlesb24b9aa2012-02-25 11:00:22 +00001619 llvm::ArrayRef<Expr *> Args) {
John McCalld681c392009-12-16 08:11:27 +00001620 DeclarationName Name = R.getLookupName();
1621
John McCalld681c392009-12-16 08:11:27 +00001622 unsigned diagnostic = diag::err_undeclared_var_use;
Douglas Gregor598b08f2009-12-31 05:20:13 +00001623 unsigned diagnostic_suggest = diag::err_undeclared_var_use_suggest;
John McCalld681c392009-12-16 08:11:27 +00001624 if (Name.getNameKind() == DeclarationName::CXXOperatorName ||
1625 Name.getNameKind() == DeclarationName::CXXLiteralOperatorName ||
Douglas Gregor598b08f2009-12-31 05:20:13 +00001626 Name.getNameKind() == DeclarationName::CXXConversionFunctionName) {
John McCalld681c392009-12-16 08:11:27 +00001627 diagnostic = diag::err_undeclared_use;
Douglas Gregor598b08f2009-12-31 05:20:13 +00001628 diagnostic_suggest = diag::err_undeclared_use_suggest;
1629 }
John McCalld681c392009-12-16 08:11:27 +00001630
Douglas Gregor598b08f2009-12-31 05:20:13 +00001631 // If the original lookup was an unqualified lookup, fake an
1632 // unqualified lookup. This is useful when (for example) the
1633 // original lookup would not have found something because it was a
1634 // dependent name.
David Blaikiec4c0e8a2012-05-28 01:26:45 +00001635 DeclContext *DC = (SS.isEmpty() && !CallsUndergoingInstantiation.empty())
1636 ? CurContext : 0;
Francois Pichetde232cb2011-11-25 01:10:54 +00001637 while (DC) {
John McCalld681c392009-12-16 08:11:27 +00001638 if (isa<CXXRecordDecl>(DC)) {
1639 LookupQualifiedName(R, DC);
1640
1641 if (!R.empty()) {
1642 // Don't give errors about ambiguities in this lookup.
1643 R.suppressDiagnostics();
1644
Francois Pichet857f9d62011-11-17 03:44:24 +00001645 // During a default argument instantiation the CurContext points
1646 // to a CXXMethodDecl; but we can't apply a this-> fixit inside a
1647 // function parameter list, hence add an explicit check.
1648 bool isDefaultArgument = !ActiveTemplateInstantiations.empty() &&
1649 ActiveTemplateInstantiations.back().Kind ==
1650 ActiveTemplateInstantiation::DefaultFunctionArgumentInstantiation;
John McCalld681c392009-12-16 08:11:27 +00001651 CXXMethodDecl *CurMethod = dyn_cast<CXXMethodDecl>(CurContext);
1652 bool isInstance = CurMethod &&
1653 CurMethod->isInstance() &&
Francois Pichet857f9d62011-11-17 03:44:24 +00001654 DC == CurMethod->getParent() && !isDefaultArgument;
1655
John McCalld681c392009-12-16 08:11:27 +00001656
1657 // Give a code modification hint to insert 'this->'.
1658 // TODO: fixit for inserting 'Base<T>::' in the other cases.
1659 // Actually quite difficult!
Nico Weberdf7dffb2012-06-20 20:21:42 +00001660 if (getLangOpts().MicrosoftMode)
1661 diagnostic = diag::warn_found_via_dependent_bases_lookup;
Nick Lewyckyc96c37f2010-07-06 19:51:49 +00001662 if (isInstance) {
Nico Weber3c10fb12012-06-22 16:39:39 +00001663 Diag(R.getNameLoc(), diagnostic) << Name
1664 << FixItHint::CreateInsertion(R.getNameLoc(), "this->");
Nick Lewyckyc96c37f2010-07-06 19:51:49 +00001665 UnresolvedLookupExpr *ULE = cast<UnresolvedLookupExpr>(
1666 CallsUndergoingInstantiation.back()->getCallee());
Nico Weber3c10fb12012-06-22 16:39:39 +00001667
Nico Weber3c10fb12012-06-22 16:39:39 +00001668 CXXMethodDecl *DepMethod;
Douglas Gregor89c0a912013-03-26 22:43:55 +00001669 if (CurMethod->isDependentContext())
1670 DepMethod = CurMethod;
1671 else if (CurMethod->getTemplatedKind() ==
Nico Weber3c10fb12012-06-22 16:39:39 +00001672 FunctionDecl::TK_FunctionTemplateSpecialization)
1673 DepMethod = cast<CXXMethodDecl>(CurMethod->getPrimaryTemplate()->
1674 getInstantiatedFromMemberTemplate()->getTemplatedDecl());
1675 else
1676 DepMethod = cast<CXXMethodDecl>(
1677 CurMethod->getInstantiatedFromMemberFunction());
1678 assert(DepMethod && "No template pattern found");
1679
1680 QualType DepThisType = DepMethod->getThisType(Context);
1681 CheckCXXThisCapture(R.getNameLoc());
1682 CXXThisExpr *DepThis = new (Context) CXXThisExpr(
1683 R.getNameLoc(), DepThisType, false);
1684 TemplateArgumentListInfo TList;
1685 if (ULE->hasExplicitTemplateArgs())
1686 ULE->copyTemplateArgumentsInto(TList);
1687
1688 CXXScopeSpec SS;
1689 SS.Adopt(ULE->getQualifierLoc());
1690 CXXDependentScopeMemberExpr *DepExpr =
1691 CXXDependentScopeMemberExpr::Create(
1692 Context, DepThis, DepThisType, true, SourceLocation(),
1693 SS.getWithLocInContext(Context),
1694 ULE->getTemplateKeywordLoc(), 0,
1695 R.getLookupNameInfo(),
1696 ULE->hasExplicitTemplateArgs() ? &TList : 0);
1697 CallsUndergoingInstantiation.back()->setCallee(DepExpr);
Nick Lewyckyc96c37f2010-07-06 19:51:49 +00001698 } else {
John McCalld681c392009-12-16 08:11:27 +00001699 Diag(R.getNameLoc(), diagnostic) << Name;
Nick Lewyckyc96c37f2010-07-06 19:51:49 +00001700 }
John McCalld681c392009-12-16 08:11:27 +00001701
1702 // Do we really want to note all of these?
1703 for (LookupResult::iterator I = R.begin(), E = R.end(); I != E; ++I)
1704 Diag((*I)->getLocation(), diag::note_dependent_var_use);
1705
Francois Pichet857f9d62011-11-17 03:44:24 +00001706 // Return true if we are inside a default argument instantiation
1707 // and the found name refers to an instance member function, otherwise
1708 // the function calling DiagnoseEmptyLookup will try to create an
1709 // implicit member call and this is wrong for default argument.
1710 if (isDefaultArgument && ((*R.begin())->isCXXInstanceMember())) {
1711 Diag(R.getNameLoc(), diag::err_member_call_without_object);
1712 return true;
1713 }
1714
John McCalld681c392009-12-16 08:11:27 +00001715 // Tell the callee to try to recover.
1716 return false;
1717 }
Douglas Gregor86b8d9f2010-08-09 22:38:14 +00001718
1719 R.clear();
John McCalld681c392009-12-16 08:11:27 +00001720 }
Francois Pichetde232cb2011-11-25 01:10:54 +00001721
1722 // In Microsoft mode, if we are performing lookup from within a friend
1723 // function definition declared at class scope then we must set
1724 // DC to the lexical parent to be able to search into the parent
1725 // class.
David Blaikiebbafb8a2012-03-11 07:00:24 +00001726 if (getLangOpts().MicrosoftMode && isa<FunctionDecl>(DC) &&
Francois Pichetde232cb2011-11-25 01:10:54 +00001727 cast<FunctionDecl>(DC)->getFriendObjectKind() &&
1728 DC->getLexicalParent()->isRecord())
1729 DC = DC->getLexicalParent();
1730 else
1731 DC = DC->getParent();
John McCalld681c392009-12-16 08:11:27 +00001732 }
1733
Douglas Gregor598b08f2009-12-31 05:20:13 +00001734 // We didn't find anything, so try to correct for a typo.
Douglas Gregorc2fa1692011-06-28 16:20:02 +00001735 TypoCorrection Corrected;
1736 if (S && (Corrected = CorrectTypo(R.getLookupNameInfo(), R.getLookupKind(),
Kaelyn Uhrain4e8942c2012-01-31 23:49:25 +00001737 S, &SS, CCC))) {
David Blaikiebbafb8a2012-03-11 07:00:24 +00001738 std::string CorrectedStr(Corrected.getAsString(getLangOpts()));
1739 std::string CorrectedQuotedStr(Corrected.getQuoted(getLangOpts()));
Kaelyn Uhrain10413a42013-07-02 23:47:44 +00001740 bool droppedSpecifier =
1741 Corrected.WillReplaceSpecifier() && Name.getAsString() == CorrectedStr;
Douglas Gregorc2fa1692011-06-28 16:20:02 +00001742 R.setLookupName(Corrected.getCorrection());
1743
Hans Wennborg38198de2011-07-12 08:45:31 +00001744 if (NamedDecl *ND = Corrected.getCorrectionDecl()) {
Kaelyn Uhrainacbdc572011-08-03 20:36:05 +00001745 if (Corrected.isOverloaded()) {
1746 OverloadCandidateSet OCS(R.getNameLoc());
1747 OverloadCandidateSet::iterator Best;
1748 for (TypoCorrection::decl_iterator CD = Corrected.begin(),
1749 CDEnd = Corrected.end();
1750 CD != CDEnd; ++CD) {
Kaelyn Uhrain62422202011-08-08 17:35:31 +00001751 if (FunctionTemplateDecl *FTD =
Kaelyn Uhrain42830922011-08-05 00:09:52 +00001752 dyn_cast<FunctionTemplateDecl>(*CD))
1753 AddTemplateOverloadCandidate(
1754 FTD, DeclAccessPair::make(FTD, AS_none), ExplicitTemplateArgs,
Ahmed Charlesb24b9aa2012-02-25 11:00:22 +00001755 Args, OCS);
Kaelyn Uhrain62422202011-08-08 17:35:31 +00001756 else if (FunctionDecl *FD = dyn_cast<FunctionDecl>(*CD))
1757 if (!ExplicitTemplateArgs || ExplicitTemplateArgs->size() == 0)
1758 AddOverloadCandidate(FD, DeclAccessPair::make(FD, AS_none),
Ahmed Charlesb24b9aa2012-02-25 11:00:22 +00001759 Args, OCS);
Kaelyn Uhrainacbdc572011-08-03 20:36:05 +00001760 }
1761 switch (OCS.BestViableFunction(*this, R.getNameLoc(), Best)) {
1762 case OR_Success:
1763 ND = Best->Function;
1764 break;
1765 default:
Kaelyn Uhrainea350182011-08-04 23:30:54 +00001766 break;
Kaelyn Uhrainacbdc572011-08-03 20:36:05 +00001767 }
1768 }
Douglas Gregorc2fa1692011-06-28 16:20:02 +00001769 R.addDecl(ND);
1770 if (isa<ValueDecl>(ND) || isa<FunctionTemplateDecl>(ND)) {
Douglas Gregor280e1ee2010-04-14 20:04:41 +00001771 if (SS.isEmpty())
Douglas Gregorc2fa1692011-06-28 16:20:02 +00001772 Diag(R.getNameLoc(), diagnostic_suggest) << Name << CorrectedQuotedStr
1773 << FixItHint::CreateReplacement(R.getNameLoc(), CorrectedStr);
Douglas Gregor280e1ee2010-04-14 20:04:41 +00001774 else
1775 Diag(R.getNameLoc(), diag::err_no_member_suggest)
Kaelyn Uhrain10413a42013-07-02 23:47:44 +00001776 << Name << computeDeclContext(SS, false) << droppedSpecifier
1777 << CorrectedQuotedStr << SS.getRange()
David Blaikie04ea41c2012-10-12 20:00:44 +00001778 << FixItHint::CreateReplacement(Corrected.getCorrectionRange(),
1779 CorrectedStr);
Ted Kremenekc6ebda12013-02-21 21:40:44 +00001780
Ted Kremenek2edaf4e2013-02-21 22:10:49 +00001781 unsigned diag = isa<ImplicitParamDecl>(ND)
1782 ? diag::note_implicit_param_decl
1783 : diag::note_previous_decl;
1784
1785 Diag(ND->getLocation(), diag)
1786 << CorrectedQuotedStr;
Douglas Gregor280e1ee2010-04-14 20:04:41 +00001787
1788 // Tell the callee to try to recover.
1789 return false;
1790 }
Alexis Huntc46382e2010-04-28 23:02:27 +00001791
Douglas Gregorc2fa1692011-06-28 16:20:02 +00001792 if (isa<TypeDecl>(ND) || isa<ObjCInterfaceDecl>(ND)) {
Douglas Gregor280e1ee2010-04-14 20:04:41 +00001793 // FIXME: If we ended up with a typo for a type name or
1794 // Objective-C class name, we're in trouble because the parser
1795 // is in the wrong place to recover. Suggest the typo
1796 // correction, but don't make it a fix-it since we're not going
1797 // to recover well anyway.
1798 if (SS.isEmpty())
Richard Trieucfc491d2011-08-02 04:35:43 +00001799 Diag(R.getNameLoc(), diagnostic_suggest)
1800 << Name << CorrectedQuotedStr;
Douglas Gregor280e1ee2010-04-14 20:04:41 +00001801 else
1802 Diag(R.getNameLoc(), diag::err_no_member_suggest)
Kaelyn Uhrain10413a42013-07-02 23:47:44 +00001803 << Name << computeDeclContext(SS, false) << droppedSpecifier
1804 << CorrectedQuotedStr << SS.getRange();
Douglas Gregor280e1ee2010-04-14 20:04:41 +00001805
1806 // Don't try to recover; it won't work.
1807 return true;
1808 }
1809 } else {
Alexis Huntc46382e2010-04-28 23:02:27 +00001810 // FIXME: We found a keyword. Suggest it, but don't provide a fix-it
Douglas Gregor280e1ee2010-04-14 20:04:41 +00001811 // because we aren't able to recover.
Douglas Gregor25363982010-01-01 00:15:04 +00001812 if (SS.isEmpty())
Douglas Gregorc2fa1692011-06-28 16:20:02 +00001813 Diag(R.getNameLoc(), diagnostic_suggest) << Name << CorrectedQuotedStr;
Kovarththanan Rajaratnamba2c6522010-03-13 10:17:05 +00001814 else
Douglas Gregor25363982010-01-01 00:15:04 +00001815 Diag(R.getNameLoc(), diag::err_no_member_suggest)
Kaelyn Uhrain10413a42013-07-02 23:47:44 +00001816 << Name << computeDeclContext(SS, false) << droppedSpecifier
1817 << CorrectedQuotedStr << SS.getRange();
Douglas Gregor25363982010-01-01 00:15:04 +00001818 return true;
1819 }
Douglas Gregor598b08f2009-12-31 05:20:13 +00001820 }
Douglas Gregorc2fa1692011-06-28 16:20:02 +00001821 R.clear();
Douglas Gregor598b08f2009-12-31 05:20:13 +00001822
1823 // Emit a special diagnostic for failed member lookups.
1824 // FIXME: computing the declaration context might fail here (?)
1825 if (!SS.isEmpty()) {
1826 Diag(R.getNameLoc(), diag::err_no_member)
1827 << Name << computeDeclContext(SS, false)
1828 << SS.getRange();
1829 return true;
1830 }
1831
John McCalld681c392009-12-16 08:11:27 +00001832 // Give up, we can't recover.
1833 Diag(R.getNameLoc(), diagnostic) << Name;
1834 return true;
1835}
1836
John McCalldadc5752010-08-24 06:29:42 +00001837ExprResult Sema::ActOnIdExpression(Scope *S,
John McCall24d18942010-08-24 22:52:39 +00001838 CXXScopeSpec &SS,
Abramo Bagnara7945c982012-01-27 09:46:47 +00001839 SourceLocation TemplateKWLoc,
John McCall24d18942010-08-24 22:52:39 +00001840 UnqualifiedId &Id,
1841 bool HasTrailingLParen,
Kaelyn Uhrain77e21fc2012-01-25 20:49:08 +00001842 bool IsAddressOfOperand,
Chad Rosierb9aff1e2013-05-24 18:32:55 +00001843 CorrectionCandidateCallback *CCC,
1844 bool IsInlineAsmIdentifier) {
Richard Trieuba63ce62011-09-09 01:45:06 +00001845 assert(!(IsAddressOfOperand && HasTrailingLParen) &&
John McCalle66edc12009-11-24 19:00:30 +00001846 "cannot be direct & operand and have a trailing lparen");
1847
1848 if (SS.isInvalid())
Douglas Gregored8f2882009-01-30 01:04:22 +00001849 return ExprError();
Douglas Gregor90a1a652009-03-19 17:26:29 +00001850
John McCall10eae182009-11-30 22:42:35 +00001851 TemplateArgumentListInfo TemplateArgsBuffer;
John McCalle66edc12009-11-24 19:00:30 +00001852
1853 // Decompose the UnqualifiedId into the following data.
Abramo Bagnarad6d2f182010-08-11 22:01:17 +00001854 DeclarationNameInfo NameInfo;
John McCalle66edc12009-11-24 19:00:30 +00001855 const TemplateArgumentListInfo *TemplateArgs;
Douglas Gregor5476205b2011-06-23 00:49:38 +00001856 DecomposeUnqualifiedId(Id, TemplateArgsBuffer, NameInfo, TemplateArgs);
Douglas Gregor90a1a652009-03-19 17:26:29 +00001857
Abramo Bagnarad6d2f182010-08-11 22:01:17 +00001858 DeclarationName Name = NameInfo.getName();
Douglas Gregor4ea80432008-11-18 15:03:34 +00001859 IdentifierInfo *II = Name.getAsIdentifierInfo();
Abramo Bagnarad6d2f182010-08-11 22:01:17 +00001860 SourceLocation NameLoc = NameInfo.getLoc();
John McCalld14a8642009-11-21 08:51:07 +00001861
John McCalle66edc12009-11-24 19:00:30 +00001862 // C++ [temp.dep.expr]p3:
1863 // An id-expression is type-dependent if it contains:
Douglas Gregorea0a0a92010-01-11 18:40:55 +00001864 // -- an identifier that was declared with a dependent type,
1865 // (note: handled after lookup)
1866 // -- a template-id that is dependent,
1867 // (note: handled in BuildTemplateIdExpr)
1868 // -- a conversion-function-id that specifies a dependent type,
John McCalle66edc12009-11-24 19:00:30 +00001869 // -- a nested-name-specifier that contains a class-name that
1870 // names a dependent type.
1871 // Determine whether this is a member of an unknown specialization;
1872 // we need to handle these differently.
Eli Friedman964dbda2010-08-06 23:41:47 +00001873 bool DependentID = false;
1874 if (Name.getNameKind() == DeclarationName::CXXConversionFunctionName &&
1875 Name.getCXXNameType()->isDependentType()) {
1876 DependentID = true;
1877 } else if (SS.isSet()) {
Chris Lattnerebb5c6c2011-02-18 01:27:55 +00001878 if (DeclContext *DC = computeDeclContext(SS, false)) {
Eli Friedman964dbda2010-08-06 23:41:47 +00001879 if (RequireCompleteDeclContext(SS, DC))
1880 return ExprError();
Eli Friedman964dbda2010-08-06 23:41:47 +00001881 } else {
1882 DependentID = true;
1883 }
1884 }
1885
Chris Lattnerebb5c6c2011-02-18 01:27:55 +00001886 if (DependentID)
Abramo Bagnara7945c982012-01-27 09:46:47 +00001887 return ActOnDependentIdExpression(SS, TemplateKWLoc, NameInfo,
1888 IsAddressOfOperand, TemplateArgs);
Chris Lattnerebb5c6c2011-02-18 01:27:55 +00001889
John McCalle66edc12009-11-24 19:00:30 +00001890 // Perform the required lookup.
Fariborz Jahanian7f4427f2011-07-12 17:16:56 +00001891 LookupResult R(*this, NameInfo,
1892 (Id.getKind() == UnqualifiedId::IK_ImplicitSelfParam)
1893 ? LookupObjCImplicitSelfParam : LookupOrdinaryName);
John McCalle66edc12009-11-24 19:00:30 +00001894 if (TemplateArgs) {
Douglas Gregor3e51e172010-05-20 20:58:56 +00001895 // Lookup the template name again to correctly establish the context in
1896 // which it was found. This is really unfortunate as we already did the
1897 // lookup to determine that it was a template name in the first place. If
1898 // this becomes a performance hit, we can work harder to preserve those
1899 // results until we get here but it's likely not worth it.
Douglas Gregor786123d2010-05-21 23:18:07 +00001900 bool MemberOfUnknownSpecialization;
1901 LookupTemplateName(R, S, SS, QualType(), /*EnteringContext=*/false,
1902 MemberOfUnknownSpecialization);
Douglas Gregora5226932011-02-04 13:35:07 +00001903
1904 if (MemberOfUnknownSpecialization ||
1905 (R.getResultKind() == LookupResult::NotFoundInCurrentInstantiation))
Abramo Bagnara7945c982012-01-27 09:46:47 +00001906 return ActOnDependentIdExpression(SS, TemplateKWLoc, NameInfo,
1907 IsAddressOfOperand, TemplateArgs);
John McCalle66edc12009-11-24 19:00:30 +00001908 } else {
Benjamin Kramer46921442012-01-20 14:57:34 +00001909 bool IvarLookupFollowUp = II && !SS.isSet() && getCurMethodDecl();
Fariborz Jahanian6fada5b2010-01-12 23:58:59 +00001910 LookupParsedName(R, S, &SS, !IvarLookupFollowUp);
Mike Stump11289f42009-09-09 15:08:12 +00001911
Douglas Gregora5226932011-02-04 13:35:07 +00001912 // If the result might be in a dependent base class, this is a dependent
1913 // id-expression.
1914 if (R.getResultKind() == LookupResult::NotFoundInCurrentInstantiation)
Abramo Bagnara7945c982012-01-27 09:46:47 +00001915 return ActOnDependentIdExpression(SS, TemplateKWLoc, NameInfo,
1916 IsAddressOfOperand, TemplateArgs);
1917
John McCalle66edc12009-11-24 19:00:30 +00001918 // If this reference is in an Objective-C method, then we need to do
1919 // some special Objective-C lookup, too.
Fariborz Jahanian6fada5b2010-01-12 23:58:59 +00001920 if (IvarLookupFollowUp) {
John McCalldadc5752010-08-24 06:29:42 +00001921 ExprResult E(LookupInObjCMethod(R, S, II, true));
John McCalle66edc12009-11-24 19:00:30 +00001922 if (E.isInvalid())
1923 return ExprError();
Mike Stump11289f42009-09-09 15:08:12 +00001924
Chris Lattnerebb5c6c2011-02-18 01:27:55 +00001925 if (Expr *Ex = E.takeAs<Expr>())
1926 return Owned(Ex);
Steve Naroffebf4cb42008-06-02 23:03:37 +00001927 }
Chris Lattner59a25942008-03-31 00:36:02 +00001928 }
Douglas Gregorf15f5d32009-02-16 19:28:42 +00001929
John McCalle66edc12009-11-24 19:00:30 +00001930 if (R.isAmbiguous())
1931 return ExprError();
1932
Douglas Gregor171c45a2009-02-18 21:56:37 +00001933 // Determine whether this name might be a candidate for
1934 // argument-dependent lookup.
John McCalle66edc12009-11-24 19:00:30 +00001935 bool ADL = UseArgumentDependentLookup(SS, R, HasTrailingLParen);
Douglas Gregor171c45a2009-02-18 21:56:37 +00001936
John McCalle66edc12009-11-24 19:00:30 +00001937 if (R.empty() && !ADL) {
Bill Wendling4073ed52007-02-13 01:51:42 +00001938 // Otherwise, this could be an implicitly declared function reference (legal
John McCalle66edc12009-11-24 19:00:30 +00001939 // in C90, extension in C99, forbidden in C++).
David Blaikiebbafb8a2012-03-11 07:00:24 +00001940 if (HasTrailingLParen && II && !getLangOpts().CPlusPlus) {
John McCalle66edc12009-11-24 19:00:30 +00001941 NamedDecl *D = ImplicitlyDefineFunction(NameLoc, *II, S);
1942 if (D) R.addDecl(D);
1943 }
1944
1945 // If this name wasn't predeclared and if this is not a function
1946 // call, diagnose the problem.
1947 if (R.empty()) {
Francois Pichetd8e4e412011-09-24 10:38:05 +00001948 // In Microsoft mode, if we are inside a template class member function
Richard Smitha3519fa2013-04-29 08:45:27 +00001949 // whose parent class has dependent base classes, and we can't resolve
1950 // an identifier, then assume the identifier is type dependent. The
1951 // goal is to postpone name lookup to instantiation time to be able to
1952 // search into the type dependent base classes.
1953 if (getLangOpts().MicrosoftMode) {
1954 CXXMethodDecl *MD = dyn_cast<CXXMethodDecl>(CurContext);
1955 if (MD && MD->getParent()->hasAnyDependentBases())
1956 return ActOnDependentIdExpression(SS, TemplateKWLoc, NameInfo,
1957 IsAddressOfOperand, TemplateArgs);
1958 }
Francois Pichetd8e4e412011-09-24 10:38:05 +00001959
Chad Rosierb9aff1e2013-05-24 18:32:55 +00001960 // Don't diagnose an empty lookup for inline assmebly.
1961 if (IsInlineAsmIdentifier)
1962 return ExprError();
1963
Kaelyn Uhrain79d01c12012-01-18 05:58:54 +00001964 CorrectionCandidateCallback DefaultValidator;
Kaelyn Uhrain77e21fc2012-01-25 20:49:08 +00001965 if (DiagnoseEmptyLookup(S, SS, R, CCC ? *CCC : DefaultValidator))
John McCalld681c392009-12-16 08:11:27 +00001966 return ExprError();
1967
1968 assert(!R.empty() &&
1969 "DiagnoseEmptyLookup returned false but added no results");
Douglas Gregor35b0bac2010-01-03 18:01:57 +00001970
1971 // If we found an Objective-C instance variable, let
1972 // LookupInObjCMethod build the appropriate expression to
Kovarththanan Rajaratnamba2c6522010-03-13 10:17:05 +00001973 // reference the ivar.
Douglas Gregor35b0bac2010-01-03 18:01:57 +00001974 if (ObjCIvarDecl *Ivar = R.getAsSingle<ObjCIvarDecl>()) {
1975 R.clear();
John McCalldadc5752010-08-24 06:29:42 +00001976 ExprResult E(LookupInObjCMethod(R, S, Ivar->getIdentifier()));
Fariborz Jahanian44653702011-09-23 23:11:38 +00001977 // In a hopelessly buggy code, Objective-C instance variable
1978 // lookup fails and no expression will be built to reference it.
1979 if (!E.isInvalid() && !E.get())
1980 return ExprError();
Benjamin Kramer62b95d82012-08-23 21:35:17 +00001981 return E;
Douglas Gregor35b0bac2010-01-03 18:01:57 +00001982 }
Steve Naroff92e30f82007-04-02 22:35:25 +00001983 }
Chris Lattner17ed4872006-11-20 04:58:19 +00001984 }
Mike Stump11289f42009-09-09 15:08:12 +00001985
John McCalle66edc12009-11-24 19:00:30 +00001986 // This is guaranteed from this point on.
1987 assert(!R.empty() || ADL);
1988
John McCall2d74de92009-12-01 22:10:20 +00001989 // Check whether this might be a C++ implicit instance member access.
John McCall24d18942010-08-24 22:52:39 +00001990 // C++ [class.mfct.non-static]p3:
1991 // When an id-expression that is not part of a class member access
1992 // syntax and not used to form a pointer to member is used in the
1993 // body of a non-static member function of class X, if name lookup
1994 // resolves the name in the id-expression to a non-static non-type
1995 // member of some class C, the id-expression is transformed into a
1996 // class member access expression using (*this) as the
1997 // postfix-expression to the left of the . operator.
John McCall8d08b9b2010-08-27 09:08:28 +00001998 //
1999 // But we don't actually need to do this for '&' operands if R
2000 // resolved to a function or overloaded function set, because the
2001 // expression is ill-formed if it actually works out to be a
2002 // non-static member function:
2003 //
2004 // C++ [expr.ref]p4:
2005 // Otherwise, if E1.E2 refers to a non-static member function. . .
2006 // [t]he expression can be used only as the left-hand operand of a
2007 // member function call.
2008 //
2009 // There are other safeguards against such uses, but it's important
2010 // to get this right here so that we don't end up making a
2011 // spuriously dependent expression if we're inside a dependent
2012 // instance method.
John McCall57500772009-12-16 12:17:52 +00002013 if (!R.empty() && (*R.begin())->isCXXClassMember()) {
John McCall8d08b9b2010-08-27 09:08:28 +00002014 bool MightBeImplicitMember;
Richard Trieuba63ce62011-09-09 01:45:06 +00002015 if (!IsAddressOfOperand)
John McCall8d08b9b2010-08-27 09:08:28 +00002016 MightBeImplicitMember = true;
2017 else if (!SS.isEmpty())
2018 MightBeImplicitMember = false;
2019 else if (R.isOverloadedResult())
2020 MightBeImplicitMember = false;
Douglas Gregor1262b062010-08-30 16:00:47 +00002021 else if (R.isUnresolvableResult())
2022 MightBeImplicitMember = true;
John McCall8d08b9b2010-08-27 09:08:28 +00002023 else
Francois Pichet783dd6e2010-11-21 06:08:52 +00002024 MightBeImplicitMember = isa<FieldDecl>(R.getFoundDecl()) ||
Reid Kleckner0a0c8892013-06-19 16:37:23 +00002025 isa<IndirectFieldDecl>(R.getFoundDecl()) ||
2026 isa<MSPropertyDecl>(R.getFoundDecl());
John McCall8d08b9b2010-08-27 09:08:28 +00002027
2028 if (MightBeImplicitMember)
Abramo Bagnara7945c982012-01-27 09:46:47 +00002029 return BuildPossibleImplicitMemberExpr(SS, TemplateKWLoc,
2030 R, TemplateArgs);
John McCallb53bbd42009-11-22 01:44:31 +00002031 }
2032
Abramo Bagnara65f7c3d2012-02-06 14:31:00 +00002033 if (TemplateArgs || TemplateKWLoc.isValid())
2034 return BuildTemplateIdExpr(SS, TemplateKWLoc, R, ADL, TemplateArgs);
John McCallb53bbd42009-11-22 01:44:31 +00002035
John McCalle66edc12009-11-24 19:00:30 +00002036 return BuildDeclarationNameExpr(SS, R, ADL);
2037}
2038
John McCall10eae182009-11-30 22:42:35 +00002039/// BuildQualifiedDeclarationNameExpr - Build a C++ qualified
2040/// declaration name, generally during template instantiation.
2041/// There's a large number of things which don't need to be done along
2042/// this path.
John McCalldadc5752010-08-24 06:29:42 +00002043ExprResult
Jeffrey Yasskinc76498d2010-04-08 16:38:48 +00002044Sema::BuildQualifiedDeclarationNameExpr(CXXScopeSpec &SS,
Richard Smithdb2630f2012-10-21 03:28:35 +00002045 const DeclarationNameInfo &NameInfo,
2046 bool IsAddressOfOperand) {
Richard Smith40c180d2012-10-23 19:56:01 +00002047 DeclContext *DC = computeDeclContext(SS, false);
2048 if (!DC)
Abramo Bagnara65f7c3d2012-02-06 14:31:00 +00002049 return BuildDependentDeclRefExpr(SS, /*TemplateKWLoc=*/SourceLocation(),
2050 NameInfo, /*TemplateArgs=*/0);
John McCalle66edc12009-11-24 19:00:30 +00002051
John McCall0b66eb32010-05-01 00:40:08 +00002052 if (RequireCompleteDeclContext(SS, DC))
Douglas Gregora02bb342010-04-28 07:04:26 +00002053 return ExprError();
2054
Abramo Bagnarad6d2f182010-08-11 22:01:17 +00002055 LookupResult R(*this, NameInfo, LookupOrdinaryName);
John McCalle66edc12009-11-24 19:00:30 +00002056 LookupQualifiedName(R, DC);
2057
2058 if (R.isAmbiguous())
2059 return ExprError();
2060
Richard Smith40c180d2012-10-23 19:56:01 +00002061 if (R.getResultKind() == LookupResult::NotFoundInCurrentInstantiation)
2062 return BuildDependentDeclRefExpr(SS, /*TemplateKWLoc=*/SourceLocation(),
2063 NameInfo, /*TemplateArgs=*/0);
2064
John McCalle66edc12009-11-24 19:00:30 +00002065 if (R.empty()) {
Abramo Bagnarad6d2f182010-08-11 22:01:17 +00002066 Diag(NameInfo.getLoc(), diag::err_no_member)
2067 << NameInfo.getName() << DC << SS.getRange();
John McCalle66edc12009-11-24 19:00:30 +00002068 return ExprError();
2069 }
2070
Richard Smithdb2630f2012-10-21 03:28:35 +00002071 // Defend against this resolving to an implicit member access. We usually
2072 // won't get here if this might be a legitimate a class member (we end up in
2073 // BuildMemberReferenceExpr instead), but this can be valid if we're forming
2074 // a pointer-to-member or in an unevaluated context in C++11.
2075 if (!R.empty() && (*R.begin())->isCXXClassMember() && !IsAddressOfOperand)
2076 return BuildPossibleImplicitMemberExpr(SS,
2077 /*TemplateKWLoc=*/SourceLocation(),
2078 R, /*TemplateArgs=*/0);
2079
2080 return BuildDeclarationNameExpr(SS, R, /* ADL */ false);
John McCalle66edc12009-11-24 19:00:30 +00002081}
2082
2083/// LookupInObjCMethod - The parser has read a name in, and Sema has
2084/// detected that we're currently inside an ObjC method. Perform some
2085/// additional lookup.
2086///
2087/// Ideally, most of this would be done by lookup, but there's
2088/// actually quite a lot of extra work involved.
2089///
2090/// Returns a null sentinel to indicate trivial success.
John McCalldadc5752010-08-24 06:29:42 +00002091ExprResult
John McCalle66edc12009-11-24 19:00:30 +00002092Sema::LookupInObjCMethod(LookupResult &Lookup, Scope *S,
Chris Lattnera36ec422010-04-11 08:28:14 +00002093 IdentifierInfo *II, bool AllowBuiltinCreation) {
John McCalle66edc12009-11-24 19:00:30 +00002094 SourceLocation Loc = Lookup.getNameLoc();
Chris Lattner87313662010-04-12 05:10:17 +00002095 ObjCMethodDecl *CurMethod = getCurMethodDecl();
Fariborz Jahanian223ca5c2013-02-18 17:22:23 +00002096
2097 // Check for error condition which is already reported.
2098 if (!CurMethod)
2099 return ExprError();
Alexis Huntc46382e2010-04-28 23:02:27 +00002100
John McCalle66edc12009-11-24 19:00:30 +00002101 // There are two cases to handle here. 1) scoped lookup could have failed,
2102 // in which case we should look for an ivar. 2) scoped lookup could have
2103 // found a decl, but that decl is outside the current instance method (i.e.
2104 // a global variable). In these two cases, we do a lookup for an ivar with
2105 // this name, if the lookup sucedes, we replace it our current decl.
2106
2107 // If we're in a class method, we don't normally want to look for
2108 // ivars. But if we don't find anything else, and there's an
2109 // ivar, that's an error.
Chris Lattner87313662010-04-12 05:10:17 +00002110 bool IsClassMethod = CurMethod->isClassMethod();
John McCalle66edc12009-11-24 19:00:30 +00002111
2112 bool LookForIvars;
2113 if (Lookup.empty())
2114 LookForIvars = true;
2115 else if (IsClassMethod)
2116 LookForIvars = false;
2117 else
2118 LookForIvars = (Lookup.isSingleResult() &&
2119 Lookup.getFoundDecl()->isDefinedOutsideFunctionOrMethod());
Fariborz Jahanian45878032010-02-09 19:31:38 +00002120 ObjCInterfaceDecl *IFace = 0;
John McCalle66edc12009-11-24 19:00:30 +00002121 if (LookForIvars) {
Chris Lattner87313662010-04-12 05:10:17 +00002122 IFace = CurMethod->getClassInterface();
John McCalle66edc12009-11-24 19:00:30 +00002123 ObjCInterfaceDecl *ClassDeclared;
Argyrios Kyrtzidis4e8b1362011-10-19 02:25:16 +00002124 ObjCIvarDecl *IV = 0;
2125 if (IFace && (IV = IFace->lookupInstanceVariable(II, ClassDeclared))) {
John McCalle66edc12009-11-24 19:00:30 +00002126 // Diagnose using an ivar in a class method.
2127 if (IsClassMethod)
2128 return ExprError(Diag(Loc, diag::error_ivar_use_in_class_method)
2129 << IV->getDeclName());
2130
2131 // If we're referencing an invalid decl, just return this as a silent
2132 // error node. The error diagnostic was already emitted on the decl.
2133 if (IV->isInvalidDecl())
2134 return ExprError();
2135
2136 // Check if referencing a field with __attribute__((deprecated)).
2137 if (DiagnoseUseOfDecl(IV, Loc))
2138 return ExprError();
2139
2140 // Diagnose the use of an ivar outside of the declaring class.
2141 if (IV->getAccessControl() == ObjCIvarDecl::Private &&
Fariborz Jahaniand6cb4a82012-03-07 00:58:41 +00002142 !declaresSameEntity(ClassDeclared, IFace) &&
David Blaikiebbafb8a2012-03-11 07:00:24 +00002143 !getLangOpts().DebuggerSupport)
John McCalle66edc12009-11-24 19:00:30 +00002144 Diag(Loc, diag::error_private_ivar_access) << IV->getDeclName();
2145
2146 // FIXME: This should use a new expr for a direct reference, don't
2147 // turn this into Self->ivar, just return a BareIVarExpr or something.
2148 IdentifierInfo &II = Context.Idents.get("self");
2149 UnqualifiedId SelfName;
Kovarththanan Rajaratnamba2c6522010-03-13 10:17:05 +00002150 SelfName.setIdentifier(&II, SourceLocation());
Fariborz Jahanian7f4427f2011-07-12 17:16:56 +00002151 SelfName.setKind(UnqualifiedId::IK_ImplicitSelfParam);
John McCalle66edc12009-11-24 19:00:30 +00002152 CXXScopeSpec SelfScopeSpec;
Abramo Bagnara7945c982012-01-27 09:46:47 +00002153 SourceLocation TemplateKWLoc;
2154 ExprResult SelfExpr = ActOnIdExpression(S, SelfScopeSpec, TemplateKWLoc,
Douglas Gregora1ed39b2010-09-22 16:33:13 +00002155 SelfName, false, false);
2156 if (SelfExpr.isInvalid())
2157 return ExprError();
2158
John Wiegley01296292011-04-08 18:41:53 +00002159 SelfExpr = DefaultLvalueConversion(SelfExpr.take());
2160 if (SelfExpr.isInvalid())
2161 return ExprError();
John McCall27584242010-12-06 20:48:59 +00002162
Nick Lewycky45b50522013-02-02 00:25:55 +00002163 MarkAnyDeclReferenced(Loc, IV, true);
Fariborz Jahaniana5063a62012-08-08 16:41:04 +00002164
2165 ObjCMethodFamily MF = CurMethod->getMethodFamily();
Fariborz Jahaniana934a022013-02-14 19:07:19 +00002166 if (MF != OMF_init && MF != OMF_dealloc && MF != OMF_finalize &&
2167 !IvarBacksCurrentMethodAccessor(IFace, CurMethod, IV))
Fariborz Jahaniana5063a62012-08-08 16:41:04 +00002168 Diag(Loc, diag::warn_direct_ivar_access) << IV->getDeclName();
Jordan Rose657b5f42012-09-28 22:21:35 +00002169
2170 ObjCIvarRefExpr *Result = new (Context) ObjCIvarRefExpr(IV, IV->getType(),
Fariborz Jahanianf12ff4df2013-04-02 18:57:54 +00002171 Loc, IV->getLocation(),
Jordan Rose657b5f42012-09-28 22:21:35 +00002172 SelfExpr.take(),
2173 true, true);
2174
2175 if (getLangOpts().ObjCAutoRefCount) {
2176 if (IV->getType().getObjCLifetime() == Qualifiers::OCL_Weak) {
2177 DiagnosticsEngine::Level Level =
2178 Diags.getDiagnosticLevel(diag::warn_arc_repeated_use_of_weak, Loc);
2179 if (Level != DiagnosticsEngine::Ignored)
Fariborz Jahanian6f829e32013-05-21 21:20:26 +00002180 recordUseOfEvaluatedWeak(Result);
Jordan Rose657b5f42012-09-28 22:21:35 +00002181 }
Fariborz Jahanian4a675082012-10-03 17:55:29 +00002182 if (CurContext->isClosure())
2183 Diag(Loc, diag::warn_implicitly_retains_self)
2184 << FixItHint::CreateInsertion(Loc, "self->");
Jordan Rose657b5f42012-09-28 22:21:35 +00002185 }
2186
2187 return Owned(Result);
John McCalle66edc12009-11-24 19:00:30 +00002188 }
Chris Lattner87313662010-04-12 05:10:17 +00002189 } else if (CurMethod->isInstanceMethod()) {
John McCalle66edc12009-11-24 19:00:30 +00002190 // We should warn if a local variable hides an ivar.
Fariborz Jahanian557fc9a2011-11-08 22:51:27 +00002191 if (ObjCInterfaceDecl *IFace = CurMethod->getClassInterface()) {
2192 ObjCInterfaceDecl *ClassDeclared;
2193 if (ObjCIvarDecl *IV = IFace->lookupInstanceVariable(II, ClassDeclared)) {
2194 if (IV->getAccessControl() != ObjCIvarDecl::Private ||
Douglas Gregor0b144e12011-12-15 00:29:59 +00002195 declaresSameEntity(IFace, ClassDeclared))
Fariborz Jahanian557fc9a2011-11-08 22:51:27 +00002196 Diag(Loc, diag::warn_ivar_use_hidden) << IV->getDeclName();
2197 }
John McCalle66edc12009-11-24 19:00:30 +00002198 }
Fariborz Jahanian028b9e12011-12-20 22:21:08 +00002199 } else if (Lookup.isSingleResult() &&
2200 Lookup.getFoundDecl()->isDefinedOutsideFunctionOrMethod()) {
2201 // If accessing a stand-alone ivar in a class method, this is an error.
2202 if (const ObjCIvarDecl *IV = dyn_cast<ObjCIvarDecl>(Lookup.getFoundDecl()))
2203 return ExprError(Diag(Loc, diag::error_ivar_use_in_class_method)
2204 << IV->getDeclName());
John McCalle66edc12009-11-24 19:00:30 +00002205 }
2206
Fariborz Jahanian6fada5b2010-01-12 23:58:59 +00002207 if (Lookup.empty() && II && AllowBuiltinCreation) {
2208 // FIXME. Consolidate this with similar code in LookupName.
2209 if (unsigned BuiltinID = II->getBuiltinID()) {
David Blaikiebbafb8a2012-03-11 07:00:24 +00002210 if (!(getLangOpts().CPlusPlus &&
Fariborz Jahanian6fada5b2010-01-12 23:58:59 +00002211 Context.BuiltinInfo.isPredefinedLibFunction(BuiltinID))) {
2212 NamedDecl *D = LazilyCreateBuiltin((IdentifierInfo *)II, BuiltinID,
2213 S, Lookup.isForRedeclaration(),
2214 Lookup.getNameLoc());
2215 if (D) Lookup.addDecl(D);
2216 }
2217 }
2218 }
John McCalle66edc12009-11-24 19:00:30 +00002219 // Sentinel value saying that we didn't do anything special.
2220 return Owned((Expr*) 0);
Douglas Gregor3256d042009-06-30 15:47:41 +00002221}
John McCalld14a8642009-11-21 08:51:07 +00002222
John McCall16df1e52010-03-30 21:47:33 +00002223/// \brief Cast a base object to a member's actual type.
2224///
2225/// Logically this happens in three phases:
2226///
2227/// * First we cast from the base type to the naming class.
2228/// The naming class is the class into which we were looking
2229/// when we found the member; it's the qualifier type if a
2230/// qualifier was provided, and otherwise it's the base type.
2231///
2232/// * Next we cast from the naming class to the declaring class.
2233/// If the member we found was brought into a class's scope by
2234/// a using declaration, this is that class; otherwise it's
2235/// the class declaring the member.
2236///
2237/// * Finally we cast from the declaring class to the "true"
2238/// declaring class of the member. This conversion does not
2239/// obey access control.
John Wiegley01296292011-04-08 18:41:53 +00002240ExprResult
2241Sema::PerformObjectMemberConversion(Expr *From,
Douglas Gregorcc3f3252010-03-03 23:55:11 +00002242 NestedNameSpecifier *Qualifier,
John McCall16df1e52010-03-30 21:47:33 +00002243 NamedDecl *FoundDecl,
Douglas Gregorcc3f3252010-03-03 23:55:11 +00002244 NamedDecl *Member) {
2245 CXXRecordDecl *RD = dyn_cast<CXXRecordDecl>(Member->getDeclContext());
2246 if (!RD)
John Wiegley01296292011-04-08 18:41:53 +00002247 return Owned(From);
Kovarththanan Rajaratnamba2c6522010-03-13 10:17:05 +00002248
Douglas Gregorcc3f3252010-03-03 23:55:11 +00002249 QualType DestRecordType;
2250 QualType DestType;
2251 QualType FromRecordType;
2252 QualType FromType = From->getType();
2253 bool PointerConversions = false;
2254 if (isa<FieldDecl>(Member)) {
2255 DestRecordType = Context.getCanonicalType(Context.getTypeDeclType(RD));
Kovarththanan Rajaratnamba2c6522010-03-13 10:17:05 +00002256
Douglas Gregorcc3f3252010-03-03 23:55:11 +00002257 if (FromType->getAs<PointerType>()) {
2258 DestType = Context.getPointerType(DestRecordType);
2259 FromRecordType = FromType->getPointeeType();
2260 PointerConversions = true;
2261 } else {
2262 DestType = DestRecordType;
2263 FromRecordType = FromType;
Fariborz Jahanianbb67b822009-07-29 18:40:24 +00002264 }
Douglas Gregorcc3f3252010-03-03 23:55:11 +00002265 } else if (CXXMethodDecl *Method = dyn_cast<CXXMethodDecl>(Member)) {
2266 if (Method->isStatic())
John Wiegley01296292011-04-08 18:41:53 +00002267 return Owned(From);
Kovarththanan Rajaratnamba2c6522010-03-13 10:17:05 +00002268
Douglas Gregorcc3f3252010-03-03 23:55:11 +00002269 DestType = Method->getThisType(Context);
2270 DestRecordType = DestType->getPointeeType();
Kovarththanan Rajaratnamba2c6522010-03-13 10:17:05 +00002271
Douglas Gregorcc3f3252010-03-03 23:55:11 +00002272 if (FromType->getAs<PointerType>()) {
2273 FromRecordType = FromType->getPointeeType();
2274 PointerConversions = true;
2275 } else {
2276 FromRecordType = FromType;
2277 DestType = DestRecordType;
2278 }
2279 } else {
2280 // No conversion necessary.
John Wiegley01296292011-04-08 18:41:53 +00002281 return Owned(From);
Douglas Gregorcc3f3252010-03-03 23:55:11 +00002282 }
Kovarththanan Rajaratnamba2c6522010-03-13 10:17:05 +00002283
Douglas Gregorcc3f3252010-03-03 23:55:11 +00002284 if (DestType->isDependentType() || FromType->isDependentType())
John Wiegley01296292011-04-08 18:41:53 +00002285 return Owned(From);
Kovarththanan Rajaratnamba2c6522010-03-13 10:17:05 +00002286
Douglas Gregorcc3f3252010-03-03 23:55:11 +00002287 // If the unqualified types are the same, no conversion is necessary.
2288 if (Context.hasSameUnqualifiedType(FromRecordType, DestRecordType))
John Wiegley01296292011-04-08 18:41:53 +00002289 return Owned(From);
Kovarththanan Rajaratnamba2c6522010-03-13 10:17:05 +00002290
John McCall16df1e52010-03-30 21:47:33 +00002291 SourceRange FromRange = From->getSourceRange();
2292 SourceLocation FromLoc = FromRange.getBegin();
2293
Eli Friedmanbe4b3632011-09-27 21:58:52 +00002294 ExprValueKind VK = From->getValueKind();
Sebastian Redlc57d34b2010-07-20 04:20:21 +00002295
Douglas Gregorcc3f3252010-03-03 23:55:11 +00002296 // C++ [class.member.lookup]p8:
Kovarththanan Rajaratnamba2c6522010-03-13 10:17:05 +00002297 // [...] Ambiguities can often be resolved by qualifying a name with its
Douglas Gregorcc3f3252010-03-03 23:55:11 +00002298 // class name.
2299 //
2300 // If the member was a qualified name and the qualified referred to a
2301 // specific base subobject type, we'll cast to that intermediate type
2302 // first and then to the object in which the member is declared. That allows
2303 // one to resolve ambiguities in, e.g., a diamond-shaped hierarchy such as:
2304 //
2305 // class Base { public: int x; };
2306 // class Derived1 : public Base { };
2307 // class Derived2 : public Base { };
2308 // class VeryDerived : public Derived1, public Derived2 { void f(); };
2309 //
2310 // void VeryDerived::f() {
2311 // x = 17; // error: ambiguous base subobjects
2312 // Derived1::x = 17; // okay, pick the Base subobject of Derived1
2313 // }
Douglas Gregorcc3f3252010-03-03 23:55:11 +00002314 if (Qualifier) {
John McCall16df1e52010-03-30 21:47:33 +00002315 QualType QType = QualType(Qualifier->getAsType(), 0);
2316 assert(!QType.isNull() && "lookup done with dependent qualifier?");
2317 assert(QType->isRecordType() && "lookup done with non-record type");
2318
2319 QualType QRecordType = QualType(QType->getAs<RecordType>(), 0);
2320
2321 // In C++98, the qualifier type doesn't actually have to be a base
2322 // type of the object type, in which case we just ignore it.
2323 // Otherwise build the appropriate casts.
2324 if (IsDerivedFrom(FromRecordType, QRecordType)) {
John McCallcf142162010-08-07 06:22:56 +00002325 CXXCastPath BasePath;
John McCall16df1e52010-03-30 21:47:33 +00002326 if (CheckDerivedToBaseConversion(FromRecordType, QRecordType,
Anders Carlssonb78feca2010-04-24 19:22:20 +00002327 FromLoc, FromRange, &BasePath))
John Wiegley01296292011-04-08 18:41:53 +00002328 return ExprError();
John McCall16df1e52010-03-30 21:47:33 +00002329
Douglas Gregorcc3f3252010-03-03 23:55:11 +00002330 if (PointerConversions)
John McCall16df1e52010-03-30 21:47:33 +00002331 QType = Context.getPointerType(QType);
John Wiegley01296292011-04-08 18:41:53 +00002332 From = ImpCastExprToType(From, QType, CK_UncheckedDerivedToBase,
2333 VK, &BasePath).take();
John McCall16df1e52010-03-30 21:47:33 +00002334
2335 FromType = QType;
2336 FromRecordType = QRecordType;
2337
2338 // If the qualifier type was the same as the destination type,
2339 // we're done.
2340 if (Context.hasSameUnqualifiedType(FromRecordType, DestRecordType))
John Wiegley01296292011-04-08 18:41:53 +00002341 return Owned(From);
Douglas Gregorcc3f3252010-03-03 23:55:11 +00002342 }
2343 }
Kovarththanan Rajaratnamba2c6522010-03-13 10:17:05 +00002344
John McCall16df1e52010-03-30 21:47:33 +00002345 bool IgnoreAccess = false;
Douglas Gregorcc3f3252010-03-03 23:55:11 +00002346
John McCall16df1e52010-03-30 21:47:33 +00002347 // If we actually found the member through a using declaration, cast
2348 // down to the using declaration's type.
2349 //
2350 // Pointer equality is fine here because only one declaration of a
2351 // class ever has member declarations.
2352 if (FoundDecl->getDeclContext() != Member->getDeclContext()) {
2353 assert(isa<UsingShadowDecl>(FoundDecl));
2354 QualType URecordType = Context.getTypeDeclType(
2355 cast<CXXRecordDecl>(FoundDecl->getDeclContext()));
2356
2357 // We only need to do this if the naming-class to declaring-class
2358 // conversion is non-trivial.
2359 if (!Context.hasSameUnqualifiedType(FromRecordType, URecordType)) {
2360 assert(IsDerivedFrom(FromRecordType, URecordType));
John McCallcf142162010-08-07 06:22:56 +00002361 CXXCastPath BasePath;
John McCall16df1e52010-03-30 21:47:33 +00002362 if (CheckDerivedToBaseConversion(FromRecordType, URecordType,
Anders Carlssonb78feca2010-04-24 19:22:20 +00002363 FromLoc, FromRange, &BasePath))
John Wiegley01296292011-04-08 18:41:53 +00002364 return ExprError();
Alexis Huntc46382e2010-04-28 23:02:27 +00002365
John McCall16df1e52010-03-30 21:47:33 +00002366 QualType UType = URecordType;
2367 if (PointerConversions)
2368 UType = Context.getPointerType(UType);
John Wiegley01296292011-04-08 18:41:53 +00002369 From = ImpCastExprToType(From, UType, CK_UncheckedDerivedToBase,
2370 VK, &BasePath).take();
John McCall16df1e52010-03-30 21:47:33 +00002371 FromType = UType;
2372 FromRecordType = URecordType;
2373 }
2374
2375 // We don't do access control for the conversion from the
2376 // declaring class to the true declaring class.
2377 IgnoreAccess = true;
Douglas Gregorcc3f3252010-03-03 23:55:11 +00002378 }
Kovarththanan Rajaratnamba2c6522010-03-13 10:17:05 +00002379
John McCallcf142162010-08-07 06:22:56 +00002380 CXXCastPath BasePath;
Anders Carlssonb78feca2010-04-24 19:22:20 +00002381 if (CheckDerivedToBaseConversion(FromRecordType, DestRecordType,
2382 FromLoc, FromRange, &BasePath,
John McCall16df1e52010-03-30 21:47:33 +00002383 IgnoreAccess))
John Wiegley01296292011-04-08 18:41:53 +00002384 return ExprError();
Kovarththanan Rajaratnamba2c6522010-03-13 10:17:05 +00002385
John Wiegley01296292011-04-08 18:41:53 +00002386 return ImpCastExprToType(From, DestType, CK_UncheckedDerivedToBase,
2387 VK, &BasePath);
Fariborz Jahanianbb67b822009-07-29 18:40:24 +00002388}
Douglas Gregor3256d042009-06-30 15:47:41 +00002389
John McCalle66edc12009-11-24 19:00:30 +00002390bool Sema::UseArgumentDependentLookup(const CXXScopeSpec &SS,
John McCallb53bbd42009-11-22 01:44:31 +00002391 const LookupResult &R,
2392 bool HasTrailingLParen) {
John McCalld14a8642009-11-21 08:51:07 +00002393 // Only when used directly as the postfix-expression of a call.
2394 if (!HasTrailingLParen)
2395 return false;
2396
2397 // Never if a scope specifier was provided.
John McCalle66edc12009-11-24 19:00:30 +00002398 if (SS.isSet())
John McCalld14a8642009-11-21 08:51:07 +00002399 return false;
2400
2401 // Only in C++ or ObjC++.
David Blaikiebbafb8a2012-03-11 07:00:24 +00002402 if (!getLangOpts().CPlusPlus)
John McCalld14a8642009-11-21 08:51:07 +00002403 return false;
2404
2405 // Turn off ADL when we find certain kinds of declarations during
2406 // normal lookup:
2407 for (LookupResult::iterator I = R.begin(), E = R.end(); I != E; ++I) {
2408 NamedDecl *D = *I;
2409
2410 // C++0x [basic.lookup.argdep]p3:
2411 // -- a declaration of a class member
2412 // Since using decls preserve this property, we check this on the
2413 // original decl.
John McCall57500772009-12-16 12:17:52 +00002414 if (D->isCXXClassMember())
John McCalld14a8642009-11-21 08:51:07 +00002415 return false;
2416
2417 // C++0x [basic.lookup.argdep]p3:
2418 // -- a block-scope function declaration that is not a
2419 // using-declaration
2420 // NOTE: we also trigger this for function templates (in fact, we
2421 // don't check the decl type at all, since all other decl types
2422 // turn off ADL anyway).
2423 if (isa<UsingShadowDecl>(D))
2424 D = cast<UsingShadowDecl>(D)->getTargetDecl();
2425 else if (D->getDeclContext()->isFunctionOrMethod())
2426 return false;
2427
2428 // C++0x [basic.lookup.argdep]p3:
2429 // -- a declaration that is neither a function or a function
2430 // template
2431 // And also for builtin functions.
2432 if (isa<FunctionDecl>(D)) {
2433 FunctionDecl *FDecl = cast<FunctionDecl>(D);
2434
2435 // But also builtin functions.
2436 if (FDecl->getBuiltinID() && FDecl->isImplicit())
2437 return false;
2438 } else if (!isa<FunctionTemplateDecl>(D))
2439 return false;
2440 }
2441
2442 return true;
2443}
2444
2445
John McCalld14a8642009-11-21 08:51:07 +00002446/// Diagnoses obvious problems with the use of the given declaration
2447/// as an expression. This is only actually called for lookups that
2448/// were not overloaded, and it doesn't promise that the declaration
2449/// will in fact be used.
2450static bool CheckDeclInExpr(Sema &S, SourceLocation Loc, NamedDecl *D) {
Richard Smithdda56e42011-04-15 14:24:37 +00002451 if (isa<TypedefNameDecl>(D)) {
John McCalld14a8642009-11-21 08:51:07 +00002452 S.Diag(Loc, diag::err_unexpected_typedef) << D->getDeclName();
2453 return true;
2454 }
2455
2456 if (isa<ObjCInterfaceDecl>(D)) {
2457 S.Diag(Loc, diag::err_unexpected_interface) << D->getDeclName();
2458 return true;
2459 }
2460
2461 if (isa<NamespaceDecl>(D)) {
2462 S.Diag(Loc, diag::err_unexpected_namespace) << D->getDeclName();
2463 return true;
2464 }
2465
2466 return false;
2467}
2468
John McCalldadc5752010-08-24 06:29:42 +00002469ExprResult
John McCalle66edc12009-11-24 19:00:30 +00002470Sema::BuildDeclarationNameExpr(const CXXScopeSpec &SS,
John McCallb53bbd42009-11-22 01:44:31 +00002471 LookupResult &R,
2472 bool NeedsADL) {
John McCall3a60c872009-12-08 22:45:53 +00002473 // If this is a single, fully-resolved result and we don't need ADL,
2474 // just build an ordinary singleton decl ref.
Douglas Gregor4b4844f2010-01-29 17:15:43 +00002475 if (!NeedsADL && R.isSingleResult() && !R.getAsSingle<FunctionTemplateDecl>())
Daniel Jasper689ae012013-03-22 10:01:35 +00002476 return BuildDeclarationNameExpr(SS, R.getLookupNameInfo(), R.getFoundDecl(),
2477 R.getRepresentativeDecl());
John McCalld14a8642009-11-21 08:51:07 +00002478
2479 // We only need to check the declaration if there's exactly one
2480 // result, because in the overloaded case the results can only be
2481 // functions and function templates.
John McCallb53bbd42009-11-22 01:44:31 +00002482 if (R.isSingleResult() &&
2483 CheckDeclInExpr(*this, R.getNameLoc(), R.getFoundDecl()))
John McCalld14a8642009-11-21 08:51:07 +00002484 return ExprError();
2485
John McCall58cc69d2010-01-27 01:50:18 +00002486 // Otherwise, just build an unresolved lookup expression. Suppress
2487 // any lookup-related diagnostics; we'll hash these out later, when
2488 // we've picked a target.
2489 R.suppressDiagnostics();
2490
John McCalld14a8642009-11-21 08:51:07 +00002491 UnresolvedLookupExpr *ULE
Douglas Gregora6e053e2010-12-15 01:34:56 +00002492 = UnresolvedLookupExpr::Create(Context, R.getNamingClass(),
Douglas Gregor0da1d432011-02-28 20:01:57 +00002493 SS.getWithLocInContext(Context),
2494 R.getLookupNameInfo(),
Douglas Gregor30a4f4c2010-05-23 18:57:34 +00002495 NeedsADL, R.isOverloadedResult(),
2496 R.begin(), R.end());
John McCalld14a8642009-11-21 08:51:07 +00002497
2498 return Owned(ULE);
2499}
Kovarththanan Rajaratnamba2c6522010-03-13 10:17:05 +00002500
John McCalld14a8642009-11-21 08:51:07 +00002501/// \brief Complete semantic analysis for a reference to the given declaration.
John McCalldadc5752010-08-24 06:29:42 +00002502ExprResult
John McCalle66edc12009-11-24 19:00:30 +00002503Sema::BuildDeclarationNameExpr(const CXXScopeSpec &SS,
Abramo Bagnarad6d2f182010-08-11 22:01:17 +00002504 const DeclarationNameInfo &NameInfo,
Daniel Jasper689ae012013-03-22 10:01:35 +00002505 NamedDecl *D, NamedDecl *FoundD) {
John McCalld14a8642009-11-21 08:51:07 +00002506 assert(D && "Cannot refer to a NULL declaration");
John McCall283b9012009-11-22 00:44:51 +00002507 assert(!isa<FunctionTemplateDecl>(D) &&
2508 "Cannot refer unambiguously to a function template");
John McCalld14a8642009-11-21 08:51:07 +00002509
Abramo Bagnarad6d2f182010-08-11 22:01:17 +00002510 SourceLocation Loc = NameInfo.getLoc();
John McCalld14a8642009-11-21 08:51:07 +00002511 if (CheckDeclInExpr(*this, Loc, D))
2512 return ExprError();
Steve Narofff1e53692007-03-23 22:27:02 +00002513
Douglas Gregore7488b92009-12-01 16:58:18 +00002514 if (TemplateDecl *Template = dyn_cast<TemplateDecl>(D)) {
2515 // Specifically diagnose references to class templates that are missing
2516 // a template argument list.
2517 Diag(Loc, diag::err_template_decl_ref)
2518 << Template << SS.getRange();
2519 Diag(Template->getLocation(), diag::note_template_decl_here);
2520 return ExprError();
2521 }
2522
2523 // Make sure that we're referring to a value.
2524 ValueDecl *VD = dyn_cast<ValueDecl>(D);
2525 if (!VD) {
Kovarththanan Rajaratnamba2c6522010-03-13 10:17:05 +00002526 Diag(Loc, diag::err_ref_non_value)
Douglas Gregore7488b92009-12-01 16:58:18 +00002527 << D << SS.getRange();
John McCallb48971d2009-12-18 18:35:10 +00002528 Diag(D->getLocation(), diag::note_declared_at);
Douglas Gregore7488b92009-12-01 16:58:18 +00002529 return ExprError();
2530 }
Sebastian Redlffbcf962009-01-18 18:53:16 +00002531
Douglas Gregor171c45a2009-02-18 21:56:37 +00002532 // Check whether this declaration can be used. Note that we suppress
2533 // this check when we're going to perform argument-dependent lookup
2534 // on this function name, because this might not be the function
2535 // that overload resolution actually selects.
John McCalld14a8642009-11-21 08:51:07 +00002536 if (DiagnoseUseOfDecl(VD, Loc))
Douglas Gregor171c45a2009-02-18 21:56:37 +00002537 return ExprError();
2538
Steve Naroff8de9c3a2008-09-05 22:11:13 +00002539 // Only create DeclRefExpr's for valid Decl's.
2540 if (VD->isInvalidDecl())
Sebastian Redlffbcf962009-01-18 18:53:16 +00002541 return ExprError();
2542
John McCallf3a88602011-02-03 08:15:49 +00002543 // Handle members of anonymous structs and unions. If we got here,
2544 // and the reference is to a class member indirect field, then this
2545 // must be the subject of a pointer-to-member expression.
2546 if (IndirectFieldDecl *indirectField = dyn_cast<IndirectFieldDecl>(VD))
2547 if (!indirectField->isCXXClassMember())
2548 return BuildAnonymousStructUnionMemberReference(SS, NameInfo.getLoc(),
2549 indirectField);
Francois Pichet783dd6e2010-11-21 06:08:52 +00002550
Eli Friedman9bb33f52012-02-03 02:04:35 +00002551 {
John McCallf4cd4f92011-02-09 01:13:10 +00002552 QualType type = VD->getType();
Daniel Dunbar7c2dc362011-02-10 18:29:28 +00002553 ExprValueKind valueKind = VK_RValue;
John McCallf4cd4f92011-02-09 01:13:10 +00002554
2555 switch (D->getKind()) {
2556 // Ignore all the non-ValueDecl kinds.
2557#define ABSTRACT_DECL(kind)
2558#define VALUE(type, base)
2559#define DECL(type, base) \
2560 case Decl::type:
2561#include "clang/AST/DeclNodes.inc"
2562 llvm_unreachable("invalid value decl kind");
John McCallf4cd4f92011-02-09 01:13:10 +00002563
2564 // These shouldn't make it here.
2565 case Decl::ObjCAtDefsField:
2566 case Decl::ObjCIvar:
2567 llvm_unreachable("forming non-member reference to ivar?");
John McCallf4cd4f92011-02-09 01:13:10 +00002568
2569 // Enum constants are always r-values and never references.
2570 // Unresolved using declarations are dependent.
2571 case Decl::EnumConstant:
2572 case Decl::UnresolvedUsingValue:
2573 valueKind = VK_RValue;
2574 break;
2575
2576 // Fields and indirect fields that got here must be for
2577 // pointer-to-member expressions; we just call them l-values for
2578 // internal consistency, because this subexpression doesn't really
2579 // exist in the high-level semantics.
2580 case Decl::Field:
2581 case Decl::IndirectField:
David Blaikiebbafb8a2012-03-11 07:00:24 +00002582 assert(getLangOpts().CPlusPlus &&
John McCallf4cd4f92011-02-09 01:13:10 +00002583 "building reference to field in C?");
2584
2585 // These can't have reference type in well-formed programs, but
2586 // for internal consistency we do this anyway.
2587 type = type.getNonReferenceType();
2588 valueKind = VK_LValue;
2589 break;
2590
2591 // Non-type template parameters are either l-values or r-values
2592 // depending on the type.
2593 case Decl::NonTypeTemplateParm: {
2594 if (const ReferenceType *reftype = type->getAs<ReferenceType>()) {
2595 type = reftype->getPointeeType();
2596 valueKind = VK_LValue; // even if the parameter is an r-value reference
2597 break;
2598 }
2599
2600 // For non-references, we need to strip qualifiers just in case
2601 // the template parameter was declared as 'const int' or whatever.
2602 valueKind = VK_RValue;
2603 type = type.getUnqualifiedType();
2604 break;
2605 }
2606
2607 case Decl::Var:
2608 // In C, "extern void blah;" is valid and is an r-value.
David Blaikiebbafb8a2012-03-11 07:00:24 +00002609 if (!getLangOpts().CPlusPlus &&
John McCallf4cd4f92011-02-09 01:13:10 +00002610 !type.hasQualifiers() &&
2611 type->isVoidType()) {
2612 valueKind = VK_RValue;
2613 break;
2614 }
2615 // fallthrough
2616
2617 case Decl::ImplicitParam:
Douglas Gregor812d8f62012-02-18 05:51:20 +00002618 case Decl::ParmVar: {
John McCallf4cd4f92011-02-09 01:13:10 +00002619 // These are always l-values.
2620 valueKind = VK_LValue;
2621 type = type.getNonReferenceType();
Eli Friedman9bb33f52012-02-03 02:04:35 +00002622
Douglas Gregor812d8f62012-02-18 05:51:20 +00002623 // FIXME: Does the addition of const really only apply in
2624 // potentially-evaluated contexts? Since the variable isn't actually
2625 // captured in an unevaluated context, it seems that the answer is no.
David Blaikie131fcb42012-08-06 22:47:24 +00002626 if (!isUnevaluatedContext()) {
Douglas Gregor812d8f62012-02-18 05:51:20 +00002627 QualType CapturedType = getCapturedDeclRefType(cast<VarDecl>(VD), Loc);
2628 if (!CapturedType.isNull())
2629 type = CapturedType;
2630 }
2631
John McCallf4cd4f92011-02-09 01:13:10 +00002632 break;
Douglas Gregor812d8f62012-02-18 05:51:20 +00002633 }
2634
John McCallf4cd4f92011-02-09 01:13:10 +00002635 case Decl::Function: {
Eli Friedman34866c72012-08-31 00:14:07 +00002636 if (unsigned BID = cast<FunctionDecl>(VD)->getBuiltinID()) {
2637 if (!Context.BuiltinInfo.isPredefinedLibFunction(BID)) {
2638 type = Context.BuiltinFnTy;
2639 valueKind = VK_RValue;
2640 break;
2641 }
2642 }
2643
John McCall2979fe02011-04-12 00:42:48 +00002644 const FunctionType *fty = type->castAs<FunctionType>();
2645
2646 // If we're referring to a function with an __unknown_anytype
2647 // result type, make the entire expression __unknown_anytype.
2648 if (fty->getResultType() == Context.UnknownAnyTy) {
2649 type = Context.UnknownAnyTy;
2650 valueKind = VK_RValue;
2651 break;
2652 }
2653
John McCallf4cd4f92011-02-09 01:13:10 +00002654 // Functions are l-values in C++.
David Blaikiebbafb8a2012-03-11 07:00:24 +00002655 if (getLangOpts().CPlusPlus) {
John McCallf4cd4f92011-02-09 01:13:10 +00002656 valueKind = VK_LValue;
2657 break;
2658 }
2659
2660 // C99 DR 316 says that, if a function type comes from a
2661 // function definition (without a prototype), that type is only
2662 // used for checking compatibility. Therefore, when referencing
2663 // the function, we pretend that we don't have the full function
2664 // type.
John McCall2979fe02011-04-12 00:42:48 +00002665 if (!cast<FunctionDecl>(VD)->hasPrototype() &&
2666 isa<FunctionProtoType>(fty))
2667 type = Context.getFunctionNoProtoType(fty->getResultType(),
2668 fty->getExtInfo());
John McCallf4cd4f92011-02-09 01:13:10 +00002669
2670 // Functions are r-values in C.
2671 valueKind = VK_RValue;
2672 break;
2673 }
2674
John McCall5e77d762013-04-16 07:28:30 +00002675 case Decl::MSProperty:
2676 valueKind = VK_LValue;
2677 break;
2678
John McCallf4cd4f92011-02-09 01:13:10 +00002679 case Decl::CXXMethod:
John McCall2979fe02011-04-12 00:42:48 +00002680 // If we're referring to a method with an __unknown_anytype
2681 // result type, make the entire expression __unknown_anytype.
2682 // This should only be possible with a type written directly.
Richard Trieucfc491d2011-08-02 04:35:43 +00002683 if (const FunctionProtoType *proto
2684 = dyn_cast<FunctionProtoType>(VD->getType()))
John McCall2979fe02011-04-12 00:42:48 +00002685 if (proto->getResultType() == Context.UnknownAnyTy) {
2686 type = Context.UnknownAnyTy;
2687 valueKind = VK_RValue;
2688 break;
2689 }
2690
John McCallf4cd4f92011-02-09 01:13:10 +00002691 // C++ methods are l-values if static, r-values if non-static.
2692 if (cast<CXXMethodDecl>(VD)->isStatic()) {
2693 valueKind = VK_LValue;
2694 break;
2695 }
2696 // fallthrough
2697
2698 case Decl::CXXConversion:
2699 case Decl::CXXDestructor:
2700 case Decl::CXXConstructor:
2701 valueKind = VK_RValue;
2702 break;
2703 }
2704
Daniel Jasper689ae012013-03-22 10:01:35 +00002705 return BuildDeclRefExpr(VD, type, valueKind, NameInfo, &SS, FoundD);
John McCallf4cd4f92011-02-09 01:13:10 +00002706 }
Chris Lattner17ed4872006-11-20 04:58:19 +00002707}
Chris Lattnere168f762006-11-10 05:29:30 +00002708
John McCall2979fe02011-04-12 00:42:48 +00002709ExprResult Sema::ActOnPredefinedExpr(SourceLocation Loc, tok::TokenKind Kind) {
Chris Lattner6307f192008-08-10 01:53:14 +00002710 PredefinedExpr::IdentType IT;
Sebastian Redlffbcf962009-01-18 18:53:16 +00002711
Chris Lattnere168f762006-11-10 05:29:30 +00002712 switch (Kind) {
David Blaikie83d382b2011-09-23 05:06:16 +00002713 default: llvm_unreachable("Unknown simple primary expr!");
Chris Lattner6307f192008-08-10 01:53:14 +00002714 case tok::kw___func__: IT = PredefinedExpr::Func; break; // [C99 6.4.2.2]
2715 case tok::kw___FUNCTION__: IT = PredefinedExpr::Function; break;
Nico Weber3a691a32012-06-23 02:07:59 +00002716 case tok::kw_L__FUNCTION__: IT = PredefinedExpr::LFunction; break;
Chris Lattner6307f192008-08-10 01:53:14 +00002717 case tok::kw___PRETTY_FUNCTION__: IT = PredefinedExpr::PrettyFunction; break;
Chris Lattnere168f762006-11-10 05:29:30 +00002718 }
Chris Lattner317e6ba2008-01-12 18:39:25 +00002719
Chris Lattnera81a0272008-01-12 08:14:25 +00002720 // Pre-defined identifiers are of type char[x], where x is the length of the
2721 // string.
Mike Stump11289f42009-09-09 15:08:12 +00002722
Anders Carlsson2fb08242009-09-08 18:24:21 +00002723 Decl *currentDecl = getCurFunctionOrMethodDecl();
Benjamin Kramer6928cf72012-12-06 15:42:21 +00002724 // Blocks and lambdas can occur at global scope. Don't emit a warning.
2725 if (!currentDecl) {
2726 if (const BlockScopeInfo *BSI = getCurBlock())
2727 currentDecl = BSI->TheDecl;
2728 else if (const LambdaScopeInfo *LSI = getCurLambda())
2729 currentDecl = LSI->CallOperator;
2730 }
2731
Anders Carlsson2fb08242009-09-08 18:24:21 +00002732 if (!currentDecl) {
Chris Lattnerf45c5ec2008-12-12 05:05:20 +00002733 Diag(Loc, diag::ext_predef_outside_function);
Anders Carlsson2fb08242009-09-08 18:24:21 +00002734 currentDecl = Context.getTranslationUnitDecl();
Chris Lattnerf45c5ec2008-12-12 05:05:20 +00002735 }
Sebastian Redlffbcf962009-01-18 18:53:16 +00002736
Anders Carlsson0b209a82009-09-11 01:22:35 +00002737 QualType ResTy;
2738 if (cast<DeclContext>(currentDecl)->isDependentContext()) {
2739 ResTy = Context.DependentTy;
2740 } else {
Anders Carlsson5bd8d192010-02-11 18:20:28 +00002741 unsigned Length = PredefinedExpr::ComputeName(IT, currentDecl).length();
Sebastian Redlffbcf962009-01-18 18:53:16 +00002742
Anders Carlsson0b209a82009-09-11 01:22:35 +00002743 llvm::APInt LengthI(32, Length + 1);
Nico Weber3052abd2012-06-29 16:39:58 +00002744 if (IT == PredefinedExpr::LFunction)
Hans Wennborg0d81e012013-05-10 10:08:40 +00002745 ResTy = Context.WideCharTy.withConst();
Nico Weber3a691a32012-06-23 02:07:59 +00002746 else
2747 ResTy = Context.CharTy.withConst();
Anders Carlsson0b209a82009-09-11 01:22:35 +00002748 ResTy = Context.getConstantArrayType(ResTy, LengthI, ArrayType::Normal, 0);
2749 }
Steve Narofff6009ed2009-01-21 00:14:39 +00002750 return Owned(new (Context) PredefinedExpr(Loc, ResTy, IT));
Chris Lattnere168f762006-11-10 05:29:30 +00002751}
2752
Richard Smithbcc22fc2012-03-09 08:00:36 +00002753ExprResult Sema::ActOnCharacterConstant(const Token &Tok, Scope *UDLScope) {
Dylan Noblesmith2c1dd272012-02-05 02:13:05 +00002754 SmallString<16> CharBuffer;
Douglas Gregordc970f02010-03-16 22:30:13 +00002755 bool Invalid = false;
Chris Lattner0e62c1c2011-07-23 10:55:15 +00002756 StringRef ThisTok = PP.getSpelling(Tok, CharBuffer, &Invalid);
Douglas Gregordc970f02010-03-16 22:30:13 +00002757 if (Invalid)
2758 return ExprError();
Sebastian Redlffbcf962009-01-18 18:53:16 +00002759
Benjamin Kramer0a1abd42010-02-27 13:44:12 +00002760 CharLiteralParser Literal(ThisTok.begin(), ThisTok.end(), Tok.getLocation(),
Douglas Gregorfb65e592011-07-27 05:40:30 +00002761 PP, Tok.getKind());
Steve Naroffae4143e2007-04-26 20:39:23 +00002762 if (Literal.hadError())
Sebastian Redlffbcf962009-01-18 18:53:16 +00002763 return ExprError();
Chris Lattneref24b382008-03-01 08:32:21 +00002764
Chris Lattnerc3847ba2009-12-30 21:19:39 +00002765 QualType Ty;
Seth Cantrell02f86052012-01-18 12:27:06 +00002766 if (Literal.isWide())
Hans Wennborg0d81e012013-05-10 10:08:40 +00002767 Ty = Context.WideCharTy; // L'x' -> wchar_t in C and C++.
Douglas Gregorfb65e592011-07-27 05:40:30 +00002768 else if (Literal.isUTF16())
Seth Cantrell02f86052012-01-18 12:27:06 +00002769 Ty = Context.Char16Ty; // u'x' -> char16_t in C11 and C++11.
Douglas Gregorfb65e592011-07-27 05:40:30 +00002770 else if (Literal.isUTF32())
Seth Cantrell02f86052012-01-18 12:27:06 +00002771 Ty = Context.Char32Ty; // U'x' -> char32_t in C11 and C++11.
David Blaikiebbafb8a2012-03-11 07:00:24 +00002772 else if (!getLangOpts().CPlusPlus || Literal.isMultiChar())
Seth Cantrell02f86052012-01-18 12:27:06 +00002773 Ty = Context.IntTy; // 'x' -> int in C, 'wxyz' -> int in C++.
Chris Lattnerc3847ba2009-12-30 21:19:39 +00002774 else
2775 Ty = Context.CharTy; // 'x' -> char in C++
Chris Lattneref24b382008-03-01 08:32:21 +00002776
Douglas Gregorfb65e592011-07-27 05:40:30 +00002777 CharacterLiteral::CharacterKind Kind = CharacterLiteral::Ascii;
2778 if (Literal.isWide())
2779 Kind = CharacterLiteral::Wide;
2780 else if (Literal.isUTF16())
2781 Kind = CharacterLiteral::UTF16;
2782 else if (Literal.isUTF32())
2783 Kind = CharacterLiteral::UTF32;
2784
Richard Smith75b67d62012-03-08 01:34:56 +00002785 Expr *Lit = new (Context) CharacterLiteral(Literal.getValue(), Kind, Ty,
2786 Tok.getLocation());
2787
2788 if (Literal.getUDSuffix().empty())
2789 return Owned(Lit);
2790
2791 // We're building a user-defined literal.
2792 IdentifierInfo *UDSuffix = &Context.Idents.get(Literal.getUDSuffix());
2793 SourceLocation UDSuffixLoc =
2794 getUDSuffixLoc(*this, Tok.getLocation(), Literal.getUDSuffixOffset());
2795
Richard Smithbcc22fc2012-03-09 08:00:36 +00002796 // Make sure we're allowed user-defined literals here.
2797 if (!UDLScope)
2798 return ExprError(Diag(UDSuffixLoc, diag::err_invalid_character_udl));
2799
Richard Smith75b67d62012-03-08 01:34:56 +00002800 // C++11 [lex.ext]p6: The literal L is treated as a call of the form
2801 // operator "" X (ch)
Richard Smithbcc22fc2012-03-09 08:00:36 +00002802 return BuildCookedLiteralOperatorCall(*this, UDLScope, UDSuffix, UDSuffixLoc,
Dmitri Gribenko8f8930f2013-05-03 15:05:50 +00002803 Lit, Tok.getLocation());
Steve Naroffae4143e2007-04-26 20:39:23 +00002804}
2805
Ted Kremeneke65b0862012-03-06 20:05:56 +00002806ExprResult Sema::ActOnIntegerConstant(SourceLocation Loc, uint64_t Val) {
2807 unsigned IntSize = Context.getTargetInfo().getIntWidth();
2808 return Owned(IntegerLiteral::Create(Context, llvm::APInt(IntSize, Val),
2809 Context.IntTy, Loc));
2810}
2811
Richard Smith39570d002012-03-08 08:45:32 +00002812static Expr *BuildFloatingLiteral(Sema &S, NumericLiteralParser &Literal,
2813 QualType Ty, SourceLocation Loc) {
2814 const llvm::fltSemantics &Format = S.Context.getFloatTypeSemantics(Ty);
2815
2816 using llvm::APFloat;
2817 APFloat Val(Format);
2818
2819 APFloat::opStatus result = Literal.GetFloatValue(Val);
2820
2821 // Overflow is always an error, but underflow is only an error if
2822 // we underflowed to zero (APFloat reports denormals as underflow).
2823 if ((result & APFloat::opOverflow) ||
2824 ((result & APFloat::opUnderflow) && Val.isZero())) {
2825 unsigned diagnostic;
2826 SmallString<20> buffer;
2827 if (result & APFloat::opOverflow) {
2828 diagnostic = diag::warn_float_overflow;
2829 APFloat::getLargest(Format).toString(buffer);
2830 } else {
2831 diagnostic = diag::warn_float_underflow;
2832 APFloat::getSmallest(Format).toString(buffer);
2833 }
2834
2835 S.Diag(Loc, diagnostic)
2836 << Ty
2837 << StringRef(buffer.data(), buffer.size());
2838 }
2839
2840 bool isExact = (result == APFloat::opOK);
2841 return FloatingLiteral::Create(S.Context, Val, isExact, Ty, Loc);
2842}
2843
Richard Smithbcc22fc2012-03-09 08:00:36 +00002844ExprResult Sema::ActOnNumericConstant(const Token &Tok, Scope *UDLScope) {
Sebastian Redlffbcf962009-01-18 18:53:16 +00002845 // Fast path for a single digit (which is quite common). A single digit
Richard Smithbcc22fc2012-03-09 08:00:36 +00002846 // cannot have a trigraph, escaped newline, radix prefix, or suffix.
Steve Narofff2fb89e2007-03-13 20:29:44 +00002847 if (Tok.getLength() == 1) {
Chris Lattner9240b3e2009-01-26 22:36:52 +00002848 const char Val = PP.getSpellingOfSingleCharacterNumericConstant(Tok);
Ted Kremeneke65b0862012-03-06 20:05:56 +00002849 return ActOnIntegerConstant(Tok.getLocation(), Val-'0');
Steve Narofff2fb89e2007-03-13 20:29:44 +00002850 }
Ted Kremeneke9814182009-01-13 23:19:12 +00002851
Dmitri Gribenko7ba91722012-09-24 09:53:54 +00002852 SmallString<128> SpellingBuffer;
2853 // NumericLiteralParser wants to overread by one character. Add padding to
2854 // the buffer in case the token is copied to the buffer. If getSpelling()
2855 // returns a StringRef to the memory buffer, it should have a null char at
2856 // the EOF, so it is also safe.
2857 SpellingBuffer.resize(Tok.getLength() + 1);
Sebastian Redlffbcf962009-01-18 18:53:16 +00002858
Chris Lattner67ca9252007-05-21 01:08:44 +00002859 // Get the spelling of the token, which eliminates trigraphs, etc.
Douglas Gregordc970f02010-03-16 22:30:13 +00002860 bool Invalid = false;
Dmitri Gribenko7ba91722012-09-24 09:53:54 +00002861 StringRef TokSpelling = PP.getSpelling(Tok, SpellingBuffer, &Invalid);
Douglas Gregordc970f02010-03-16 22:30:13 +00002862 if (Invalid)
2863 return ExprError();
Sebastian Redlffbcf962009-01-18 18:53:16 +00002864
Dmitri Gribenko7ba91722012-09-24 09:53:54 +00002865 NumericLiteralParser Literal(TokSpelling, Tok.getLocation(), PP);
Steve Narofff2fb89e2007-03-13 20:29:44 +00002866 if (Literal.hadError)
Sebastian Redlffbcf962009-01-18 18:53:16 +00002867 return ExprError();
2868
Richard Smith39570d002012-03-08 08:45:32 +00002869 if (Literal.hasUDSuffix()) {
2870 // We're building a user-defined literal.
2871 IdentifierInfo *UDSuffix = &Context.Idents.get(Literal.getUDSuffix());
2872 SourceLocation UDSuffixLoc =
2873 getUDSuffixLoc(*this, Tok.getLocation(), Literal.getUDSuffixOffset());
2874
Richard Smithbcc22fc2012-03-09 08:00:36 +00002875 // Make sure we're allowed user-defined literals here.
2876 if (!UDLScope)
2877 return ExprError(Diag(UDSuffixLoc, diag::err_invalid_numeric_udl));
Richard Smith39570d002012-03-08 08:45:32 +00002878
Richard Smithbcc22fc2012-03-09 08:00:36 +00002879 QualType CookedTy;
Richard Smith39570d002012-03-08 08:45:32 +00002880 if (Literal.isFloatingLiteral()) {
2881 // C++11 [lex.ext]p4: If S contains a literal operator with parameter type
2882 // long double, the literal is treated as a call of the form
2883 // operator "" X (f L)
Richard Smithbcc22fc2012-03-09 08:00:36 +00002884 CookedTy = Context.LongDoubleTy;
Richard Smith39570d002012-03-08 08:45:32 +00002885 } else {
2886 // C++11 [lex.ext]p3: If S contains a literal operator with parameter type
2887 // unsigned long long, the literal is treated as a call of the form
2888 // operator "" X (n ULL)
Richard Smithbcc22fc2012-03-09 08:00:36 +00002889 CookedTy = Context.UnsignedLongLongTy;
Richard Smith39570d002012-03-08 08:45:32 +00002890 }
2891
Richard Smithbcc22fc2012-03-09 08:00:36 +00002892 DeclarationName OpName =
2893 Context.DeclarationNames.getCXXLiteralOperatorName(UDSuffix);
2894 DeclarationNameInfo OpNameInfo(OpName, UDSuffixLoc);
2895 OpNameInfo.setCXXLiteralOperatorNameLoc(UDSuffixLoc);
2896
2897 // Perform literal operator lookup to determine if we're building a raw
2898 // literal or a cooked one.
2899 LookupResult R(*this, OpName, UDSuffixLoc, LookupOrdinaryName);
Dmitri Gribenko8f8930f2013-05-03 15:05:50 +00002900 switch (LookupLiteralOperator(UDLScope, R, CookedTy,
Richard Smithbcc22fc2012-03-09 08:00:36 +00002901 /*AllowRawAndTemplate*/true)) {
2902 case LOLR_Error:
2903 return ExprError();
2904
2905 case LOLR_Cooked: {
2906 Expr *Lit;
2907 if (Literal.isFloatingLiteral()) {
2908 Lit = BuildFloatingLiteral(*this, Literal, CookedTy, Tok.getLocation());
2909 } else {
2910 llvm::APInt ResultVal(Context.getTargetInfo().getLongLongWidth(), 0);
2911 if (Literal.GetIntegerValue(ResultVal))
Eli Friedman088d39a2013-07-23 00:25:18 +00002912 Diag(Tok.getLocation(), diag::err_integer_too_large);
Richard Smithbcc22fc2012-03-09 08:00:36 +00002913 Lit = IntegerLiteral::Create(Context, ResultVal, CookedTy,
2914 Tok.getLocation());
2915 }
Dmitri Gribenko8f8930f2013-05-03 15:05:50 +00002916 return BuildLiteralOperatorCall(R, OpNameInfo, Lit,
Richard Smithbcc22fc2012-03-09 08:00:36 +00002917 Tok.getLocation());
2918 }
2919
2920 case LOLR_Raw: {
2921 // C++11 [lit.ext]p3, p4: If S contains a raw literal operator, the
2922 // literal is treated as a call of the form
2923 // operator "" X ("n")
2924 SourceLocation TokLoc = Tok.getLocation();
2925 unsigned Length = Literal.getUDSuffixOffset();
2926 QualType StrTy = Context.getConstantArrayType(
Richard Smithbe8229c2013-01-23 23:38:20 +00002927 Context.CharTy.withConst(), llvm::APInt(32, Length + 1),
Richard Smithbcc22fc2012-03-09 08:00:36 +00002928 ArrayType::Normal, 0);
2929 Expr *Lit = StringLiteral::Create(
Dmitri Gribenko7ba91722012-09-24 09:53:54 +00002930 Context, StringRef(TokSpelling.data(), Length), StringLiteral::Ascii,
Richard Smithbcc22fc2012-03-09 08:00:36 +00002931 /*Pascal*/false, StrTy, &TokLoc, 1);
Dmitri Gribenko8f8930f2013-05-03 15:05:50 +00002932 return BuildLiteralOperatorCall(R, OpNameInfo, Lit, TokLoc);
Richard Smithbcc22fc2012-03-09 08:00:36 +00002933 }
2934
2935 case LOLR_Template:
2936 // C++11 [lit.ext]p3, p4: Otherwise (S contains a literal operator
2937 // template), L is treated as a call fo the form
2938 // operator "" X <'c1', 'c2', ... 'ck'>()
2939 // where n is the source character sequence c1 c2 ... ck.
2940 TemplateArgumentListInfo ExplicitArgs;
2941 unsigned CharBits = Context.getIntWidth(Context.CharTy);
2942 bool CharIsUnsigned = Context.CharTy->isUnsignedIntegerType();
2943 llvm::APSInt Value(CharBits, CharIsUnsigned);
2944 for (unsigned I = 0, N = Literal.getUDSuffixOffset(); I != N; ++I) {
Dmitri Gribenko7ba91722012-09-24 09:53:54 +00002945 Value = TokSpelling[I];
Benjamin Kramer6003ad52012-06-07 15:09:51 +00002946 TemplateArgument Arg(Context, Value, Context.CharTy);
Richard Smithbcc22fc2012-03-09 08:00:36 +00002947 TemplateArgumentLocInfo ArgInfo;
2948 ExplicitArgs.addArgument(TemplateArgumentLoc(Arg, ArgInfo));
2949 }
Dmitri Gribenko44ebbd52013-05-05 00:41:58 +00002950 return BuildLiteralOperatorCall(R, OpNameInfo, None, Tok.getLocation(),
2951 &ExplicitArgs);
Richard Smithbcc22fc2012-03-09 08:00:36 +00002952 }
2953
2954 llvm_unreachable("unexpected literal operator lookup result");
Richard Smith39570d002012-03-08 08:45:32 +00002955 }
2956
Chris Lattner1c20a172007-08-26 03:42:43 +00002957 Expr *Res;
Sebastian Redlffbcf962009-01-18 18:53:16 +00002958
Chris Lattner1c20a172007-08-26 03:42:43 +00002959 if (Literal.isFloatingLiteral()) {
Chris Lattnerec0a6d92007-09-22 18:29:59 +00002960 QualType Ty;
Chris Lattner9a8d1d92008-06-30 18:32:54 +00002961 if (Literal.isFloat)
Chris Lattnerec0a6d92007-09-22 18:29:59 +00002962 Ty = Context.FloatTy;
Chris Lattner9a8d1d92008-06-30 18:32:54 +00002963 else if (!Literal.isLong)
Chris Lattnerec0a6d92007-09-22 18:29:59 +00002964 Ty = Context.DoubleTy;
Chris Lattner9a8d1d92008-06-30 18:32:54 +00002965 else
Chris Lattner7570e9c2008-03-08 08:52:55 +00002966 Ty = Context.LongDoubleTy;
Chris Lattner9a8d1d92008-06-30 18:32:54 +00002967
Richard Smith39570d002012-03-08 08:45:32 +00002968 Res = BuildFloatingLiteral(*this, Literal, Ty, Tok.getLocation());
Sebastian Redlffbcf962009-01-18 18:53:16 +00002969
Peter Collingbournec77f85b2011-03-11 19:24:59 +00002970 if (Ty == Context.DoubleTy) {
David Blaikiebbafb8a2012-03-11 07:00:24 +00002971 if (getLangOpts().SinglePrecisionConstants) {
John Wiegley01296292011-04-08 18:41:53 +00002972 Res = ImpCastExprToType(Res, Context.FloatTy, CK_FloatingCast).take();
David Blaikiebbafb8a2012-03-11 07:00:24 +00002973 } else if (getLangOpts().OpenCL && !getOpenCLOptions().cl_khr_fp64) {
Peter Collingbournec77f85b2011-03-11 19:24:59 +00002974 Diag(Tok.getLocation(), diag::warn_double_const_requires_fp64);
John Wiegley01296292011-04-08 18:41:53 +00002975 Res = ImpCastExprToType(Res, Context.FloatTy, CK_FloatingCast).take();
Peter Collingbournec77f85b2011-03-11 19:24:59 +00002976 }
2977 }
Chris Lattner1c20a172007-08-26 03:42:43 +00002978 } else if (!Literal.isIntegerLiteral()) {
Sebastian Redlffbcf962009-01-18 18:53:16 +00002979 return ExprError();
Chris Lattner1c20a172007-08-26 03:42:43 +00002980 } else {
Chris Lattner24d5bfe2008-04-02 04:24:33 +00002981 QualType Ty;
Chris Lattner67ca9252007-05-21 01:08:44 +00002982
Dmitri Gribenko1cd23052012-09-24 18:19:21 +00002983 // 'long long' is a C99 or C++11 feature.
2984 if (!getLangOpts().C99 && Literal.isLongLong) {
2985 if (getLangOpts().CPlusPlus)
2986 Diag(Tok.getLocation(),
Richard Smith2bf7fdb2013-01-02 11:42:31 +00002987 getLangOpts().CPlusPlus11 ?
Dmitri Gribenko1cd23052012-09-24 18:19:21 +00002988 diag::warn_cxx98_compat_longlong : diag::ext_cxx11_longlong);
2989 else
2990 Diag(Tok.getLocation(), diag::ext_c99_longlong);
2991 }
Neil Boothac582c52007-08-29 22:00:19 +00002992
Chris Lattner67ca9252007-05-21 01:08:44 +00002993 // Get the value in the widest-possible width.
Stephen Canonfdc6c1a2012-05-03 22:49:43 +00002994 unsigned MaxWidth = Context.getTargetInfo().getIntMaxTWidth();
2995 // The microsoft literal suffix extensions support 128-bit literals, which
2996 // may be wider than [u]intmax_t.
Richard Smithe6a56db2012-11-29 05:41:51 +00002997 // FIXME: Actually, they don't. We seem to have accidentally invented the
2998 // i128 suffix.
2999 if (Literal.isMicrosoftInteger && MaxWidth < 128 &&
3000 PP.getTargetInfo().hasInt128Type())
Stephen Canonfdc6c1a2012-05-03 22:49:43 +00003001 MaxWidth = 128;
3002 llvm::APInt ResultVal(MaxWidth, 0);
Sebastian Redlffbcf962009-01-18 18:53:16 +00003003
Chris Lattner67ca9252007-05-21 01:08:44 +00003004 if (Literal.GetIntegerValue(ResultVal)) {
Eli Friedman088d39a2013-07-23 00:25:18 +00003005 // If this value didn't fit into uintmax_t, error and force to ull.
3006 Diag(Tok.getLocation(), diag::err_integer_too_large);
Chris Lattner24d5bfe2008-04-02 04:24:33 +00003007 Ty = Context.UnsignedLongLongTy;
3008 assert(Context.getTypeSize(Ty) == ResultVal.getBitWidth() &&
Chris Lattner37e05872008-03-05 18:54:05 +00003009 "long long is not intmax_t?");
Steve Naroff09ef4742007-03-09 23:16:33 +00003010 } else {
Chris Lattner67ca9252007-05-21 01:08:44 +00003011 // If this value fits into a ULL, try to figure out what else it fits into
3012 // according to the rules of C99 6.4.4.1p5.
Sebastian Redlffbcf962009-01-18 18:53:16 +00003013
Chris Lattner67ca9252007-05-21 01:08:44 +00003014 // Octal, Hexadecimal, and integers with a U suffix are allowed to
3015 // be an unsigned int.
3016 bool AllowUnsigned = Literal.isUnsigned || Literal.getRadix() != 10;
3017
3018 // Check from smallest to largest, picking the smallest type we can.
Chris Lattner55258cf2008-05-09 05:59:00 +00003019 unsigned Width = 0;
Chris Lattner7b939cf2007-08-23 21:58:08 +00003020 if (!Literal.isLong && !Literal.isLongLong) {
3021 // Are int/unsigned possibilities?
Douglas Gregore8bbc122011-09-02 00:18:52 +00003022 unsigned IntSize = Context.getTargetInfo().getIntWidth();
Sebastian Redlffbcf962009-01-18 18:53:16 +00003023
Chris Lattner67ca9252007-05-21 01:08:44 +00003024 // Does it fit in a unsigned int?
3025 if (ResultVal.isIntN(IntSize)) {
3026 // Does it fit in a signed int?
3027 if (!Literal.isUnsigned && ResultVal[IntSize-1] == 0)
Chris Lattner24d5bfe2008-04-02 04:24:33 +00003028 Ty = Context.IntTy;
Chris Lattner67ca9252007-05-21 01:08:44 +00003029 else if (AllowUnsigned)
Chris Lattner24d5bfe2008-04-02 04:24:33 +00003030 Ty = Context.UnsignedIntTy;
Chris Lattner55258cf2008-05-09 05:59:00 +00003031 Width = IntSize;
Chris Lattner67ca9252007-05-21 01:08:44 +00003032 }
Chris Lattner67ca9252007-05-21 01:08:44 +00003033 }
Sebastian Redlffbcf962009-01-18 18:53:16 +00003034
Chris Lattner67ca9252007-05-21 01:08:44 +00003035 // Are long/unsigned long possibilities?
Chris Lattner24d5bfe2008-04-02 04:24:33 +00003036 if (Ty.isNull() && !Literal.isLongLong) {
Douglas Gregore8bbc122011-09-02 00:18:52 +00003037 unsigned LongSize = Context.getTargetInfo().getLongWidth();
Sebastian Redlffbcf962009-01-18 18:53:16 +00003038
Chris Lattner67ca9252007-05-21 01:08:44 +00003039 // Does it fit in a unsigned long?
3040 if (ResultVal.isIntN(LongSize)) {
3041 // Does it fit in a signed long?
3042 if (!Literal.isUnsigned && ResultVal[LongSize-1] == 0)
Chris Lattner24d5bfe2008-04-02 04:24:33 +00003043 Ty = Context.LongTy;
Chris Lattner67ca9252007-05-21 01:08:44 +00003044 else if (AllowUnsigned)
Chris Lattner24d5bfe2008-04-02 04:24:33 +00003045 Ty = Context.UnsignedLongTy;
Chris Lattner55258cf2008-05-09 05:59:00 +00003046 Width = LongSize;
Chris Lattner67ca9252007-05-21 01:08:44 +00003047 }
Sebastian Redlffbcf962009-01-18 18:53:16 +00003048 }
3049
Stephen Canonfdc6c1a2012-05-03 22:49:43 +00003050 // Check long long if needed.
Chris Lattner24d5bfe2008-04-02 04:24:33 +00003051 if (Ty.isNull()) {
Douglas Gregore8bbc122011-09-02 00:18:52 +00003052 unsigned LongLongSize = Context.getTargetInfo().getLongLongWidth();
Sebastian Redlffbcf962009-01-18 18:53:16 +00003053
Chris Lattner67ca9252007-05-21 01:08:44 +00003054 // Does it fit in a unsigned long long?
3055 if (ResultVal.isIntN(LongLongSize)) {
3056 // Does it fit in a signed long long?
Francois Pichetc3e73b32011-01-11 23:38:13 +00003057 // To be compatible with MSVC, hex integer literals ending with the
3058 // LL or i64 suffix are always signed in Microsoft mode.
Francois Pichetbf711d92011-01-11 12:23:00 +00003059 if (!Literal.isUnsigned && (ResultVal[LongLongSize-1] == 0 ||
David Blaikiebbafb8a2012-03-11 07:00:24 +00003060 (getLangOpts().MicrosoftExt && Literal.isLongLong)))
Chris Lattner24d5bfe2008-04-02 04:24:33 +00003061 Ty = Context.LongLongTy;
Chris Lattner67ca9252007-05-21 01:08:44 +00003062 else if (AllowUnsigned)
Chris Lattner24d5bfe2008-04-02 04:24:33 +00003063 Ty = Context.UnsignedLongLongTy;
Chris Lattner55258cf2008-05-09 05:59:00 +00003064 Width = LongLongSize;
Chris Lattner67ca9252007-05-21 01:08:44 +00003065 }
3066 }
Stephen Canonfdc6c1a2012-05-03 22:49:43 +00003067
3068 // If it doesn't fit in unsigned long long, and we're using Microsoft
3069 // extensions, then its a 128-bit integer literal.
Richard Smithe6a56db2012-11-29 05:41:51 +00003070 if (Ty.isNull() && Literal.isMicrosoftInteger &&
3071 PP.getTargetInfo().hasInt128Type()) {
Stephen Canonfdc6c1a2012-05-03 22:49:43 +00003072 if (Literal.isUnsigned)
3073 Ty = Context.UnsignedInt128Ty;
3074 else
3075 Ty = Context.Int128Ty;
3076 Width = 128;
3077 }
Sebastian Redlffbcf962009-01-18 18:53:16 +00003078
Chris Lattner67ca9252007-05-21 01:08:44 +00003079 // If we still couldn't decide a type, we probably have something that
3080 // does not fit in a signed long long, but has no U suffix.
Chris Lattner24d5bfe2008-04-02 04:24:33 +00003081 if (Ty.isNull()) {
Eli Friedmanab091872013-07-26 00:06:45 +00003082 Diag(Tok.getLocation(), diag::warn_integer_too_large_for_signed);
Chris Lattner24d5bfe2008-04-02 04:24:33 +00003083 Ty = Context.UnsignedLongLongTy;
Douglas Gregore8bbc122011-09-02 00:18:52 +00003084 Width = Context.getTargetInfo().getLongLongWidth();
Chris Lattner67ca9252007-05-21 01:08:44 +00003085 }
Sebastian Redlffbcf962009-01-18 18:53:16 +00003086
Chris Lattner55258cf2008-05-09 05:59:00 +00003087 if (ResultVal.getBitWidth() != Width)
Jay Foad6d4db0c2010-12-07 08:25:34 +00003088 ResultVal = ResultVal.trunc(Width);
Steve Naroff09ef4742007-03-09 23:16:33 +00003089 }
Argyrios Kyrtzidis43b20572010-08-28 09:06:06 +00003090 Res = IntegerLiteral::Create(Context, ResultVal, Ty, Tok.getLocation());
Steve Naroff09ef4742007-03-09 23:16:33 +00003091 }
Sebastian Redlffbcf962009-01-18 18:53:16 +00003092
Chris Lattner1c20a172007-08-26 03:42:43 +00003093 // If this is an imaginary literal, create the ImaginaryLiteral wrapper.
3094 if (Literal.isImaginary)
Mike Stump11289f42009-09-09 15:08:12 +00003095 Res = new (Context) ImaginaryLiteral(Res,
Steve Narofff6009ed2009-01-21 00:14:39 +00003096 Context.getComplexType(Res->getType()));
Sebastian Redlffbcf962009-01-18 18:53:16 +00003097
3098 return Owned(Res);
Chris Lattnere168f762006-11-10 05:29:30 +00003099}
3100
Richard Trieuba63ce62011-09-09 01:45:06 +00003101ExprResult Sema::ActOnParenExpr(SourceLocation L, SourceLocation R, Expr *E) {
Chris Lattner24d5bfe2008-04-02 04:24:33 +00003102 assert((E != 0) && "ActOnParenExpr() missing expr");
Steve Narofff6009ed2009-01-21 00:14:39 +00003103 return Owned(new (Context) ParenExpr(L, R, E));
Chris Lattnere168f762006-11-10 05:29:30 +00003104}
3105
Chandler Carruth62da79c2011-05-26 08:53:12 +00003106static bool CheckVecStepTraitOperandType(Sema &S, QualType T,
3107 SourceLocation Loc,
3108 SourceRange ArgRange) {
3109 // [OpenCL 1.1 6.11.12] "The vec_step built-in function takes a built-in
3110 // scalar or vector data type argument..."
3111 // Every built-in scalar type (OpenCL 1.1 6.1.1) is either an arithmetic
3112 // type (C99 6.2.5p18) or void.
3113 if (!(T->isArithmeticType() || T->isVoidType() || T->isVectorType())) {
3114 S.Diag(Loc, diag::err_vecstep_non_scalar_vector_type)
3115 << T << ArgRange;
3116 return true;
3117 }
3118
3119 assert((T->isVoidType() || !T->isIncompleteType()) &&
3120 "Scalar types should always be complete");
3121 return false;
3122}
3123
Chandler Carruthcea1aac2011-05-26 08:53:16 +00003124static bool CheckExtensionTraitOperandType(Sema &S, QualType T,
3125 SourceLocation Loc,
3126 SourceRange ArgRange,
3127 UnaryExprOrTypeTrait TraitKind) {
3128 // C99 6.5.3.4p1:
Richard Smith9cf21ae2013-03-18 23:37:25 +00003129 if (T->isFunctionType() &&
3130 (TraitKind == UETT_SizeOf || TraitKind == UETT_AlignOf)) {
3131 // sizeof(function)/alignof(function) is allowed as an extension.
3132 S.Diag(Loc, diag::ext_sizeof_alignof_function_type)
3133 << TraitKind << ArgRange;
Chandler Carruthcea1aac2011-05-26 08:53:16 +00003134 return false;
3135 }
3136
3137 // Allow sizeof(void)/alignof(void) as an extension.
3138 if (T->isVoidType()) {
Richard Smith9cf21ae2013-03-18 23:37:25 +00003139 S.Diag(Loc, diag::ext_sizeof_alignof_void_type) << TraitKind << ArgRange;
Chandler Carruthcea1aac2011-05-26 08:53:16 +00003140 return false;
3141 }
3142
3143 return true;
3144}
3145
3146static bool CheckObjCTraitOperandConstraints(Sema &S, QualType T,
3147 SourceLocation Loc,
3148 SourceRange ArgRange,
3149 UnaryExprOrTypeTrait TraitKind) {
John McCallf2538342012-07-31 05:14:30 +00003150 // Reject sizeof(interface) and sizeof(interface<proto>) if the
3151 // runtime doesn't allow it.
3152 if (!S.LangOpts.ObjCRuntime.allowsSizeofAlignof() && T->isObjCObjectType()) {
Chandler Carruthcea1aac2011-05-26 08:53:16 +00003153 S.Diag(Loc, diag::err_sizeof_nonfragile_interface)
3154 << T << (TraitKind == UETT_SizeOf)
3155 << ArgRange;
3156 return true;
3157 }
3158
3159 return false;
3160}
3161
Benjamin Kramer054faa52013-03-29 21:43:21 +00003162/// \brief Check whether E is a pointer from a decayed array type (the decayed
3163/// pointer type is equal to T) and emit a warning if it is.
3164static void warnOnSizeofOnArrayDecay(Sema &S, SourceLocation Loc, QualType T,
3165 Expr *E) {
3166 // Don't warn if the operation changed the type.
3167 if (T != E->getType())
3168 return;
3169
3170 // Now look for array decays.
3171 ImplicitCastExpr *ICE = dyn_cast<ImplicitCastExpr>(E);
3172 if (!ICE || ICE->getCastKind() != CK_ArrayToPointerDecay)
3173 return;
3174
3175 S.Diag(Loc, diag::warn_sizeof_array_decay) << ICE->getSourceRange()
3176 << ICE->getType()
3177 << ICE->getSubExpr()->getType();
3178}
3179
Chandler Carruth14502c22011-05-26 08:53:10 +00003180/// \brief Check the constrains on expression operands to unary type expression
3181/// and type traits.
3182///
Chandler Carruth7c430c02011-05-27 01:33:31 +00003183/// Completes any types necessary and validates the constraints on the operand
3184/// expression. The logic mostly mirrors the type-based overload, but may modify
3185/// the expression as it completes the type for that expression through template
3186/// instantiation, etc.
Richard Trieuba63ce62011-09-09 01:45:06 +00003187bool Sema::CheckUnaryExprOrTypeTraitOperand(Expr *E,
Chandler Carruth14502c22011-05-26 08:53:10 +00003188 UnaryExprOrTypeTrait ExprKind) {
Richard Trieuba63ce62011-09-09 01:45:06 +00003189 QualType ExprTy = E->getType();
John McCall768439e2013-05-06 07:40:34 +00003190 assert(!ExprTy->isReferenceType());
Chandler Carruth7c430c02011-05-27 01:33:31 +00003191
3192 if (ExprKind == UETT_VecStep)
Richard Trieuba63ce62011-09-09 01:45:06 +00003193 return CheckVecStepTraitOperandType(*this, ExprTy, E->getExprLoc(),
3194 E->getSourceRange());
Chandler Carruth7c430c02011-05-27 01:33:31 +00003195
3196 // Whitelist some types as extensions
Richard Trieuba63ce62011-09-09 01:45:06 +00003197 if (!CheckExtensionTraitOperandType(*this, ExprTy, E->getExprLoc(),
3198 E->getSourceRange(), ExprKind))
Chandler Carruth7c430c02011-05-27 01:33:31 +00003199 return false;
3200
Richard Trieuba63ce62011-09-09 01:45:06 +00003201 if (RequireCompleteExprType(E,
Douglas Gregor7bfb2d02012-05-04 16:32:21 +00003202 diag::err_sizeof_alignof_incomplete_type,
3203 ExprKind, E->getSourceRange()))
Chandler Carruth7c430c02011-05-27 01:33:31 +00003204 return true;
3205
John McCall768439e2013-05-06 07:40:34 +00003206 // Completing the expression's type may have changed it.
Richard Trieuba63ce62011-09-09 01:45:06 +00003207 ExprTy = E->getType();
John McCall768439e2013-05-06 07:40:34 +00003208 assert(!ExprTy->isReferenceType());
Chandler Carruth7c430c02011-05-27 01:33:31 +00003209
Richard Trieuba63ce62011-09-09 01:45:06 +00003210 if (CheckObjCTraitOperandConstraints(*this, ExprTy, E->getExprLoc(),
3211 E->getSourceRange(), ExprKind))
Chandler Carruth7c430c02011-05-27 01:33:31 +00003212 return true;
3213
Nico Weber0870deb2011-06-15 02:47:03 +00003214 if (ExprKind == UETT_SizeOf) {
Richard Trieuba63ce62011-09-09 01:45:06 +00003215 if (DeclRefExpr *DeclRef = dyn_cast<DeclRefExpr>(E->IgnoreParens())) {
Nico Weber0870deb2011-06-15 02:47:03 +00003216 if (ParmVarDecl *PVD = dyn_cast<ParmVarDecl>(DeclRef->getFoundDecl())) {
3217 QualType OType = PVD->getOriginalType();
3218 QualType Type = PVD->getType();
3219 if (Type->isPointerType() && OType->isArrayType()) {
Richard Trieuba63ce62011-09-09 01:45:06 +00003220 Diag(E->getExprLoc(), diag::warn_sizeof_array_param)
Nico Weber0870deb2011-06-15 02:47:03 +00003221 << Type << OType;
3222 Diag(PVD->getLocation(), diag::note_declared_at);
3223 }
3224 }
3225 }
Benjamin Kramer054faa52013-03-29 21:43:21 +00003226
3227 // Warn on "sizeof(array op x)" and "sizeof(x op array)", where the array
3228 // decays into a pointer and returns an unintended result. This is most
3229 // likely a typo for "sizeof(array) op x".
3230 if (BinaryOperator *BO = dyn_cast<BinaryOperator>(E->IgnoreParens())) {
3231 warnOnSizeofOnArrayDecay(*this, BO->getOperatorLoc(), BO->getType(),
3232 BO->getLHS());
3233 warnOnSizeofOnArrayDecay(*this, BO->getOperatorLoc(), BO->getType(),
3234 BO->getRHS());
3235 }
Nico Weber0870deb2011-06-15 02:47:03 +00003236 }
3237
Chandler Carruth7c430c02011-05-27 01:33:31 +00003238 return false;
Chandler Carruth14502c22011-05-26 08:53:10 +00003239}
3240
3241/// \brief Check the constraints on operands to unary expression and type
3242/// traits.
3243///
3244/// This will complete any types necessary, and validate the various constraints
3245/// on those operands.
3246///
Steve Naroff71b59a92007-06-04 22:22:31 +00003247/// The UsualUnaryConversions() function is *not* called by this routine.
Chandler Carruth14502c22011-05-26 08:53:10 +00003248/// C99 6.3.2.1p[2-4] all state:
3249/// Except when it is the operand of the sizeof operator ...
3250///
3251/// C++ [expr.sizeof]p4
3252/// The lvalue-to-rvalue, array-to-pointer, and function-to-pointer
3253/// standard conversions are not applied to the operand of sizeof.
3254///
3255/// This policy is followed for all of the unary trait expressions.
Richard Trieuba63ce62011-09-09 01:45:06 +00003256bool Sema::CheckUnaryExprOrTypeTraitOperand(QualType ExprType,
Peter Collingbournee190dee2011-03-11 19:24:49 +00003257 SourceLocation OpLoc,
3258 SourceRange ExprRange,
3259 UnaryExprOrTypeTrait ExprKind) {
Richard Trieuba63ce62011-09-09 01:45:06 +00003260 if (ExprType->isDependentType())
Sebastian Redl8d2ccae2009-02-26 14:39:58 +00003261 return false;
3262
Sebastian Redl22e2e5c2009-11-23 17:18:46 +00003263 // C++ [expr.sizeof]p2: "When applied to a reference or a reference type,
3264 // the result is the size of the referenced type."
3265 // C++ [expr.alignof]p3: "When alignof is applied to a reference type, the
3266 // result shall be the alignment of the referenced type."
Richard Trieuba63ce62011-09-09 01:45:06 +00003267 if (const ReferenceType *Ref = ExprType->getAs<ReferenceType>())
3268 ExprType = Ref->getPointeeType();
Sebastian Redl22e2e5c2009-11-23 17:18:46 +00003269
Chandler Carruth62da79c2011-05-26 08:53:12 +00003270 if (ExprKind == UETT_VecStep)
Richard Trieuba63ce62011-09-09 01:45:06 +00003271 return CheckVecStepTraitOperandType(*this, ExprType, OpLoc, ExprRange);
Peter Collingbournee190dee2011-03-11 19:24:49 +00003272
Chandler Carruthcea1aac2011-05-26 08:53:16 +00003273 // Whitelist some types as extensions
Richard Trieuba63ce62011-09-09 01:45:06 +00003274 if (!CheckExtensionTraitOperandType(*this, ExprType, OpLoc, ExprRange,
Chandler Carruthcea1aac2011-05-26 08:53:16 +00003275 ExprKind))
Chris Lattnerb1355b12009-01-24 19:46:37 +00003276 return false;
Mike Stump11289f42009-09-09 15:08:12 +00003277
Richard Trieuba63ce62011-09-09 01:45:06 +00003278 if (RequireCompleteType(OpLoc, ExprType,
Douglas Gregor7bfb2d02012-05-04 16:32:21 +00003279 diag::err_sizeof_alignof_incomplete_type,
3280 ExprKind, ExprRange))
Chris Lattner62975a72009-04-24 00:30:45 +00003281 return true;
Mike Stump11289f42009-09-09 15:08:12 +00003282
Richard Trieuba63ce62011-09-09 01:45:06 +00003283 if (CheckObjCTraitOperandConstraints(*this, ExprType, OpLoc, ExprRange,
Chandler Carruthcea1aac2011-05-26 08:53:16 +00003284 ExprKind))
Chris Lattnercd2a8c52009-04-24 22:30:50 +00003285 return true;
Mike Stump11289f42009-09-09 15:08:12 +00003286
Chris Lattner62975a72009-04-24 00:30:45 +00003287 return false;
Steve Naroff043d45d2007-05-15 02:32:35 +00003288}
3289
Chandler Carruth14502c22011-05-26 08:53:10 +00003290static bool CheckAlignOfExpr(Sema &S, Expr *E) {
Chris Lattner8dff0172009-01-24 20:17:12 +00003291 E = E->IgnoreParens();
Sebastian Redl8d2ccae2009-02-26 14:39:58 +00003292
Sebastian Redl8d2ccae2009-02-26 14:39:58 +00003293 // Cannot know anything else if the expression is dependent.
3294 if (E->isTypeDependent())
3295 return false;
3296
John McCall768439e2013-05-06 07:40:34 +00003297 if (E->getObjectKind() == OK_BitField) {
Chandler Carruth14502c22011-05-26 08:53:10 +00003298 S.Diag(E->getExprLoc(), diag::err_sizeof_alignof_bitfield)
3299 << 1 << E->getSourceRange();
Douglas Gregor71235ec2009-05-02 02:18:30 +00003300 return true;
Chris Lattner8dff0172009-01-24 20:17:12 +00003301 }
Douglas Gregor71235ec2009-05-02 02:18:30 +00003302
John McCall768439e2013-05-06 07:40:34 +00003303 ValueDecl *D = 0;
3304 if (DeclRefExpr *DRE = dyn_cast<DeclRefExpr>(E)) {
3305 D = DRE->getDecl();
3306 } else if (MemberExpr *ME = dyn_cast<MemberExpr>(E)) {
3307 D = ME->getMemberDecl();
3308 }
3309
3310 // If it's a field, require the containing struct to have a
3311 // complete definition so that we can compute the layout.
3312 //
3313 // This requires a very particular set of circumstances. For a
3314 // field to be contained within an incomplete type, we must in the
3315 // process of parsing that type. To have an expression refer to a
3316 // field, it must be an id-expression or a member-expression, but
3317 // the latter are always ill-formed when the base type is
3318 // incomplete, including only being partially complete. An
3319 // id-expression can never refer to a field in C because fields
3320 // are not in the ordinary namespace. In C++, an id-expression
3321 // can implicitly be a member access, but only if there's an
3322 // implicit 'this' value, and all such contexts are subject to
3323 // delayed parsing --- except for trailing return types in C++11.
3324 // And if an id-expression referring to a field occurs in a
3325 // context that lacks a 'this' value, it's ill-formed --- except,
3326 // agian, in C++11, where such references are allowed in an
3327 // unevaluated context. So C++11 introduces some new complexity.
3328 //
3329 // For the record, since __alignof__ on expressions is a GCC
3330 // extension, GCC seems to permit this but always gives the
3331 // nonsensical answer 0.
3332 //
3333 // We don't really need the layout here --- we could instead just
3334 // directly check for all the appropriate alignment-lowing
3335 // attributes --- but that would require duplicating a lot of
3336 // logic that just isn't worth duplicating for such a marginal
3337 // use-case.
3338 if (FieldDecl *FD = dyn_cast_or_null<FieldDecl>(D)) {
3339 // Fast path this check, since we at least know the record has a
3340 // definition if we can find a member of it.
3341 if (!FD->getParent()->isCompleteDefinition()) {
3342 S.Diag(E->getExprLoc(), diag::err_alignof_member_of_incomplete_type)
3343 << E->getSourceRange();
3344 return true;
3345 }
3346
3347 // Otherwise, if it's a field, and the field doesn't have
3348 // reference type, then it must have a complete type (or be a
3349 // flexible array member, which we explicitly want to
3350 // white-list anyway), which makes the following checks trivial.
3351 if (!FD->getType()->isReferenceType())
Douglas Gregor71235ec2009-05-02 02:18:30 +00003352 return false;
John McCall768439e2013-05-06 07:40:34 +00003353 }
Douglas Gregor71235ec2009-05-02 02:18:30 +00003354
Chandler Carruth14502c22011-05-26 08:53:10 +00003355 return S.CheckUnaryExprOrTypeTraitOperand(E, UETT_AlignOf);
Peter Collingbournee190dee2011-03-11 19:24:49 +00003356}
3357
Chandler Carruth14502c22011-05-26 08:53:10 +00003358bool Sema::CheckVecStepExpr(Expr *E) {
Peter Collingbournee190dee2011-03-11 19:24:49 +00003359 E = E->IgnoreParens();
3360
3361 // Cannot know anything else if the expression is dependent.
3362 if (E->isTypeDependent())
3363 return false;
3364
Chandler Carruth14502c22011-05-26 08:53:10 +00003365 return CheckUnaryExprOrTypeTraitOperand(E, UETT_VecStep);
Chris Lattner8dff0172009-01-24 20:17:12 +00003366}
3367
Douglas Gregor0950e412009-03-13 21:01:28 +00003368/// \brief Build a sizeof or alignof expression given a type operand.
John McCalldadc5752010-08-24 06:29:42 +00003369ExprResult
Peter Collingbournee190dee2011-03-11 19:24:49 +00003370Sema::CreateUnaryExprOrTypeTraitExpr(TypeSourceInfo *TInfo,
3371 SourceLocation OpLoc,
3372 UnaryExprOrTypeTrait ExprKind,
3373 SourceRange R) {
John McCallbcd03502009-12-07 02:54:59 +00003374 if (!TInfo)
Douglas Gregor0950e412009-03-13 21:01:28 +00003375 return ExprError();
3376
John McCallbcd03502009-12-07 02:54:59 +00003377 QualType T = TInfo->getType();
John McCall4c98fd82009-11-04 07:28:41 +00003378
Douglas Gregor0950e412009-03-13 21:01:28 +00003379 if (!T->isDependentType() &&
Peter Collingbournee190dee2011-03-11 19:24:49 +00003380 CheckUnaryExprOrTypeTraitOperand(T, OpLoc, R, ExprKind))
Douglas Gregor0950e412009-03-13 21:01:28 +00003381 return ExprError();
3382
3383 // C99 6.5.3.4p4: the type (an unsigned integer type) is size_t.
Peter Collingbournee190dee2011-03-11 19:24:49 +00003384 return Owned(new (Context) UnaryExprOrTypeTraitExpr(ExprKind, TInfo,
3385 Context.getSizeType(),
3386 OpLoc, R.getEnd()));
Douglas Gregor0950e412009-03-13 21:01:28 +00003387}
3388
3389/// \brief Build a sizeof or alignof expression given an expression
3390/// operand.
John McCalldadc5752010-08-24 06:29:42 +00003391ExprResult
Chandler Carrutha923fb22011-05-29 07:32:14 +00003392Sema::CreateUnaryExprOrTypeTraitExpr(Expr *E, SourceLocation OpLoc,
3393 UnaryExprOrTypeTrait ExprKind) {
Douglas Gregor835af982011-06-22 23:21:00 +00003394 ExprResult PE = CheckPlaceholderExpr(E);
3395 if (PE.isInvalid())
3396 return ExprError();
3397
3398 E = PE.get();
3399
Douglas Gregor0950e412009-03-13 21:01:28 +00003400 // Verify that the operand is valid.
3401 bool isInvalid = false;
3402 if (E->isTypeDependent()) {
3403 // Delay type-checking for type-dependent expressions.
Peter Collingbournee190dee2011-03-11 19:24:49 +00003404 } else if (ExprKind == UETT_AlignOf) {
Chandler Carruth14502c22011-05-26 08:53:10 +00003405 isInvalid = CheckAlignOfExpr(*this, E);
Peter Collingbournee190dee2011-03-11 19:24:49 +00003406 } else if (ExprKind == UETT_VecStep) {
Chandler Carruth14502c22011-05-26 08:53:10 +00003407 isInvalid = CheckVecStepExpr(E);
John McCalld25db7e2013-05-06 21:39:12 +00003408 } else if (E->refersToBitField()) { // C99 6.5.3.4p1.
Chandler Carruth14502c22011-05-26 08:53:10 +00003409 Diag(E->getExprLoc(), diag::err_sizeof_alignof_bitfield) << 0;
Douglas Gregor0950e412009-03-13 21:01:28 +00003410 isInvalid = true;
3411 } else {
Chandler Carruth14502c22011-05-26 08:53:10 +00003412 isInvalid = CheckUnaryExprOrTypeTraitOperand(E, UETT_SizeOf);
Douglas Gregor0950e412009-03-13 21:01:28 +00003413 }
3414
3415 if (isInvalid)
3416 return ExprError();
3417
Eli Friedmane0afc982012-01-21 01:01:51 +00003418 if (ExprKind == UETT_SizeOf && E->getType()->isVariableArrayType()) {
Benjamin Kramerd81108f2012-11-14 15:08:31 +00003419 PE = TransformToPotentiallyEvaluated(E);
Eli Friedmane0afc982012-01-21 01:01:51 +00003420 if (PE.isInvalid()) return ExprError();
3421 E = PE.take();
3422 }
3423
Douglas Gregor0950e412009-03-13 21:01:28 +00003424 // C99 6.5.3.4p4: the type (an unsigned integer type) is size_t.
Chandler Carruth14502c22011-05-26 08:53:10 +00003425 return Owned(new (Context) UnaryExprOrTypeTraitExpr(
Chandler Carrutha923fb22011-05-29 07:32:14 +00003426 ExprKind, E, Context.getSizeType(), OpLoc,
Chandler Carruth14502c22011-05-26 08:53:10 +00003427 E->getSourceRange().getEnd()));
Douglas Gregor0950e412009-03-13 21:01:28 +00003428}
3429
Peter Collingbournee190dee2011-03-11 19:24:49 +00003430/// ActOnUnaryExprOrTypeTraitExpr - Handle @c sizeof(type) and @c sizeof @c
3431/// expr and the same for @c alignof and @c __alignof
Sebastian Redl6f282892008-11-11 17:56:53 +00003432/// Note that the ArgRange is invalid if isType is false.
John McCalldadc5752010-08-24 06:29:42 +00003433ExprResult
Peter Collingbournee190dee2011-03-11 19:24:49 +00003434Sema::ActOnUnaryExprOrTypeTraitExpr(SourceLocation OpLoc,
Richard Trieuba63ce62011-09-09 01:45:06 +00003435 UnaryExprOrTypeTrait ExprKind, bool IsType,
Peter Collingbournee190dee2011-03-11 19:24:49 +00003436 void *TyOrEx, const SourceRange &ArgRange) {
Chris Lattner0d8b1a12006-11-20 04:34:45 +00003437 // If error parsing type, ignore.
Sebastian Redlc215cfc2009-01-19 00:08:26 +00003438 if (TyOrEx == 0) return ExprError();
Steve Naroff043d45d2007-05-15 02:32:35 +00003439
Richard Trieuba63ce62011-09-09 01:45:06 +00003440 if (IsType) {
John McCallbcd03502009-12-07 02:54:59 +00003441 TypeSourceInfo *TInfo;
John McCallba7bf592010-08-24 05:47:05 +00003442 (void) GetTypeFromParser(ParsedType::getFromOpaquePtr(TyOrEx), &TInfo);
Peter Collingbournee190dee2011-03-11 19:24:49 +00003443 return CreateUnaryExprOrTypeTraitExpr(TInfo, OpLoc, ExprKind, ArgRange);
Mike Stump11289f42009-09-09 15:08:12 +00003444 }
Sebastian Redl6f282892008-11-11 17:56:53 +00003445
Douglas Gregor0950e412009-03-13 21:01:28 +00003446 Expr *ArgEx = (Expr *)TyOrEx;
Chandler Carrutha923fb22011-05-29 07:32:14 +00003447 ExprResult Result = CreateUnaryExprOrTypeTraitExpr(ArgEx, OpLoc, ExprKind);
Benjamin Kramer62b95d82012-08-23 21:35:17 +00003448 return Result;
Chris Lattnere168f762006-11-10 05:29:30 +00003449}
3450
John Wiegley01296292011-04-08 18:41:53 +00003451static QualType CheckRealImagOperand(Sema &S, ExprResult &V, SourceLocation Loc,
Richard Trieuba63ce62011-09-09 01:45:06 +00003452 bool IsReal) {
John Wiegley01296292011-04-08 18:41:53 +00003453 if (V.get()->isTypeDependent())
John McCall4bc41ae2010-11-18 19:01:18 +00003454 return S.Context.DependentTy;
Mike Stump11289f42009-09-09 15:08:12 +00003455
John McCall34376a62010-12-04 03:47:34 +00003456 // _Real and _Imag are only l-values for normal l-values.
John Wiegley01296292011-04-08 18:41:53 +00003457 if (V.get()->getObjectKind() != OK_Ordinary) {
3458 V = S.DefaultLvalueConversion(V.take());
3459 if (V.isInvalid())
3460 return QualType();
3461 }
John McCall34376a62010-12-04 03:47:34 +00003462
Chris Lattnere267f5d2007-08-26 05:39:26 +00003463 // These operators return the element type of a complex type.
John Wiegley01296292011-04-08 18:41:53 +00003464 if (const ComplexType *CT = V.get()->getType()->getAs<ComplexType>())
Chris Lattner30b5dd02007-08-24 21:16:53 +00003465 return CT->getElementType();
Mike Stump11289f42009-09-09 15:08:12 +00003466
Chris Lattnere267f5d2007-08-26 05:39:26 +00003467 // Otherwise they pass through real integer and floating point types here.
John Wiegley01296292011-04-08 18:41:53 +00003468 if (V.get()->getType()->isArithmeticType())
3469 return V.get()->getType();
Mike Stump11289f42009-09-09 15:08:12 +00003470
John McCall36226622010-10-12 02:09:17 +00003471 // Test for placeholders.
John McCall3aef3d82011-04-10 19:13:55 +00003472 ExprResult PR = S.CheckPlaceholderExpr(V.get());
John McCall36226622010-10-12 02:09:17 +00003473 if (PR.isInvalid()) return QualType();
John Wiegley01296292011-04-08 18:41:53 +00003474 if (PR.get() != V.get()) {
Benjamin Kramer62b95d82012-08-23 21:35:17 +00003475 V = PR;
Richard Trieuba63ce62011-09-09 01:45:06 +00003476 return CheckRealImagOperand(S, V, Loc, IsReal);
John McCall36226622010-10-12 02:09:17 +00003477 }
3478
Chris Lattnere267f5d2007-08-26 05:39:26 +00003479 // Reject anything else.
John Wiegley01296292011-04-08 18:41:53 +00003480 S.Diag(Loc, diag::err_realimag_invalid_type) << V.get()->getType()
Richard Trieuba63ce62011-09-09 01:45:06 +00003481 << (IsReal ? "__real" : "__imag");
Chris Lattnere267f5d2007-08-26 05:39:26 +00003482 return QualType();
Chris Lattner30b5dd02007-08-24 21:16:53 +00003483}
3484
3485
Chris Lattnere168f762006-11-10 05:29:30 +00003486
John McCalldadc5752010-08-24 06:29:42 +00003487ExprResult
Sebastian Redlc215cfc2009-01-19 00:08:26 +00003488Sema::ActOnPostfixUnaryOp(Scope *S, SourceLocation OpLoc,
John McCallb268a282010-08-23 23:25:46 +00003489 tok::TokenKind Kind, Expr *Input) {
John McCalle3027922010-08-25 11:45:40 +00003490 UnaryOperatorKind Opc;
Chris Lattnere168f762006-11-10 05:29:30 +00003491 switch (Kind) {
David Blaikie83d382b2011-09-23 05:06:16 +00003492 default: llvm_unreachable("Unknown unary op!");
John McCalle3027922010-08-25 11:45:40 +00003493 case tok::plusplus: Opc = UO_PostInc; break;
3494 case tok::minusminus: Opc = UO_PostDec; break;
Chris Lattnere168f762006-11-10 05:29:30 +00003495 }
Sebastian Redlc215cfc2009-01-19 00:08:26 +00003496
Sebastian Redla9351792012-02-11 23:51:47 +00003497 // Since this might is a postfix expression, get rid of ParenListExprs.
3498 ExprResult Result = MaybeConvertParenListExprToParenExpr(S, Input);
3499 if (Result.isInvalid()) return ExprError();
3500 Input = Result.take();
3501
John McCallb268a282010-08-23 23:25:46 +00003502 return BuildUnaryOp(S, OpLoc, Opc, Input);
Chris Lattnere168f762006-11-10 05:29:30 +00003503}
3504
John McCallf2538342012-07-31 05:14:30 +00003505/// \brief Diagnose if arithmetic on the given ObjC pointer is illegal.
3506///
3507/// \return true on error
3508static bool checkArithmeticOnObjCPointer(Sema &S,
3509 SourceLocation opLoc,
3510 Expr *op) {
3511 assert(op->getType()->isObjCObjectPointerType());
3512 if (S.LangOpts.ObjCRuntime.allowsPointerArithmetic())
3513 return false;
3514
3515 S.Diag(opLoc, diag::err_arithmetic_nonfragile_interface)
3516 << op->getType()->castAs<ObjCObjectPointerType>()->getPointeeType()
3517 << op->getSourceRange();
3518 return true;
3519}
3520
John McCalldadc5752010-08-24 06:29:42 +00003521ExprResult
John McCallf22d0ac2013-03-04 01:30:55 +00003522Sema::ActOnArraySubscriptExpr(Scope *S, Expr *base, SourceLocation lbLoc,
3523 Expr *idx, SourceLocation rbLoc) {
Nate Begeman5ec4b312009-08-10 23:49:36 +00003524 // Since this might be a postfix expression, get rid of ParenListExprs.
John McCallf22d0ac2013-03-04 01:30:55 +00003525 if (isa<ParenListExpr>(base)) {
3526 ExprResult result = MaybeConvertParenListExprToParenExpr(S, base);
3527 if (result.isInvalid()) return ExprError();
3528 base = result.take();
3529 }
Nate Begeman5ec4b312009-08-10 23:49:36 +00003530
John McCallf22d0ac2013-03-04 01:30:55 +00003531 // Handle any non-overload placeholder types in the base and index
3532 // expressions. We can't handle overloads here because the other
3533 // operand might be an overloadable type, in which case the overload
3534 // resolution for the operator overload should get the first crack
3535 // at the overload.
3536 if (base->getType()->isNonOverloadPlaceholderType()) {
3537 ExprResult result = CheckPlaceholderExpr(base);
3538 if (result.isInvalid()) return ExprError();
3539 base = result.take();
3540 }
3541 if (idx->getType()->isNonOverloadPlaceholderType()) {
3542 ExprResult result = CheckPlaceholderExpr(idx);
3543 if (result.isInvalid()) return ExprError();
3544 idx = result.take();
3545 }
Mike Stump11289f42009-09-09 15:08:12 +00003546
John McCallf22d0ac2013-03-04 01:30:55 +00003547 // Build an unanalyzed expression if either operand is type-dependent.
David Blaikiebbafb8a2012-03-11 07:00:24 +00003548 if (getLangOpts().CPlusPlus &&
John McCallf22d0ac2013-03-04 01:30:55 +00003549 (base->isTypeDependent() || idx->isTypeDependent())) {
3550 return Owned(new (Context) ArraySubscriptExpr(base, idx,
John McCall7decc9e2010-11-18 06:31:45 +00003551 Context.DependentTy,
3552 VK_LValue, OK_Ordinary,
John McCallf22d0ac2013-03-04 01:30:55 +00003553 rbLoc));
Douglas Gregor7a77a6b2009-05-19 00:01:19 +00003554 }
3555
John McCallf22d0ac2013-03-04 01:30:55 +00003556 // Use C++ overloaded-operator rules if either operand has record
3557 // type. The spec says to do this if either type is *overloadable*,
3558 // but enum types can't declare subscript operators or conversion
3559 // operators, so there's nothing interesting for overload resolution
3560 // to do if there aren't any record types involved.
3561 //
3562 // ObjC pointers have their own subscripting logic that is not tied
3563 // to overload resolution and so should not take this path.
David Blaikiebbafb8a2012-03-11 07:00:24 +00003564 if (getLangOpts().CPlusPlus &&
John McCallf22d0ac2013-03-04 01:30:55 +00003565 (base->getType()->isRecordType() ||
3566 (!base->getType()->isObjCObjectPointerType() &&
3567 idx->getType()->isRecordType()))) {
3568 return CreateOverloadedArraySubscriptExpr(lbLoc, rbLoc, base, idx);
Douglas Gregor40412ac2008-11-19 17:17:41 +00003569 }
3570
John McCallf22d0ac2013-03-04 01:30:55 +00003571 return CreateBuiltinArraySubscriptExpr(base, lbLoc, idx, rbLoc);
Sebastian Redladba46e2009-10-29 20:17:01 +00003572}
3573
John McCalldadc5752010-08-24 06:29:42 +00003574ExprResult
John McCallb268a282010-08-23 23:25:46 +00003575Sema::CreateBuiltinArraySubscriptExpr(Expr *Base, SourceLocation LLoc,
Richard Trieuba63ce62011-09-09 01:45:06 +00003576 Expr *Idx, SourceLocation RLoc) {
John McCallb268a282010-08-23 23:25:46 +00003577 Expr *LHSExp = Base;
3578 Expr *RHSExp = Idx;
Sebastian Redladba46e2009-10-29 20:17:01 +00003579
Chris Lattner36d572b2007-07-16 00:14:47 +00003580 // Perform default conversions.
John Wiegley01296292011-04-08 18:41:53 +00003581 if (!LHSExp->getType()->getAs<VectorType>()) {
3582 ExprResult Result = DefaultFunctionArrayLvalueConversion(LHSExp);
3583 if (Result.isInvalid())
3584 return ExprError();
3585 LHSExp = Result.take();
3586 }
3587 ExprResult Result = DefaultFunctionArrayLvalueConversion(RHSExp);
3588 if (Result.isInvalid())
3589 return ExprError();
3590 RHSExp = Result.take();
Sebastian Redlc215cfc2009-01-19 00:08:26 +00003591
Chris Lattner36d572b2007-07-16 00:14:47 +00003592 QualType LHSTy = LHSExp->getType(), RHSTy = RHSExp->getType();
John McCall7decc9e2010-11-18 06:31:45 +00003593 ExprValueKind VK = VK_LValue;
3594 ExprObjectKind OK = OK_Ordinary;
Steve Narofff1e53692007-03-23 22:27:02 +00003595
Steve Naroffc1aadb12007-03-28 21:49:40 +00003596 // C99 6.5.2.1p2: the expression e1[e2] is by definition precisely equivalent
Chris Lattnerf17bd422007-08-30 17:45:32 +00003597 // to the expression *((e1)+(e2)). This means the array "Base" may actually be
Mike Stump4e1f26a2009-02-19 03:04:26 +00003598 // in the subscript position. As a result, we need to derive the array base
Steve Narofff1e53692007-03-23 22:27:02 +00003599 // and index from the expression types.
Chris Lattner36d572b2007-07-16 00:14:47 +00003600 Expr *BaseExpr, *IndexExpr;
3601 QualType ResultType;
Sebastian Redl8d2ccae2009-02-26 14:39:58 +00003602 if (LHSTy->isDependentType() || RHSTy->isDependentType()) {
3603 BaseExpr = LHSExp;
3604 IndexExpr = RHSExp;
3605 ResultType = Context.DependentTy;
Ted Kremenekc23c7e62009-07-29 21:53:49 +00003606 } else if (const PointerType *PTy = LHSTy->getAs<PointerType>()) {
Chris Lattner36d572b2007-07-16 00:14:47 +00003607 BaseExpr = LHSExp;
3608 IndexExpr = RHSExp;
Chris Lattner36d572b2007-07-16 00:14:47 +00003609 ResultType = PTy->getPointeeType();
Mike Stump11289f42009-09-09 15:08:12 +00003610 } else if (const ObjCObjectPointerType *PTy =
John McCallf2538342012-07-31 05:14:30 +00003611 LHSTy->getAs<ObjCObjectPointerType>()) {
Steve Naroff7cae42b2009-07-10 23:34:53 +00003612 BaseExpr = LHSExp;
3613 IndexExpr = RHSExp;
John McCallf2538342012-07-31 05:14:30 +00003614
3615 // Use custom logic if this should be the pseudo-object subscript
3616 // expression.
3617 if (!LangOpts.ObjCRuntime.isSubscriptPointerArithmetic())
3618 return BuildObjCSubscriptExpression(RLoc, BaseExpr, IndexExpr, 0, 0);
3619
Steve Naroff7cae42b2009-07-10 23:34:53 +00003620 ResultType = PTy->getPointeeType();
John McCallf2538342012-07-31 05:14:30 +00003621 if (!LangOpts.ObjCRuntime.allowsPointerArithmetic()) {
3622 Diag(LLoc, diag::err_subscript_nonfragile_interface)
3623 << ResultType << BaseExpr->getSourceRange();
3624 return ExprError();
3625 }
Fariborz Jahanianba0afde2012-03-28 17:56:49 +00003626 } else if (const PointerType *PTy = RHSTy->getAs<PointerType>()) {
3627 // Handle the uncommon case of "123[Ptr]".
3628 BaseExpr = RHSExp;
3629 IndexExpr = LHSExp;
3630 ResultType = PTy->getPointeeType();
Mike Stump11289f42009-09-09 15:08:12 +00003631 } else if (const ObjCObjectPointerType *PTy =
John McCall9dd450b2009-09-21 23:43:11 +00003632 RHSTy->getAs<ObjCObjectPointerType>()) {
Steve Naroff7cae42b2009-07-10 23:34:53 +00003633 // Handle the uncommon case of "123[Ptr]".
3634 BaseExpr = RHSExp;
3635 IndexExpr = LHSExp;
3636 ResultType = PTy->getPointeeType();
John McCallf2538342012-07-31 05:14:30 +00003637 if (!LangOpts.ObjCRuntime.allowsPointerArithmetic()) {
3638 Diag(LLoc, diag::err_subscript_nonfragile_interface)
3639 << ResultType << BaseExpr->getSourceRange();
3640 return ExprError();
3641 }
John McCall9dd450b2009-09-21 23:43:11 +00003642 } else if (const VectorType *VTy = LHSTy->getAs<VectorType>()) {
Chris Lattner41977962007-07-31 19:29:30 +00003643 BaseExpr = LHSExp; // vectors: V[123]
Chris Lattner36d572b2007-07-16 00:14:47 +00003644 IndexExpr = RHSExp;
John McCall7decc9e2010-11-18 06:31:45 +00003645 VK = LHSExp->getValueKind();
3646 if (VK != VK_RValue)
3647 OK = OK_VectorComponent;
Nate Begemanc1bf0612009-01-18 00:45:31 +00003648
Chris Lattner36d572b2007-07-16 00:14:47 +00003649 // FIXME: need to deal with const...
3650 ResultType = VTy->getElementType();
Eli Friedmanab2784f2009-04-25 23:46:54 +00003651 } else if (LHSTy->isArrayType()) {
3652 // If we see an array that wasn't promoted by
Douglas Gregorb92a1562010-02-03 00:27:59 +00003653 // DefaultFunctionArrayLvalueConversion, it must be an array that
Eli Friedmanab2784f2009-04-25 23:46:54 +00003654 // wasn't promoted because of the C90 rule that doesn't
3655 // allow promoting non-lvalue arrays. Warn, then
3656 // force the promotion here.
3657 Diag(LHSExp->getLocStart(), diag::ext_subscript_non_lvalue) <<
3658 LHSExp->getSourceRange();
John Wiegley01296292011-04-08 18:41:53 +00003659 LHSExp = ImpCastExprToType(LHSExp, Context.getArrayDecayedType(LHSTy),
3660 CK_ArrayToPointerDecay).take();
Eli Friedmanab2784f2009-04-25 23:46:54 +00003661 LHSTy = LHSExp->getType();
3662
3663 BaseExpr = LHSExp;
3664 IndexExpr = RHSExp;
Ted Kremenekc23c7e62009-07-29 21:53:49 +00003665 ResultType = LHSTy->getAs<PointerType>()->getPointeeType();
Eli Friedmanab2784f2009-04-25 23:46:54 +00003666 } else if (RHSTy->isArrayType()) {
3667 // Same as previous, except for 123[f().a] case
3668 Diag(RHSExp->getLocStart(), diag::ext_subscript_non_lvalue) <<
3669 RHSExp->getSourceRange();
John Wiegley01296292011-04-08 18:41:53 +00003670 RHSExp = ImpCastExprToType(RHSExp, Context.getArrayDecayedType(RHSTy),
3671 CK_ArrayToPointerDecay).take();
Eli Friedmanab2784f2009-04-25 23:46:54 +00003672 RHSTy = RHSExp->getType();
3673
3674 BaseExpr = RHSExp;
3675 IndexExpr = LHSExp;
Ted Kremenekc23c7e62009-07-29 21:53:49 +00003676 ResultType = RHSTy->getAs<PointerType>()->getPointeeType();
Steve Naroffb3096442007-06-09 03:47:53 +00003677 } else {
Chris Lattner003af242009-04-25 22:50:55 +00003678 return ExprError(Diag(LLoc, diag::err_typecheck_subscript_value)
3679 << LHSExp->getSourceRange() << RHSExp->getSourceRange());
Sebastian Redlc215cfc2009-01-19 00:08:26 +00003680 }
Steve Naroffc1aadb12007-03-28 21:49:40 +00003681 // C99 6.5.2.1p1
Douglas Gregor5cc2c8b2010-07-23 15:58:24 +00003682 if (!IndexExpr->getType()->isIntegerType() && !IndexExpr->isTypeDependent())
Chris Lattner003af242009-04-25 22:50:55 +00003683 return ExprError(Diag(LLoc, diag::err_typecheck_subscript_not_integer)
3684 << IndexExpr->getSourceRange());
Steve Naroffb29cdd52007-07-10 18:23:31 +00003685
Daniel Dunbar4782a6e2009-09-17 06:31:17 +00003686 if ((IndexExpr->getType()->isSpecificBuiltinType(BuiltinType::Char_S) ||
Sam Weinigb7608d72009-09-14 20:14:57 +00003687 IndexExpr->getType()->isSpecificBuiltinType(BuiltinType::Char_U))
3688 && !IndexExpr->isTypeDependent())
Sam Weinig914244e2009-09-14 01:58:58 +00003689 Diag(LLoc, diag::warn_subscript_is_char) << IndexExpr->getSourceRange();
3690
Douglas Gregorac1fb652009-03-24 19:52:54 +00003691 // C99 6.5.2.1p1: "shall have type "pointer to *object* type". Similarly,
Mike Stump11289f42009-09-09 15:08:12 +00003692 // C++ [expr.sub]p1: The type "T" shall be a completely-defined object
3693 // type. Note that Functions are not objects, and that (in C99 parlance)
Douglas Gregorac1fb652009-03-24 19:52:54 +00003694 // incomplete types are not object types.
3695 if (ResultType->isFunctionType()) {
3696 Diag(BaseExpr->getLocStart(), diag::err_subscript_function_type)
3697 << ResultType << BaseExpr->getSourceRange();
3698 return ExprError();
3699 }
Mike Stump11289f42009-09-09 15:08:12 +00003700
David Blaikiebbafb8a2012-03-11 07:00:24 +00003701 if (ResultType->isVoidType() && !getLangOpts().CPlusPlus) {
Abramo Bagnara3aabb4b2010-09-13 06:50:07 +00003702 // GNU extension: subscripting on pointer to void
Chandler Carruth4cc3f292011-06-27 16:32:27 +00003703 Diag(LLoc, diag::ext_gnu_subscript_void_type)
3704 << BaseExpr->getSourceRange();
John McCall4bc41ae2010-11-18 19:01:18 +00003705
3706 // C forbids expressions of unqualified void type from being l-values.
3707 // See IsCForbiddenLValueType.
3708 if (!ResultType.hasQualifiers()) VK = VK_RValue;
Abramo Bagnara3aabb4b2010-09-13 06:50:07 +00003709 } else if (!ResultType->isDependentType() &&
Mike Stump11289f42009-09-09 15:08:12 +00003710 RequireCompleteType(LLoc, ResultType,
Douglas Gregor7bfb2d02012-05-04 16:32:21 +00003711 diag::err_subscript_incomplete_type, BaseExpr))
Douglas Gregorac1fb652009-03-24 19:52:54 +00003712 return ExprError();
Mike Stump11289f42009-09-09 15:08:12 +00003713
John McCall4bc41ae2010-11-18 19:01:18 +00003714 assert(VK == VK_RValue || LangOpts.CPlusPlus ||
Douglas Gregor5476205b2011-06-23 00:49:38 +00003715 !ResultType.isCForbiddenLValueType());
John McCall4bc41ae2010-11-18 19:01:18 +00003716
Mike Stump4e1f26a2009-02-19 03:04:26 +00003717 return Owned(new (Context) ArraySubscriptExpr(LHSExp, RHSExp,
John McCall7decc9e2010-11-18 06:31:45 +00003718 ResultType, VK, OK, RLoc));
Chris Lattnere168f762006-11-10 05:29:30 +00003719}
3720
John McCalldadc5752010-08-24 06:29:42 +00003721ExprResult Sema::BuildCXXDefaultArgExpr(SourceLocation CallLoc,
Nico Weber44887f62010-11-29 18:19:25 +00003722 FunctionDecl *FD,
3723 ParmVarDecl *Param) {
Anders Carlsson355933d2009-08-25 03:49:14 +00003724 if (Param->hasUnparsedDefaultArg()) {
Douglas Gregor8a01b2a2010-09-11 20:24:53 +00003725 Diag(CallLoc,
Nico Weberebd45a02010-11-30 04:44:33 +00003726 diag::err_use_of_default_argument_to_function_declared_later) <<
Anders Carlsson355933d2009-08-25 03:49:14 +00003727 FD << cast<CXXRecordDecl>(FD->getDeclContext())->getDeclName();
Mike Stump11289f42009-09-09 15:08:12 +00003728 Diag(UnparsedDefaultArgLocs[Param],
Nico Weberebd45a02010-11-30 04:44:33 +00003729 diag::note_default_argument_declared_here);
Douglas Gregor8a01b2a2010-09-11 20:24:53 +00003730 return ExprError();
3731 }
3732
3733 if (Param->hasUninstantiatedDefaultArg()) {
3734 Expr *UninstExpr = Param->getUninstantiatedDefaultArg();
Anders Carlsson355933d2009-08-25 03:49:14 +00003735
Richard Smith505df232012-07-22 23:45:10 +00003736 EnterExpressionEvaluationContext EvalContext(*this, PotentiallyEvaluated,
3737 Param);
3738
Douglas Gregor8a01b2a2010-09-11 20:24:53 +00003739 // Instantiate the expression.
Richard Smith47752e42013-05-03 23:46:09 +00003740 MultiLevelTemplateArgumentList MutiLevelArgList
Douglas Gregor8a01b2a2010-09-11 20:24:53 +00003741 = getTemplateInstantiationArgs(FD, 0, /*RelativeToPrimary=*/true);
Anders Carlsson657bad42009-09-05 05:14:19 +00003742
Richard Smith80934652012-07-16 01:09:10 +00003743 InstantiatingTemplate Inst(*this, CallLoc, Param,
Richard Smith47752e42013-05-03 23:46:09 +00003744 MutiLevelArgList.getInnermost());
Richard Smith8a874c92012-07-08 02:38:24 +00003745 if (Inst)
3746 return ExprError();
Anders Carlsson355933d2009-08-25 03:49:14 +00003747
Nico Weber44887f62010-11-29 18:19:25 +00003748 ExprResult Result;
3749 {
3750 // C++ [dcl.fct.default]p5:
3751 // The names in the [default argument] expression are bound, and
3752 // the semantic constraints are checked, at the point where the
3753 // default argument expression appears.
Nico Weberebd45a02010-11-30 04:44:33 +00003754 ContextRAII SavedContext(*this, FD);
Douglas Gregora86bc002012-02-16 21:36:18 +00003755 LocalInstantiationScope Local(*this);
Richard Smith47752e42013-05-03 23:46:09 +00003756 Result = SubstExpr(UninstExpr, MutiLevelArgList);
Nico Weber44887f62010-11-29 18:19:25 +00003757 }
Douglas Gregor8a01b2a2010-09-11 20:24:53 +00003758 if (Result.isInvalid())
3759 return ExprError();
Mike Stump11289f42009-09-09 15:08:12 +00003760
Douglas Gregor8a01b2a2010-09-11 20:24:53 +00003761 // Check the expression as an initializer for the parameter.
3762 InitializedEntity Entity
Fariborz Jahanian8fb87ae2010-09-24 17:30:16 +00003763 = InitializedEntity::InitializeParameter(Context, Param);
Douglas Gregor8a01b2a2010-09-11 20:24:53 +00003764 InitializationKind Kind
3765 = InitializationKind::CreateCopy(Param->getLocation(),
Daniel Dunbar62ee6412012-03-09 18:35:03 +00003766 /*FIXME:EqualLoc*/UninstExpr->getLocStart());
Douglas Gregor8a01b2a2010-09-11 20:24:53 +00003767 Expr *ResultE = Result.takeAs<Expr>();
Douglas Gregor25ab25f2009-12-23 18:19:08 +00003768
Dmitri Gribenko8f8930f2013-05-03 15:05:50 +00003769 InitializationSequence InitSeq(*this, Entity, Kind, ResultE);
Benjamin Kramercc4c49d2012-08-23 23:38:35 +00003770 Result = InitSeq.Perform(*this, Entity, Kind, ResultE);
Douglas Gregor8a01b2a2010-09-11 20:24:53 +00003771 if (Result.isInvalid())
3772 return ExprError();
Kovarththanan Rajaratnamba2c6522010-03-13 10:17:05 +00003773
David Blaikief68e8092012-04-30 18:21:31 +00003774 Expr *Arg = Result.takeAs<Expr>();
Richard Smithc406cb72013-01-17 01:17:56 +00003775 CheckCompletedExpr(Arg, Param->getOuterLocStart());
Douglas Gregor8a01b2a2010-09-11 20:24:53 +00003776 // Build the default argument expression.
David Blaikief68e8092012-04-30 18:21:31 +00003777 return Owned(CXXDefaultArgExpr::Create(Context, CallLoc, Param, Arg));
Anders Carlsson355933d2009-08-25 03:49:14 +00003778 }
3779
Douglas Gregor8a01b2a2010-09-11 20:24:53 +00003780 // If the default expression creates temporaries, we need to
3781 // push them to the current stack of expression temporaries so they'll
3782 // be properly destroyed.
3783 // FIXME: We should really be rebuilding the default argument with new
3784 // bound temporaries; see the comment in PR5810.
John McCall28fc7092011-11-10 05:35:25 +00003785 // We don't need to do that with block decls, though, because
3786 // blocks in default argument expression can never capture anything.
3787 if (isa<ExprWithCleanups>(Param->getInit())) {
3788 // Set the "needs cleanups" bit regardless of whether there are
3789 // any explicit objects.
John McCall31168b02011-06-15 23:02:42 +00003790 ExprNeedsCleanups = true;
John McCall28fc7092011-11-10 05:35:25 +00003791
3792 // Append all the objects to the cleanup list. Right now, this
3793 // should always be a no-op, because blocks in default argument
3794 // expressions should never be able to capture anything.
3795 assert(!cast<ExprWithCleanups>(Param->getInit())->getNumObjects() &&
3796 "default argument expression has capturing blocks?");
Douglas Gregor6ed2fee2010-09-14 22:55:20 +00003797 }
Douglas Gregor8a01b2a2010-09-11 20:24:53 +00003798
3799 // We already type-checked the argument, so we know it works.
Douglas Gregor32b3de52010-09-11 23:32:50 +00003800 // Just mark all of the declarations in this potentially-evaluated expression
3801 // as being "referenced".
Douglas Gregor680e9e02012-02-21 19:11:17 +00003802 MarkDeclarationsReferencedInExpr(Param->getDefaultArg(),
3803 /*SkipLocalVariables=*/true);
Douglas Gregor033f6752009-12-23 23:03:06 +00003804 return Owned(CXXDefaultArgExpr::Create(Context, CallLoc, Param));
Anders Carlsson355933d2009-08-25 03:49:14 +00003805}
3806
Richard Smith55ce3522012-06-25 20:30:08 +00003807
3808Sema::VariadicCallType
3809Sema::getVariadicCallType(FunctionDecl *FDecl, const FunctionProtoType *Proto,
3810 Expr *Fn) {
3811 if (Proto && Proto->isVariadic()) {
3812 if (dyn_cast_or_null<CXXConstructorDecl>(FDecl))
3813 return VariadicConstructor;
3814 else if (Fn && Fn->getType()->isBlockPointerType())
3815 return VariadicBlock;
3816 else if (FDecl) {
3817 if (CXXMethodDecl *Method = dyn_cast_or_null<CXXMethodDecl>(FDecl))
3818 if (Method->isInstance())
3819 return VariadicMethod;
Richard Trieu9be9c682013-06-22 02:30:38 +00003820 } else if (Fn && Fn->getType() == Context.BoundMemberTy)
3821 return VariadicMethod;
Richard Smith55ce3522012-06-25 20:30:08 +00003822 return VariadicFunction;
3823 }
3824 return VariadicDoesNotApply;
3825}
3826
Kaelyn Uhrain476c8232013-07-08 23:13:44 +00003827namespace {
3828class FunctionCallCCC : public FunctionCallFilterCCC {
3829public:
3830 FunctionCallCCC(Sema &SemaRef, const IdentifierInfo *FuncName,
3831 unsigned NumArgs, bool HasExplicitTemplateArgs)
3832 : FunctionCallFilterCCC(SemaRef, NumArgs, HasExplicitTemplateArgs),
3833 FunctionName(FuncName) {}
3834
3835 virtual bool ValidateCandidate(const TypoCorrection &candidate) {
3836 if (!candidate.getCorrectionSpecifier() ||
3837 candidate.getCorrectionAsIdentifierInfo() != FunctionName) {
3838 return false;
3839 }
3840
3841 return FunctionCallFilterCCC::ValidateCandidate(candidate);
3842 }
3843
3844private:
3845 const IdentifierInfo *const FunctionName;
3846};
3847}
3848
3849static TypoCorrection TryTypoCorrectionForCall(Sema &S,
3850 DeclarationNameInfo FuncName,
3851 ArrayRef<Expr *> Args) {
3852 FunctionCallCCC CCC(S, FuncName.getName().getAsIdentifierInfo(),
3853 Args.size(), false);
3854 if (TypoCorrection Corrected =
3855 S.CorrectTypo(FuncName, Sema::LookupOrdinaryName,
3856 S.getScopeForContext(S.CurContext), NULL, CCC)) {
3857 if (NamedDecl *ND = Corrected.getCorrectionDecl()) {
3858 if (Corrected.isOverloaded()) {
3859 OverloadCandidateSet OCS(FuncName.getLoc());
3860 OverloadCandidateSet::iterator Best;
3861 for (TypoCorrection::decl_iterator CD = Corrected.begin(),
3862 CDEnd = Corrected.end();
3863 CD != CDEnd; ++CD) {
3864 if (FunctionDecl *FD = dyn_cast<FunctionDecl>(*CD))
3865 S.AddOverloadCandidate(FD, DeclAccessPair::make(FD, AS_none), Args,
3866 OCS);
3867 }
3868 switch (OCS.BestViableFunction(S, FuncName.getLoc(), Best)) {
3869 case OR_Success:
3870 ND = Best->Function;
3871 Corrected.setCorrectionDecl(ND);
3872 break;
3873 default:
3874 break;
3875 }
3876 }
3877 if (isa<ValueDecl>(ND) || isa<FunctionTemplateDecl>(ND)) {
3878 return Corrected;
3879 }
3880 }
3881 }
3882 return TypoCorrection();
3883}
3884
Douglas Gregor97fd6e22008-12-22 05:46:06 +00003885/// ConvertArgumentsForCall - Converts the arguments specified in
3886/// Args/NumArgs to the parameter types of the function FDecl with
3887/// function prototype Proto. Call is the call expression itself, and
3888/// Fn is the function expression. For a C++ member function, this
3889/// routine does not attempt to convert the object argument. Returns
3890/// true if the call is ill-formed.
Mike Stump4e1f26a2009-02-19 03:04:26 +00003891bool
3892Sema::ConvertArgumentsForCall(CallExpr *Call, Expr *Fn,
Douglas Gregor97fd6e22008-12-22 05:46:06 +00003893 FunctionDecl *FDecl,
Douglas Gregordeaad8c2009-02-26 23:50:07 +00003894 const FunctionProtoType *Proto,
Dmitri Gribenko9c785c22013-05-09 21:02:07 +00003895 ArrayRef<Expr *> Args,
Peter Collingbourne619a8c72011-10-02 23:49:29 +00003896 SourceLocation RParenLoc,
3897 bool IsExecConfig) {
John McCallbebede42011-02-26 05:39:39 +00003898 // Bail out early if calling a builtin with custom typechecking.
3899 // We don't need to do this in the
3900 if (FDecl)
3901 if (unsigned ID = FDecl->getBuiltinID())
3902 if (Context.BuiltinInfo.hasCustomTypechecking(ID))
3903 return false;
3904
Mike Stump4e1f26a2009-02-19 03:04:26 +00003905 // C99 6.5.2.2p7 - the arguments are implicitly converted, as if by
Douglas Gregor97fd6e22008-12-22 05:46:06 +00003906 // assignment, to the types of the corresponding parameter, ...
3907 unsigned NumArgsInProto = Proto->getNumArgs();
Douglas Gregorb6b99612009-01-23 21:30:56 +00003908 bool Invalid = false;
Peter Collingbourne740afe22011-10-02 23:49:20 +00003909 unsigned MinArgs = FDecl ? FDecl->getMinRequiredArguments() : NumArgsInProto;
Peter Collingbourne619a8c72011-10-02 23:49:29 +00003910 unsigned FnKind = Fn->getType()->isBlockPointerType()
3911 ? 1 /* block */
3912 : (IsExecConfig ? 3 /* kernel function (exec config) */
3913 : 0 /* function */);
Kovarththanan Rajaratnamba2c6522010-03-13 10:17:05 +00003914
Douglas Gregor97fd6e22008-12-22 05:46:06 +00003915 // If too few arguments are available (and we don't have default
3916 // arguments for the remaining parameters), don't make the call.
Dmitri Gribenko9c785c22013-05-09 21:02:07 +00003917 if (Args.size() < NumArgsInProto) {
3918 if (Args.size() < MinArgs) {
Kaelyn Uhrain476c8232013-07-08 23:13:44 +00003919 TypoCorrection TC;
3920 if (FDecl && (TC = TryTypoCorrectionForCall(
3921 *this, DeclarationNameInfo(FDecl->getDeclName(),
3922 Fn->getLocStart()),
3923 Args))) {
3924 std::string CorrectedStr(TC.getAsString(getLangOpts()));
3925 std::string CorrectedQuotedStr(TC.getQuoted(getLangOpts()));
3926 unsigned diag_id =
3927 MinArgs == NumArgsInProto && !Proto->isVariadic()
3928 ? diag::err_typecheck_call_too_few_args_suggest
3929 : diag::err_typecheck_call_too_few_args_at_least_suggest;
3930 Diag(RParenLoc, diag_id)
3931 << FnKind << MinArgs << static_cast<unsigned>(Args.size())
3932 << Fn->getSourceRange() << CorrectedQuotedStr
3933 << FixItHint::CreateReplacement(TC.getCorrectionRange(),
3934 CorrectedStr);
Richard Trieu2ac682a2013-07-31 00:48:10 +00003935 Diag(TC.getCorrectionDecl()->getLocStart(),
Kaelyn Uhrain476c8232013-07-08 23:13:44 +00003936 diag::note_previous_decl) << CorrectedQuotedStr;
3937 } else if (MinArgs == 1 && FDecl && FDecl->getParamDecl(0)->getDeclName())
Richard Smith10ff50d2012-05-11 05:16:41 +00003938 Diag(RParenLoc, MinArgs == NumArgsInProto && !Proto->isVariadic()
3939 ? diag::err_typecheck_call_too_few_args_one
3940 : diag::err_typecheck_call_too_few_args_at_least_one)
3941 << FnKind
3942 << FDecl->getParamDecl(0) << Fn->getSourceRange();
3943 else
3944 Diag(RParenLoc, MinArgs == NumArgsInProto && !Proto->isVariadic()
3945 ? diag::err_typecheck_call_too_few_args
3946 : diag::err_typecheck_call_too_few_args_at_least)
3947 << FnKind
Dmitri Gribenko9c785c22013-05-09 21:02:07 +00003948 << MinArgs << static_cast<unsigned>(Args.size())
3949 << Fn->getSourceRange();
Peter Collingbourne3bc84ca2011-07-29 00:24:42 +00003950
3951 // Emit the location of the prototype.
Kaelyn Uhrain476c8232013-07-08 23:13:44 +00003952 if (!TC && FDecl && !FDecl->getBuiltinID() && !IsExecConfig)
Peter Collingbourne3bc84ca2011-07-29 00:24:42 +00003953 Diag(FDecl->getLocStart(), diag::note_callee_decl)
3954 << FDecl;
3955
3956 return true;
3957 }
Ted Kremenek5a201952009-02-07 01:47:29 +00003958 Call->setNumArgs(Context, NumArgsInProto);
Douglas Gregor97fd6e22008-12-22 05:46:06 +00003959 }
3960
3961 // If too many are passed and not variadic, error on the extras and drop
3962 // them.
Dmitri Gribenko9c785c22013-05-09 21:02:07 +00003963 if (Args.size() > NumArgsInProto) {
Douglas Gregor97fd6e22008-12-22 05:46:06 +00003964 if (!Proto->isVariadic()) {
Kaelyn Uhrain476c8232013-07-08 23:13:44 +00003965 TypoCorrection TC;
3966 if (FDecl && (TC = TryTypoCorrectionForCall(
3967 *this, DeclarationNameInfo(FDecl->getDeclName(),
3968 Fn->getLocStart()),
3969 Args))) {
3970 std::string CorrectedStr(TC.getAsString(getLangOpts()));
3971 std::string CorrectedQuotedStr(TC.getQuoted(getLangOpts()));
3972 unsigned diag_id =
3973 MinArgs == NumArgsInProto && !Proto->isVariadic()
3974 ? diag::err_typecheck_call_too_many_args_suggest
3975 : diag::err_typecheck_call_too_many_args_at_most_suggest;
3976 Diag(Args[NumArgsInProto]->getLocStart(), diag_id)
3977 << FnKind << NumArgsInProto << static_cast<unsigned>(Args.size())
3978 << Fn->getSourceRange() << CorrectedQuotedStr
3979 << FixItHint::CreateReplacement(TC.getCorrectionRange(),
3980 CorrectedStr);
Richard Trieu2ac682a2013-07-31 00:48:10 +00003981 Diag(TC.getCorrectionDecl()->getLocStart(),
Kaelyn Uhrain476c8232013-07-08 23:13:44 +00003982 diag::note_previous_decl) << CorrectedQuotedStr;
3983 } else if (NumArgsInProto == 1 && FDecl && FDecl->getParamDecl(0)->getDeclName())
Richard Smithd72da152012-05-15 06:21:54 +00003984 Diag(Args[NumArgsInProto]->getLocStart(),
3985 MinArgs == NumArgsInProto
3986 ? diag::err_typecheck_call_too_many_args_one
3987 : diag::err_typecheck_call_too_many_args_at_most_one)
3988 << FnKind
Dmitri Gribenko9c785c22013-05-09 21:02:07 +00003989 << FDecl->getParamDecl(0) << static_cast<unsigned>(Args.size())
3990 << Fn->getSourceRange()
Richard Smithd72da152012-05-15 06:21:54 +00003991 << SourceRange(Args[NumArgsInProto]->getLocStart(),
Dmitri Gribenko9c785c22013-05-09 21:02:07 +00003992 Args.back()->getLocEnd());
Richard Smithd72da152012-05-15 06:21:54 +00003993 else
3994 Diag(Args[NumArgsInProto]->getLocStart(),
3995 MinArgs == NumArgsInProto
3996 ? diag::err_typecheck_call_too_many_args
3997 : diag::err_typecheck_call_too_many_args_at_most)
3998 << FnKind
Dmitri Gribenko9c785c22013-05-09 21:02:07 +00003999 << NumArgsInProto << static_cast<unsigned>(Args.size())
4000 << Fn->getSourceRange()
Richard Smithd72da152012-05-15 06:21:54 +00004001 << SourceRange(Args[NumArgsInProto]->getLocStart(),
Dmitri Gribenko9c785c22013-05-09 21:02:07 +00004002 Args.back()->getLocEnd());
Ted Kremenek99a337e2011-04-04 17:22:27 +00004003
4004 // Emit the location of the prototype.
Kaelyn Uhrain476c8232013-07-08 23:13:44 +00004005 if (!TC && FDecl && !FDecl->getBuiltinID() && !IsExecConfig)
Peter Collingbourne3bc84ca2011-07-29 00:24:42 +00004006 Diag(FDecl->getLocStart(), diag::note_callee_decl)
4007 << FDecl;
Ted Kremenek99a337e2011-04-04 17:22:27 +00004008
Douglas Gregor97fd6e22008-12-22 05:46:06 +00004009 // This deletes the extra arguments.
Ted Kremenek5a201952009-02-07 01:47:29 +00004010 Call->setNumArgs(Context, NumArgsInProto);
Fariborz Jahanian835026e2009-11-24 18:29:37 +00004011 return true;
Douglas Gregor97fd6e22008-12-22 05:46:06 +00004012 }
Douglas Gregor97fd6e22008-12-22 05:46:06 +00004013 }
Chris Lattner0e62c1c2011-07-23 10:55:15 +00004014 SmallVector<Expr *, 8> AllArgs;
Richard Smith55ce3522012-06-25 20:30:08 +00004015 VariadicCallType CallType = getVariadicCallType(FDecl, Proto, Fn);
4016
Daniel Dunbar62ee6412012-03-09 18:35:03 +00004017 Invalid = GatherArgumentsForCall(Call->getLocStart(), FDecl,
Dmitri Gribenko9c785c22013-05-09 21:02:07 +00004018 Proto, 0, Args, AllArgs, CallType);
Fariborz Jahanian835026e2009-11-24 18:29:37 +00004019 if (Invalid)
4020 return true;
4021 unsigned TotalNumArgs = AllArgs.size();
4022 for (unsigned i = 0; i < TotalNumArgs; ++i)
4023 Call->setArg(i, AllArgs[i]);
Kovarththanan Rajaratnamba2c6522010-03-13 10:17:05 +00004024
Fariborz Jahanian835026e2009-11-24 18:29:37 +00004025 return false;
4026}
Mike Stump4e1f26a2009-02-19 03:04:26 +00004027
Fariborz Jahanian835026e2009-11-24 18:29:37 +00004028bool Sema::GatherArgumentsForCall(SourceLocation CallLoc,
4029 FunctionDecl *FDecl,
4030 const FunctionProtoType *Proto,
4031 unsigned FirstProtoArg,
Dmitri Gribenko9c785c22013-05-09 21:02:07 +00004032 ArrayRef<Expr *> Args,
Craig Topper5603df42013-07-05 19:34:19 +00004033 SmallVectorImpl<Expr *> &AllArgs,
Douglas Gregor6073dca2012-02-24 23:56:31 +00004034 VariadicCallType CallType,
Richard Smith6b216962013-02-05 05:52:24 +00004035 bool AllowExplicit,
4036 bool IsListInitialization) {
Fariborz Jahanian835026e2009-11-24 18:29:37 +00004037 unsigned NumArgsInProto = Proto->getNumArgs();
Dmitri Gribenko9c785c22013-05-09 21:02:07 +00004038 unsigned NumArgsToCheck = Args.size();
Fariborz Jahanian835026e2009-11-24 18:29:37 +00004039 bool Invalid = false;
Dmitri Gribenko9c785c22013-05-09 21:02:07 +00004040 if (Args.size() != NumArgsInProto)
Fariborz Jahanian835026e2009-11-24 18:29:37 +00004041 // Use default arguments for missing arguments
4042 NumArgsToCheck = NumArgsInProto;
4043 unsigned ArgIx = 0;
Douglas Gregor97fd6e22008-12-22 05:46:06 +00004044 // Continue to check argument types (even if we have too few/many args).
Fariborz Jahanian835026e2009-11-24 18:29:37 +00004045 for (unsigned i = FirstProtoArg; i != NumArgsToCheck; i++) {
Douglas Gregor97fd6e22008-12-22 05:46:06 +00004046 QualType ProtoArgType = Proto->getArgType(i);
Kovarththanan Rajaratnamba2c6522010-03-13 10:17:05 +00004047
Douglas Gregor97fd6e22008-12-22 05:46:06 +00004048 Expr *Arg;
Peter Collingbournea48f33f2011-10-19 00:16:45 +00004049 ParmVarDecl *Param;
Dmitri Gribenko9c785c22013-05-09 21:02:07 +00004050 if (ArgIx < Args.size()) {
Fariborz Jahanian835026e2009-11-24 18:29:37 +00004051 Arg = Args[ArgIx++];
Kovarththanan Rajaratnamba2c6522010-03-13 10:17:05 +00004052
Daniel Dunbar62ee6412012-03-09 18:35:03 +00004053 if (RequireCompleteType(Arg->getLocStart(),
Eli Friedman3164fb12009-03-22 22:00:50 +00004054 ProtoArgType,
Douglas Gregor7bfb2d02012-05-04 16:32:21 +00004055 diag::err_call_incomplete_argument, Arg))
Eli Friedman3164fb12009-03-22 22:00:50 +00004056 return true;
Kovarththanan Rajaratnamba2c6522010-03-13 10:17:05 +00004057
Douglas Gregorbbeb5c32009-12-22 16:09:06 +00004058 // Pass the argument
Peter Collingbournea48f33f2011-10-19 00:16:45 +00004059 Param = 0;
Douglas Gregorbbeb5c32009-12-22 16:09:06 +00004060 if (FDecl && i < FDecl->getNumParams())
4061 Param = FDecl->getParamDecl(i);
Douglas Gregor96596c92009-12-22 07:24:36 +00004062
John McCall4124c492011-10-17 18:40:02 +00004063 // Strip the unbridged-cast placeholder expression off, if applicable.
Fariborz Jahanian48d94c82013-07-31 18:39:08 +00004064 bool CFAudited = false;
John McCall4124c492011-10-17 18:40:02 +00004065 if (Arg->getType() == Context.ARCUnbridgedCastTy &&
4066 FDecl && FDecl->hasAttr<CFAuditedTransferAttr>() &&
4067 (!Param || !Param->hasAttr<CFConsumedAttr>()))
4068 Arg = stripARCUnbridgedCast(Arg);
Fariborz Jahanian48d94c82013-07-31 18:39:08 +00004069 else if (FDecl && FDecl->hasAttr<CFAuditedTransferAttr>() &&
4070 (!Param || !Param->hasAttr<CFConsumedAttr>()))
4071 CFAudited = true;
John McCall4124c492011-10-17 18:40:02 +00004072
Rafael Espindola8778c282012-11-29 16:09:03 +00004073 InitializedEntity Entity = Param ?
4074 InitializedEntity::InitializeParameter(Context, Param, ProtoArgType)
4075 : InitializedEntity::InitializeParameter(Context, ProtoArgType,
4076 Proto->isArgConsumed(i));
Fariborz Jahanian131996b2013-07-31 18:21:45 +00004077
4078 // Remember that parameter belongs to a CF audited API.
Fariborz Jahanian48d94c82013-07-31 18:39:08 +00004079 if (CFAudited)
Fariborz Jahanian131996b2013-07-31 18:21:45 +00004080 Entity.setParameterCFAudited();
4081
John McCalldadc5752010-08-24 06:29:42 +00004082 ExprResult ArgE = PerformCopyInitialization(Entity,
John McCall34376a62010-12-04 03:47:34 +00004083 SourceLocation(),
Douglas Gregor6073dca2012-02-24 23:56:31 +00004084 Owned(Arg),
Richard Smith6b216962013-02-05 05:52:24 +00004085 IsListInitialization,
Douglas Gregor6073dca2012-02-24 23:56:31 +00004086 AllowExplicit);
Douglas Gregorbbeb5c32009-12-22 16:09:06 +00004087 if (ArgE.isInvalid())
4088 return true;
4089
4090 Arg = ArgE.takeAs<Expr>();
Anders Carlsson84613c42009-06-12 16:51:40 +00004091 } else {
Jordan Rose755a2ff2013-03-15 21:41:35 +00004092 assert(FDecl && "can't use default arguments without a known callee");
Peter Collingbournea48f33f2011-10-19 00:16:45 +00004093 Param = FDecl->getParamDecl(i);
Kovarththanan Rajaratnamba2c6522010-03-13 10:17:05 +00004094
John McCalldadc5752010-08-24 06:29:42 +00004095 ExprResult ArgExpr =
Fariborz Jahanian835026e2009-11-24 18:29:37 +00004096 BuildCXXDefaultArgExpr(CallLoc, FDecl, Param);
Anders Carlsson355933d2009-08-25 03:49:14 +00004097 if (ArgExpr.isInvalid())
4098 return true;
Kovarththanan Rajaratnamba2c6522010-03-13 10:17:05 +00004099
Anders Carlsson355933d2009-08-25 03:49:14 +00004100 Arg = ArgExpr.takeAs<Expr>();
Anders Carlsson84613c42009-06-12 16:51:40 +00004101 }
Kaelyn Uhrain2e7aa5a2011-08-05 23:18:04 +00004102
4103 // Check for array bounds violations for each argument to the call. This
4104 // check only triggers warnings when the argument isn't a more complex Expr
4105 // with its own checking, such as a BinaryOperator.
4106 CheckArrayAccess(Arg);
4107
Peter Collingbournea48f33f2011-10-19 00:16:45 +00004108 // Check for violations of C99 static array rules (C99 6.7.5.3p7).
4109 CheckStaticArrayArgument(CallLoc, Param, Arg);
4110
Fariborz Jahanian835026e2009-11-24 18:29:37 +00004111 AllArgs.push_back(Arg);
Douglas Gregor97fd6e22008-12-22 05:46:06 +00004112 }
Kovarththanan Rajaratnamba2c6522010-03-13 10:17:05 +00004113
Douglas Gregor97fd6e22008-12-22 05:46:06 +00004114 // If this is a variadic call, handle args passed through "...".
Fariborz Jahanian6f2d25e2009-11-24 19:27:49 +00004115 if (CallType != VariadicDoesNotApply) {
John McCall2979fe02011-04-12 00:42:48 +00004116 // Assume that extern "C" functions with variadic arguments that
4117 // return __unknown_anytype aren't *really* variadic.
4118 if (Proto->getResultType() == Context.UnknownAnyTy &&
4119 FDecl && FDecl->isExternC()) {
Dmitri Gribenko9c785c22013-05-09 21:02:07 +00004120 for (unsigned i = ArgIx, e = Args.size(); i != e; ++i) {
John McCallcc5788c2013-03-04 07:34:02 +00004121 QualType paramType; // ignored
4122 ExprResult arg = checkUnknownAnyArg(CallLoc, Args[i], paramType);
John McCall2979fe02011-04-12 00:42:48 +00004123 Invalid |= arg.isInvalid();
4124 AllArgs.push_back(arg.take());
4125 }
4126
4127 // Otherwise do argument promotion, (C99 6.5.2.2p7).
4128 } else {
Dmitri Gribenko9c785c22013-05-09 21:02:07 +00004129 for (unsigned i = ArgIx, e = Args.size(); i != e; ++i) {
Richard Trieucfc491d2011-08-02 04:35:43 +00004130 ExprResult Arg = DefaultVariadicArgumentPromotion(Args[i], CallType,
4131 FDecl);
John McCall2979fe02011-04-12 00:42:48 +00004132 Invalid |= Arg.isInvalid();
4133 AllArgs.push_back(Arg.take());
4134 }
Douglas Gregor97fd6e22008-12-22 05:46:06 +00004135 }
Ted Kremenekd41f3462011-09-26 23:36:13 +00004136
4137 // Check for array bounds violations.
Dmitri Gribenko9c785c22013-05-09 21:02:07 +00004138 for (unsigned i = ArgIx, e = Args.size(); i != e; ++i)
Ted Kremenekd41f3462011-09-26 23:36:13 +00004139 CheckArrayAccess(Args[i]);
Douglas Gregor97fd6e22008-12-22 05:46:06 +00004140 }
Douglas Gregorb6b99612009-01-23 21:30:56 +00004141 return Invalid;
Douglas Gregor97fd6e22008-12-22 05:46:06 +00004142}
4143
Peter Collingbournea48f33f2011-10-19 00:16:45 +00004144static void DiagnoseCalleeStaticArrayParam(Sema &S, ParmVarDecl *PVD) {
4145 TypeLoc TL = PVD->getTypeSourceInfo()->getTypeLoc();
Reid Kleckner8a365022013-06-24 17:51:48 +00004146 if (DecayedTypeLoc DTL = TL.getAs<DecayedTypeLoc>())
4147 TL = DTL.getOriginalLoc();
David Blaikie6adc78e2013-02-18 22:06:02 +00004148 if (ArrayTypeLoc ATL = TL.getAs<ArrayTypeLoc>())
Peter Collingbournea48f33f2011-10-19 00:16:45 +00004149 S.Diag(PVD->getLocation(), diag::note_callee_static_array)
David Blaikie6adc78e2013-02-18 22:06:02 +00004150 << ATL.getLocalSourceRange();
Peter Collingbournea48f33f2011-10-19 00:16:45 +00004151}
4152
4153/// CheckStaticArrayArgument - If the given argument corresponds to a static
4154/// array parameter, check that it is non-null, and that if it is formed by
4155/// array-to-pointer decay, the underlying array is sufficiently large.
4156///
4157/// C99 6.7.5.3p7: If the keyword static also appears within the [ and ] of the
4158/// array type derivation, then for each call to the function, the value of the
4159/// corresponding actual argument shall provide access to the first element of
4160/// an array with at least as many elements as specified by the size expression.
4161void
4162Sema::CheckStaticArrayArgument(SourceLocation CallLoc,
4163 ParmVarDecl *Param,
4164 const Expr *ArgExpr) {
4165 // Static array parameters are not supported in C++.
David Blaikiebbafb8a2012-03-11 07:00:24 +00004166 if (!Param || getLangOpts().CPlusPlus)
Peter Collingbournea48f33f2011-10-19 00:16:45 +00004167 return;
4168
4169 QualType OrigTy = Param->getOriginalType();
4170
4171 const ArrayType *AT = Context.getAsArrayType(OrigTy);
4172 if (!AT || AT->getSizeModifier() != ArrayType::Static)
4173 return;
4174
4175 if (ArgExpr->isNullPointerConstant(Context,
4176 Expr::NPC_NeverValueDependent)) {
4177 Diag(CallLoc, diag::warn_null_arg) << ArgExpr->getSourceRange();
4178 DiagnoseCalleeStaticArrayParam(*this, Param);
4179 return;
4180 }
4181
4182 const ConstantArrayType *CAT = dyn_cast<ConstantArrayType>(AT);
4183 if (!CAT)
4184 return;
4185
4186 const ConstantArrayType *ArgCAT =
4187 Context.getAsConstantArrayType(ArgExpr->IgnoreParenImpCasts()->getType());
4188 if (!ArgCAT)
4189 return;
4190
4191 if (ArgCAT->getSize().ult(CAT->getSize())) {
4192 Diag(CallLoc, diag::warn_static_array_too_small)
4193 << ArgExpr->getSourceRange()
4194 << (unsigned) ArgCAT->getSize().getZExtValue()
4195 << (unsigned) CAT->getSize().getZExtValue();
4196 DiagnoseCalleeStaticArrayParam(*this, Param);
4197 }
4198}
4199
John McCall2979fe02011-04-12 00:42:48 +00004200/// Given a function expression of unknown-any type, try to rebuild it
4201/// to have a function type.
4202static ExprResult rebuildUnknownAnyFunction(Sema &S, Expr *fn);
4203
John McCall5e77d762013-04-16 07:28:30 +00004204/// Is the given type a placeholder that we need to lower out
4205/// immediately during argument processing?
4206static bool isPlaceholderToRemoveAsArg(QualType type) {
4207 // Placeholders are never sugared.
4208 const BuiltinType *placeholder = dyn_cast<BuiltinType>(type);
4209 if (!placeholder) return false;
4210
4211 switch (placeholder->getKind()) {
4212 // Ignore all the non-placeholder types.
4213#define PLACEHOLDER_TYPE(ID, SINGLETON_ID)
4214#define BUILTIN_TYPE(ID, SINGLETON_ID) case BuiltinType::ID:
4215#include "clang/AST/BuiltinTypes.def"
4216 return false;
4217
4218 // We cannot lower out overload sets; they might validly be resolved
4219 // by the call machinery.
4220 case BuiltinType::Overload:
4221 return false;
4222
4223 // Unbridged casts in ARC can be handled in some call positions and
4224 // should be left in place.
4225 case BuiltinType::ARCUnbridgedCast:
4226 return false;
4227
4228 // Pseudo-objects should be converted as soon as possible.
4229 case BuiltinType::PseudoObject:
4230 return true;
4231
4232 // The debugger mode could theoretically but currently does not try
4233 // to resolve unknown-typed arguments based on known parameter types.
4234 case BuiltinType::UnknownAny:
4235 return true;
4236
4237 // These are always invalid as call arguments and should be reported.
4238 case BuiltinType::BoundMember:
4239 case BuiltinType::BuiltinFn:
4240 return true;
4241 }
4242 llvm_unreachable("bad builtin type kind");
4243}
4244
4245/// Check an argument list for placeholders that we won't try to
4246/// handle later.
4247static bool checkArgsForPlaceholders(Sema &S, MultiExprArg args) {
4248 // Apply this processing to all the arguments at once instead of
4249 // dying at the first failure.
4250 bool hasInvalid = false;
4251 for (size_t i = 0, e = args.size(); i != e; i++) {
4252 if (isPlaceholderToRemoveAsArg(args[i]->getType())) {
4253 ExprResult result = S.CheckPlaceholderExpr(args[i]);
4254 if (result.isInvalid()) hasInvalid = true;
4255 else args[i] = result.take();
4256 }
4257 }
4258 return hasInvalid;
4259}
4260
Steve Naroff83895f72007-09-16 03:34:24 +00004261/// ActOnCallExpr - Handle a call to Fn with the specified array of arguments.
Chris Lattnere168f762006-11-10 05:29:30 +00004262/// This provides the location of the left/right parens and a list of comma
4263/// locations.
John McCalldadc5752010-08-24 06:29:42 +00004264ExprResult
John McCallb268a282010-08-23 23:25:46 +00004265Sema::ActOnCallExpr(Scope *S, Expr *Fn, SourceLocation LParenLoc,
Richard Trieuba63ce62011-09-09 01:45:06 +00004266 MultiExprArg ArgExprs, SourceLocation RParenLoc,
Peter Collingbourne619a8c72011-10-02 23:49:29 +00004267 Expr *ExecConfig, bool IsExecConfig) {
Nate Begeman5ec4b312009-08-10 23:49:36 +00004268 // Since this might be a postfix expression, get rid of ParenListExprs.
John McCalldadc5752010-08-24 06:29:42 +00004269 ExprResult Result = MaybeConvertParenListExprToParenExpr(S, Fn);
John McCallb268a282010-08-23 23:25:46 +00004270 if (Result.isInvalid()) return ExprError();
4271 Fn = Result.take();
Mike Stump11289f42009-09-09 15:08:12 +00004272
John McCall5e77d762013-04-16 07:28:30 +00004273 if (checkArgsForPlaceholders(*this, ArgExprs))
4274 return ExprError();
4275
David Blaikiebbafb8a2012-03-11 07:00:24 +00004276 if (getLangOpts().CPlusPlus) {
Douglas Gregorad8a3362009-09-04 17:36:40 +00004277 // If this is a pseudo-destructor expression, build the call immediately.
4278 if (isa<CXXPseudoDestructorExpr>(Fn)) {
Benjamin Kramerc215e762012-08-24 11:54:20 +00004279 if (!ArgExprs.empty()) {
Douglas Gregorad8a3362009-09-04 17:36:40 +00004280 // Pseudo-destructor calls should not have any arguments.
4281 Diag(Fn->getLocStart(), diag::err_pseudo_dtor_call_with_args)
Douglas Gregora771f462010-03-31 17:46:05 +00004282 << FixItHint::CreateRemoval(
Benjamin Kramerc215e762012-08-24 11:54:20 +00004283 SourceRange(ArgExprs[0]->getLocStart(),
4284 ArgExprs.back()->getLocEnd()));
Douglas Gregorad8a3362009-09-04 17:36:40 +00004285 }
Mike Stump11289f42009-09-09 15:08:12 +00004286
Dmitri Gribenko78852e92013-05-05 20:40:26 +00004287 return Owned(new (Context) CallExpr(Context, Fn, None,
Benjamin Kramerc215e762012-08-24 11:54:20 +00004288 Context.VoidTy, VK_RValue,
4289 RParenLoc));
Douglas Gregorad8a3362009-09-04 17:36:40 +00004290 }
John McCall5e77d762013-04-16 07:28:30 +00004291 if (Fn->getType() == Context.PseudoObjectTy) {
4292 ExprResult result = CheckPlaceholderExpr(Fn);
4293 if (result.isInvalid()) return ExprError();
4294 Fn = result.take();
4295 }
Mike Stump11289f42009-09-09 15:08:12 +00004296
Douglas Gregorb8a9a412009-02-04 15:01:18 +00004297 // Determine whether this is a dependent call inside a C++ template,
Mike Stump4e1f26a2009-02-19 03:04:26 +00004298 // in which case we won't do any semantic analysis now.
Mike Stump87c57ac2009-05-16 07:39:55 +00004299 // FIXME: Will need to cache the results of name lookup (including ADL) in
4300 // Fn.
Douglas Gregorb8a9a412009-02-04 15:01:18 +00004301 bool Dependent = false;
4302 if (Fn->isTypeDependent())
4303 Dependent = true;
Benjamin Kramerc215e762012-08-24 11:54:20 +00004304 else if (Expr::hasAnyTypeDependentArguments(ArgExprs))
Douglas Gregorb8a9a412009-02-04 15:01:18 +00004305 Dependent = true;
4306
Peter Collingbourne41f85462011-02-09 21:07:24 +00004307 if (Dependent) {
4308 if (ExecConfig) {
4309 return Owned(new (Context) CUDAKernelCallExpr(
Benjamin Kramerc215e762012-08-24 11:54:20 +00004310 Context, Fn, cast<CallExpr>(ExecConfig), ArgExprs,
Peter Collingbourne41f85462011-02-09 21:07:24 +00004311 Context.DependentTy, VK_RValue, RParenLoc));
4312 } else {
Benjamin Kramerc215e762012-08-24 11:54:20 +00004313 return Owned(new (Context) CallExpr(Context, Fn, ArgExprs,
Peter Collingbourne41f85462011-02-09 21:07:24 +00004314 Context.DependentTy, VK_RValue,
4315 RParenLoc));
4316 }
4317 }
Douglas Gregorb8a9a412009-02-04 15:01:18 +00004318
4319 // Determine whether this is a call to an object (C++ [over.call.object]).
4320 if (Fn->getType()->isRecordType())
Benjamin Kramerc215e762012-08-24 11:54:20 +00004321 return Owned(BuildCallToObjectOfClassType(S, Fn, LParenLoc,
Dmitri Gribenkod3b75562013-05-09 23:32:58 +00004322 ArgExprs, RParenLoc));
Douglas Gregorb8a9a412009-02-04 15:01:18 +00004323
John McCall2979fe02011-04-12 00:42:48 +00004324 if (Fn->getType() == Context.UnknownAnyTy) {
4325 ExprResult result = rebuildUnknownAnyFunction(*this, Fn);
4326 if (result.isInvalid()) return ExprError();
4327 Fn = result.take();
4328 }
4329
John McCall0009fcc2011-04-26 20:42:42 +00004330 if (Fn->getType() == Context.BoundMemberTy) {
Dmitri Gribenko9c785c22013-05-09 21:02:07 +00004331 return BuildCallToMemberFunction(S, Fn, LParenLoc, ArgExprs, RParenLoc);
John McCall10eae182009-11-30 22:42:35 +00004332 }
John McCall0009fcc2011-04-26 20:42:42 +00004333 }
John McCall10eae182009-11-30 22:42:35 +00004334
John McCall0009fcc2011-04-26 20:42:42 +00004335 // Check for overloaded calls. This can happen even in C due to extensions.
4336 if (Fn->getType() == Context.OverloadTy) {
4337 OverloadExpr::FindResult find = OverloadExpr::find(Fn);
4338
Douglas Gregorcda22702011-10-13 18:10:35 +00004339 // We aren't supposed to apply this logic for if there's an '&' involved.
Douglas Gregorf4a06c22011-10-13 18:26:27 +00004340 if (!find.HasFormOfMemberPointer) {
John McCall0009fcc2011-04-26 20:42:42 +00004341 OverloadExpr *ovl = find.Expression;
4342 if (isa<UnresolvedLookupExpr>(ovl)) {
4343 UnresolvedLookupExpr *ULE = cast<UnresolvedLookupExpr>(ovl);
Dmitri Gribenko9c785c22013-05-09 21:02:07 +00004344 return BuildOverloadedCallExpr(S, Fn, ULE, LParenLoc, ArgExprs,
4345 RParenLoc, ExecConfig);
John McCall0009fcc2011-04-26 20:42:42 +00004346 } else {
Dmitri Gribenko9c785c22013-05-09 21:02:07 +00004347 return BuildCallToMemberFunction(S, Fn, LParenLoc, ArgExprs,
4348 RParenLoc);
Anders Carlsson61914b52009-10-03 17:40:22 +00004349 }
4350 }
Douglas Gregor97fd6e22008-12-22 05:46:06 +00004351 }
4352
Douglas Gregore254f902009-02-04 00:32:51 +00004353 // If we're directly calling a function, get the appropriate declaration.
Douglas Gregord8fb1e32011-12-01 01:37:36 +00004354 if (Fn->getType() == Context.UnknownAnyTy) {
4355 ExprResult result = rebuildUnknownAnyFunction(*this, Fn);
4356 if (result.isInvalid()) return ExprError();
4357 Fn = result.take();
4358 }
Mike Stump4e1f26a2009-02-19 03:04:26 +00004359
Eli Friedmane14b1992009-12-26 03:35:45 +00004360 Expr *NakedFn = Fn->IgnoreParens();
Douglas Gregor928479e2010-11-09 20:03:54 +00004361
John McCall57500772009-12-16 12:17:52 +00004362 NamedDecl *NDecl = 0;
Douglas Gregor59f16ed2010-10-25 20:48:33 +00004363 if (UnaryOperator *UnOp = dyn_cast<UnaryOperator>(NakedFn))
4364 if (UnOp->getOpcode() == UO_AddrOf)
4365 NakedFn = UnOp->getSubExpr()->IgnoreParens();
4366
John McCall57500772009-12-16 12:17:52 +00004367 if (isa<DeclRefExpr>(NakedFn))
4368 NDecl = cast<DeclRefExpr>(NakedFn)->getDecl();
John McCall0009fcc2011-04-26 20:42:42 +00004369 else if (isa<MemberExpr>(NakedFn))
4370 NDecl = cast<MemberExpr>(NakedFn)->getMemberDecl();
John McCall57500772009-12-16 12:17:52 +00004371
Dmitri Gribenko9c785c22013-05-09 21:02:07 +00004372 return BuildResolvedCallExpr(Fn, NDecl, LParenLoc, ArgExprs, RParenLoc,
4373 ExecConfig, IsExecConfig);
Peter Collingbourne41f85462011-02-09 21:07:24 +00004374}
4375
4376ExprResult
4377Sema::ActOnCUDAExecConfigExpr(Scope *S, SourceLocation LLLLoc,
Richard Trieuba63ce62011-09-09 01:45:06 +00004378 MultiExprArg ExecConfig, SourceLocation GGGLoc) {
Peter Collingbourne41f85462011-02-09 21:07:24 +00004379 FunctionDecl *ConfigDecl = Context.getcudaConfigureCallDecl();
4380 if (!ConfigDecl)
4381 return ExprError(Diag(LLLLoc, diag::err_undeclared_var_use)
4382 << "cudaConfigureCall");
4383 QualType ConfigQTy = ConfigDecl->getType();
4384
4385 DeclRefExpr *ConfigDR = new (Context) DeclRefExpr(
John McCall113bee02012-03-10 09:33:50 +00004386 ConfigDecl, false, ConfigQTy, VK_LValue, LLLLoc);
Eli Friedmanfa0df832012-02-02 03:46:19 +00004387 MarkFunctionReferenced(LLLLoc, ConfigDecl);
Peter Collingbourne41f85462011-02-09 21:07:24 +00004388
Peter Collingbourne619a8c72011-10-02 23:49:29 +00004389 return ActOnCallExpr(S, ConfigDR, LLLLoc, ExecConfig, GGGLoc, 0,
4390 /*IsExecConfig=*/true);
John McCall2d74de92009-12-01 22:10:20 +00004391}
4392
Tanya Lattner55808c12011-06-04 00:47:47 +00004393/// ActOnAsTypeExpr - create a new asType (bitcast) from the arguments.
4394///
4395/// __builtin_astype( value, dst type )
4396///
Richard Trieuba63ce62011-09-09 01:45:06 +00004397ExprResult Sema::ActOnAsTypeExpr(Expr *E, ParsedType ParsedDestTy,
Tanya Lattner55808c12011-06-04 00:47:47 +00004398 SourceLocation BuiltinLoc,
4399 SourceLocation RParenLoc) {
4400 ExprValueKind VK = VK_RValue;
4401 ExprObjectKind OK = OK_Ordinary;
Richard Trieuba63ce62011-09-09 01:45:06 +00004402 QualType DstTy = GetTypeFromParser(ParsedDestTy);
4403 QualType SrcTy = E->getType();
Tanya Lattner55808c12011-06-04 00:47:47 +00004404 if (Context.getTypeSize(DstTy) != Context.getTypeSize(SrcTy))
4405 return ExprError(Diag(BuiltinLoc,
4406 diag::err_invalid_astype_of_different_size)
Peter Collingbourne23f1bee2011-06-08 15:15:17 +00004407 << DstTy
4408 << SrcTy
Richard Trieuba63ce62011-09-09 01:45:06 +00004409 << E->getSourceRange());
4410 return Owned(new (Context) AsTypeExpr(E, DstTy, VK, OK, BuiltinLoc,
Richard Trieucfc491d2011-08-02 04:35:43 +00004411 RParenLoc));
Tanya Lattner55808c12011-06-04 00:47:47 +00004412}
4413
John McCall57500772009-12-16 12:17:52 +00004414/// BuildResolvedCallExpr - Build a call to a resolved expression,
4415/// i.e. an expression not of \p OverloadTy. The expression should
John McCall2d74de92009-12-01 22:10:20 +00004416/// unary-convert to an expression of function-pointer or
4417/// block-pointer type.
4418///
4419/// \param NDecl the declaration being called, if available
John McCalldadc5752010-08-24 06:29:42 +00004420ExprResult
John McCall2d74de92009-12-01 22:10:20 +00004421Sema::BuildResolvedCallExpr(Expr *Fn, NamedDecl *NDecl,
4422 SourceLocation LParenLoc,
Dmitri Gribenko9c785c22013-05-09 21:02:07 +00004423 ArrayRef<Expr *> Args,
Peter Collingbourne41f85462011-02-09 21:07:24 +00004424 SourceLocation RParenLoc,
Peter Collingbourne619a8c72011-10-02 23:49:29 +00004425 Expr *Config, bool IsExecConfig) {
John McCall2d74de92009-12-01 22:10:20 +00004426 FunctionDecl *FDecl = dyn_cast_or_null<FunctionDecl>(NDecl);
Eli Friedman34866c72012-08-31 00:14:07 +00004427 unsigned BuiltinID = (FDecl ? FDecl->getBuiltinID() : 0);
John McCall2d74de92009-12-01 22:10:20 +00004428
Chris Lattneraa9c7ae2008-04-08 04:40:51 +00004429 // Promote the function operand.
Eli Friedman34866c72012-08-31 00:14:07 +00004430 // We special-case function promotion here because we only allow promoting
4431 // builtin functions to function pointers in the callee of a call.
4432 ExprResult Result;
4433 if (BuiltinID &&
4434 Fn->getType()->isSpecificBuiltinType(BuiltinType::BuiltinFn)) {
4435 Result = ImpCastExprToType(Fn, Context.getPointerType(FDecl->getType()),
4436 CK_BuiltinFnToFnPtr).take();
4437 } else {
4438 Result = UsualUnaryConversions(Fn);
4439 }
John Wiegley01296292011-04-08 18:41:53 +00004440 if (Result.isInvalid())
4441 return ExprError();
4442 Fn = Result.take();
Chris Lattneraa9c7ae2008-04-08 04:40:51 +00004443
Chris Lattner08464942007-12-28 05:29:59 +00004444 // Make the call expr early, before semantic checks. This guarantees cleanup
4445 // of arguments and function on error.
Peter Collingbourne41f85462011-02-09 21:07:24 +00004446 CallExpr *TheCall;
Eric Christopher13586ab2012-05-30 01:14:28 +00004447 if (Config)
Peter Collingbourne41f85462011-02-09 21:07:24 +00004448 TheCall = new (Context) CUDAKernelCallExpr(Context, Fn,
Dmitri Gribenko9c785c22013-05-09 21:02:07 +00004449 cast<CallExpr>(Config), Args,
4450 Context.BoolTy, VK_RValue,
Peter Collingbourne41f85462011-02-09 21:07:24 +00004451 RParenLoc);
Eric Christopher13586ab2012-05-30 01:14:28 +00004452 else
Dmitri Gribenko9c785c22013-05-09 21:02:07 +00004453 TheCall = new (Context) CallExpr(Context, Fn, Args, Context.BoolTy,
4454 VK_RValue, RParenLoc);
Sebastian Redlc215cfc2009-01-19 00:08:26 +00004455
John McCallbebede42011-02-26 05:39:39 +00004456 // Bail out early if calling a builtin with custom typechecking.
4457 if (BuiltinID && Context.BuiltinInfo.hasCustomTypechecking(BuiltinID))
4458 return CheckBuiltinFunctionCall(BuiltinID, TheCall);
4459
John McCall31996342011-04-07 08:22:57 +00004460 retry:
Steve Naroff8de9c3a2008-09-05 22:11:13 +00004461 const FunctionType *FuncT;
John McCallbebede42011-02-26 05:39:39 +00004462 if (const PointerType *PT = Fn->getType()->getAs<PointerType>()) {
Steve Naroff8de9c3a2008-09-05 22:11:13 +00004463 // C99 6.5.2.2p1 - "The expression that denotes the called function shall
4464 // have type pointer to function".
John McCall9dd450b2009-09-21 23:43:11 +00004465 FuncT = PT->getPointeeType()->getAs<FunctionType>();
John McCallbebede42011-02-26 05:39:39 +00004466 if (FuncT == 0)
4467 return ExprError(Diag(LParenLoc, diag::err_typecheck_call_not_function)
4468 << Fn->getType() << Fn->getSourceRange());
4469 } else if (const BlockPointerType *BPT =
4470 Fn->getType()->getAs<BlockPointerType>()) {
4471 FuncT = BPT->getPointeeType()->castAs<FunctionType>();
4472 } else {
John McCall31996342011-04-07 08:22:57 +00004473 // Handle calls to expressions of unknown-any type.
4474 if (Fn->getType() == Context.UnknownAnyTy) {
John McCall2979fe02011-04-12 00:42:48 +00004475 ExprResult rewrite = rebuildUnknownAnyFunction(*this, Fn);
John McCall31996342011-04-07 08:22:57 +00004476 if (rewrite.isInvalid()) return ExprError();
4477 Fn = rewrite.take();
John McCall39439732011-04-09 22:50:59 +00004478 TheCall->setCallee(Fn);
John McCall31996342011-04-07 08:22:57 +00004479 goto retry;
4480 }
4481
Sebastian Redlc215cfc2009-01-19 00:08:26 +00004482 return ExprError(Diag(LParenLoc, diag::err_typecheck_call_not_function)
4483 << Fn->getType() << Fn->getSourceRange());
John McCallbebede42011-02-26 05:39:39 +00004484 }
Sebastian Redlc215cfc2009-01-19 00:08:26 +00004485
David Blaikiebbafb8a2012-03-11 07:00:24 +00004486 if (getLangOpts().CUDA) {
Peter Collingbourne4b66c472011-02-23 01:53:29 +00004487 if (Config) {
4488 // CUDA: Kernel calls must be to global functions
4489 if (FDecl && !FDecl->hasAttr<CUDAGlobalAttr>())
4490 return ExprError(Diag(LParenLoc,diag::err_kern_call_not_global_function)
4491 << FDecl->getName() << Fn->getSourceRange());
4492
4493 // CUDA: Kernel function must have 'void' return type
4494 if (!FuncT->getResultType()->isVoidType())
4495 return ExprError(Diag(LParenLoc, diag::err_kern_type_not_void_return)
4496 << Fn->getType() << Fn->getSourceRange());
Peter Collingbourne34a20b02011-10-02 23:49:15 +00004497 } else {
4498 // CUDA: Calls to global functions must be configured
4499 if (FDecl && FDecl->hasAttr<CUDAGlobalAttr>())
4500 return ExprError(Diag(LParenLoc, diag::err_global_call_not_config)
4501 << FDecl->getName() << Fn->getSourceRange());
Peter Collingbourne4b66c472011-02-23 01:53:29 +00004502 }
4503 }
4504
Eli Friedman3164fb12009-03-22 22:00:50 +00004505 // Check for a valid return type
Kovarththanan Rajaratnamba2c6522010-03-13 10:17:05 +00004506 if (CheckCallReturnType(FuncT->getResultType(),
Daniel Dunbar62ee6412012-03-09 18:35:03 +00004507 Fn->getLocStart(), TheCall,
Anders Carlsson7f84ed92009-10-09 23:51:55 +00004508 FDecl))
Eli Friedman3164fb12009-03-22 22:00:50 +00004509 return ExprError();
4510
Chris Lattner08464942007-12-28 05:29:59 +00004511 // We know the result type of the call, set it.
Douglas Gregor603d81b2010-07-13 08:18:22 +00004512 TheCall->setType(FuncT->getCallResultType(Context));
John McCall7decc9e2010-11-18 06:31:45 +00004513 TheCall->setValueKind(Expr::getValueKindForType(FuncT->getResultType()));
Sebastian Redlc215cfc2009-01-19 00:08:26 +00004514
Richard Smith55ce3522012-06-25 20:30:08 +00004515 const FunctionProtoType *Proto = dyn_cast<FunctionProtoType>(FuncT);
4516 if (Proto) {
Dmitri Gribenko9c785c22013-05-09 21:02:07 +00004517 if (ConvertArgumentsForCall(TheCall, Fn, FDecl, Proto, Args, RParenLoc,
4518 IsExecConfig))
Sebastian Redlc215cfc2009-01-19 00:08:26 +00004519 return ExprError();
Chris Lattner08464942007-12-28 05:29:59 +00004520 } else {
Douglas Gregordeaad8c2009-02-26 23:50:07 +00004521 assert(isa<FunctionNoProtoType>(FuncT) && "Unknown FunctionType!");
Sebastian Redlc215cfc2009-01-19 00:08:26 +00004522
Douglas Gregord8e97de2009-04-02 15:37:10 +00004523 if (FDecl) {
4524 // Check if we have too few/too many template arguments, based
4525 // on our knowledge of the function definition.
4526 const FunctionDecl *Def = 0;
Dmitri Gribenko9c785c22013-05-09 21:02:07 +00004527 if (FDecl->hasBody(Def) && Args.size() != Def->param_size()) {
Richard Smith55ce3522012-06-25 20:30:08 +00004528 Proto = Def->getType()->getAs<FunctionProtoType>();
Dmitri Gribenko9c785c22013-05-09 21:02:07 +00004529 if (!Proto || !(Proto->isVariadic() && Args.size() >= Def->param_size()))
Eli Friedmanfcbf7d22009-06-01 09:24:59 +00004530 Diag(RParenLoc, diag::warn_call_wrong_number_of_arguments)
Dmitri Gribenko9c785c22013-05-09 21:02:07 +00004531 << (Args.size() > Def->param_size()) << FDecl << Fn->getSourceRange();
Eli Friedmanfcbf7d22009-06-01 09:24:59 +00004532 }
Douglas Gregor8e09a722010-10-25 20:39:23 +00004533
4534 // If the function we're calling isn't a function prototype, but we have
4535 // a function prototype from a prior declaratiom, use that prototype.
4536 if (!FDecl->hasPrototype())
4537 Proto = FDecl->getType()->getAs<FunctionProtoType>();
Douglas Gregord8e97de2009-04-02 15:37:10 +00004538 }
4539
Steve Naroff0b661582007-08-28 23:30:39 +00004540 // Promote the arguments (C99 6.5.2.2p6).
Dmitri Gribenko9c785c22013-05-09 21:02:07 +00004541 for (unsigned i = 0, e = Args.size(); i != e; i++) {
Chris Lattner08464942007-12-28 05:29:59 +00004542 Expr *Arg = Args[i];
Douglas Gregor8e09a722010-10-25 20:39:23 +00004543
4544 if (Proto && i < Proto->getNumArgs()) {
Douglas Gregor8e09a722010-10-25 20:39:23 +00004545 InitializedEntity Entity
4546 = InitializedEntity::InitializeParameter(Context,
John McCall31168b02011-06-15 23:02:42 +00004547 Proto->getArgType(i),
4548 Proto->isArgConsumed(i));
Douglas Gregor8e09a722010-10-25 20:39:23 +00004549 ExprResult ArgE = PerformCopyInitialization(Entity,
4550 SourceLocation(),
4551 Owned(Arg));
4552 if (ArgE.isInvalid())
4553 return true;
4554
4555 Arg = ArgE.takeAs<Expr>();
4556
4557 } else {
John Wiegley01296292011-04-08 18:41:53 +00004558 ExprResult ArgE = DefaultArgumentPromotion(Arg);
4559
4560 if (ArgE.isInvalid())
4561 return true;
4562
4563 Arg = ArgE.takeAs<Expr>();
Douglas Gregor8e09a722010-10-25 20:39:23 +00004564 }
4565
Daniel Dunbar62ee6412012-03-09 18:35:03 +00004566 if (RequireCompleteType(Arg->getLocStart(),
Douglas Gregor83025412010-10-26 05:45:40 +00004567 Arg->getType(),
Douglas Gregor7bfb2d02012-05-04 16:32:21 +00004568 diag::err_call_incomplete_argument, Arg))
Douglas Gregor83025412010-10-26 05:45:40 +00004569 return ExprError();
4570
Chris Lattner08464942007-12-28 05:29:59 +00004571 TheCall->setArg(i, Arg);
Steve Naroff0b661582007-08-28 23:30:39 +00004572 }
Steve Naroffae4143e2007-04-26 20:39:23 +00004573 }
Chris Lattner08464942007-12-28 05:29:59 +00004574
Douglas Gregor97fd6e22008-12-22 05:46:06 +00004575 if (CXXMethodDecl *Method = dyn_cast_or_null<CXXMethodDecl>(FDecl))
4576 if (!Method->isStatic())
Sebastian Redlc215cfc2009-01-19 00:08:26 +00004577 return ExprError(Diag(LParenLoc, diag::err_member_call_without_object)
4578 << Fn->getSourceRange());
Douglas Gregor97fd6e22008-12-22 05:46:06 +00004579
Fariborz Jahanian0aa5c452009-05-15 20:33:25 +00004580 // Check for sentinels
4581 if (NDecl)
Dmitri Gribenko9c785c22013-05-09 21:02:07 +00004582 DiagnoseSentinelCalls(NDecl, LParenLoc, Args);
Mike Stump11289f42009-09-09 15:08:12 +00004583
Chris Lattnerb87b1b32007-08-10 20:18:51 +00004584 // Do special checking on direct calls to functions.
Anders Carlssonbc4c1072009-08-16 01:56:34 +00004585 if (FDecl) {
Richard Smith55ce3522012-06-25 20:30:08 +00004586 if (CheckFunctionCall(FDecl, TheCall, Proto))
Anders Carlssonbc4c1072009-08-16 01:56:34 +00004587 return ExprError();
Mike Stump11289f42009-09-09 15:08:12 +00004588
John McCallbebede42011-02-26 05:39:39 +00004589 if (BuiltinID)
Fariborz Jahaniane8473c22010-11-30 17:35:24 +00004590 return CheckBuiltinFunctionCall(BuiltinID, TheCall);
Anders Carlssonbc4c1072009-08-16 01:56:34 +00004591 } else if (NDecl) {
Richard Trieu664c4c62013-06-20 21:03:13 +00004592 if (CheckPointerCall(NDecl, TheCall, Proto))
Anders Carlssonbc4c1072009-08-16 01:56:34 +00004593 return ExprError();
Richard Trieu41bc0992013-06-22 00:20:41 +00004594 } else {
4595 if (CheckOtherCall(TheCall, Proto))
4596 return ExprError();
Anders Carlssonbc4c1072009-08-16 01:56:34 +00004597 }
Chris Lattnerb87b1b32007-08-10 20:18:51 +00004598
John McCallb268a282010-08-23 23:25:46 +00004599 return MaybeBindToTemporary(TheCall);
Chris Lattnere168f762006-11-10 05:29:30 +00004600}
4601
John McCalldadc5752010-08-24 06:29:42 +00004602ExprResult
John McCallba7bf592010-08-24 05:47:05 +00004603Sema::ActOnCompoundLiteral(SourceLocation LParenLoc, ParsedType Ty,
John McCallb268a282010-08-23 23:25:46 +00004604 SourceLocation RParenLoc, Expr *InitExpr) {
David Blaikie7d170102013-05-15 07:37:26 +00004605 assert(Ty && "ActOnCompoundLiteral(): missing type");
Steve Naroff57eb2c52007-07-19 21:32:11 +00004606 // FIXME: put back this assert when initializers are worked out.
Steve Naroff83895f72007-09-16 03:34:24 +00004607 //assert((InitExpr != 0) && "ActOnCompoundLiteral(): missing expression");
John McCalle15bbff2010-01-18 19:35:47 +00004608
4609 TypeSourceInfo *TInfo;
4610 QualType literalType = GetTypeFromParser(Ty, &TInfo);
4611 if (!TInfo)
4612 TInfo = Context.getTrivialTypeSourceInfo(literalType);
4613
John McCallb268a282010-08-23 23:25:46 +00004614 return BuildCompoundLiteralExpr(LParenLoc, TInfo, RParenLoc, InitExpr);
John McCalle15bbff2010-01-18 19:35:47 +00004615}
4616
John McCalldadc5752010-08-24 06:29:42 +00004617ExprResult
John McCalle15bbff2010-01-18 19:35:47 +00004618Sema::BuildCompoundLiteralExpr(SourceLocation LParenLoc, TypeSourceInfo *TInfo,
Richard Trieuba63ce62011-09-09 01:45:06 +00004619 SourceLocation RParenLoc, Expr *LiteralExpr) {
John McCalle15bbff2010-01-18 19:35:47 +00004620 QualType literalType = TInfo->getType();
Anders Carlsson2c1ec6d2007-12-05 07:24:19 +00004621
Eli Friedman37a186d2008-05-20 05:22:08 +00004622 if (literalType->isArrayType()) {
Argyrios Kyrtzidis85663562010-11-08 19:14:19 +00004623 if (RequireCompleteType(LParenLoc, Context.getBaseElementType(literalType),
Douglas Gregor7bfb2d02012-05-04 16:32:21 +00004624 diag::err_illegal_decl_array_incomplete_type,
4625 SourceRange(LParenLoc,
4626 LiteralExpr->getSourceRange().getEnd())))
Argyrios Kyrtzidis85663562010-11-08 19:14:19 +00004627 return ExprError();
Chris Lattner7adf0762008-08-04 07:31:14 +00004628 if (literalType->isVariableArrayType())
Sebastian Redlb5d49352009-01-19 22:31:54 +00004629 return ExprError(Diag(LParenLoc, diag::err_variable_object_no_init)
Richard Trieuba63ce62011-09-09 01:45:06 +00004630 << SourceRange(LParenLoc, LiteralExpr->getSourceRange().getEnd()));
Douglas Gregor1c37d9e2009-05-21 23:48:18 +00004631 } else if (!literalType->isDependentType() &&
4632 RequireCompleteType(LParenLoc, literalType,
Douglas Gregor7bfb2d02012-05-04 16:32:21 +00004633 diag::err_typecheck_decl_incomplete_type,
4634 SourceRange(LParenLoc, LiteralExpr->getSourceRange().getEnd())))
Sebastian Redlb5d49352009-01-19 22:31:54 +00004635 return ExprError();
Eli Friedman37a186d2008-05-20 05:22:08 +00004636
Douglas Gregor85dabae2009-12-16 01:38:02 +00004637 InitializedEntity Entity
Jordan Rose6c0505e2013-05-06 16:48:12 +00004638 = InitializedEntity::InitializeCompoundLiteralInit(TInfo);
Douglas Gregor85dabae2009-12-16 01:38:02 +00004639 InitializationKind Kind
John McCall31168b02011-06-15 23:02:42 +00004640 = InitializationKind::CreateCStyleCast(LParenLoc,
Sebastian Redl0501c632012-02-12 16:37:36 +00004641 SourceRange(LParenLoc, RParenLoc),
4642 /*InitList=*/true);
Dmitri Gribenko8f8930f2013-05-03 15:05:50 +00004643 InitializationSequence InitSeq(*this, Entity, Kind, LiteralExpr);
Benjamin Kramercc4c49d2012-08-23 23:38:35 +00004644 ExprResult Result = InitSeq.Perform(*this, Entity, Kind, LiteralExpr,
4645 &literalType);
Eli Friedmana553d4a2009-12-22 02:35:53 +00004646 if (Result.isInvalid())
Sebastian Redlb5d49352009-01-19 22:31:54 +00004647 return ExprError();
Richard Trieuba63ce62011-09-09 01:45:06 +00004648 LiteralExpr = Result.get();
Steve Naroffd32419d2008-01-14 18:19:28 +00004649
Chris Lattner79413952008-12-04 23:50:19 +00004650 bool isFileScope = getCurFunctionOrMethodDecl() == 0;
Eli Friedman4c27ac22013-07-16 22:40:53 +00004651 if (!getLangOpts().CPlusPlus && isFileScope) { // 6.5.2.5p3
Richard Trieuba63ce62011-09-09 01:45:06 +00004652 if (CheckForConstantInitializer(LiteralExpr, literalType))
Sebastian Redlb5d49352009-01-19 22:31:54 +00004653 return ExprError();
Steve Naroff98f72032008-01-10 22:15:12 +00004654 }
Eli Friedmana553d4a2009-12-22 02:35:53 +00004655
John McCall7decc9e2010-11-18 06:31:45 +00004656 // In C, compound literals are l-values for some reason.
David Blaikiebbafb8a2012-03-11 07:00:24 +00004657 ExprValueKind VK = getLangOpts().CPlusPlus ? VK_RValue : VK_LValue;
John McCall7decc9e2010-11-18 06:31:45 +00004658
Douglas Gregor9b71f0c2011-06-17 04:59:12 +00004659 return MaybeBindToTemporary(
4660 new (Context) CompoundLiteralExpr(LParenLoc, TInfo, literalType,
Richard Trieuba63ce62011-09-09 01:45:06 +00004661 VK, LiteralExpr, isFileScope));
Steve Narofffbd09832007-07-19 01:06:55 +00004662}
4663
John McCalldadc5752010-08-24 06:29:42 +00004664ExprResult
Richard Trieuba63ce62011-09-09 01:45:06 +00004665Sema::ActOnInitList(SourceLocation LBraceLoc, MultiExprArg InitArgList,
Sebastian Redlb5d49352009-01-19 22:31:54 +00004666 SourceLocation RBraceLoc) {
John McCall526ab472011-10-25 17:37:35 +00004667 // Immediately handle non-overload placeholders. Overloads can be
4668 // resolved contextually, but everything else here can't.
Benjamin Kramerc215e762012-08-24 11:54:20 +00004669 for (unsigned I = 0, E = InitArgList.size(); I != E; ++I) {
4670 if (InitArgList[I]->getType()->isNonOverloadPlaceholderType()) {
4671 ExprResult result = CheckPlaceholderExpr(InitArgList[I]);
John McCall526ab472011-10-25 17:37:35 +00004672
4673 // Ignore failures; dropping the entire initializer list because
4674 // of one failure would be terrible for indexing/etc.
4675 if (result.isInvalid()) continue;
4676
Benjamin Kramerc215e762012-08-24 11:54:20 +00004677 InitArgList[I] = result.take();
John McCall526ab472011-10-25 17:37:35 +00004678 }
4679 }
4680
Steve Naroff30d242c2007-09-15 18:49:24 +00004681 // Semantic analysis for initializers is done by ActOnDeclarator() and
Mike Stump4e1f26a2009-02-19 03:04:26 +00004682 // CheckInitializer() - it requires knowledge of the object being intialized.
Sebastian Redlb5d49352009-01-19 22:31:54 +00004683
Benjamin Kramerc215e762012-08-24 11:54:20 +00004684 InitListExpr *E = new (Context) InitListExpr(Context, LBraceLoc, InitArgList,
4685 RBraceLoc);
Chris Lattner24d5bfe2008-04-02 04:24:33 +00004686 E->setType(Context.VoidTy); // FIXME: just a place holder for now.
Sebastian Redlb5d49352009-01-19 22:31:54 +00004687 return Owned(E);
Steve Narofffbd09832007-07-19 01:06:55 +00004688}
4689
John McCallcd78e802011-09-10 01:16:55 +00004690/// Do an explicit extend of the given block pointer if we're in ARC.
4691static void maybeExtendBlockObject(Sema &S, ExprResult &E) {
4692 assert(E.get()->getType()->isBlockPointerType());
4693 assert(E.get()->isRValue());
4694
4695 // Only do this in an r-value context.
David Blaikiebbafb8a2012-03-11 07:00:24 +00004696 if (!S.getLangOpts().ObjCAutoRefCount) return;
John McCallcd78e802011-09-10 01:16:55 +00004697
4698 E = ImplicitCastExpr::Create(S.Context, E.get()->getType(),
John McCall2d637d22011-09-10 06:18:15 +00004699 CK_ARCExtendBlockObject, E.get(),
John McCallcd78e802011-09-10 01:16:55 +00004700 /*base path*/ 0, VK_RValue);
4701 S.ExprNeedsCleanups = true;
4702}
4703
4704/// Prepare a conversion of the given expression to an ObjC object
4705/// pointer type.
4706CastKind Sema::PrepareCastToObjCObjectPointer(ExprResult &E) {
4707 QualType type = E.get()->getType();
4708 if (type->isObjCObjectPointerType()) {
4709 return CK_BitCast;
4710 } else if (type->isBlockPointerType()) {
4711 maybeExtendBlockObject(*this, E);
4712 return CK_BlockPointerToObjCPointerCast;
4713 } else {
4714 assert(type->isPointerType());
4715 return CK_CPointerToObjCPointerCast;
4716 }
4717}
4718
John McCalld7646252010-11-14 08:17:51 +00004719/// Prepares for a scalar cast, performing all the necessary stages
4720/// except the final cast and returning the kind required.
John McCall9776e432011-10-06 23:25:11 +00004721CastKind Sema::PrepareScalarCast(ExprResult &Src, QualType DestTy) {
John McCalld7646252010-11-14 08:17:51 +00004722 // Both Src and Dest are scalar types, i.e. arithmetic or pointer.
4723 // Also, callers should have filtered out the invalid cases with
4724 // pointers. Everything else should be possible.
4725
John Wiegley01296292011-04-08 18:41:53 +00004726 QualType SrcTy = Src.get()->getType();
John McCall9776e432011-10-06 23:25:11 +00004727 if (Context.hasSameUnqualifiedType(SrcTy, DestTy))
John McCalle3027922010-08-25 11:45:40 +00004728 return CK_NoOp;
Anders Carlsson094c4592009-10-18 18:12:03 +00004729
John McCall9320b872011-09-09 05:25:32 +00004730 switch (Type::ScalarTypeKind SrcKind = SrcTy->getScalarTypeKind()) {
John McCall8cb679e2010-11-15 09:13:47 +00004731 case Type::STK_MemberPointer:
4732 llvm_unreachable("member pointer type in C");
Abramo Bagnaraba854972011-01-04 09:50:03 +00004733
John McCall9320b872011-09-09 05:25:32 +00004734 case Type::STK_CPointer:
4735 case Type::STK_BlockPointer:
4736 case Type::STK_ObjCObjectPointer:
John McCall8cb679e2010-11-15 09:13:47 +00004737 switch (DestTy->getScalarTypeKind()) {
John McCall9320b872011-09-09 05:25:32 +00004738 case Type::STK_CPointer:
4739 return CK_BitCast;
4740 case Type::STK_BlockPointer:
4741 return (SrcKind == Type::STK_BlockPointer
4742 ? CK_BitCast : CK_AnyPointerToBlockPointerCast);
4743 case Type::STK_ObjCObjectPointer:
4744 if (SrcKind == Type::STK_ObjCObjectPointer)
4745 return CK_BitCast;
David Blaikie8a40f702012-01-17 06:56:22 +00004746 if (SrcKind == Type::STK_CPointer)
John McCall9320b872011-09-09 05:25:32 +00004747 return CK_CPointerToObjCPointerCast;
David Blaikie8a40f702012-01-17 06:56:22 +00004748 maybeExtendBlockObject(*this, Src);
4749 return CK_BlockPointerToObjCPointerCast;
John McCall8cb679e2010-11-15 09:13:47 +00004750 case Type::STK_Bool:
4751 return CK_PointerToBoolean;
4752 case Type::STK_Integral:
4753 return CK_PointerToIntegral;
4754 case Type::STK_Floating:
4755 case Type::STK_FloatingComplex:
4756 case Type::STK_IntegralComplex:
4757 case Type::STK_MemberPointer:
4758 llvm_unreachable("illegal cast from pointer");
4759 }
David Blaikie8a40f702012-01-17 06:56:22 +00004760 llvm_unreachable("Should have returned before this");
Kovarththanan Rajaratnamba2c6522010-03-13 10:17:05 +00004761
John McCall8cb679e2010-11-15 09:13:47 +00004762 case Type::STK_Bool: // casting from bool is like casting from an integer
4763 case Type::STK_Integral:
4764 switch (DestTy->getScalarTypeKind()) {
John McCall9320b872011-09-09 05:25:32 +00004765 case Type::STK_CPointer:
4766 case Type::STK_ObjCObjectPointer:
4767 case Type::STK_BlockPointer:
John McCall9776e432011-10-06 23:25:11 +00004768 if (Src.get()->isNullPointerConstant(Context,
Richard Trieucfc491d2011-08-02 04:35:43 +00004769 Expr::NPC_ValueDependentIsNull))
John McCalle84af4e2010-11-13 01:35:44 +00004770 return CK_NullToPointer;
John McCalle3027922010-08-25 11:45:40 +00004771 return CK_IntegralToPointer;
John McCall8cb679e2010-11-15 09:13:47 +00004772 case Type::STK_Bool:
4773 return CK_IntegralToBoolean;
4774 case Type::STK_Integral:
John McCalld7646252010-11-14 08:17:51 +00004775 return CK_IntegralCast;
John McCall8cb679e2010-11-15 09:13:47 +00004776 case Type::STK_Floating:
John McCalle3027922010-08-25 11:45:40 +00004777 return CK_IntegralToFloating;
John McCall8cb679e2010-11-15 09:13:47 +00004778 case Type::STK_IntegralComplex:
John McCall9776e432011-10-06 23:25:11 +00004779 Src = ImpCastExprToType(Src.take(),
4780 DestTy->castAs<ComplexType>()->getElementType(),
4781 CK_IntegralCast);
John McCalld7646252010-11-14 08:17:51 +00004782 return CK_IntegralRealToComplex;
John McCall8cb679e2010-11-15 09:13:47 +00004783 case Type::STK_FloatingComplex:
John McCall9776e432011-10-06 23:25:11 +00004784 Src = ImpCastExprToType(Src.take(),
4785 DestTy->castAs<ComplexType>()->getElementType(),
4786 CK_IntegralToFloating);
John McCalld7646252010-11-14 08:17:51 +00004787 return CK_FloatingRealToComplex;
John McCall8cb679e2010-11-15 09:13:47 +00004788 case Type::STK_MemberPointer:
4789 llvm_unreachable("member pointer type in C");
John McCalld7646252010-11-14 08:17:51 +00004790 }
David Blaikie8a40f702012-01-17 06:56:22 +00004791 llvm_unreachable("Should have returned before this");
Kovarththanan Rajaratnamba2c6522010-03-13 10:17:05 +00004792
John McCall8cb679e2010-11-15 09:13:47 +00004793 case Type::STK_Floating:
4794 switch (DestTy->getScalarTypeKind()) {
4795 case Type::STK_Floating:
John McCalle3027922010-08-25 11:45:40 +00004796 return CK_FloatingCast;
John McCall8cb679e2010-11-15 09:13:47 +00004797 case Type::STK_Bool:
4798 return CK_FloatingToBoolean;
4799 case Type::STK_Integral:
John McCalle3027922010-08-25 11:45:40 +00004800 return CK_FloatingToIntegral;
John McCall8cb679e2010-11-15 09:13:47 +00004801 case Type::STK_FloatingComplex:
John McCall9776e432011-10-06 23:25:11 +00004802 Src = ImpCastExprToType(Src.take(),
4803 DestTy->castAs<ComplexType>()->getElementType(),
4804 CK_FloatingCast);
John McCalld7646252010-11-14 08:17:51 +00004805 return CK_FloatingRealToComplex;
John McCall8cb679e2010-11-15 09:13:47 +00004806 case Type::STK_IntegralComplex:
John McCall9776e432011-10-06 23:25:11 +00004807 Src = ImpCastExprToType(Src.take(),
4808 DestTy->castAs<ComplexType>()->getElementType(),
4809 CK_FloatingToIntegral);
John McCalld7646252010-11-14 08:17:51 +00004810 return CK_IntegralRealToComplex;
John McCall9320b872011-09-09 05:25:32 +00004811 case Type::STK_CPointer:
4812 case Type::STK_ObjCObjectPointer:
4813 case Type::STK_BlockPointer:
John McCall8cb679e2010-11-15 09:13:47 +00004814 llvm_unreachable("valid float->pointer cast?");
4815 case Type::STK_MemberPointer:
4816 llvm_unreachable("member pointer type in C");
John McCalld7646252010-11-14 08:17:51 +00004817 }
David Blaikie8a40f702012-01-17 06:56:22 +00004818 llvm_unreachable("Should have returned before this");
John McCalld7646252010-11-14 08:17:51 +00004819
John McCall8cb679e2010-11-15 09:13:47 +00004820 case Type::STK_FloatingComplex:
4821 switch (DestTy->getScalarTypeKind()) {
4822 case Type::STK_FloatingComplex:
John McCalld7646252010-11-14 08:17:51 +00004823 return CK_FloatingComplexCast;
John McCall8cb679e2010-11-15 09:13:47 +00004824 case Type::STK_IntegralComplex:
John McCalld7646252010-11-14 08:17:51 +00004825 return CK_FloatingComplexToIntegralComplex;
John McCallfcef3cf2010-12-14 17:51:41 +00004826 case Type::STK_Floating: {
John McCall9776e432011-10-06 23:25:11 +00004827 QualType ET = SrcTy->castAs<ComplexType>()->getElementType();
4828 if (Context.hasSameType(ET, DestTy))
John McCallfcef3cf2010-12-14 17:51:41 +00004829 return CK_FloatingComplexToReal;
John McCall9776e432011-10-06 23:25:11 +00004830 Src = ImpCastExprToType(Src.take(), ET, CK_FloatingComplexToReal);
John McCallfcef3cf2010-12-14 17:51:41 +00004831 return CK_FloatingCast;
4832 }
John McCall8cb679e2010-11-15 09:13:47 +00004833 case Type::STK_Bool:
John McCalld7646252010-11-14 08:17:51 +00004834 return CK_FloatingComplexToBoolean;
John McCall8cb679e2010-11-15 09:13:47 +00004835 case Type::STK_Integral:
John McCall9776e432011-10-06 23:25:11 +00004836 Src = ImpCastExprToType(Src.take(),
4837 SrcTy->castAs<ComplexType>()->getElementType(),
4838 CK_FloatingComplexToReal);
John McCalld7646252010-11-14 08:17:51 +00004839 return CK_FloatingToIntegral;
John McCall9320b872011-09-09 05:25:32 +00004840 case Type::STK_CPointer:
4841 case Type::STK_ObjCObjectPointer:
4842 case Type::STK_BlockPointer:
John McCall8cb679e2010-11-15 09:13:47 +00004843 llvm_unreachable("valid complex float->pointer cast?");
4844 case Type::STK_MemberPointer:
4845 llvm_unreachable("member pointer type in C");
John McCalld7646252010-11-14 08:17:51 +00004846 }
David Blaikie8a40f702012-01-17 06:56:22 +00004847 llvm_unreachable("Should have returned before this");
John McCalld7646252010-11-14 08:17:51 +00004848
John McCall8cb679e2010-11-15 09:13:47 +00004849 case Type::STK_IntegralComplex:
4850 switch (DestTy->getScalarTypeKind()) {
4851 case Type::STK_FloatingComplex:
John McCalld7646252010-11-14 08:17:51 +00004852 return CK_IntegralComplexToFloatingComplex;
John McCall8cb679e2010-11-15 09:13:47 +00004853 case Type::STK_IntegralComplex:
John McCalld7646252010-11-14 08:17:51 +00004854 return CK_IntegralComplexCast;
John McCallfcef3cf2010-12-14 17:51:41 +00004855 case Type::STK_Integral: {
John McCall9776e432011-10-06 23:25:11 +00004856 QualType ET = SrcTy->castAs<ComplexType>()->getElementType();
4857 if (Context.hasSameType(ET, DestTy))
John McCallfcef3cf2010-12-14 17:51:41 +00004858 return CK_IntegralComplexToReal;
John McCall9776e432011-10-06 23:25:11 +00004859 Src = ImpCastExprToType(Src.take(), ET, CK_IntegralComplexToReal);
John McCallfcef3cf2010-12-14 17:51:41 +00004860 return CK_IntegralCast;
4861 }
John McCall8cb679e2010-11-15 09:13:47 +00004862 case Type::STK_Bool:
John McCalld7646252010-11-14 08:17:51 +00004863 return CK_IntegralComplexToBoolean;
John McCall8cb679e2010-11-15 09:13:47 +00004864 case Type::STK_Floating:
John McCall9776e432011-10-06 23:25:11 +00004865 Src = ImpCastExprToType(Src.take(),
4866 SrcTy->castAs<ComplexType>()->getElementType(),
4867 CK_IntegralComplexToReal);
John McCalld7646252010-11-14 08:17:51 +00004868 return CK_IntegralToFloating;
John McCall9320b872011-09-09 05:25:32 +00004869 case Type::STK_CPointer:
4870 case Type::STK_ObjCObjectPointer:
4871 case Type::STK_BlockPointer:
John McCall8cb679e2010-11-15 09:13:47 +00004872 llvm_unreachable("valid complex int->pointer cast?");
4873 case Type::STK_MemberPointer:
4874 llvm_unreachable("member pointer type in C");
John McCalld7646252010-11-14 08:17:51 +00004875 }
David Blaikie8a40f702012-01-17 06:56:22 +00004876 llvm_unreachable("Should have returned before this");
Anders Carlsson094c4592009-10-18 18:12:03 +00004877 }
Kovarththanan Rajaratnamba2c6522010-03-13 10:17:05 +00004878
John McCalld7646252010-11-14 08:17:51 +00004879 llvm_unreachable("Unhandled scalar cast");
Anders Carlsson094c4592009-10-18 18:12:03 +00004880}
4881
Anders Carlsson525b76b2009-10-16 02:48:28 +00004882bool Sema::CheckVectorCast(SourceRange R, QualType VectorTy, QualType Ty,
John McCalle3027922010-08-25 11:45:40 +00004883 CastKind &Kind) {
Anders Carlssonde71adf2007-11-27 05:51:55 +00004884 assert(VectorTy->isVectorType() && "Not a vector type!");
Mike Stump4e1f26a2009-02-19 03:04:26 +00004885
Anders Carlssonde71adf2007-11-27 05:51:55 +00004886 if (Ty->isVectorType() || Ty->isIntegerType()) {
Chris Lattner37e05872008-03-05 18:54:05 +00004887 if (Context.getTypeSize(VectorTy) != Context.getTypeSize(Ty))
Anders Carlssonde71adf2007-11-27 05:51:55 +00004888 return Diag(R.getBegin(),
Mike Stump4e1f26a2009-02-19 03:04:26 +00004889 Ty->isVectorType() ?
Anders Carlssonde71adf2007-11-27 05:51:55 +00004890 diag::err_invalid_conversion_between_vectors :
Chris Lattner3b054132008-11-19 05:08:23 +00004891 diag::err_invalid_conversion_between_vector_and_integer)
Chris Lattner1e5665e2008-11-24 06:25:27 +00004892 << VectorTy << Ty << R;
Anders Carlssonde71adf2007-11-27 05:51:55 +00004893 } else
4894 return Diag(R.getBegin(),
Chris Lattner3b054132008-11-19 05:08:23 +00004895 diag::err_invalid_conversion_between_vector_and_scalar)
Chris Lattner1e5665e2008-11-24 06:25:27 +00004896 << VectorTy << Ty << R;
Mike Stump4e1f26a2009-02-19 03:04:26 +00004897
John McCalle3027922010-08-25 11:45:40 +00004898 Kind = CK_BitCast;
Anders Carlssonde71adf2007-11-27 05:51:55 +00004899 return false;
4900}
4901
John Wiegley01296292011-04-08 18:41:53 +00004902ExprResult Sema::CheckExtVectorCast(SourceRange R, QualType DestTy,
4903 Expr *CastExpr, CastKind &Kind) {
Nate Begemanc69b7402009-06-26 00:50:28 +00004904 assert(DestTy->isExtVectorType() && "Not an extended vector type!");
Kovarththanan Rajaratnamba2c6522010-03-13 10:17:05 +00004905
Anders Carlsson43d70f82009-10-16 05:23:41 +00004906 QualType SrcTy = CastExpr->getType();
Kovarththanan Rajaratnamba2c6522010-03-13 10:17:05 +00004907
Nate Begemanc8961a42009-06-27 22:05:55 +00004908 // If SrcTy is a VectorType, the total size must match to explicitly cast to
4909 // an ExtVectorType.
Tobias Grosser766bcc22011-09-22 13:03:14 +00004910 // In OpenCL, casts between vectors of different types are not allowed.
4911 // (See OpenCL 6.2).
Nate Begemanc69b7402009-06-26 00:50:28 +00004912 if (SrcTy->isVectorType()) {
Tobias Grosser766bcc22011-09-22 13:03:14 +00004913 if (Context.getTypeSize(DestTy) != Context.getTypeSize(SrcTy)
David Blaikiebbafb8a2012-03-11 07:00:24 +00004914 || (getLangOpts().OpenCL &&
Tobias Grosser766bcc22011-09-22 13:03:14 +00004915 (DestTy.getCanonicalType() != SrcTy.getCanonicalType()))) {
John Wiegley01296292011-04-08 18:41:53 +00004916 Diag(R.getBegin(),diag::err_invalid_conversion_between_ext_vectors)
Nate Begemanc69b7402009-06-26 00:50:28 +00004917 << DestTy << SrcTy << R;
John Wiegley01296292011-04-08 18:41:53 +00004918 return ExprError();
4919 }
John McCalle3027922010-08-25 11:45:40 +00004920 Kind = CK_BitCast;
John Wiegley01296292011-04-08 18:41:53 +00004921 return Owned(CastExpr);
Nate Begemanc69b7402009-06-26 00:50:28 +00004922 }
4923
Nate Begemanbd956c42009-06-28 02:36:38 +00004924 // All non-pointer scalars can be cast to ExtVector type. The appropriate
Nate Begemanc69b7402009-06-26 00:50:28 +00004925 // conversion will take place first from scalar to elt type, and then
4926 // splat from elt type to vector.
Nate Begemanbd956c42009-06-28 02:36:38 +00004927 if (SrcTy->isPointerType())
4928 return Diag(R.getBegin(),
4929 diag::err_invalid_conversion_between_vector_and_scalar)
4930 << DestTy << SrcTy << R;
Eli Friedman06ed2a52009-10-20 08:27:19 +00004931
4932 QualType DestElemTy = DestTy->getAs<ExtVectorType>()->getElementType();
John Wiegley01296292011-04-08 18:41:53 +00004933 ExprResult CastExprRes = Owned(CastExpr);
John McCall9776e432011-10-06 23:25:11 +00004934 CastKind CK = PrepareScalarCast(CastExprRes, DestElemTy);
John Wiegley01296292011-04-08 18:41:53 +00004935 if (CastExprRes.isInvalid())
4936 return ExprError();
4937 CastExpr = ImpCastExprToType(CastExprRes.take(), DestElemTy, CK).take();
Kovarththanan Rajaratnamba2c6522010-03-13 10:17:05 +00004938
John McCalle3027922010-08-25 11:45:40 +00004939 Kind = CK_VectorSplat;
John Wiegley01296292011-04-08 18:41:53 +00004940 return Owned(CastExpr);
Nate Begemanc69b7402009-06-26 00:50:28 +00004941}
4942
John McCalldadc5752010-08-24 06:29:42 +00004943ExprResult
Argyrios Kyrtzidis7192a3b2011-07-01 22:22:59 +00004944Sema::ActOnCastExpr(Scope *S, SourceLocation LParenLoc,
4945 Declarator &D, ParsedType &Ty,
Richard Trieuba63ce62011-09-09 01:45:06 +00004946 SourceLocation RParenLoc, Expr *CastExpr) {
4947 assert(!D.isInvalidType() && (CastExpr != 0) &&
Sebastian Redlb5d49352009-01-19 22:31:54 +00004948 "ActOnCastExpr(): missing type or expr");
Steve Naroff1a2cf6b2007-07-16 23:25:18 +00004949
Richard Trieuba63ce62011-09-09 01:45:06 +00004950 TypeSourceInfo *castTInfo = GetTypeForDeclaratorCast(D, CastExpr->getType());
Argyrios Kyrtzidis7192a3b2011-07-01 22:22:59 +00004951 if (D.isInvalidType())
4952 return ExprError();
4953
David Blaikiebbafb8a2012-03-11 07:00:24 +00004954 if (getLangOpts().CPlusPlus) {
Argyrios Kyrtzidis7192a3b2011-07-01 22:22:59 +00004955 // Check that there are no default arguments (C++ only).
4956 CheckExtraCXXDefaultArguments(D);
4957 }
4958
John McCall42856de2011-10-01 05:17:03 +00004959 checkUnusedDeclAttributes(D);
4960
Argyrios Kyrtzidis7192a3b2011-07-01 22:22:59 +00004961 QualType castType = castTInfo->getType();
4962 Ty = CreateParsedType(castType, castTInfo);
Mike Stump11289f42009-09-09 15:08:12 +00004963
Argyrios Kyrtzidisd8701b62011-07-01 22:22:54 +00004964 bool isVectorLiteral = false;
4965
4966 // Check for an altivec or OpenCL literal,
4967 // i.e. all the elements are integer constants.
Richard Trieuba63ce62011-09-09 01:45:06 +00004968 ParenExpr *PE = dyn_cast<ParenExpr>(CastExpr);
4969 ParenListExpr *PLE = dyn_cast<ParenListExpr>(CastExpr);
David Blaikiebbafb8a2012-03-11 07:00:24 +00004970 if ((getLangOpts().AltiVec || getLangOpts().OpenCL)
Tobias Grosser0a3a22f2011-09-21 18:28:29 +00004971 && castType->isVectorType() && (PE || PLE)) {
Argyrios Kyrtzidisd8701b62011-07-01 22:22:54 +00004972 if (PLE && PLE->getNumExprs() == 0) {
4973 Diag(PLE->getExprLoc(), diag::err_altivec_empty_initializer);
4974 return ExprError();
4975 }
4976 if (PE || PLE->getNumExprs() == 1) {
4977 Expr *E = (PE ? PE->getSubExpr() : PLE->getExpr(0));
4978 if (!E->getType()->isVectorType())
4979 isVectorLiteral = true;
4980 }
4981 else
4982 isVectorLiteral = true;
4983 }
4984
4985 // If this is a vector initializer, '(' type ')' '(' init, ..., init ')'
4986 // then handle it as such.
4987 if (isVectorLiteral)
Richard Trieuba63ce62011-09-09 01:45:06 +00004988 return BuildVectorLiteral(LParenLoc, RParenLoc, CastExpr, castTInfo);
Argyrios Kyrtzidisd8701b62011-07-01 22:22:54 +00004989
Nate Begeman5ec4b312009-08-10 23:49:36 +00004990 // If the Expr being casted is a ParenListExpr, handle it specially.
Argyrios Kyrtzidisd8701b62011-07-01 22:22:54 +00004991 // This is not an AltiVec-style cast, so turn the ParenListExpr into a
4992 // sequence of BinOp comma operators.
Richard Trieuba63ce62011-09-09 01:45:06 +00004993 if (isa<ParenListExpr>(CastExpr)) {
4994 ExprResult Result = MaybeConvertParenListExprToParenExpr(S, CastExpr);
Argyrios Kyrtzidisd8701b62011-07-01 22:22:54 +00004995 if (Result.isInvalid()) return ExprError();
Richard Trieuba63ce62011-09-09 01:45:06 +00004996 CastExpr = Result.take();
Argyrios Kyrtzidisd8701b62011-07-01 22:22:54 +00004997 }
John McCallebe54742010-01-15 18:56:44 +00004998
Richard Trieuba63ce62011-09-09 01:45:06 +00004999 return BuildCStyleCastExpr(LParenLoc, castTInfo, RParenLoc, CastExpr);
John McCallebe54742010-01-15 18:56:44 +00005000}
5001
Argyrios Kyrtzidisd8701b62011-07-01 22:22:54 +00005002ExprResult Sema::BuildVectorLiteral(SourceLocation LParenLoc,
5003 SourceLocation RParenLoc, Expr *E,
5004 TypeSourceInfo *TInfo) {
5005 assert((isa<ParenListExpr>(E) || isa<ParenExpr>(E)) &&
5006 "Expected paren or paren list expression");
5007
5008 Expr **exprs;
5009 unsigned numExprs;
5010 Expr *subExpr;
Richard Smith9ca91012013-02-05 05:55:57 +00005011 SourceLocation LiteralLParenLoc, LiteralRParenLoc;
Argyrios Kyrtzidisd8701b62011-07-01 22:22:54 +00005012 if (ParenListExpr *PE = dyn_cast<ParenListExpr>(E)) {
Richard Smith9ca91012013-02-05 05:55:57 +00005013 LiteralLParenLoc = PE->getLParenLoc();
5014 LiteralRParenLoc = PE->getRParenLoc();
Argyrios Kyrtzidisd8701b62011-07-01 22:22:54 +00005015 exprs = PE->getExprs();
5016 numExprs = PE->getNumExprs();
Richard Smith9ca91012013-02-05 05:55:57 +00005017 } else { // isa<ParenExpr> by assertion at function entrance
5018 LiteralLParenLoc = cast<ParenExpr>(E)->getLParen();
5019 LiteralRParenLoc = cast<ParenExpr>(E)->getRParen();
Argyrios Kyrtzidisd8701b62011-07-01 22:22:54 +00005020 subExpr = cast<ParenExpr>(E)->getSubExpr();
5021 exprs = &subExpr;
5022 numExprs = 1;
5023 }
5024
5025 QualType Ty = TInfo->getType();
5026 assert(Ty->isVectorType() && "Expected vector type");
5027
Chris Lattner0e62c1c2011-07-23 10:55:15 +00005028 SmallVector<Expr *, 8> initExprs;
Tanya Lattner83559382011-07-15 23:07:01 +00005029 const VectorType *VTy = Ty->getAs<VectorType>();
5030 unsigned numElems = Ty->getAs<VectorType>()->getNumElements();
5031
Argyrios Kyrtzidisd8701b62011-07-01 22:22:54 +00005032 // '(...)' form of vector initialization in AltiVec: the number of
5033 // initializers must be one or must match the size of the vector.
5034 // If a single value is specified in the initializer then it will be
5035 // replicated to all the components of the vector
Tanya Lattner83559382011-07-15 23:07:01 +00005036 if (VTy->getVectorKind() == VectorType::AltiVecVector) {
Argyrios Kyrtzidisd8701b62011-07-01 22:22:54 +00005037 // The number of initializers must be one or must match the size of the
5038 // vector. If a single value is specified in the initializer then it will
5039 // be replicated to all the components of the vector
5040 if (numExprs == 1) {
5041 QualType ElemTy = Ty->getAs<VectorType>()->getElementType();
Richard Smith01ebacd2011-10-27 23:31:58 +00005042 ExprResult Literal = DefaultLvalueConversion(exprs[0]);
5043 if (Literal.isInvalid())
5044 return ExprError();
Argyrios Kyrtzidisd8701b62011-07-01 22:22:54 +00005045 Literal = ImpCastExprToType(Literal.take(), ElemTy,
John McCall9776e432011-10-06 23:25:11 +00005046 PrepareScalarCast(Literal, ElemTy));
Argyrios Kyrtzidisd8701b62011-07-01 22:22:54 +00005047 return BuildCStyleCastExpr(LParenLoc, TInfo, RParenLoc, Literal.take());
5048 }
5049 else if (numExprs < numElems) {
5050 Diag(E->getExprLoc(),
5051 diag::err_incorrect_number_of_vector_initializers);
5052 return ExprError();
5053 }
5054 else
Benjamin Kramer8001f742012-02-14 12:06:21 +00005055 initExprs.append(exprs, exprs + numExprs);
Argyrios Kyrtzidisd8701b62011-07-01 22:22:54 +00005056 }
Tanya Lattner83559382011-07-15 23:07:01 +00005057 else {
5058 // For OpenCL, when the number of initializers is a single value,
5059 // it will be replicated to all components of the vector.
David Blaikiebbafb8a2012-03-11 07:00:24 +00005060 if (getLangOpts().OpenCL &&
Tanya Lattner83559382011-07-15 23:07:01 +00005061 VTy->getVectorKind() == VectorType::GenericVector &&
5062 numExprs == 1) {
5063 QualType ElemTy = Ty->getAs<VectorType>()->getElementType();
Richard Smith01ebacd2011-10-27 23:31:58 +00005064 ExprResult Literal = DefaultLvalueConversion(exprs[0]);
5065 if (Literal.isInvalid())
5066 return ExprError();
Tanya Lattner83559382011-07-15 23:07:01 +00005067 Literal = ImpCastExprToType(Literal.take(), ElemTy,
John McCall9776e432011-10-06 23:25:11 +00005068 PrepareScalarCast(Literal, ElemTy));
Tanya Lattner83559382011-07-15 23:07:01 +00005069 return BuildCStyleCastExpr(LParenLoc, TInfo, RParenLoc, Literal.take());
5070 }
5071
Benjamin Kramer8001f742012-02-14 12:06:21 +00005072 initExprs.append(exprs, exprs + numExprs);
Tanya Lattner83559382011-07-15 23:07:01 +00005073 }
Argyrios Kyrtzidisd8701b62011-07-01 22:22:54 +00005074 // FIXME: This means that pretty-printing the final AST will produce curly
5075 // braces instead of the original commas.
Richard Smith9ca91012013-02-05 05:55:57 +00005076 InitListExpr *initE = new (Context) InitListExpr(Context, LiteralLParenLoc,
5077 initExprs, LiteralRParenLoc);
Argyrios Kyrtzidisd8701b62011-07-01 22:22:54 +00005078 initE->setType(Ty);
5079 return BuildCompoundLiteralExpr(LParenLoc, TInfo, RParenLoc, initE);
5080}
5081
Sebastian Redla9351792012-02-11 23:51:47 +00005082/// This is not an AltiVec-style cast or or C++ direct-initialization, so turn
5083/// the ParenListExpr into a sequence of comma binary operators.
John McCalldadc5752010-08-24 06:29:42 +00005084ExprResult
Richard Trieuba63ce62011-09-09 01:45:06 +00005085Sema::MaybeConvertParenListExprToParenExpr(Scope *S, Expr *OrigExpr) {
5086 ParenListExpr *E = dyn_cast<ParenListExpr>(OrigExpr);
Nate Begeman5ec4b312009-08-10 23:49:36 +00005087 if (!E)
Richard Trieuba63ce62011-09-09 01:45:06 +00005088 return Owned(OrigExpr);
Mike Stump11289f42009-09-09 15:08:12 +00005089
John McCalldadc5752010-08-24 06:29:42 +00005090 ExprResult Result(E->getExpr(0));
Mike Stump11289f42009-09-09 15:08:12 +00005091
Nate Begeman5ec4b312009-08-10 23:49:36 +00005092 for (unsigned i = 1, e = E->getNumExprs(); i != e && !Result.isInvalid(); ++i)
John McCallb268a282010-08-23 23:25:46 +00005093 Result = ActOnBinOp(S, E->getExprLoc(), tok::comma, Result.get(),
5094 E->getExpr(i));
Mike Stump11289f42009-09-09 15:08:12 +00005095
John McCallb268a282010-08-23 23:25:46 +00005096 if (Result.isInvalid()) return ExprError();
5097
5098 return ActOnParenExpr(E->getLParenLoc(), E->getRParenLoc(), Result.get());
Nate Begeman5ec4b312009-08-10 23:49:36 +00005099}
5100
Sebastian Redla9351792012-02-11 23:51:47 +00005101ExprResult Sema::ActOnParenListExpr(SourceLocation L,
5102 SourceLocation R,
5103 MultiExprArg Val) {
Benjamin Kramerc215e762012-08-24 11:54:20 +00005104 Expr *expr = new (Context) ParenListExpr(Context, L, Val, R);
Nate Begeman5ec4b312009-08-10 23:49:36 +00005105 return Owned(expr);
5106}
5107
Chandler Carrutha8bea4b2011-02-18 23:54:50 +00005108/// \brief Emit a specialized diagnostic when one expression is a null pointer
Richard Trieu27ae4cb2011-09-02 01:51:02 +00005109/// constant and the other is not a pointer. Returns true if a diagnostic is
5110/// emitted.
Richard Trieud33e46e2011-09-06 20:06:39 +00005111bool Sema::DiagnoseConditionalForNull(Expr *LHSExpr, Expr *RHSExpr,
Chandler Carrutha8bea4b2011-02-18 23:54:50 +00005112 SourceLocation QuestionLoc) {
Richard Trieud33e46e2011-09-06 20:06:39 +00005113 Expr *NullExpr = LHSExpr;
5114 Expr *NonPointerExpr = RHSExpr;
Chandler Carrutha8bea4b2011-02-18 23:54:50 +00005115 Expr::NullPointerConstantKind NullKind =
5116 NullExpr->isNullPointerConstant(Context,
5117 Expr::NPC_ValueDependentIsNotNull);
5118
5119 if (NullKind == Expr::NPCK_NotNull) {
Richard Trieud33e46e2011-09-06 20:06:39 +00005120 NullExpr = RHSExpr;
5121 NonPointerExpr = LHSExpr;
Chandler Carrutha8bea4b2011-02-18 23:54:50 +00005122 NullKind =
5123 NullExpr->isNullPointerConstant(Context,
5124 Expr::NPC_ValueDependentIsNotNull);
5125 }
5126
5127 if (NullKind == Expr::NPCK_NotNull)
5128 return false;
5129
David Blaikie1c7c8f72012-08-08 17:33:31 +00005130 if (NullKind == Expr::NPCK_ZeroExpression)
5131 return false;
5132
5133 if (NullKind == Expr::NPCK_ZeroLiteral) {
Chandler Carrutha8bea4b2011-02-18 23:54:50 +00005134 // In this case, check to make sure that we got here from a "NULL"
5135 // string in the source code.
5136 NullExpr = NullExpr->IgnoreParenImpCasts();
John McCall462c0552011-03-08 07:59:04 +00005137 SourceLocation loc = NullExpr->getExprLoc();
5138 if (!findMacroSpelling(loc, "NULL"))
Chandler Carrutha8bea4b2011-02-18 23:54:50 +00005139 return false;
5140 }
5141
Richard Smith89645bc2013-01-02 12:01:23 +00005142 int DiagType = (NullKind == Expr::NPCK_CXX11_nullptr);
Chandler Carrutha8bea4b2011-02-18 23:54:50 +00005143 Diag(QuestionLoc, diag::err_typecheck_cond_incompatible_operands_null)
5144 << NonPointerExpr->getType() << DiagType
5145 << NonPointerExpr->getSourceRange();
5146 return true;
5147}
5148
Richard Trieu27ae4cb2011-09-02 01:51:02 +00005149/// \brief Return false if the condition expression is valid, true otherwise.
5150static bool checkCondition(Sema &S, Expr *Cond) {
5151 QualType CondTy = Cond->getType();
5152
5153 // C99 6.5.15p2
5154 if (CondTy->isScalarType()) return false;
5155
Tanya Lattnerdaa74b92013-04-03 23:55:58 +00005156 // OpenCL v1.1 s6.3.i says the condition is allowed to be a vector or scalar.
David Blaikiebbafb8a2012-03-11 07:00:24 +00005157 if (S.getLangOpts().OpenCL && CondTy->isVectorType())
Richard Trieu27ae4cb2011-09-02 01:51:02 +00005158 return false;
5159
5160 // Emit the proper error message.
David Blaikiebbafb8a2012-03-11 07:00:24 +00005161 S.Diag(Cond->getLocStart(), S.getLangOpts().OpenCL ?
Richard Trieu27ae4cb2011-09-02 01:51:02 +00005162 diag::err_typecheck_cond_expect_scalar :
5163 diag::err_typecheck_cond_expect_scalar_or_vector)
5164 << CondTy;
5165 return true;
5166}
5167
5168/// \brief Return false if the two expressions can be converted to a vector,
5169/// true otherwise
5170static bool checkConditionalConvertScalarsToVectors(Sema &S, ExprResult &LHS,
5171 ExprResult &RHS,
5172 QualType CondTy) {
5173 // Both operands should be of scalar type.
5174 if (!LHS.get()->getType()->isScalarType()) {
5175 S.Diag(LHS.get()->getLocStart(), diag::err_typecheck_cond_expect_scalar)
5176 << CondTy;
5177 return true;
5178 }
5179 if (!RHS.get()->getType()->isScalarType()) {
5180 S.Diag(RHS.get()->getLocStart(), diag::err_typecheck_cond_expect_scalar)
5181 << CondTy;
5182 return true;
5183 }
5184
5185 // Implicity convert these scalars to the type of the condition.
5186 LHS = S.ImpCastExprToType(LHS.take(), CondTy, CK_IntegralCast);
5187 RHS = S.ImpCastExprToType(RHS.take(), CondTy, CK_IntegralCast);
5188 return false;
5189}
5190
5191/// \brief Handle when one or both operands are void type.
5192static QualType checkConditionalVoidType(Sema &S, ExprResult &LHS,
5193 ExprResult &RHS) {
5194 Expr *LHSExpr = LHS.get();
5195 Expr *RHSExpr = RHS.get();
5196
5197 if (!LHSExpr->getType()->isVoidType())
5198 S.Diag(RHSExpr->getLocStart(), diag::ext_typecheck_cond_one_void)
5199 << RHSExpr->getSourceRange();
5200 if (!RHSExpr->getType()->isVoidType())
5201 S.Diag(LHSExpr->getLocStart(), diag::ext_typecheck_cond_one_void)
5202 << LHSExpr->getSourceRange();
5203 LHS = S.ImpCastExprToType(LHS.take(), S.Context.VoidTy, CK_ToVoid);
5204 RHS = S.ImpCastExprToType(RHS.take(), S.Context.VoidTy, CK_ToVoid);
5205 return S.Context.VoidTy;
5206}
5207
5208/// \brief Return false if the NullExpr can be promoted to PointerTy,
5209/// true otherwise.
5210static bool checkConditionalNullPointer(Sema &S, ExprResult &NullExpr,
5211 QualType PointerTy) {
5212 if ((!PointerTy->isAnyPointerType() && !PointerTy->isBlockPointerType()) ||
5213 !NullExpr.get()->isNullPointerConstant(S.Context,
5214 Expr::NPC_ValueDependentIsNull))
5215 return true;
5216
5217 NullExpr = S.ImpCastExprToType(NullExpr.take(), PointerTy, CK_NullToPointer);
5218 return false;
5219}
5220
5221/// \brief Checks compatibility between two pointers and return the resulting
5222/// type.
5223static QualType checkConditionalPointerCompatibility(Sema &S, ExprResult &LHS,
5224 ExprResult &RHS,
5225 SourceLocation Loc) {
5226 QualType LHSTy = LHS.get()->getType();
5227 QualType RHSTy = RHS.get()->getType();
5228
5229 if (S.Context.hasSameType(LHSTy, RHSTy)) {
5230 // Two identical pointers types are always compatible.
5231 return LHSTy;
5232 }
5233
5234 QualType lhptee, rhptee;
5235
5236 // Get the pointee types.
Fariborz Jahanian1edacec2013-06-07 16:07:38 +00005237 bool IsBlockPointer = false;
John McCall9320b872011-09-09 05:25:32 +00005238 if (const BlockPointerType *LHSBTy = LHSTy->getAs<BlockPointerType>()) {
5239 lhptee = LHSBTy->getPointeeType();
5240 rhptee = RHSTy->castAs<BlockPointerType>()->getPointeeType();
Fariborz Jahanian1edacec2013-06-07 16:07:38 +00005241 IsBlockPointer = true;
Richard Trieu27ae4cb2011-09-02 01:51:02 +00005242 } else {
John McCall9320b872011-09-09 05:25:32 +00005243 lhptee = LHSTy->castAs<PointerType>()->getPointeeType();
5244 rhptee = RHSTy->castAs<PointerType>()->getPointeeType();
Richard Trieu27ae4cb2011-09-02 01:51:02 +00005245 }
5246
Eli Friedman57a75392012-04-05 22:30:04 +00005247 // C99 6.5.15p6: If both operands are pointers to compatible types or to
5248 // differently qualified versions of compatible types, the result type is
5249 // a pointer to an appropriately qualified version of the composite
5250 // type.
5251
5252 // Only CVR-qualifiers exist in the standard, and the differently-qualified
5253 // clause doesn't make sense for our extensions. E.g. address space 2 should
5254 // be incompatible with address space 3: they may live on different devices or
5255 // anything.
5256 Qualifiers lhQual = lhptee.getQualifiers();
5257 Qualifiers rhQual = rhptee.getQualifiers();
5258
5259 unsigned MergedCVRQual = lhQual.getCVRQualifiers() | rhQual.getCVRQualifiers();
5260 lhQual.removeCVRQualifiers();
5261 rhQual.removeCVRQualifiers();
5262
5263 lhptee = S.Context.getQualifiedType(lhptee.getUnqualifiedType(), lhQual);
5264 rhptee = S.Context.getQualifiedType(rhptee.getUnqualifiedType(), rhQual);
5265
5266 QualType CompositeTy = S.Context.mergeTypes(lhptee, rhptee);
5267
5268 if (CompositeTy.isNull()) {
Richard Trieu27ae4cb2011-09-02 01:51:02 +00005269 S.Diag(Loc, diag::warn_typecheck_cond_incompatible_pointers)
5270 << LHSTy << RHSTy << LHS.get()->getSourceRange()
5271 << RHS.get()->getSourceRange();
5272 // In this situation, we assume void* type. No especially good
5273 // reason, but this is what gcc does, and we do have to pick
5274 // to get a consistent AST.
5275 QualType incompatTy = S.Context.getPointerType(S.Context.VoidTy);
5276 LHS = S.ImpCastExprToType(LHS.take(), incompatTy, CK_BitCast);
5277 RHS = S.ImpCastExprToType(RHS.take(), incompatTy, CK_BitCast);
5278 return incompatTy;
5279 }
5280
5281 // The pointer types are compatible.
Eli Friedman57a75392012-04-05 22:30:04 +00005282 QualType ResultTy = CompositeTy.withCVRQualifiers(MergedCVRQual);
Fariborz Jahanian1edacec2013-06-07 16:07:38 +00005283 if (IsBlockPointer)
Fariborz Jahanian44d23b82013-06-07 00:48:14 +00005284 ResultTy = S.Context.getBlockPointerType(ResultTy);
5285 else
5286 ResultTy = S.Context.getPointerType(ResultTy);
Richard Trieu27ae4cb2011-09-02 01:51:02 +00005287
Eli Friedman57a75392012-04-05 22:30:04 +00005288 LHS = S.ImpCastExprToType(LHS.take(), ResultTy, CK_BitCast);
5289 RHS = S.ImpCastExprToType(RHS.take(), ResultTy, CK_BitCast);
5290 return ResultTy;
Richard Trieu27ae4cb2011-09-02 01:51:02 +00005291}
5292
5293/// \brief Return the resulting type when the operands are both block pointers.
5294static QualType checkConditionalBlockPointerCompatibility(Sema &S,
5295 ExprResult &LHS,
5296 ExprResult &RHS,
5297 SourceLocation Loc) {
5298 QualType LHSTy = LHS.get()->getType();
5299 QualType RHSTy = RHS.get()->getType();
5300
5301 if (!LHSTy->isBlockPointerType() || !RHSTy->isBlockPointerType()) {
5302 if (LHSTy->isVoidPointerType() || RHSTy->isVoidPointerType()) {
5303 QualType destType = S.Context.getPointerType(S.Context.VoidTy);
5304 LHS = S.ImpCastExprToType(LHS.take(), destType, CK_BitCast);
5305 RHS = S.ImpCastExprToType(RHS.take(), destType, CK_BitCast);
5306 return destType;
5307 }
5308 S.Diag(Loc, diag::err_typecheck_cond_incompatible_operands)
5309 << LHSTy << RHSTy << LHS.get()->getSourceRange()
5310 << RHS.get()->getSourceRange();
5311 return QualType();
5312 }
5313
5314 // We have 2 block pointer types.
5315 return checkConditionalPointerCompatibility(S, LHS, RHS, Loc);
5316}
5317
5318/// \brief Return the resulting type when the operands are both pointers.
5319static QualType
5320checkConditionalObjectPointersCompatibility(Sema &S, ExprResult &LHS,
5321 ExprResult &RHS,
5322 SourceLocation Loc) {
5323 // get the pointer types
5324 QualType LHSTy = LHS.get()->getType();
5325 QualType RHSTy = RHS.get()->getType();
5326
5327 // get the "pointed to" types
5328 QualType lhptee = LHSTy->getAs<PointerType>()->getPointeeType();
5329 QualType rhptee = RHSTy->getAs<PointerType>()->getPointeeType();
5330
5331 // ignore qualifiers on void (C99 6.5.15p3, clause 6)
5332 if (lhptee->isVoidType() && rhptee->isIncompleteOrObjectType()) {
5333 // Figure out necessary qualifiers (C99 6.5.15p6)
5334 QualType destPointee
5335 = S.Context.getQualifiedType(lhptee, rhptee.getQualifiers());
5336 QualType destType = S.Context.getPointerType(destPointee);
5337 // Add qualifiers if necessary.
5338 LHS = S.ImpCastExprToType(LHS.take(), destType, CK_NoOp);
5339 // Promote to void*.
5340 RHS = S.ImpCastExprToType(RHS.take(), destType, CK_BitCast);
5341 return destType;
5342 }
5343 if (rhptee->isVoidType() && lhptee->isIncompleteOrObjectType()) {
5344 QualType destPointee
5345 = S.Context.getQualifiedType(rhptee, lhptee.getQualifiers());
5346 QualType destType = S.Context.getPointerType(destPointee);
5347 // Add qualifiers if necessary.
5348 RHS = S.ImpCastExprToType(RHS.take(), destType, CK_NoOp);
5349 // Promote to void*.
5350 LHS = S.ImpCastExprToType(LHS.take(), destType, CK_BitCast);
5351 return destType;
5352 }
5353
5354 return checkConditionalPointerCompatibility(S, LHS, RHS, Loc);
5355}
5356
5357/// \brief Return false if the first expression is not an integer and the second
5358/// expression is not a pointer, true otherwise.
5359static bool checkPointerIntegerMismatch(Sema &S, ExprResult &Int,
5360 Expr* PointerExpr, SourceLocation Loc,
Richard Trieuba63ce62011-09-09 01:45:06 +00005361 bool IsIntFirstExpr) {
Richard Trieu27ae4cb2011-09-02 01:51:02 +00005362 if (!PointerExpr->getType()->isPointerType() ||
5363 !Int.get()->getType()->isIntegerType())
5364 return false;
5365
Richard Trieuba63ce62011-09-09 01:45:06 +00005366 Expr *Expr1 = IsIntFirstExpr ? Int.get() : PointerExpr;
5367 Expr *Expr2 = IsIntFirstExpr ? PointerExpr : Int.get();
Richard Trieu27ae4cb2011-09-02 01:51:02 +00005368
5369 S.Diag(Loc, diag::warn_typecheck_cond_pointer_integer_mismatch)
5370 << Expr1->getType() << Expr2->getType()
5371 << Expr1->getSourceRange() << Expr2->getSourceRange();
5372 Int = S.ImpCastExprToType(Int.take(), PointerExpr->getType(),
5373 CK_IntegralToPointer);
5374 return true;
5375}
5376
Richard Trieud33e46e2011-09-06 20:06:39 +00005377/// Note that LHS is not null here, even if this is the gnu "x ?: y" extension.
5378/// In that case, LHS = cond.
Chris Lattner2c486602009-02-18 04:38:20 +00005379/// C99 6.5.15
Richard Trieucfc491d2011-08-02 04:35:43 +00005380QualType Sema::CheckConditionalOperands(ExprResult &Cond, ExprResult &LHS,
5381 ExprResult &RHS, ExprValueKind &VK,
5382 ExprObjectKind &OK,
Chris Lattner2c486602009-02-18 04:38:20 +00005383 SourceLocation QuestionLoc) {
Douglas Gregor1beec452011-03-12 01:48:56 +00005384
Richard Trieud33e46e2011-09-06 20:06:39 +00005385 ExprResult LHSResult = CheckPlaceholderExpr(LHS.get());
5386 if (!LHSResult.isUsable()) return QualType();
Benjamin Kramer62b95d82012-08-23 21:35:17 +00005387 LHS = LHSResult;
Douglas Gregor0124e9b2010-11-09 21:07:58 +00005388
Richard Trieud33e46e2011-09-06 20:06:39 +00005389 ExprResult RHSResult = CheckPlaceholderExpr(RHS.get());
5390 if (!RHSResult.isUsable()) return QualType();
Benjamin Kramer62b95d82012-08-23 21:35:17 +00005391 RHS = RHSResult;
Douglas Gregor0124e9b2010-11-09 21:07:58 +00005392
Sebastian Redl1a99f442009-04-16 17:51:27 +00005393 // C++ is sufficiently different to merit its own checker.
David Blaikiebbafb8a2012-03-11 07:00:24 +00005394 if (getLangOpts().CPlusPlus)
John McCallc07a0c72011-02-17 10:25:35 +00005395 return CXXCheckConditionalOperands(Cond, LHS, RHS, VK, OK, QuestionLoc);
John McCall7decc9e2010-11-18 06:31:45 +00005396
5397 VK = VK_RValue;
John McCall4bc41ae2010-11-18 19:01:18 +00005398 OK = OK_Ordinary;
Sebastian Redl1a99f442009-04-16 17:51:27 +00005399
John Wiegley01296292011-04-08 18:41:53 +00005400 Cond = UsualUnaryConversions(Cond.take());
5401 if (Cond.isInvalid())
5402 return QualType();
Eli Friedmane6d33952013-07-08 20:20:06 +00005403 UsualArithmeticConversions(LHS, RHS);
5404 if (LHS.isInvalid() || RHS.isInvalid())
John Wiegley01296292011-04-08 18:41:53 +00005405 return QualType();
5406
5407 QualType CondTy = Cond.get()->getType();
5408 QualType LHSTy = LHS.get()->getType();
5409 QualType RHSTy = RHS.get()->getType();
Steve Naroff31090012007-07-16 21:54:35 +00005410
Steve Naroffa78fe7e2007-05-16 19:47:19 +00005411 // first, check the condition.
Richard Trieu27ae4cb2011-09-02 01:51:02 +00005412 if (checkCondition(*this, Cond.get()))
5413 return QualType();
Mike Stump4e1f26a2009-02-19 03:04:26 +00005414
Chris Lattnere2949f42008-01-06 22:42:25 +00005415 // Now check the two expressions.
Nate Begeman5ec4b312009-08-10 23:49:36 +00005416 if (LHSTy->isVectorType() || RHSTy->isVectorType())
Eli Friedman1408bc92011-06-23 18:10:35 +00005417 return CheckVectorOperands(LHS, RHS, QuestionLoc, /*isCompAssign*/false);
Douglas Gregor4619e432008-12-05 23:32:09 +00005418
Tanya Lattnerdaa74b92013-04-03 23:55:58 +00005419 // If the condition is a vector, and both operands are scalar,
Nate Begemanabb5a732010-09-20 22:41:17 +00005420 // attempt to implicity convert them to the vector type to act like the
Tanya Lattnerdaa74b92013-04-03 23:55:58 +00005421 // built in select. (OpenCL v1.1 s6.3.i)
David Blaikiebbafb8a2012-03-11 07:00:24 +00005422 if (getLangOpts().OpenCL && CondTy->isVectorType())
Richard Trieu27ae4cb2011-09-02 01:51:02 +00005423 if (checkConditionalConvertScalarsToVectors(*this, LHS, RHS, CondTy))
Nate Begemanabb5a732010-09-20 22:41:17 +00005424 return QualType();
Nate Begemanabb5a732010-09-20 22:41:17 +00005425
Chris Lattnere2949f42008-01-06 22:42:25 +00005426 // If both operands have arithmetic type, do the usual arithmetic conversions
5427 // to find a common type: C99 6.5.15p3,5.
Eli Friedmane6d33952013-07-08 20:20:06 +00005428 if (LHSTy->isArithmeticType() && RHSTy->isArithmeticType())
John Wiegley01296292011-04-08 18:41:53 +00005429 return LHS.get()->getType();
Mike Stump4e1f26a2009-02-19 03:04:26 +00005430
Chris Lattnere2949f42008-01-06 22:42:25 +00005431 // If both operands are the same structure or union type, the result is that
5432 // type.
Ted Kremenekc23c7e62009-07-29 21:53:49 +00005433 if (const RecordType *LHSRT = LHSTy->getAs<RecordType>()) { // C99 6.5.15p3
5434 if (const RecordType *RHSRT = RHSTy->getAs<RecordType>())
Chris Lattner2ab40a62007-11-26 01:40:58 +00005435 if (LHSRT->getDecl() == RHSRT->getDecl())
Mike Stump4e1f26a2009-02-19 03:04:26 +00005436 // "If both the operands have structure or union type, the result has
Chris Lattnere2949f42008-01-06 22:42:25 +00005437 // that type." This implies that CV qualifiers are dropped.
Chris Lattner432cff52009-02-18 04:28:32 +00005438 return LHSTy.getUnqualifiedType();
Eli Friedmanba961a92009-03-23 00:24:07 +00005439 // FIXME: Type of conditional expression must be complete in C mode.
Steve Naroffa78fe7e2007-05-16 19:47:19 +00005440 }
Mike Stump4e1f26a2009-02-19 03:04:26 +00005441
Chris Lattnere2949f42008-01-06 22:42:25 +00005442 // C99 6.5.15p5: "If both operands have void type, the result has void type."
Steve Naroffbf1516c2008-05-12 21:44:38 +00005443 // The following || allows only one side to be void (a GCC-ism).
Chris Lattner432cff52009-02-18 04:28:32 +00005444 if (LHSTy->isVoidType() || RHSTy->isVoidType()) {
Richard Trieu27ae4cb2011-09-02 01:51:02 +00005445 return checkConditionalVoidType(*this, LHS, RHS);
Steve Naroffbf1516c2008-05-12 21:44:38 +00005446 }
Richard Trieu27ae4cb2011-09-02 01:51:02 +00005447
Steve Naroff039ad3c2008-01-08 01:11:38 +00005448 // C99 6.5.15p6 - "if one operand is a null pointer constant, the result has
5449 // the type of the other operand."
Richard Trieu27ae4cb2011-09-02 01:51:02 +00005450 if (!checkConditionalNullPointer(*this, RHS, LHSTy)) return LHSTy;
5451 if (!checkConditionalNullPointer(*this, LHS, RHSTy)) return RHSTy;
Kovarththanan Rajaratnamba2c6522010-03-13 10:17:05 +00005452
Fariborz Jahaniana430f712009-12-10 19:47:41 +00005453 // All objective-c pointer type analysis is done here.
5454 QualType compositeType = FindCompositeObjCPointerType(LHS, RHS,
5455 QuestionLoc);
John Wiegley01296292011-04-08 18:41:53 +00005456 if (LHS.isInvalid() || RHS.isInvalid())
5457 return QualType();
Fariborz Jahaniana430f712009-12-10 19:47:41 +00005458 if (!compositeType.isNull())
5459 return compositeType;
Kovarththanan Rajaratnamba2c6522010-03-13 10:17:05 +00005460
5461
Steve Naroff05efa972009-07-01 14:36:47 +00005462 // Handle block pointer types.
Richard Trieu27ae4cb2011-09-02 01:51:02 +00005463 if (LHSTy->isBlockPointerType() || RHSTy->isBlockPointerType())
5464 return checkConditionalBlockPointerCompatibility(*this, LHS, RHS,
5465 QuestionLoc);
Kovarththanan Rajaratnamba2c6522010-03-13 10:17:05 +00005466
Steve Naroff05efa972009-07-01 14:36:47 +00005467 // Check constraints for C object pointers types (C99 6.5.15p3,6).
Richard Trieu27ae4cb2011-09-02 01:51:02 +00005468 if (LHSTy->isPointerType() && RHSTy->isPointerType())
5469 return checkConditionalObjectPointersCompatibility(*this, LHS, RHS,
5470 QuestionLoc);
Mike Stump11289f42009-09-09 15:08:12 +00005471
John McCalle84af4e2010-11-13 01:35:44 +00005472 // GCC compatibility: soften pointer/integer mismatch. Note that
5473 // null pointers have been filtered out by this point.
Richard Trieu27ae4cb2011-09-02 01:51:02 +00005474 if (checkPointerIntegerMismatch(*this, LHS, RHS.get(), QuestionLoc,
5475 /*isIntFirstExpr=*/true))
Steve Naroff05efa972009-07-01 14:36:47 +00005476 return RHSTy;
Richard Trieu27ae4cb2011-09-02 01:51:02 +00005477 if (checkPointerIntegerMismatch(*this, RHS, LHS.get(), QuestionLoc,
5478 /*isIntFirstExpr=*/false))
Steve Naroff05efa972009-07-01 14:36:47 +00005479 return LHSTy;
Daniel Dunbar484603b2008-09-11 23:12:46 +00005480
Chandler Carrutha8bea4b2011-02-18 23:54:50 +00005481 // Emit a better diagnostic if one of the expressions is a null pointer
5482 // constant and the other is not a pointer type. In this case, the user most
5483 // likely forgot to take the address of the other expression.
John Wiegley01296292011-04-08 18:41:53 +00005484 if (DiagnoseConditionalForNull(LHS.get(), RHS.get(), QuestionLoc))
Chandler Carrutha8bea4b2011-02-18 23:54:50 +00005485 return QualType();
5486
Chris Lattnere2949f42008-01-06 22:42:25 +00005487 // Otherwise, the operands are not compatible.
Chris Lattner432cff52009-02-18 04:28:32 +00005488 Diag(QuestionLoc, diag::err_typecheck_cond_incompatible_operands)
Richard Trieucfc491d2011-08-02 04:35:43 +00005489 << LHSTy << RHSTy << LHS.get()->getSourceRange()
5490 << RHS.get()->getSourceRange();
Steve Naroffa78fe7e2007-05-16 19:47:19 +00005491 return QualType();
Steve Narofff8a28c52007-05-15 20:29:32 +00005492}
5493
Fariborz Jahaniana430f712009-12-10 19:47:41 +00005494/// FindCompositeObjCPointerType - Helper method to find composite type of
5495/// two objective-c pointer types of the two input expressions.
John Wiegley01296292011-04-08 18:41:53 +00005496QualType Sema::FindCompositeObjCPointerType(ExprResult &LHS, ExprResult &RHS,
Richard Trieucfc491d2011-08-02 04:35:43 +00005497 SourceLocation QuestionLoc) {
John Wiegley01296292011-04-08 18:41:53 +00005498 QualType LHSTy = LHS.get()->getType();
5499 QualType RHSTy = RHS.get()->getType();
Kovarththanan Rajaratnamba2c6522010-03-13 10:17:05 +00005500
Fariborz Jahaniana430f712009-12-10 19:47:41 +00005501 // Handle things like Class and struct objc_class*. Here we case the result
5502 // to the pseudo-builtin, because that will be implicitly cast back to the
5503 // redefinition type if an attempt is made to access its fields.
5504 if (LHSTy->isObjCClassType() &&
Douglas Gregor97673472011-08-11 20:58:55 +00005505 (Context.hasSameType(RHSTy, Context.getObjCClassRedefinitionType()))) {
John McCall9320b872011-09-09 05:25:32 +00005506 RHS = ImpCastExprToType(RHS.take(), LHSTy, CK_CPointerToObjCPointerCast);
Fariborz Jahaniana430f712009-12-10 19:47:41 +00005507 return LHSTy;
5508 }
5509 if (RHSTy->isObjCClassType() &&
Douglas Gregor97673472011-08-11 20:58:55 +00005510 (Context.hasSameType(LHSTy, Context.getObjCClassRedefinitionType()))) {
John McCall9320b872011-09-09 05:25:32 +00005511 LHS = ImpCastExprToType(LHS.take(), RHSTy, CK_CPointerToObjCPointerCast);
Fariborz Jahaniana430f712009-12-10 19:47:41 +00005512 return RHSTy;
5513 }
5514 // And the same for struct objc_object* / id
5515 if (LHSTy->isObjCIdType() &&
Douglas Gregor97673472011-08-11 20:58:55 +00005516 (Context.hasSameType(RHSTy, Context.getObjCIdRedefinitionType()))) {
John McCall9320b872011-09-09 05:25:32 +00005517 RHS = ImpCastExprToType(RHS.take(), LHSTy, CK_CPointerToObjCPointerCast);
Fariborz Jahaniana430f712009-12-10 19:47:41 +00005518 return LHSTy;
5519 }
5520 if (RHSTy->isObjCIdType() &&
Douglas Gregor97673472011-08-11 20:58:55 +00005521 (Context.hasSameType(LHSTy, Context.getObjCIdRedefinitionType()))) {
John McCall9320b872011-09-09 05:25:32 +00005522 LHS = ImpCastExprToType(LHS.take(), RHSTy, CK_CPointerToObjCPointerCast);
Fariborz Jahaniana430f712009-12-10 19:47:41 +00005523 return RHSTy;
5524 }
5525 // And the same for struct objc_selector* / SEL
5526 if (Context.isObjCSelType(LHSTy) &&
Douglas Gregor97673472011-08-11 20:58:55 +00005527 (Context.hasSameType(RHSTy, Context.getObjCSelRedefinitionType()))) {
John Wiegley01296292011-04-08 18:41:53 +00005528 RHS = ImpCastExprToType(RHS.take(), LHSTy, CK_BitCast);
Fariborz Jahaniana430f712009-12-10 19:47:41 +00005529 return LHSTy;
5530 }
5531 if (Context.isObjCSelType(RHSTy) &&
Douglas Gregor97673472011-08-11 20:58:55 +00005532 (Context.hasSameType(LHSTy, Context.getObjCSelRedefinitionType()))) {
John Wiegley01296292011-04-08 18:41:53 +00005533 LHS = ImpCastExprToType(LHS.take(), RHSTy, CK_BitCast);
Fariborz Jahaniana430f712009-12-10 19:47:41 +00005534 return RHSTy;
5535 }
5536 // Check constraints for Objective-C object pointers types.
5537 if (LHSTy->isObjCObjectPointerType() && RHSTy->isObjCObjectPointerType()) {
Kovarththanan Rajaratnamba2c6522010-03-13 10:17:05 +00005538
Fariborz Jahaniana430f712009-12-10 19:47:41 +00005539 if (Context.getCanonicalType(LHSTy) == Context.getCanonicalType(RHSTy)) {
5540 // Two identical object pointer types are always compatible.
5541 return LHSTy;
5542 }
John McCall9320b872011-09-09 05:25:32 +00005543 const ObjCObjectPointerType *LHSOPT = LHSTy->castAs<ObjCObjectPointerType>();
5544 const ObjCObjectPointerType *RHSOPT = RHSTy->castAs<ObjCObjectPointerType>();
Fariborz Jahaniana430f712009-12-10 19:47:41 +00005545 QualType compositeType = LHSTy;
Kovarththanan Rajaratnamba2c6522010-03-13 10:17:05 +00005546
Fariborz Jahaniana430f712009-12-10 19:47:41 +00005547 // If both operands are interfaces and either operand can be
5548 // assigned to the other, use that type as the composite
5549 // type. This allows
5550 // xxx ? (A*) a : (B*) b
5551 // where B is a subclass of A.
5552 //
5553 // Additionally, as for assignment, if either type is 'id'
5554 // allow silent coercion. Finally, if the types are
5555 // incompatible then make sure to use 'id' as the composite
5556 // type so the result is acceptable for sending messages to.
Kovarththanan Rajaratnamba2c6522010-03-13 10:17:05 +00005557
Fariborz Jahaniana430f712009-12-10 19:47:41 +00005558 // FIXME: Consider unifying with 'areComparableObjCPointerTypes'.
5559 // It could return the composite type.
5560 if (Context.canAssignObjCInterfaces(LHSOPT, RHSOPT)) {
5561 compositeType = RHSOPT->isObjCBuiltinType() ? RHSTy : LHSTy;
5562 } else if (Context.canAssignObjCInterfaces(RHSOPT, LHSOPT)) {
5563 compositeType = LHSOPT->isObjCBuiltinType() ? LHSTy : RHSTy;
5564 } else if ((LHSTy->isObjCQualifiedIdType() ||
5565 RHSTy->isObjCQualifiedIdType()) &&
5566 Context.ObjCQualifiedIdTypesAreCompatible(LHSTy, RHSTy, true)) {
5567 // Need to handle "id<xx>" explicitly.
5568 // GCC allows qualified id and any Objective-C type to devolve to
5569 // id. Currently localizing to here until clear this should be
5570 // part of ObjCQualifiedIdTypesAreCompatible.
5571 compositeType = Context.getObjCIdType();
5572 } else if (LHSTy->isObjCIdType() || RHSTy->isObjCIdType()) {
5573 compositeType = Context.getObjCIdType();
Kovarththanan Rajaratnamba2c6522010-03-13 10:17:05 +00005574 } else if (!(compositeType =
Fariborz Jahaniana430f712009-12-10 19:47:41 +00005575 Context.areCommonBaseCompatible(LHSOPT, RHSOPT)).isNull())
5576 ;
5577 else {
5578 Diag(QuestionLoc, diag::ext_typecheck_cond_incompatible_operands)
5579 << LHSTy << RHSTy
John Wiegley01296292011-04-08 18:41:53 +00005580 << LHS.get()->getSourceRange() << RHS.get()->getSourceRange();
Fariborz Jahaniana430f712009-12-10 19:47:41 +00005581 QualType incompatTy = Context.getObjCIdType();
John Wiegley01296292011-04-08 18:41:53 +00005582 LHS = ImpCastExprToType(LHS.take(), incompatTy, CK_BitCast);
5583 RHS = ImpCastExprToType(RHS.take(), incompatTy, CK_BitCast);
Fariborz Jahaniana430f712009-12-10 19:47:41 +00005584 return incompatTy;
5585 }
5586 // The object pointer types are compatible.
John Wiegley01296292011-04-08 18:41:53 +00005587 LHS = ImpCastExprToType(LHS.take(), compositeType, CK_BitCast);
5588 RHS = ImpCastExprToType(RHS.take(), compositeType, CK_BitCast);
Fariborz Jahaniana430f712009-12-10 19:47:41 +00005589 return compositeType;
5590 }
5591 // Check Objective-C object pointer types and 'void *'
5592 if (LHSTy->isVoidPointerType() && RHSTy->isObjCObjectPointerType()) {
David Blaikiebbafb8a2012-03-11 07:00:24 +00005593 if (getLangOpts().ObjCAutoRefCount) {
Eli Friedman8a78a582012-02-25 00:23:44 +00005594 // ARC forbids the implicit conversion of object pointers to 'void *',
5595 // so these types are not compatible.
5596 Diag(QuestionLoc, diag::err_cond_voidptr_arc) << LHSTy << RHSTy
5597 << LHS.get()->getSourceRange() << RHS.get()->getSourceRange();
5598 LHS = RHS = true;
5599 return QualType();
5600 }
Fariborz Jahaniana430f712009-12-10 19:47:41 +00005601 QualType lhptee = LHSTy->getAs<PointerType>()->getPointeeType();
5602 QualType rhptee = RHSTy->getAs<ObjCObjectPointerType>()->getPointeeType();
5603 QualType destPointee
5604 = Context.getQualifiedType(lhptee, rhptee.getQualifiers());
5605 QualType destType = Context.getPointerType(destPointee);
5606 // Add qualifiers if necessary.
John Wiegley01296292011-04-08 18:41:53 +00005607 LHS = ImpCastExprToType(LHS.take(), destType, CK_NoOp);
Fariborz Jahaniana430f712009-12-10 19:47:41 +00005608 // Promote to void*.
John Wiegley01296292011-04-08 18:41:53 +00005609 RHS = ImpCastExprToType(RHS.take(), destType, CK_BitCast);
Fariborz Jahaniana430f712009-12-10 19:47:41 +00005610 return destType;
5611 }
5612 if (LHSTy->isObjCObjectPointerType() && RHSTy->isVoidPointerType()) {
David Blaikiebbafb8a2012-03-11 07:00:24 +00005613 if (getLangOpts().ObjCAutoRefCount) {
Eli Friedman8a78a582012-02-25 00:23:44 +00005614 // ARC forbids the implicit conversion of object pointers to 'void *',
5615 // so these types are not compatible.
5616 Diag(QuestionLoc, diag::err_cond_voidptr_arc) << LHSTy << RHSTy
5617 << LHS.get()->getSourceRange() << RHS.get()->getSourceRange();
5618 LHS = RHS = true;
5619 return QualType();
5620 }
Fariborz Jahaniana430f712009-12-10 19:47:41 +00005621 QualType lhptee = LHSTy->getAs<ObjCObjectPointerType>()->getPointeeType();
5622 QualType rhptee = RHSTy->getAs<PointerType>()->getPointeeType();
5623 QualType destPointee
5624 = Context.getQualifiedType(rhptee, lhptee.getQualifiers());
5625 QualType destType = Context.getPointerType(destPointee);
5626 // Add qualifiers if necessary.
John Wiegley01296292011-04-08 18:41:53 +00005627 RHS = ImpCastExprToType(RHS.take(), destType, CK_NoOp);
Fariborz Jahaniana430f712009-12-10 19:47:41 +00005628 // Promote to void*.
John Wiegley01296292011-04-08 18:41:53 +00005629 LHS = ImpCastExprToType(LHS.take(), destType, CK_BitCast);
Fariborz Jahaniana430f712009-12-10 19:47:41 +00005630 return destType;
5631 }
5632 return QualType();
5633}
5634
Chandler Carruthb00e8c02011-06-16 01:05:14 +00005635/// SuggestParentheses - Emit a note with a fixit hint that wraps
Hans Wennborgcf9bac42011-06-03 18:00:36 +00005636/// ParenRange in parentheses.
5637static void SuggestParentheses(Sema &Self, SourceLocation Loc,
Chandler Carruthb00e8c02011-06-16 01:05:14 +00005638 const PartialDiagnostic &Note,
5639 SourceRange ParenRange) {
5640 SourceLocation EndLoc = Self.PP.getLocForEndOfToken(ParenRange.getEnd());
5641 if (ParenRange.getBegin().isFileID() && ParenRange.getEnd().isFileID() &&
5642 EndLoc.isValid()) {
5643 Self.Diag(Loc, Note)
5644 << FixItHint::CreateInsertion(ParenRange.getBegin(), "(")
5645 << FixItHint::CreateInsertion(EndLoc, ")");
5646 } else {
5647 // We can't display the parentheses, so just show the bare note.
5648 Self.Diag(Loc, Note) << ParenRange;
Hans Wennborgcf9bac42011-06-03 18:00:36 +00005649 }
Hans Wennborgcf9bac42011-06-03 18:00:36 +00005650}
5651
5652static bool IsArithmeticOp(BinaryOperatorKind Opc) {
5653 return Opc >= BO_Mul && Opc <= BO_Shr;
5654}
5655
Hans Wennborgde2e67e2011-06-09 17:06:51 +00005656/// IsArithmeticBinaryExpr - Returns true if E is an arithmetic binary
5657/// expression, either using a built-in or overloaded operator,
Richard Trieud33e46e2011-09-06 20:06:39 +00005658/// and sets *OpCode to the opcode and *RHSExprs to the right-hand side
5659/// expression.
Hans Wennborgde2e67e2011-06-09 17:06:51 +00005660static bool IsArithmeticBinaryExpr(Expr *E, BinaryOperatorKind *Opcode,
Richard Trieud33e46e2011-09-06 20:06:39 +00005661 Expr **RHSExprs) {
Hans Wennborgbe207b32011-09-12 12:07:30 +00005662 // Don't strip parenthesis: we should not warn if E is in parenthesis.
5663 E = E->IgnoreImpCasts();
Hans Wennborgde2e67e2011-06-09 17:06:51 +00005664 E = E->IgnoreConversionOperator();
Hans Wennborgbe207b32011-09-12 12:07:30 +00005665 E = E->IgnoreImpCasts();
Hans Wennborgde2e67e2011-06-09 17:06:51 +00005666
5667 // Built-in binary operator.
5668 if (BinaryOperator *OP = dyn_cast<BinaryOperator>(E)) {
5669 if (IsArithmeticOp(OP->getOpcode())) {
5670 *Opcode = OP->getOpcode();
Richard Trieud33e46e2011-09-06 20:06:39 +00005671 *RHSExprs = OP->getRHS();
Hans Wennborgde2e67e2011-06-09 17:06:51 +00005672 return true;
5673 }
5674 }
5675
5676 // Overloaded operator.
5677 if (CXXOperatorCallExpr *Call = dyn_cast<CXXOperatorCallExpr>(E)) {
5678 if (Call->getNumArgs() != 2)
5679 return false;
5680
5681 // Make sure this is really a binary operator that is safe to pass into
5682 // BinaryOperator::getOverloadedOpcode(), e.g. it's not a subscript op.
5683 OverloadedOperatorKind OO = Call->getOperator();
Benjamin Kramer0345f9f2013-03-30 11:56:00 +00005684 if (OO < OO_Plus || OO > OO_Arrow ||
5685 OO == OO_PlusPlus || OO == OO_MinusMinus)
Hans Wennborgde2e67e2011-06-09 17:06:51 +00005686 return false;
5687
5688 BinaryOperatorKind OpKind = BinaryOperator::getOverloadedOpcode(OO);
5689 if (IsArithmeticOp(OpKind)) {
5690 *Opcode = OpKind;
Richard Trieud33e46e2011-09-06 20:06:39 +00005691 *RHSExprs = Call->getArg(1);
Hans Wennborgde2e67e2011-06-09 17:06:51 +00005692 return true;
5693 }
5694 }
5695
5696 return false;
5697}
5698
Hans Wennborgcf9bac42011-06-03 18:00:36 +00005699static bool IsLogicOp(BinaryOperatorKind Opc) {
5700 return (Opc >= BO_LT && Opc <= BO_NE) || (Opc >= BO_LAnd && Opc <= BO_LOr);
5701}
5702
Hans Wennborgde2e67e2011-06-09 17:06:51 +00005703/// ExprLooksBoolean - Returns true if E looks boolean, i.e. it has boolean type
5704/// or is a logical expression such as (x==y) which has int type, but is
5705/// commonly interpreted as boolean.
5706static bool ExprLooksBoolean(Expr *E) {
5707 E = E->IgnoreParenImpCasts();
5708
5709 if (E->getType()->isBooleanType())
5710 return true;
5711 if (BinaryOperator *OP = dyn_cast<BinaryOperator>(E))
5712 return IsLogicOp(OP->getOpcode());
5713 if (UnaryOperator *OP = dyn_cast<UnaryOperator>(E))
5714 return OP->getOpcode() == UO_LNot;
5715
5716 return false;
5717}
5718
Hans Wennborgcf9bac42011-06-03 18:00:36 +00005719/// DiagnoseConditionalPrecedence - Emit a warning when a conditional operator
5720/// and binary operator are mixed in a way that suggests the programmer assumed
5721/// the conditional operator has higher precedence, for example:
5722/// "int x = a + someBinaryCondition ? 1 : 2".
5723static void DiagnoseConditionalPrecedence(Sema &Self,
5724 SourceLocation OpLoc,
Chandler Carruth08dc2ba2011-06-16 01:05:08 +00005725 Expr *Condition,
Richard Trieud33e46e2011-09-06 20:06:39 +00005726 Expr *LHSExpr,
5727 Expr *RHSExpr) {
Hans Wennborgde2e67e2011-06-09 17:06:51 +00005728 BinaryOperatorKind CondOpcode;
5729 Expr *CondRHS;
Hans Wennborgcf9bac42011-06-03 18:00:36 +00005730
Chandler Carruth08dc2ba2011-06-16 01:05:08 +00005731 if (!IsArithmeticBinaryExpr(Condition, &CondOpcode, &CondRHS))
Hans Wennborgde2e67e2011-06-09 17:06:51 +00005732 return;
5733 if (!ExprLooksBoolean(CondRHS))
5734 return;
Hans Wennborgcf9bac42011-06-03 18:00:36 +00005735
Hans Wennborgde2e67e2011-06-09 17:06:51 +00005736 // The condition is an arithmetic binary expression, with a right-
5737 // hand side that looks boolean, so warn.
Hans Wennborgcf9bac42011-06-03 18:00:36 +00005738
Chandler Carruthb00e8c02011-06-16 01:05:14 +00005739 Self.Diag(OpLoc, diag::warn_precedence_conditional)
Chandler Carruth08dc2ba2011-06-16 01:05:08 +00005740 << Condition->getSourceRange()
Hans Wennborgde2e67e2011-06-09 17:06:51 +00005741 << BinaryOperator::getOpcodeStr(CondOpcode);
Hans Wennborgcf9bac42011-06-03 18:00:36 +00005742
Chandler Carruthb00e8c02011-06-16 01:05:14 +00005743 SuggestParentheses(Self, OpLoc,
David Blaikiedac86fd2012-10-08 01:19:49 +00005744 Self.PDiag(diag::note_precedence_silence)
Chandler Carruthb00e8c02011-06-16 01:05:14 +00005745 << BinaryOperator::getOpcodeStr(CondOpcode),
5746 SourceRange(Condition->getLocStart(), Condition->getLocEnd()));
Chandler Carruthf51c5a52011-06-21 23:04:18 +00005747
5748 SuggestParentheses(Self, OpLoc,
5749 Self.PDiag(diag::note_precedence_conditional_first),
Richard Trieud33e46e2011-09-06 20:06:39 +00005750 SourceRange(CondRHS->getLocStart(), RHSExpr->getLocEnd()));
Hans Wennborgcf9bac42011-06-03 18:00:36 +00005751}
5752
Steve Naroff83895f72007-09-16 03:34:24 +00005753/// ActOnConditionalOp - Parse a ?: operation. Note that 'LHS' may be null
Chris Lattnere168f762006-11-10 05:29:30 +00005754/// in the case of a the GNU conditional expr extension.
John McCalldadc5752010-08-24 06:29:42 +00005755ExprResult Sema::ActOnConditionalOp(SourceLocation QuestionLoc,
John McCallc07a0c72011-02-17 10:25:35 +00005756 SourceLocation ColonLoc,
5757 Expr *CondExpr, Expr *LHSExpr,
5758 Expr *RHSExpr) {
Chris Lattner2ab40a62007-11-26 01:40:58 +00005759 // If this is the gnu "x ?: y" extension, analyze the types as though the LHS
5760 // was the condition.
John McCallc07a0c72011-02-17 10:25:35 +00005761 OpaqueValueExpr *opaqueValue = 0;
5762 Expr *commonExpr = 0;
5763 if (LHSExpr == 0) {
5764 commonExpr = CondExpr;
Fariborz Jahanian3caab6c2013-05-17 16:29:36 +00005765 // Lower out placeholder types first. This is important so that we don't
5766 // try to capture a placeholder. This happens in few cases in C++; such
5767 // as Objective-C++'s dictionary subscripting syntax.
5768 if (commonExpr->hasPlaceholderType()) {
5769 ExprResult result = CheckPlaceholderExpr(commonExpr);
5770 if (!result.isUsable()) return ExprError();
5771 commonExpr = result.take();
5772 }
John McCallc07a0c72011-02-17 10:25:35 +00005773 // We usually want to apply unary conversions *before* saving, except
5774 // in the special case of a C++ l-value conditional.
David Blaikiebbafb8a2012-03-11 07:00:24 +00005775 if (!(getLangOpts().CPlusPlus
John McCallc07a0c72011-02-17 10:25:35 +00005776 && !commonExpr->isTypeDependent()
5777 && commonExpr->getValueKind() == RHSExpr->getValueKind()
5778 && commonExpr->isGLValue()
5779 && commonExpr->isOrdinaryOrBitFieldObject()
5780 && RHSExpr->isOrdinaryOrBitFieldObject()
5781 && Context.hasSameType(commonExpr->getType(), RHSExpr->getType()))) {
John Wiegley01296292011-04-08 18:41:53 +00005782 ExprResult commonRes = UsualUnaryConversions(commonExpr);
5783 if (commonRes.isInvalid())
5784 return ExprError();
5785 commonExpr = commonRes.take();
John McCallc07a0c72011-02-17 10:25:35 +00005786 }
5787
5788 opaqueValue = new (Context) OpaqueValueExpr(commonExpr->getExprLoc(),
5789 commonExpr->getType(),
5790 commonExpr->getValueKind(),
Douglas Gregor2d5aea02012-02-23 22:17:26 +00005791 commonExpr->getObjectKind(),
5792 commonExpr);
John McCallc07a0c72011-02-17 10:25:35 +00005793 LHSExpr = CondExpr = opaqueValue;
Fariborz Jahanianc6bf0bd2010-08-31 18:02:20 +00005794 }
Sebastian Redlb5d49352009-01-19 22:31:54 +00005795
John McCall7decc9e2010-11-18 06:31:45 +00005796 ExprValueKind VK = VK_RValue;
John McCall4bc41ae2010-11-18 19:01:18 +00005797 ExprObjectKind OK = OK_Ordinary;
John Wiegley01296292011-04-08 18:41:53 +00005798 ExprResult Cond = Owned(CondExpr), LHS = Owned(LHSExpr), RHS = Owned(RHSExpr);
5799 QualType result = CheckConditionalOperands(Cond, LHS, RHS,
John McCallc07a0c72011-02-17 10:25:35 +00005800 VK, OK, QuestionLoc);
John Wiegley01296292011-04-08 18:41:53 +00005801 if (result.isNull() || Cond.isInvalid() || LHS.isInvalid() ||
5802 RHS.isInvalid())
Sebastian Redlb5d49352009-01-19 22:31:54 +00005803 return ExprError();
5804
Hans Wennborgcf9bac42011-06-03 18:00:36 +00005805 DiagnoseConditionalPrecedence(*this, QuestionLoc, Cond.get(), LHS.get(),
5806 RHS.get());
5807
John McCallc07a0c72011-02-17 10:25:35 +00005808 if (!commonExpr)
John Wiegley01296292011-04-08 18:41:53 +00005809 return Owned(new (Context) ConditionalOperator(Cond.take(), QuestionLoc,
5810 LHS.take(), ColonLoc,
5811 RHS.take(), result, VK, OK));
John McCallc07a0c72011-02-17 10:25:35 +00005812
5813 return Owned(new (Context)
John Wiegley01296292011-04-08 18:41:53 +00005814 BinaryConditionalOperator(commonExpr, opaqueValue, Cond.take(), LHS.take(),
Richard Trieucfc491d2011-08-02 04:35:43 +00005815 RHS.take(), QuestionLoc, ColonLoc, result, VK,
5816 OK));
Chris Lattnere168f762006-11-10 05:29:30 +00005817}
5818
John McCallaba90822011-01-31 23:13:11 +00005819// checkPointerTypesForAssignment - This is a very tricky routine (despite
Mike Stump4e1f26a2009-02-19 03:04:26 +00005820// being closely modeled after the C99 spec:-). The odd characteristic of this
Steve Naroff3f597292007-05-11 22:18:03 +00005821// routine is it effectively iqnores the qualifiers on the top level pointee.
5822// This circumvents the usual type rules specified in 6.2.7p1 & 6.7.5.[1-3].
5823// FIXME: add a couple examples in this comment.
John McCallaba90822011-01-31 23:13:11 +00005824static Sema::AssignConvertType
Richard Trieua871b972011-09-06 20:21:22 +00005825checkPointerTypesForAssignment(Sema &S, QualType LHSType, QualType RHSType) {
5826 assert(LHSType.isCanonical() && "LHS not canonicalized!");
5827 assert(RHSType.isCanonical() && "RHS not canonicalized!");
Mike Stump4e1f26a2009-02-19 03:04:26 +00005828
Steve Naroff1f4d7272007-05-11 04:00:31 +00005829 // get the "pointed to" type (ignoring qualifiers at the top level)
John McCall4fff8f62011-02-01 00:10:29 +00005830 const Type *lhptee, *rhptee;
5831 Qualifiers lhq, rhq;
Richard Trieua871b972011-09-06 20:21:22 +00005832 llvm::tie(lhptee, lhq) = cast<PointerType>(LHSType)->getPointeeType().split();
5833 llvm::tie(rhptee, rhq) = cast<PointerType>(RHSType)->getPointeeType().split();
Mike Stump4e1f26a2009-02-19 03:04:26 +00005834
John McCallaba90822011-01-31 23:13:11 +00005835 Sema::AssignConvertType ConvTy = Sema::Compatible;
Mike Stump4e1f26a2009-02-19 03:04:26 +00005836
5837 // C99 6.5.16.1p1: This following citation is common to constraints
5838 // 3 & 4 (below). ...and the type *pointed to* by the left has all the
5839 // qualifiers of the type *pointed to* by the right;
John McCall4fff8f62011-02-01 00:10:29 +00005840 Qualifiers lq;
5841
John McCall31168b02011-06-15 23:02:42 +00005842 // As a special case, 'non-__weak A *' -> 'non-__weak const *' is okay.
5843 if (lhq.getObjCLifetime() != rhq.getObjCLifetime() &&
5844 lhq.compatiblyIncludesObjCLifetime(rhq)) {
5845 // Ignore lifetime for further calculation.
5846 lhq.removeObjCLifetime();
5847 rhq.removeObjCLifetime();
5848 }
5849
John McCall4fff8f62011-02-01 00:10:29 +00005850 if (!lhq.compatiblyIncludes(rhq)) {
5851 // Treat address-space mismatches as fatal. TODO: address subspaces
5852 if (lhq.getAddressSpace() != rhq.getAddressSpace())
5853 ConvTy = Sema::IncompatiblePointerDiscardsQualifiers;
5854
John McCall31168b02011-06-15 23:02:42 +00005855 // It's okay to add or remove GC or lifetime qualifiers when converting to
John McCall78535952011-03-26 02:56:45 +00005856 // and from void*.
John McCall18ce25e2012-02-08 00:46:36 +00005857 else if (lhq.withoutObjCGCAttr().withoutObjCLifetime()
John McCall31168b02011-06-15 23:02:42 +00005858 .compatiblyIncludes(
John McCall18ce25e2012-02-08 00:46:36 +00005859 rhq.withoutObjCGCAttr().withoutObjCLifetime())
John McCall78535952011-03-26 02:56:45 +00005860 && (lhptee->isVoidType() || rhptee->isVoidType()))
5861 ; // keep old
5862
John McCall31168b02011-06-15 23:02:42 +00005863 // Treat lifetime mismatches as fatal.
5864 else if (lhq.getObjCLifetime() != rhq.getObjCLifetime())
5865 ConvTy = Sema::IncompatiblePointerDiscardsQualifiers;
5866
John McCall4fff8f62011-02-01 00:10:29 +00005867 // For GCC compatibility, other qualifier mismatches are treated
5868 // as still compatible in C.
5869 else ConvTy = Sema::CompatiblePointerDiscardsQualifiers;
5870 }
Steve Naroff3f597292007-05-11 22:18:03 +00005871
Mike Stump4e1f26a2009-02-19 03:04:26 +00005872 // C99 6.5.16.1p1 (constraint 4): If one operand is a pointer to an object or
5873 // incomplete type and the other is a pointer to a qualified or unqualified
Steve Naroff3f597292007-05-11 22:18:03 +00005874 // version of void...
Chris Lattner0a788432008-01-03 22:56:36 +00005875 if (lhptee->isVoidType()) {
Chris Lattnerb3a176d2008-04-02 06:59:01 +00005876 if (rhptee->isIncompleteOrObjectType())
Chris Lattner9bad62c2008-01-04 18:04:52 +00005877 return ConvTy;
Mike Stump4e1f26a2009-02-19 03:04:26 +00005878
Chris Lattner0a788432008-01-03 22:56:36 +00005879 // As an extension, we allow cast to/from void* to function pointer.
Chris Lattnerb3a176d2008-04-02 06:59:01 +00005880 assert(rhptee->isFunctionType());
John McCallaba90822011-01-31 23:13:11 +00005881 return Sema::FunctionVoidPointer;
Chris Lattner0a788432008-01-03 22:56:36 +00005882 }
Mike Stump4e1f26a2009-02-19 03:04:26 +00005883
Chris Lattner0a788432008-01-03 22:56:36 +00005884 if (rhptee->isVoidType()) {
Chris Lattnerb3a176d2008-04-02 06:59:01 +00005885 if (lhptee->isIncompleteOrObjectType())
Chris Lattner9bad62c2008-01-04 18:04:52 +00005886 return ConvTy;
Chris Lattner0a788432008-01-03 22:56:36 +00005887
5888 // As an extension, we allow cast to/from void* to function pointer.
Chris Lattnerb3a176d2008-04-02 06:59:01 +00005889 assert(lhptee->isFunctionType());
John McCallaba90822011-01-31 23:13:11 +00005890 return Sema::FunctionVoidPointer;
Chris Lattner0a788432008-01-03 22:56:36 +00005891 }
John McCall4fff8f62011-02-01 00:10:29 +00005892
Mike Stump4e1f26a2009-02-19 03:04:26 +00005893 // C99 6.5.16.1p1 (constraint 3): both operands are pointers to qualified or
Steve Naroff3f597292007-05-11 22:18:03 +00005894 // unqualified versions of compatible types, ...
John McCall4fff8f62011-02-01 00:10:29 +00005895 QualType ltrans = QualType(lhptee, 0), rtrans = QualType(rhptee, 0);
5896 if (!S.Context.typesAreCompatible(ltrans, rtrans)) {
Eli Friedman80160bd2009-03-22 23:59:44 +00005897 // Check if the pointee types are compatible ignoring the sign.
5898 // We explicitly check for char so that we catch "char" vs
5899 // "unsigned char" on systems where "char" is unsigned.
Chris Lattnerec3a1562009-10-17 20:33:28 +00005900 if (lhptee->isCharType())
John McCall4fff8f62011-02-01 00:10:29 +00005901 ltrans = S.Context.UnsignedCharTy;
Douglas Gregor5cc2c8b2010-07-23 15:58:24 +00005902 else if (lhptee->hasSignedIntegerRepresentation())
John McCall4fff8f62011-02-01 00:10:29 +00005903 ltrans = S.Context.getCorrespondingUnsignedType(ltrans);
Kovarththanan Rajaratnamba2c6522010-03-13 10:17:05 +00005904
Chris Lattnerec3a1562009-10-17 20:33:28 +00005905 if (rhptee->isCharType())
John McCall4fff8f62011-02-01 00:10:29 +00005906 rtrans = S.Context.UnsignedCharTy;
Douglas Gregor5cc2c8b2010-07-23 15:58:24 +00005907 else if (rhptee->hasSignedIntegerRepresentation())
John McCall4fff8f62011-02-01 00:10:29 +00005908 rtrans = S.Context.getCorrespondingUnsignedType(rtrans);
Chris Lattnerec3a1562009-10-17 20:33:28 +00005909
John McCall4fff8f62011-02-01 00:10:29 +00005910 if (ltrans == rtrans) {
Eli Friedman80160bd2009-03-22 23:59:44 +00005911 // Types are compatible ignoring the sign. Qualifier incompatibility
5912 // takes priority over sign incompatibility because the sign
5913 // warning can be disabled.
John McCallaba90822011-01-31 23:13:11 +00005914 if (ConvTy != Sema::Compatible)
Eli Friedman80160bd2009-03-22 23:59:44 +00005915 return ConvTy;
John McCall4fff8f62011-02-01 00:10:29 +00005916
John McCallaba90822011-01-31 23:13:11 +00005917 return Sema::IncompatiblePointerSign;
Eli Friedman80160bd2009-03-22 23:59:44 +00005918 }
Kovarththanan Rajaratnamba2c6522010-03-13 10:17:05 +00005919
Fariborz Jahaniand7aa9d82009-11-07 20:20:40 +00005920 // If we are a multi-level pointer, it's possible that our issue is simply
5921 // one of qualification - e.g. char ** -> const char ** is not allowed. If
5922 // the eventual target type is the same and the pointers have the same
5923 // level of indirection, this must be the issue.
John McCallaba90822011-01-31 23:13:11 +00005924 if (isa<PointerType>(lhptee) && isa<PointerType>(rhptee)) {
Fariborz Jahaniand7aa9d82009-11-07 20:20:40 +00005925 do {
John McCall4fff8f62011-02-01 00:10:29 +00005926 lhptee = cast<PointerType>(lhptee)->getPointeeType().getTypePtr();
5927 rhptee = cast<PointerType>(rhptee)->getPointeeType().getTypePtr();
John McCallaba90822011-01-31 23:13:11 +00005928 } while (isa<PointerType>(lhptee) && isa<PointerType>(rhptee));
Kovarththanan Rajaratnamba2c6522010-03-13 10:17:05 +00005929
John McCall4fff8f62011-02-01 00:10:29 +00005930 if (lhptee == rhptee)
John McCallaba90822011-01-31 23:13:11 +00005931 return Sema::IncompatibleNestedPointerQualifiers;
Fariborz Jahaniand7aa9d82009-11-07 20:20:40 +00005932 }
Kovarththanan Rajaratnamba2c6522010-03-13 10:17:05 +00005933
Eli Friedman80160bd2009-03-22 23:59:44 +00005934 // General pointer incompatibility takes priority over qualifiers.
John McCallaba90822011-01-31 23:13:11 +00005935 return Sema::IncompatiblePointer;
Eli Friedman80160bd2009-03-22 23:59:44 +00005936 }
David Blaikiebbafb8a2012-03-11 07:00:24 +00005937 if (!S.getLangOpts().CPlusPlus &&
Fariborz Jahanian48c69102011-10-05 00:05:34 +00005938 S.IsNoReturnConversion(ltrans, rtrans, ltrans))
5939 return Sema::IncompatiblePointer;
Chris Lattner9bad62c2008-01-04 18:04:52 +00005940 return ConvTy;
Steve Naroff1f4d7272007-05-11 04:00:31 +00005941}
5942
John McCallaba90822011-01-31 23:13:11 +00005943/// checkBlockPointerTypesForAssignment - This routine determines whether two
Steve Naroff081c7422008-09-04 15:10:53 +00005944/// block pointer types are compatible or whether a block and normal pointer
5945/// are compatible. It is more restrict than comparing two function pointer
5946// types.
John McCallaba90822011-01-31 23:13:11 +00005947static Sema::AssignConvertType
Richard Trieua871b972011-09-06 20:21:22 +00005948checkBlockPointerTypesForAssignment(Sema &S, QualType LHSType,
5949 QualType RHSType) {
5950 assert(LHSType.isCanonical() && "LHS not canonicalized!");
5951 assert(RHSType.isCanonical() && "RHS not canonicalized!");
John McCallaba90822011-01-31 23:13:11 +00005952
Steve Naroff081c7422008-09-04 15:10:53 +00005953 QualType lhptee, rhptee;
Mike Stump4e1f26a2009-02-19 03:04:26 +00005954
Steve Naroff081c7422008-09-04 15:10:53 +00005955 // get the "pointed to" type (ignoring qualifiers at the top level)
Richard Trieua871b972011-09-06 20:21:22 +00005956 lhptee = cast<BlockPointerType>(LHSType)->getPointeeType();
5957 rhptee = cast<BlockPointerType>(RHSType)->getPointeeType();
Mike Stump4e1f26a2009-02-19 03:04:26 +00005958
John McCallaba90822011-01-31 23:13:11 +00005959 // In C++, the types have to match exactly.
David Blaikiebbafb8a2012-03-11 07:00:24 +00005960 if (S.getLangOpts().CPlusPlus)
John McCallaba90822011-01-31 23:13:11 +00005961 return Sema::IncompatibleBlockPointer;
Mike Stump4e1f26a2009-02-19 03:04:26 +00005962
John McCallaba90822011-01-31 23:13:11 +00005963 Sema::AssignConvertType ConvTy = Sema::Compatible;
Mike Stump4e1f26a2009-02-19 03:04:26 +00005964
Steve Naroff081c7422008-09-04 15:10:53 +00005965 // For blocks we enforce that qualifiers are identical.
John McCallaba90822011-01-31 23:13:11 +00005966 if (lhptee.getLocalQualifiers() != rhptee.getLocalQualifiers())
5967 ConvTy = Sema::CompatiblePointerDiscardsQualifiers;
Mike Stump4e1f26a2009-02-19 03:04:26 +00005968
Richard Trieua871b972011-09-06 20:21:22 +00005969 if (!S.Context.typesAreBlockPointerCompatible(LHSType, RHSType))
John McCallaba90822011-01-31 23:13:11 +00005970 return Sema::IncompatibleBlockPointer;
5971
Steve Naroff081c7422008-09-04 15:10:53 +00005972 return ConvTy;
5973}
5974
John McCallaba90822011-01-31 23:13:11 +00005975/// checkObjCPointerTypesForAssignment - Compares two objective-c pointer types
Fariborz Jahanian410f2eb2009-12-08 18:24:49 +00005976/// for assignment compatibility.
John McCallaba90822011-01-31 23:13:11 +00005977static Sema::AssignConvertType
Richard Trieua871b972011-09-06 20:21:22 +00005978checkObjCPointerTypesForAssignment(Sema &S, QualType LHSType,
5979 QualType RHSType) {
5980 assert(LHSType.isCanonical() && "LHS was not canonicalized!");
5981 assert(RHSType.isCanonical() && "RHS was not canonicalized!");
John McCallaba90822011-01-31 23:13:11 +00005982
Richard Trieua871b972011-09-06 20:21:22 +00005983 if (LHSType->isObjCBuiltinType()) {
Fariborz Jahaniand5bb8cb2010-03-19 18:06:10 +00005984 // Class is not compatible with ObjC object pointers.
Richard Trieua871b972011-09-06 20:21:22 +00005985 if (LHSType->isObjCClassType() && !RHSType->isObjCBuiltinType() &&
5986 !RHSType->isObjCQualifiedClassType())
John McCallaba90822011-01-31 23:13:11 +00005987 return Sema::IncompatiblePointer;
5988 return Sema::Compatible;
Fariborz Jahaniand5bb8cb2010-03-19 18:06:10 +00005989 }
Richard Trieua871b972011-09-06 20:21:22 +00005990 if (RHSType->isObjCBuiltinType()) {
Richard Trieua871b972011-09-06 20:21:22 +00005991 if (RHSType->isObjCClassType() && !LHSType->isObjCBuiltinType() &&
5992 !LHSType->isObjCQualifiedClassType())
Fariborz Jahaniand923eb02011-09-15 20:40:18 +00005993 return Sema::IncompatiblePointer;
John McCallaba90822011-01-31 23:13:11 +00005994 return Sema::Compatible;
Fariborz Jahaniand5bb8cb2010-03-19 18:06:10 +00005995 }
Richard Trieua871b972011-09-06 20:21:22 +00005996 QualType lhptee = LHSType->getAs<ObjCObjectPointerType>()->getPointeeType();
5997 QualType rhptee = RHSType->getAs<ObjCObjectPointerType>()->getPointeeType();
Kovarththanan Rajaratnamba2c6522010-03-13 10:17:05 +00005998
Fariborz Jahaniane74d47e2012-01-12 22:12:08 +00005999 if (!lhptee.isAtLeastAsQualifiedAs(rhptee) &&
6000 // make an exception for id<P>
6001 !LHSType->isObjCQualifiedIdType())
John McCallaba90822011-01-31 23:13:11 +00006002 return Sema::CompatiblePointerDiscardsQualifiers;
6003
Richard Trieua871b972011-09-06 20:21:22 +00006004 if (S.Context.typesAreCompatible(LHSType, RHSType))
John McCallaba90822011-01-31 23:13:11 +00006005 return Sema::Compatible;
Richard Trieua871b972011-09-06 20:21:22 +00006006 if (LHSType->isObjCQualifiedIdType() || RHSType->isObjCQualifiedIdType())
John McCallaba90822011-01-31 23:13:11 +00006007 return Sema::IncompatibleObjCQualifiedId;
6008 return Sema::IncompatiblePointer;
Fariborz Jahanian410f2eb2009-12-08 18:24:49 +00006009}
6010
John McCall29600e12010-11-16 02:32:08 +00006011Sema::AssignConvertType
Douglas Gregorc03a1082011-01-28 02:26:04 +00006012Sema::CheckAssignmentConstraints(SourceLocation Loc,
Richard Trieua871b972011-09-06 20:21:22 +00006013 QualType LHSType, QualType RHSType) {
John McCall29600e12010-11-16 02:32:08 +00006014 // Fake up an opaque expression. We don't actually care about what
6015 // cast operations are required, so if CheckAssignmentConstraints
6016 // adds casts to this they'll be wasted, but fortunately that doesn't
6017 // usually happen on valid code.
Richard Trieua871b972011-09-06 20:21:22 +00006018 OpaqueValueExpr RHSExpr(Loc, RHSType, VK_RValue);
6019 ExprResult RHSPtr = &RHSExpr;
John McCall29600e12010-11-16 02:32:08 +00006020 CastKind K = CK_Invalid;
6021
Richard Trieua871b972011-09-06 20:21:22 +00006022 return CheckAssignmentConstraints(LHSType, RHSPtr, K);
John McCall29600e12010-11-16 02:32:08 +00006023}
6024
Mike Stump4e1f26a2009-02-19 03:04:26 +00006025/// CheckAssignmentConstraints (C99 6.5.16) - This routine currently
6026/// has code to accommodate several GCC extensions when type checking
Steve Naroff17f76e02007-05-03 21:03:48 +00006027/// pointers. Here are some objectionable examples that GCC considers warnings:
6028///
6029/// int a, *pint;
6030/// short *pshort;
6031/// struct foo *pfoo;
6032///
6033/// pint = pshort; // warning: assignment from incompatible pointer type
6034/// a = pint; // warning: assignment makes integer from pointer without a cast
6035/// pint = a; // warning: assignment makes pointer from integer without a cast
6036/// pint = pfoo; // warning: assignment from incompatible pointer type
6037///
6038/// As a result, the code for dealing with pointers is more complex than the
Mike Stump4e1f26a2009-02-19 03:04:26 +00006039/// C99 spec dictates.
Steve Naroff17f76e02007-05-03 21:03:48 +00006040///
John McCall8cb679e2010-11-15 09:13:47 +00006041/// Sets 'Kind' for any result kind except Incompatible.
Chris Lattner9bad62c2008-01-04 18:04:52 +00006042Sema::AssignConvertType
Richard Trieude4958f2011-09-06 20:30:53 +00006043Sema::CheckAssignmentConstraints(QualType LHSType, ExprResult &RHS,
John McCall8cb679e2010-11-15 09:13:47 +00006044 CastKind &Kind) {
Richard Trieude4958f2011-09-06 20:30:53 +00006045 QualType RHSType = RHS.get()->getType();
6046 QualType OrigLHSType = LHSType;
John McCall29600e12010-11-16 02:32:08 +00006047
Chris Lattnera52c2f22008-01-04 23:18:45 +00006048 // Get canonical types. We're not formatting these types, just comparing
6049 // them.
Richard Trieude4958f2011-09-06 20:30:53 +00006050 LHSType = Context.getCanonicalType(LHSType).getUnqualifiedType();
6051 RHSType = Context.getCanonicalType(RHSType).getUnqualifiedType();
Eli Friedman3360d892008-05-30 18:07:22 +00006052
John McCalle5255932011-01-31 22:28:28 +00006053 // Common case: no conversion required.
Richard Trieude4958f2011-09-06 20:30:53 +00006054 if (LHSType == RHSType) {
John McCall8cb679e2010-11-15 09:13:47 +00006055 Kind = CK_NoOp;
John McCall8cb679e2010-11-15 09:13:47 +00006056 return Compatible;
David Chisnall9f57c292009-08-17 16:35:33 +00006057 }
6058
Eli Friedman93ee5ca2012-06-16 02:19:17 +00006059 // If we have an atomic type, try a non-atomic assignment, then just add an
6060 // atomic qualification step.
David Chisnallfa35df62012-01-16 17:27:18 +00006061 if (const AtomicType *AtomicTy = dyn_cast<AtomicType>(LHSType)) {
Eli Friedman93ee5ca2012-06-16 02:19:17 +00006062 Sema::AssignConvertType result =
6063 CheckAssignmentConstraints(AtomicTy->getValueType(), RHS, Kind);
6064 if (result != Compatible)
6065 return result;
6066 if (Kind != CK_NoOp)
6067 RHS = ImpCastExprToType(RHS.take(), AtomicTy->getValueType(), Kind);
6068 Kind = CK_NonAtomicToAtomic;
6069 return Compatible;
David Chisnallfa35df62012-01-16 17:27:18 +00006070 }
6071
Douglas Gregor6b754842008-10-28 00:22:11 +00006072 // If the left-hand side is a reference type, then we are in a
6073 // (rare!) case where we've allowed the use of references in C,
6074 // e.g., as a parameter type in a built-in function. In this case,
6075 // just make sure that the type referenced is compatible with the
6076 // right-hand side type. The caller is responsible for adjusting
Richard Trieude4958f2011-09-06 20:30:53 +00006077 // LHSType so that the resulting expression does not have reference
Douglas Gregor6b754842008-10-28 00:22:11 +00006078 // type.
Richard Trieude4958f2011-09-06 20:30:53 +00006079 if (const ReferenceType *LHSTypeRef = LHSType->getAs<ReferenceType>()) {
6080 if (Context.typesAreCompatible(LHSTypeRef->getPointeeType(), RHSType)) {
John McCall8cb679e2010-11-15 09:13:47 +00006081 Kind = CK_LValueBitCast;
Anders Carlsson24ebce62007-10-12 23:56:29 +00006082 return Compatible;
John McCall8cb679e2010-11-15 09:13:47 +00006083 }
Chris Lattnera52c2f22008-01-04 23:18:45 +00006084 return Incompatible;
Fariborz Jahaniana1e34202007-12-19 17:45:58 +00006085 }
John McCalle5255932011-01-31 22:28:28 +00006086
Nate Begemanbd956c42009-06-28 02:36:38 +00006087 // Allow scalar to ExtVector assignments, and assignments of an ExtVector type
6088 // to the same ExtVector type.
Richard Trieude4958f2011-09-06 20:30:53 +00006089 if (LHSType->isExtVectorType()) {
6090 if (RHSType->isExtVectorType())
John McCall8cb679e2010-11-15 09:13:47 +00006091 return Incompatible;
Richard Trieude4958f2011-09-06 20:30:53 +00006092 if (RHSType->isArithmeticType()) {
John McCall29600e12010-11-16 02:32:08 +00006093 // CK_VectorSplat does T -> vector T, so first cast to the
6094 // element type.
Richard Trieude4958f2011-09-06 20:30:53 +00006095 QualType elType = cast<ExtVectorType>(LHSType)->getElementType();
6096 if (elType != RHSType) {
John McCall9776e432011-10-06 23:25:11 +00006097 Kind = PrepareScalarCast(RHS, elType);
Richard Trieude4958f2011-09-06 20:30:53 +00006098 RHS = ImpCastExprToType(RHS.take(), elType, Kind);
John McCall29600e12010-11-16 02:32:08 +00006099 }
6100 Kind = CK_VectorSplat;
Nate Begemanbd956c42009-06-28 02:36:38 +00006101 return Compatible;
John McCall8cb679e2010-11-15 09:13:47 +00006102 }
Nate Begemanbd956c42009-06-28 02:36:38 +00006103 }
Mike Stump11289f42009-09-09 15:08:12 +00006104
John McCalle5255932011-01-31 22:28:28 +00006105 // Conversions to or from vector type.
Richard Trieude4958f2011-09-06 20:30:53 +00006106 if (LHSType->isVectorType() || RHSType->isVectorType()) {
6107 if (LHSType->isVectorType() && RHSType->isVectorType()) {
Bob Wilson01856f32010-12-02 00:25:15 +00006108 // Allow assignments of an AltiVec vector type to an equivalent GCC
6109 // vector type and vice versa
Richard Trieude4958f2011-09-06 20:30:53 +00006110 if (Context.areCompatibleVectorTypes(LHSType, RHSType)) {
Bob Wilson01856f32010-12-02 00:25:15 +00006111 Kind = CK_BitCast;
6112 return Compatible;
6113 }
6114
Douglas Gregor59e8b3b2010-08-06 10:14:59 +00006115 // If we are allowing lax vector conversions, and LHS and RHS are both
6116 // vectors, the total size only needs to be the same. This is a bitcast;
6117 // no bits are changed but the result type is different.
David Blaikiebbafb8a2012-03-11 07:00:24 +00006118 if (getLangOpts().LaxVectorConversions &&
Richard Trieude4958f2011-09-06 20:30:53 +00006119 (Context.getTypeSize(LHSType) == Context.getTypeSize(RHSType))) {
John McCall3065d042010-11-15 10:08:00 +00006120 Kind = CK_BitCast;
Anders Carlssondb5a9b62009-01-30 23:17:46 +00006121 return IncompatibleVectors;
John McCall8cb679e2010-11-15 09:13:47 +00006122 }
Chris Lattner881a2122008-01-04 23:32:24 +00006123 }
6124 return Incompatible;
Mike Stump4e1f26a2009-02-19 03:04:26 +00006125 }
Eli Friedman3360d892008-05-30 18:07:22 +00006126
John McCalle5255932011-01-31 22:28:28 +00006127 // Arithmetic conversions.
Richard Trieude4958f2011-09-06 20:30:53 +00006128 if (LHSType->isArithmeticType() && RHSType->isArithmeticType() &&
David Blaikiebbafb8a2012-03-11 07:00:24 +00006129 !(getLangOpts().CPlusPlus && LHSType->isEnumeralType())) {
John McCall9776e432011-10-06 23:25:11 +00006130 Kind = PrepareScalarCast(RHS, LHSType);
Steve Naroff98cf3e92007-06-06 18:38:38 +00006131 return Compatible;
John McCall8cb679e2010-11-15 09:13:47 +00006132 }
Eli Friedman3360d892008-05-30 18:07:22 +00006133
John McCalle5255932011-01-31 22:28:28 +00006134 // Conversions to normal pointers.
Richard Trieude4958f2011-09-06 20:30:53 +00006135 if (const PointerType *LHSPointer = dyn_cast<PointerType>(LHSType)) {
John McCalle5255932011-01-31 22:28:28 +00006136 // U* -> T*
Richard Trieude4958f2011-09-06 20:30:53 +00006137 if (isa<PointerType>(RHSType)) {
John McCall8cb679e2010-11-15 09:13:47 +00006138 Kind = CK_BitCast;
Richard Trieude4958f2011-09-06 20:30:53 +00006139 return checkPointerTypesForAssignment(*this, LHSType, RHSType);
John McCall8cb679e2010-11-15 09:13:47 +00006140 }
Mike Stump4e1f26a2009-02-19 03:04:26 +00006141
John McCalle5255932011-01-31 22:28:28 +00006142 // int -> T*
Richard Trieude4958f2011-09-06 20:30:53 +00006143 if (RHSType->isIntegerType()) {
John McCalle5255932011-01-31 22:28:28 +00006144 Kind = CK_IntegralToPointer; // FIXME: null?
6145 return IntToPointer;
Steve Naroff7cae42b2009-07-10 23:34:53 +00006146 }
John McCalle5255932011-01-31 22:28:28 +00006147
6148 // C pointers are not compatible with ObjC object pointers,
6149 // with two exceptions:
Richard Trieude4958f2011-09-06 20:30:53 +00006150 if (isa<ObjCObjectPointerType>(RHSType)) {
John McCalle5255932011-01-31 22:28:28 +00006151 // - conversions to void*
Richard Trieude4958f2011-09-06 20:30:53 +00006152 if (LHSPointer->getPointeeType()->isVoidType()) {
John McCall9320b872011-09-09 05:25:32 +00006153 Kind = CK_BitCast;
John McCalle5255932011-01-31 22:28:28 +00006154 return Compatible;
6155 }
6156
6157 // - conversions from 'Class' to the redefinition type
Richard Trieude4958f2011-09-06 20:30:53 +00006158 if (RHSType->isObjCClassType() &&
6159 Context.hasSameType(LHSType,
Douglas Gregor97673472011-08-11 20:58:55 +00006160 Context.getObjCClassRedefinitionType())) {
John McCall8cb679e2010-11-15 09:13:47 +00006161 Kind = CK_BitCast;
Douglas Gregore7dd1452008-11-27 00:44:28 +00006162 return Compatible;
John McCall8cb679e2010-11-15 09:13:47 +00006163 }
Douglas Gregor486b74e2011-09-27 16:10:05 +00006164
John McCalle5255932011-01-31 22:28:28 +00006165 Kind = CK_BitCast;
6166 return IncompatiblePointer;
6167 }
6168
6169 // U^ -> void*
Richard Trieude4958f2011-09-06 20:30:53 +00006170 if (RHSType->getAs<BlockPointerType>()) {
6171 if (LHSPointer->getPointeeType()->isVoidType()) {
John McCalle5255932011-01-31 22:28:28 +00006172 Kind = CK_BitCast;
Steve Naroff32d072c2008-09-29 18:10:17 +00006173 return Compatible;
John McCall8cb679e2010-11-15 09:13:47 +00006174 }
Steve Naroff32d072c2008-09-29 18:10:17 +00006175 }
John McCalle5255932011-01-31 22:28:28 +00006176
Steve Naroff081c7422008-09-04 15:10:53 +00006177 return Incompatible;
6178 }
6179
John McCalle5255932011-01-31 22:28:28 +00006180 // Conversions to block pointers.
Richard Trieude4958f2011-09-06 20:30:53 +00006181 if (isa<BlockPointerType>(LHSType)) {
John McCalle5255932011-01-31 22:28:28 +00006182 // U^ -> T^
Richard Trieude4958f2011-09-06 20:30:53 +00006183 if (RHSType->isBlockPointerType()) {
John McCall9320b872011-09-09 05:25:32 +00006184 Kind = CK_BitCast;
Richard Trieude4958f2011-09-06 20:30:53 +00006185 return checkBlockPointerTypesForAssignment(*this, LHSType, RHSType);
John McCalle5255932011-01-31 22:28:28 +00006186 }
6187
6188 // int or null -> T^
Richard Trieude4958f2011-09-06 20:30:53 +00006189 if (RHSType->isIntegerType()) {
John McCall8cb679e2010-11-15 09:13:47 +00006190 Kind = CK_IntegralToPointer; // FIXME: null
Eli Friedman8163b7a2009-02-25 04:20:42 +00006191 return IntToBlockPointer;
John McCall8cb679e2010-11-15 09:13:47 +00006192 }
6193
John McCalle5255932011-01-31 22:28:28 +00006194 // id -> T^
David Blaikiebbafb8a2012-03-11 07:00:24 +00006195 if (getLangOpts().ObjC1 && RHSType->isObjCIdType()) {
John McCalle5255932011-01-31 22:28:28 +00006196 Kind = CK_AnyPointerToBlockPointerCast;
Steve Naroff32d072c2008-09-29 18:10:17 +00006197 return Compatible;
John McCalle5255932011-01-31 22:28:28 +00006198 }
Steve Naroff32d072c2008-09-29 18:10:17 +00006199
John McCalle5255932011-01-31 22:28:28 +00006200 // void* -> T^
Richard Trieude4958f2011-09-06 20:30:53 +00006201 if (const PointerType *RHSPT = RHSType->getAs<PointerType>())
John McCalle5255932011-01-31 22:28:28 +00006202 if (RHSPT->getPointeeType()->isVoidType()) {
6203 Kind = CK_AnyPointerToBlockPointerCast;
Douglas Gregore7dd1452008-11-27 00:44:28 +00006204 return Compatible;
John McCalle5255932011-01-31 22:28:28 +00006205 }
John McCall8cb679e2010-11-15 09:13:47 +00006206
Chris Lattnera52c2f22008-01-04 23:18:45 +00006207 return Incompatible;
6208 }
6209
John McCalle5255932011-01-31 22:28:28 +00006210 // Conversions to Objective-C pointers.
Richard Trieude4958f2011-09-06 20:30:53 +00006211 if (isa<ObjCObjectPointerType>(LHSType)) {
John McCalle5255932011-01-31 22:28:28 +00006212 // A* -> B*
Richard Trieude4958f2011-09-06 20:30:53 +00006213 if (RHSType->isObjCObjectPointerType()) {
John McCalle5255932011-01-31 22:28:28 +00006214 Kind = CK_BitCast;
Fariborz Jahanian6f472e82011-07-07 18:55:47 +00006215 Sema::AssignConvertType result =
Richard Trieude4958f2011-09-06 20:30:53 +00006216 checkObjCPointerTypesForAssignment(*this, LHSType, RHSType);
David Blaikiebbafb8a2012-03-11 07:00:24 +00006217 if (getLangOpts().ObjCAutoRefCount &&
Fariborz Jahanian6f472e82011-07-07 18:55:47 +00006218 result == Compatible &&
Richard Trieude4958f2011-09-06 20:30:53 +00006219 !CheckObjCARCUnavailableWeakConversion(OrigLHSType, RHSType))
Fariborz Jahanian7fcce682011-07-07 23:04:17 +00006220 result = IncompatibleObjCWeakRef;
Fariborz Jahanian6f472e82011-07-07 18:55:47 +00006221 return result;
John McCalle5255932011-01-31 22:28:28 +00006222 }
6223
6224 // int or null -> A*
Richard Trieude4958f2011-09-06 20:30:53 +00006225 if (RHSType->isIntegerType()) {
John McCall8cb679e2010-11-15 09:13:47 +00006226 Kind = CK_IntegralToPointer; // FIXME: null
Steve Naroff7cae42b2009-07-10 23:34:53 +00006227 return IntToPointer;
John McCall8cb679e2010-11-15 09:13:47 +00006228 }
6229
John McCalle5255932011-01-31 22:28:28 +00006230 // In general, C pointers are not compatible with ObjC object pointers,
6231 // with two exceptions:
Richard Trieude4958f2011-09-06 20:30:53 +00006232 if (isa<PointerType>(RHSType)) {
John McCall9320b872011-09-09 05:25:32 +00006233 Kind = CK_CPointerToObjCPointerCast;
6234
John McCalle5255932011-01-31 22:28:28 +00006235 // - conversions from 'void*'
Richard Trieude4958f2011-09-06 20:30:53 +00006236 if (RHSType->isVoidPointerType()) {
Steve Naroffaccc4882009-07-20 17:56:53 +00006237 return Compatible;
John McCalle5255932011-01-31 22:28:28 +00006238 }
6239
6240 // - conversions to 'Class' from its redefinition type
Richard Trieude4958f2011-09-06 20:30:53 +00006241 if (LHSType->isObjCClassType() &&
6242 Context.hasSameType(RHSType,
Douglas Gregor97673472011-08-11 20:58:55 +00006243 Context.getObjCClassRedefinitionType())) {
John McCalle5255932011-01-31 22:28:28 +00006244 return Compatible;
6245 }
6246
Steve Naroffaccc4882009-07-20 17:56:53 +00006247 return IncompatiblePointer;
Steve Naroff7cae42b2009-07-10 23:34:53 +00006248 }
John McCalle5255932011-01-31 22:28:28 +00006249
6250 // T^ -> A*
Richard Trieude4958f2011-09-06 20:30:53 +00006251 if (RHSType->isBlockPointerType()) {
John McCallcd78e802011-09-10 01:16:55 +00006252 maybeExtendBlockObject(*this, RHS);
John McCall9320b872011-09-09 05:25:32 +00006253 Kind = CK_BlockPointerToObjCPointerCast;
Steve Naroff7cae42b2009-07-10 23:34:53 +00006254 return Compatible;
John McCalle5255932011-01-31 22:28:28 +00006255 }
6256
Steve Naroff7cae42b2009-07-10 23:34:53 +00006257 return Incompatible;
6258 }
John McCalle5255932011-01-31 22:28:28 +00006259
6260 // Conversions from pointers that are not covered by the above.
Richard Trieude4958f2011-09-06 20:30:53 +00006261 if (isa<PointerType>(RHSType)) {
John McCalle5255932011-01-31 22:28:28 +00006262 // T* -> _Bool
Richard Trieude4958f2011-09-06 20:30:53 +00006263 if (LHSType == Context.BoolTy) {
John McCall8cb679e2010-11-15 09:13:47 +00006264 Kind = CK_PointerToBoolean;
Eli Friedman3360d892008-05-30 18:07:22 +00006265 return Compatible;
John McCall8cb679e2010-11-15 09:13:47 +00006266 }
Eli Friedman3360d892008-05-30 18:07:22 +00006267
John McCalle5255932011-01-31 22:28:28 +00006268 // T* -> int
Richard Trieude4958f2011-09-06 20:30:53 +00006269 if (LHSType->isIntegerType()) {
John McCall8cb679e2010-11-15 09:13:47 +00006270 Kind = CK_PointerToIntegral;
Chris Lattner940cfeb2008-01-04 18:22:42 +00006271 return PointerToInt;
John McCall8cb679e2010-11-15 09:13:47 +00006272 }
Mike Stump4e1f26a2009-02-19 03:04:26 +00006273
Chris Lattnera52c2f22008-01-04 23:18:45 +00006274 return Incompatible;
Chris Lattnera52c2f22008-01-04 23:18:45 +00006275 }
John McCalle5255932011-01-31 22:28:28 +00006276
6277 // Conversions from Objective-C pointers that are not covered by the above.
Richard Trieude4958f2011-09-06 20:30:53 +00006278 if (isa<ObjCObjectPointerType>(RHSType)) {
John McCalle5255932011-01-31 22:28:28 +00006279 // T* -> _Bool
Richard Trieude4958f2011-09-06 20:30:53 +00006280 if (LHSType == Context.BoolTy) {
John McCall8cb679e2010-11-15 09:13:47 +00006281 Kind = CK_PointerToBoolean;
Steve Naroff7cae42b2009-07-10 23:34:53 +00006282 return Compatible;
John McCall8cb679e2010-11-15 09:13:47 +00006283 }
Steve Naroff7cae42b2009-07-10 23:34:53 +00006284
John McCalle5255932011-01-31 22:28:28 +00006285 // T* -> int
Richard Trieude4958f2011-09-06 20:30:53 +00006286 if (LHSType->isIntegerType()) {
John McCall8cb679e2010-11-15 09:13:47 +00006287 Kind = CK_PointerToIntegral;
Steve Naroff7cae42b2009-07-10 23:34:53 +00006288 return PointerToInt;
John McCall8cb679e2010-11-15 09:13:47 +00006289 }
6290
Steve Naroff7cae42b2009-07-10 23:34:53 +00006291 return Incompatible;
6292 }
Eli Friedman3360d892008-05-30 18:07:22 +00006293
John McCalle5255932011-01-31 22:28:28 +00006294 // struct A -> struct B
Richard Trieude4958f2011-09-06 20:30:53 +00006295 if (isa<TagType>(LHSType) && isa<TagType>(RHSType)) {
6296 if (Context.typesAreCompatible(LHSType, RHSType)) {
John McCall8cb679e2010-11-15 09:13:47 +00006297 Kind = CK_NoOp;
Steve Naroff98cf3e92007-06-06 18:38:38 +00006298 return Compatible;
John McCall8cb679e2010-11-15 09:13:47 +00006299 }
Bill Wendling216423b2007-05-30 06:30:29 +00006300 }
John McCalle5255932011-01-31 22:28:28 +00006301
Steve Naroff98cf3e92007-06-06 18:38:38 +00006302 return Incompatible;
Steve Naroff9eb24652007-05-02 21:58:15 +00006303}
6304
Douglas Gregor0cfbdab2009-04-29 22:16:16 +00006305/// \brief Constructs a transparent union from an expression that is
6306/// used to initialize the transparent union.
Richard Trieucfc491d2011-08-02 04:35:43 +00006307static void ConstructTransparentUnion(Sema &S, ASTContext &C,
6308 ExprResult &EResult, QualType UnionType,
6309 FieldDecl *Field) {
Douglas Gregor0cfbdab2009-04-29 22:16:16 +00006310 // Build an initializer list that designates the appropriate member
6311 // of the transparent union.
John Wiegley01296292011-04-08 18:41:53 +00006312 Expr *E = EResult.take();
Ted Kremenekac034612010-04-13 23:39:13 +00006313 InitListExpr *Initializer = new (C) InitListExpr(C, SourceLocation(),
Benjamin Kramerc215e762012-08-24 11:54:20 +00006314 E, SourceLocation());
Douglas Gregor0cfbdab2009-04-29 22:16:16 +00006315 Initializer->setType(UnionType);
6316 Initializer->setInitializedFieldInUnion(Field);
6317
6318 // Build a compound literal constructing a value of the transparent
6319 // union type from this initializer list.
John McCalle15bbff2010-01-18 19:35:47 +00006320 TypeSourceInfo *unionTInfo = C.getTrivialTypeSourceInfo(UnionType);
John Wiegley01296292011-04-08 18:41:53 +00006321 EResult = S.Owned(
6322 new (C) CompoundLiteralExpr(SourceLocation(), unionTInfo, UnionType,
6323 VK_RValue, Initializer, false));
Douglas Gregor0cfbdab2009-04-29 22:16:16 +00006324}
6325
6326Sema::AssignConvertType
Richard Trieucfc491d2011-08-02 04:35:43 +00006327Sema::CheckTransparentUnionArgumentConstraints(QualType ArgType,
Richard Trieueb299142011-09-06 20:40:12 +00006328 ExprResult &RHS) {
6329 QualType RHSType = RHS.get()->getType();
Douglas Gregor0cfbdab2009-04-29 22:16:16 +00006330
Mike Stump11289f42009-09-09 15:08:12 +00006331 // If the ArgType is a Union type, we want to handle a potential
Douglas Gregor0cfbdab2009-04-29 22:16:16 +00006332 // transparent_union GCC extension.
6333 const RecordType *UT = ArgType->getAsUnionType();
Argyrios Kyrtzidisb4b64ca2009-06-30 02:34:44 +00006334 if (!UT || !UT->getDecl()->hasAttr<TransparentUnionAttr>())
Douglas Gregor0cfbdab2009-04-29 22:16:16 +00006335 return Incompatible;
6336
6337 // The field to initialize within the transparent union.
6338 RecordDecl *UD = UT->getDecl();
6339 FieldDecl *InitField = 0;
6340 // It's compatible if the expression matches any of the fields.
Argyrios Kyrtzidiscfbfe782009-06-30 02:36:12 +00006341 for (RecordDecl::field_iterator it = UD->field_begin(),
6342 itend = UD->field_end();
Douglas Gregor0cfbdab2009-04-29 22:16:16 +00006343 it != itend; ++it) {
6344 if (it->getType()->isPointerType()) {
6345 // If the transparent union contains a pointer type, we allow:
6346 // 1) void pointer
6347 // 2) null pointer constant
Richard Trieueb299142011-09-06 20:40:12 +00006348 if (RHSType->isPointerType())
John McCall9320b872011-09-09 05:25:32 +00006349 if (RHSType->castAs<PointerType>()->getPointeeType()->isVoidType()) {
Richard Trieueb299142011-09-06 20:40:12 +00006350 RHS = ImpCastExprToType(RHS.take(), it->getType(), CK_BitCast);
David Blaikie40ed2972012-06-06 20:45:41 +00006351 InitField = *it;
Douglas Gregor0cfbdab2009-04-29 22:16:16 +00006352 break;
6353 }
Mike Stump11289f42009-09-09 15:08:12 +00006354
Richard Trieueb299142011-09-06 20:40:12 +00006355 if (RHS.get()->isNullPointerConstant(Context,
6356 Expr::NPC_ValueDependentIsNull)) {
6357 RHS = ImpCastExprToType(RHS.take(), it->getType(),
6358 CK_NullToPointer);
David Blaikie40ed2972012-06-06 20:45:41 +00006359 InitField = *it;
Douglas Gregor0cfbdab2009-04-29 22:16:16 +00006360 break;
6361 }
6362 }
6363
John McCall8cb679e2010-11-15 09:13:47 +00006364 CastKind Kind = CK_Invalid;
Richard Trieueb299142011-09-06 20:40:12 +00006365 if (CheckAssignmentConstraints(it->getType(), RHS, Kind)
Douglas Gregor0cfbdab2009-04-29 22:16:16 +00006366 == Compatible) {
Richard Trieueb299142011-09-06 20:40:12 +00006367 RHS = ImpCastExprToType(RHS.take(), it->getType(), Kind);
David Blaikie40ed2972012-06-06 20:45:41 +00006368 InitField = *it;
Douglas Gregor0cfbdab2009-04-29 22:16:16 +00006369 break;
6370 }
6371 }
6372
6373 if (!InitField)
6374 return Incompatible;
6375
Richard Trieueb299142011-09-06 20:40:12 +00006376 ConstructTransparentUnion(*this, Context, RHS, ArgType, InitField);
Douglas Gregor0cfbdab2009-04-29 22:16:16 +00006377 return Compatible;
6378}
6379
Chris Lattner9bad62c2008-01-04 18:04:52 +00006380Sema::AssignConvertType
Sebastian Redlb49c46c2011-09-24 17:48:00 +00006381Sema::CheckSingleAssignmentConstraints(QualType LHSType, ExprResult &RHS,
Fariborz Jahanian25eef192013-07-31 21:40:51 +00006382 bool Diagnose,
6383 bool DiagnoseCFAudited) {
David Blaikiebbafb8a2012-03-11 07:00:24 +00006384 if (getLangOpts().CPlusPlus) {
Eli Friedman0dfb8892011-10-06 23:00:33 +00006385 if (!LHSType->isRecordType() && !LHSType->isAtomicType()) {
Douglas Gregor9a657932008-10-21 23:43:52 +00006386 // C++ 5.17p3: If the left operand is not of class type, the
6387 // expression is implicitly converted (C++ 4) to the
6388 // cv-unqualified type of the left operand.
Sebastian Redlcc152642011-10-16 18:19:06 +00006389 ExprResult Res;
6390 if (Diagnose) {
6391 Res = PerformImplicitConversion(RHS.get(), LHSType.getUnqualifiedType(),
6392 AA_Assigning);
6393 } else {
6394 ImplicitConversionSequence ICS =
6395 TryImplicitConversion(RHS.get(), LHSType.getUnqualifiedType(),
6396 /*SuppressUserConversions=*/false,
6397 /*AllowExplicit=*/false,
6398 /*InOverloadResolution=*/false,
6399 /*CStyle=*/false,
6400 /*AllowObjCWritebackConversion=*/false);
6401 if (ICS.isFailure())
6402 return Incompatible;
6403 Res = PerformImplicitConversion(RHS.get(), LHSType.getUnqualifiedType(),
6404 ICS, AA_Assigning);
6405 }
John Wiegley01296292011-04-08 18:41:53 +00006406 if (Res.isInvalid())
Douglas Gregor9a657932008-10-21 23:43:52 +00006407 return Incompatible;
Fariborz Jahanian7fcce682011-07-07 23:04:17 +00006408 Sema::AssignConvertType result = Compatible;
David Blaikiebbafb8a2012-03-11 07:00:24 +00006409 if (getLangOpts().ObjCAutoRefCount &&
Richard Trieueb299142011-09-06 20:40:12 +00006410 !CheckObjCARCUnavailableWeakConversion(LHSType,
6411 RHS.get()->getType()))
Fariborz Jahanian7fcce682011-07-07 23:04:17 +00006412 result = IncompatibleObjCWeakRef;
Benjamin Kramer62b95d82012-08-23 21:35:17 +00006413 RHS = Res;
Fariborz Jahanian7fcce682011-07-07 23:04:17 +00006414 return result;
Douglas Gregor9a657932008-10-21 23:43:52 +00006415 }
6416
6417 // FIXME: Currently, we fall through and treat C++ classes like C
6418 // structures.
Eli Friedman0dfb8892011-10-06 23:00:33 +00006419 // FIXME: We also fall through for atomics; not sure what should
6420 // happen there, though.
Sebastian Redlb49c46c2011-09-24 17:48:00 +00006421 }
Douglas Gregor9a657932008-10-21 23:43:52 +00006422
Steve Naroff0ee0b0a2007-11-27 17:58:44 +00006423 // C99 6.5.16.1p1: the left operand is a pointer and the right is
6424 // a null pointer constant.
Richard Trieueb299142011-09-06 20:40:12 +00006425 if ((LHSType->isPointerType() ||
6426 LHSType->isObjCObjectPointerType() ||
6427 LHSType->isBlockPointerType())
6428 && RHS.get()->isNullPointerConstant(Context,
6429 Expr::NPC_ValueDependentIsNull)) {
6430 RHS = ImpCastExprToType(RHS.take(), LHSType, CK_NullToPointer);
Steve Naroff0ee0b0a2007-11-27 17:58:44 +00006431 return Compatible;
6432 }
Mike Stump4e1f26a2009-02-19 03:04:26 +00006433
Chris Lattnere6dcd502007-10-16 02:55:40 +00006434 // This check seems unnatural, however it is necessary to ensure the proper
Steve Naroffb8ea4fb2007-07-13 23:32:42 +00006435 // conversion of functions/arrays. If the conversion were done for all
Douglas Gregora121b752009-11-03 16:56:39 +00006436 // DeclExpr's (created by ActOnIdExpression), it would mess up the unary
Nick Lewyckyef7c0ff2010-08-05 06:27:49 +00006437 // expressions that suppress this implicit conversion (&, sizeof).
Chris Lattnere6dcd502007-10-16 02:55:40 +00006438 //
Mike Stump4e1f26a2009-02-19 03:04:26 +00006439 // Suppress this for references: C++ 8.5.3p5.
Richard Trieueb299142011-09-06 20:40:12 +00006440 if (!LHSType->isReferenceType()) {
6441 RHS = DefaultFunctionArrayLvalueConversion(RHS.take());
6442 if (RHS.isInvalid())
John Wiegley01296292011-04-08 18:41:53 +00006443 return Incompatible;
6444 }
Steve Naroff0c1c7ed2007-08-24 22:33:52 +00006445
John McCall8cb679e2010-11-15 09:13:47 +00006446 CastKind Kind = CK_Invalid;
Chris Lattner9bad62c2008-01-04 18:04:52 +00006447 Sema::AssignConvertType result =
Richard Trieueb299142011-09-06 20:40:12 +00006448 CheckAssignmentConstraints(LHSType, RHS, Kind);
Mike Stump4e1f26a2009-02-19 03:04:26 +00006449
Steve Naroff0c1c7ed2007-08-24 22:33:52 +00006450 // C99 6.5.16.1p2: The value of the right operand is converted to the
6451 // type of the assignment expression.
Douglas Gregor6b754842008-10-28 00:22:11 +00006452 // CheckAssignmentConstraints allows the left-hand side to be a reference,
6453 // so that we can use references in built-in functions even in C.
6454 // The getNonReferenceType() call makes sure that the resulting expression
6455 // does not have reference type.
Fariborz Jahanian374089e2013-07-31 17:12:26 +00006456 if (result != Incompatible && RHS.get()->getType() != LHSType) {
6457 QualType Ty = LHSType.getNonLValueExprType(Context);
6458 Expr *E = RHS.take();
6459 if (getLangOpts().ObjCAutoRefCount)
Fariborz Jahanian25eef192013-07-31 21:40:51 +00006460 CheckObjCARCConversion(SourceRange(), Ty, E, CCK_ImplicitConversion,
6461 DiagnoseCFAudited);
Fariborz Jahanian374089e2013-07-31 17:12:26 +00006462 RHS = ImpCastExprToType(E, Ty, Kind);
6463 }
Steve Naroff0c1c7ed2007-08-24 22:33:52 +00006464 return result;
Steve Naroffb8ea4fb2007-07-13 23:32:42 +00006465}
6466
Richard Trieueb299142011-09-06 20:40:12 +00006467QualType Sema::InvalidOperands(SourceLocation Loc, ExprResult &LHS,
6468 ExprResult &RHS) {
Chris Lattner377d1f82008-11-18 22:52:51 +00006469 Diag(Loc, diag::err_typecheck_invalid_operands)
Richard Trieueb299142011-09-06 20:40:12 +00006470 << LHS.get()->getType() << RHS.get()->getType()
6471 << LHS.get()->getSourceRange() << RHS.get()->getSourceRange();
Chris Lattner5c11c412007-12-12 05:47:28 +00006472 return QualType();
Steve Naroff6f49f5d2007-05-29 14:23:36 +00006473}
6474
Richard Trieu859d23f2011-09-06 21:01:04 +00006475QualType Sema::CheckVectorOperands(ExprResult &LHS, ExprResult &RHS,
Richard Trieuba63ce62011-09-09 01:45:06 +00006476 SourceLocation Loc, bool IsCompAssign) {
Richard Smith508ebf32011-10-28 03:31:48 +00006477 if (!IsCompAssign) {
6478 LHS = DefaultFunctionArrayLvalueConversion(LHS.take());
6479 if (LHS.isInvalid())
6480 return QualType();
6481 }
6482 RHS = DefaultFunctionArrayLvalueConversion(RHS.take());
6483 if (RHS.isInvalid())
6484 return QualType();
6485
Mike Stump4e1f26a2009-02-19 03:04:26 +00006486 // For conversion purposes, we ignore any qualifiers.
Nate Begeman002e4bd2008-04-04 01:30:25 +00006487 // For example, "const float" and "float" are equivalent.
Richard Trieu859d23f2011-09-06 21:01:04 +00006488 QualType LHSType =
6489 Context.getCanonicalType(LHS.get()->getType()).getUnqualifiedType();
6490 QualType RHSType =
6491 Context.getCanonicalType(RHS.get()->getType()).getUnqualifiedType();
Mike Stump4e1f26a2009-02-19 03:04:26 +00006492
Nate Begeman191a6b12008-07-14 18:02:46 +00006493 // If the vector types are identical, return.
Richard Trieu859d23f2011-09-06 21:01:04 +00006494 if (LHSType == RHSType)
6495 return LHSType;
Nate Begeman330aaa72007-12-30 02:59:45 +00006496
Douglas Gregor59e8b3b2010-08-06 10:14:59 +00006497 // Handle the case of equivalent AltiVec and GCC vector types
Richard Trieu859d23f2011-09-06 21:01:04 +00006498 if (LHSType->isVectorType() && RHSType->isVectorType() &&
6499 Context.areCompatibleVectorTypes(LHSType, RHSType)) {
6500 if (LHSType->isExtVectorType()) {
6501 RHS = ImpCastExprToType(RHS.take(), LHSType, CK_BitCast);
6502 return LHSType;
Eli Friedman1408bc92011-06-23 18:10:35 +00006503 }
6504
Richard Trieuba63ce62011-09-09 01:45:06 +00006505 if (!IsCompAssign)
Richard Trieu859d23f2011-09-06 21:01:04 +00006506 LHS = ImpCastExprToType(LHS.take(), RHSType, CK_BitCast);
6507 return RHSType;
Douglas Gregor59e8b3b2010-08-06 10:14:59 +00006508 }
6509
David Blaikiebbafb8a2012-03-11 07:00:24 +00006510 if (getLangOpts().LaxVectorConversions &&
Richard Trieu859d23f2011-09-06 21:01:04 +00006511 Context.getTypeSize(LHSType) == Context.getTypeSize(RHSType)) {
Eli Friedman1408bc92011-06-23 18:10:35 +00006512 // If we are allowing lax vector conversions, and LHS and RHS are both
6513 // vectors, the total size only needs to be the same. This is a
6514 // bitcast; no bits are changed but the result type is different.
6515 // FIXME: Should we really be allowing this?
Richard Trieu859d23f2011-09-06 21:01:04 +00006516 RHS = ImpCastExprToType(RHS.take(), LHSType, CK_BitCast);
6517 return LHSType;
Eli Friedman1408bc92011-06-23 18:10:35 +00006518 }
6519
Nate Begemanbd956c42009-06-28 02:36:38 +00006520 // Canonicalize the ExtVector to the LHS, remember if we swapped so we can
6521 // swap back (so that we don't reverse the inputs to a subtract, for instance.
6522 bool swapped = false;
Richard Trieuba63ce62011-09-09 01:45:06 +00006523 if (RHSType->isExtVectorType() && !IsCompAssign) {
Nate Begemanbd956c42009-06-28 02:36:38 +00006524 swapped = true;
Richard Trieu859d23f2011-09-06 21:01:04 +00006525 std::swap(RHS, LHS);
6526 std::swap(RHSType, LHSType);
Nate Begemanbd956c42009-06-28 02:36:38 +00006527 }
Mike Stump11289f42009-09-09 15:08:12 +00006528
Nate Begeman886448d2009-06-28 19:12:57 +00006529 // Handle the case of an ext vector and scalar.
Richard Trieu859d23f2011-09-06 21:01:04 +00006530 if (const ExtVectorType *LV = LHSType->getAs<ExtVectorType>()) {
Nate Begemanbd956c42009-06-28 02:36:38 +00006531 QualType EltTy = LV->getElementType();
Richard Trieu859d23f2011-09-06 21:01:04 +00006532 if (EltTy->isIntegralType(Context) && RHSType->isIntegralType(Context)) {
6533 int order = Context.getIntegerTypeOrder(EltTy, RHSType);
John McCall8cb679e2010-11-15 09:13:47 +00006534 if (order > 0)
Richard Trieu859d23f2011-09-06 21:01:04 +00006535 RHS = ImpCastExprToType(RHS.take(), EltTy, CK_IntegralCast);
John McCall8cb679e2010-11-15 09:13:47 +00006536 if (order >= 0) {
Richard Trieu859d23f2011-09-06 21:01:04 +00006537 RHS = ImpCastExprToType(RHS.take(), LHSType, CK_VectorSplat);
6538 if (swapped) std::swap(RHS, LHS);
6539 return LHSType;
Nate Begemanbd956c42009-06-28 02:36:38 +00006540 }
6541 }
Jin-Gu Kang0b5ca602013-06-08 02:15:36 +00006542 if (EltTy->isRealFloatingType() && RHSType->isScalarType()) {
6543 if (RHSType->isRealFloatingType()) {
6544 int order = Context.getFloatingTypeOrder(EltTy, RHSType);
6545 if (order > 0)
6546 RHS = ImpCastExprToType(RHS.take(), EltTy, CK_FloatingCast);
6547 if (order >= 0) {
6548 RHS = ImpCastExprToType(RHS.take(), LHSType, CK_VectorSplat);
6549 if (swapped) std::swap(RHS, LHS);
6550 return LHSType;
6551 }
6552 }
6553 if (RHSType->isIntegralType(Context)) {
6554 RHS = ImpCastExprToType(RHS.take(), EltTy, CK_IntegralToFloating);
Richard Trieu859d23f2011-09-06 21:01:04 +00006555 RHS = ImpCastExprToType(RHS.take(), LHSType, CK_VectorSplat);
6556 if (swapped) std::swap(RHS, LHS);
6557 return LHSType;
Nate Begemanbd956c42009-06-28 02:36:38 +00006558 }
Nate Begeman330aaa72007-12-30 02:59:45 +00006559 }
6560 }
Mike Stump11289f42009-09-09 15:08:12 +00006561
Nate Begeman886448d2009-06-28 19:12:57 +00006562 // Vectors of different size or scalar and non-ext-vector are errors.
Richard Trieu859d23f2011-09-06 21:01:04 +00006563 if (swapped) std::swap(RHS, LHS);
Chris Lattner377d1f82008-11-18 22:52:51 +00006564 Diag(Loc, diag::err_typecheck_vector_not_convertable)
Richard Trieu859d23f2011-09-06 21:01:04 +00006565 << LHS.get()->getType() << RHS.get()->getType()
6566 << LHS.get()->getSourceRange() << RHS.get()->getSourceRange();
Steve Naroff84ff4b42007-07-09 21:31:10 +00006567 return QualType();
Sebastian Redl112a97662009-02-07 00:15:38 +00006568}
6569
Richard Trieuf8916e12011-09-16 00:53:10 +00006570// checkArithmeticNull - Detect when a NULL constant is used improperly in an
6571// expression. These are mainly cases where the null pointer is used as an
6572// integer instead of a pointer.
6573static void checkArithmeticNull(Sema &S, ExprResult &LHS, ExprResult &RHS,
6574 SourceLocation Loc, bool IsCompare) {
6575 // The canonical way to check for a GNU null is with isNullPointerConstant,
6576 // but we use a bit of a hack here for speed; this is a relatively
6577 // hot path, and isNullPointerConstant is slow.
6578 bool LHSNull = isa<GNUNullExpr>(LHS.get()->IgnoreParenImpCasts());
6579 bool RHSNull = isa<GNUNullExpr>(RHS.get()->IgnoreParenImpCasts());
6580
6581 QualType NonNullType = LHSNull ? RHS.get()->getType() : LHS.get()->getType();
6582
6583 // Avoid analyzing cases where the result will either be invalid (and
6584 // diagnosed as such) or entirely valid and not something to warn about.
6585 if ((!LHSNull && !RHSNull) || NonNullType->isBlockPointerType() ||
6586 NonNullType->isMemberPointerType() || NonNullType->isFunctionType())
6587 return;
6588
6589 // Comparison operations would not make sense with a null pointer no matter
6590 // what the other expression is.
6591 if (!IsCompare) {
6592 S.Diag(Loc, diag::warn_null_in_arithmetic_operation)
6593 << (LHSNull ? LHS.get()->getSourceRange() : SourceRange())
6594 << (RHSNull ? RHS.get()->getSourceRange() : SourceRange());
6595 return;
6596 }
6597
6598 // The rest of the operations only make sense with a null pointer
6599 // if the other expression is a pointer.
6600 if (LHSNull == RHSNull || NonNullType->isAnyPointerType() ||
6601 NonNullType->canDecayToPointerType())
6602 return;
6603
6604 S.Diag(Loc, diag::warn_null_in_comparison_operation)
6605 << LHSNull /* LHS is NULL */ << NonNullType
6606 << LHS.get()->getSourceRange() << RHS.get()->getSourceRange();
6607}
6608
Richard Trieu859d23f2011-09-06 21:01:04 +00006609QualType Sema::CheckMultiplyDivideOperands(ExprResult &LHS, ExprResult &RHS,
Richard Trieucfc491d2011-08-02 04:35:43 +00006610 SourceLocation Loc,
Richard Trieuba63ce62011-09-09 01:45:06 +00006611 bool IsCompAssign, bool IsDiv) {
Richard Trieuf8916e12011-09-16 00:53:10 +00006612 checkArithmeticNull(*this, LHS, RHS, Loc, /*isCompare=*/false);
6613
Richard Trieu859d23f2011-09-06 21:01:04 +00006614 if (LHS.get()->getType()->isVectorType() ||
6615 RHS.get()->getType()->isVectorType())
Richard Trieuba63ce62011-09-09 01:45:06 +00006616 return CheckVectorOperands(LHS, RHS, Loc, IsCompAssign);
Mike Stump4e1f26a2009-02-19 03:04:26 +00006617
Richard Trieuba63ce62011-09-09 01:45:06 +00006618 QualType compType = UsualArithmeticConversions(LHS, RHS, IsCompAssign);
Richard Trieu859d23f2011-09-06 21:01:04 +00006619 if (LHS.isInvalid() || RHS.isInvalid())
John Wiegley01296292011-04-08 18:41:53 +00006620 return QualType();
Mike Stump4e1f26a2009-02-19 03:04:26 +00006621
David Chisnallfa35df62012-01-16 17:27:18 +00006622
Eli Friedman93ee5ca2012-06-16 02:19:17 +00006623 if (compType.isNull() || !compType->isArithmeticType())
Richard Trieu859d23f2011-09-06 21:01:04 +00006624 return InvalidOperands(Loc, LHS, RHS);
Kovarththanan Rajaratnamba2c6522010-03-13 10:17:05 +00006625
Chris Lattnerfaa54172010-01-12 21:23:57 +00006626 // Check for division by zero.
Chandler Carruthc41c8b32013-06-14 08:57:18 +00006627 llvm::APSInt RHSValue;
6628 if (IsDiv && !RHS.get()->isValueDependent() &&
6629 RHS.get()->EvaluateAsInt(RHSValue, Context) && RHSValue == 0)
6630 DiagRuntimeBehavior(Loc, RHS.get(),
6631 PDiag(diag::warn_division_by_zero)
6632 << RHS.get()->getSourceRange());
Kovarththanan Rajaratnamba2c6522010-03-13 10:17:05 +00006633
Chris Lattnerfaa54172010-01-12 21:23:57 +00006634 return compType;
Steve Naroff26c8ea52007-03-21 21:08:52 +00006635}
6636
Chris Lattnerfaa54172010-01-12 21:23:57 +00006637QualType Sema::CheckRemainderOperands(
Richard Trieuba63ce62011-09-09 01:45:06 +00006638 ExprResult &LHS, ExprResult &RHS, SourceLocation Loc, bool IsCompAssign) {
Richard Trieuf8916e12011-09-16 00:53:10 +00006639 checkArithmeticNull(*this, LHS, RHS, Loc, /*isCompare=*/false);
6640
Richard Trieu859d23f2011-09-06 21:01:04 +00006641 if (LHS.get()->getType()->isVectorType() ||
6642 RHS.get()->getType()->isVectorType()) {
6643 if (LHS.get()->getType()->hasIntegerRepresentation() &&
6644 RHS.get()->getType()->hasIntegerRepresentation())
Richard Trieuba63ce62011-09-09 01:45:06 +00006645 return CheckVectorOperands(LHS, RHS, Loc, IsCompAssign);
Richard Trieu859d23f2011-09-06 21:01:04 +00006646 return InvalidOperands(Loc, LHS, RHS);
Daniel Dunbar0d2bfec2009-01-05 22:55:36 +00006647 }
Steve Naroffb8ea4fb2007-07-13 23:32:42 +00006648
Richard Trieuba63ce62011-09-09 01:45:06 +00006649 QualType compType = UsualArithmeticConversions(LHS, RHS, IsCompAssign);
Richard Trieu859d23f2011-09-06 21:01:04 +00006650 if (LHS.isInvalid() || RHS.isInvalid())
John Wiegley01296292011-04-08 18:41:53 +00006651 return QualType();
Mike Stump4e1f26a2009-02-19 03:04:26 +00006652
Eli Friedman93ee5ca2012-06-16 02:19:17 +00006653 if (compType.isNull() || !compType->isIntegerType())
Richard Trieu859d23f2011-09-06 21:01:04 +00006654 return InvalidOperands(Loc, LHS, RHS);
Kovarththanan Rajaratnamba2c6522010-03-13 10:17:05 +00006655
Chris Lattnerfaa54172010-01-12 21:23:57 +00006656 // Check for remainder by zero.
Chandler Carruthc41c8b32013-06-14 08:57:18 +00006657 llvm::APSInt RHSValue;
6658 if (!RHS.get()->isValueDependent() &&
6659 RHS.get()->EvaluateAsInt(RHSValue, Context) && RHSValue == 0)
6660 DiagRuntimeBehavior(Loc, RHS.get(),
6661 PDiag(diag::warn_remainder_by_zero)
6662 << RHS.get()->getSourceRange());
Kovarththanan Rajaratnamba2c6522010-03-13 10:17:05 +00006663
Chris Lattnerfaa54172010-01-12 21:23:57 +00006664 return compType;
Steve Naroff218bc2b2007-05-04 21:54:46 +00006665}
6666
Chandler Carruthc9332212011-06-27 08:02:19 +00006667/// \brief Diagnose invalid arithmetic on two void pointers.
6668static void diagnoseArithmeticOnTwoVoidPointers(Sema &S, SourceLocation Loc,
Richard Trieu4ae7e972011-09-06 21:13:51 +00006669 Expr *LHSExpr, Expr *RHSExpr) {
David Blaikiebbafb8a2012-03-11 07:00:24 +00006670 S.Diag(Loc, S.getLangOpts().CPlusPlus
Chandler Carruthc9332212011-06-27 08:02:19 +00006671 ? diag::err_typecheck_pointer_arith_void_type
6672 : diag::ext_gnu_void_ptr)
Richard Trieu4ae7e972011-09-06 21:13:51 +00006673 << 1 /* two pointers */ << LHSExpr->getSourceRange()
6674 << RHSExpr->getSourceRange();
Chandler Carruthc9332212011-06-27 08:02:19 +00006675}
6676
6677/// \brief Diagnose invalid arithmetic on a void pointer.
6678static void diagnoseArithmeticOnVoidPointer(Sema &S, SourceLocation Loc,
6679 Expr *Pointer) {
David Blaikiebbafb8a2012-03-11 07:00:24 +00006680 S.Diag(Loc, S.getLangOpts().CPlusPlus
Chandler Carruthc9332212011-06-27 08:02:19 +00006681 ? diag::err_typecheck_pointer_arith_void_type
6682 : diag::ext_gnu_void_ptr)
6683 << 0 /* one pointer */ << Pointer->getSourceRange();
6684}
6685
6686/// \brief Diagnose invalid arithmetic on two function pointers.
6687static void diagnoseArithmeticOnTwoFunctionPointers(Sema &S, SourceLocation Loc,
6688 Expr *LHS, Expr *RHS) {
6689 assert(LHS->getType()->isAnyPointerType());
6690 assert(RHS->getType()->isAnyPointerType());
David Blaikiebbafb8a2012-03-11 07:00:24 +00006691 S.Diag(Loc, S.getLangOpts().CPlusPlus
Chandler Carruthc9332212011-06-27 08:02:19 +00006692 ? diag::err_typecheck_pointer_arith_function_type
6693 : diag::ext_gnu_ptr_func_arith)
6694 << 1 /* two pointers */ << LHS->getType()->getPointeeType()
6695 // We only show the second type if it differs from the first.
6696 << (unsigned)!S.Context.hasSameUnqualifiedType(LHS->getType(),
6697 RHS->getType())
6698 << RHS->getType()->getPointeeType()
6699 << LHS->getSourceRange() << RHS->getSourceRange();
6700}
6701
6702/// \brief Diagnose invalid arithmetic on a function pointer.
6703static void diagnoseArithmeticOnFunctionPointer(Sema &S, SourceLocation Loc,
6704 Expr *Pointer) {
6705 assert(Pointer->getType()->isAnyPointerType());
David Blaikiebbafb8a2012-03-11 07:00:24 +00006706 S.Diag(Loc, S.getLangOpts().CPlusPlus
Chandler Carruthc9332212011-06-27 08:02:19 +00006707 ? diag::err_typecheck_pointer_arith_function_type
6708 : diag::ext_gnu_ptr_func_arith)
6709 << 0 /* one pointer */ << Pointer->getType()->getPointeeType()
6710 << 0 /* one pointer, so only one type */
6711 << Pointer->getSourceRange();
6712}
6713
Richard Trieu993f3ab2011-09-12 18:08:02 +00006714/// \brief Emit error if Operand is incomplete pointer type
Richard Trieuaba22802011-09-02 02:15:37 +00006715///
6716/// \returns True if pointer has incomplete type
6717static bool checkArithmeticIncompletePointerType(Sema &S, SourceLocation Loc,
6718 Expr *Operand) {
John McCallf2538342012-07-31 05:14:30 +00006719 assert(Operand->getType()->isAnyPointerType() &&
6720 !Operand->getType()->isDependentType());
6721 QualType PointeeTy = Operand->getType()->getPointeeType();
6722 return S.RequireCompleteType(Loc, PointeeTy,
6723 diag::err_typecheck_arithmetic_incomplete_type,
6724 PointeeTy, Operand->getSourceRange());
Richard Trieuaba22802011-09-02 02:15:37 +00006725}
6726
Chandler Carruthc9332212011-06-27 08:02:19 +00006727/// \brief Check the validity of an arithmetic pointer operand.
6728///
6729/// If the operand has pointer type, this code will check for pointer types
6730/// which are invalid in arithmetic operations. These will be diagnosed
6731/// appropriately, including whether or not the use is supported as an
6732/// extension.
6733///
6734/// \returns True when the operand is valid to use (even if as an extension).
6735static bool checkArithmeticOpPointerOperand(Sema &S, SourceLocation Loc,
6736 Expr *Operand) {
6737 if (!Operand->getType()->isAnyPointerType()) return true;
6738
6739 QualType PointeeTy = Operand->getType()->getPointeeType();
6740 if (PointeeTy->isVoidType()) {
6741 diagnoseArithmeticOnVoidPointer(S, Loc, Operand);
David Blaikiebbafb8a2012-03-11 07:00:24 +00006742 return !S.getLangOpts().CPlusPlus;
Chandler Carruthc9332212011-06-27 08:02:19 +00006743 }
6744 if (PointeeTy->isFunctionType()) {
6745 diagnoseArithmeticOnFunctionPointer(S, Loc, Operand);
David Blaikiebbafb8a2012-03-11 07:00:24 +00006746 return !S.getLangOpts().CPlusPlus;
Chandler Carruthc9332212011-06-27 08:02:19 +00006747 }
6748
Richard Trieuaba22802011-09-02 02:15:37 +00006749 if (checkArithmeticIncompletePointerType(S, Loc, Operand)) return false;
Chandler Carruthc9332212011-06-27 08:02:19 +00006750
6751 return true;
6752}
6753
6754/// \brief Check the validity of a binary arithmetic operation w.r.t. pointer
6755/// operands.
6756///
6757/// This routine will diagnose any invalid arithmetic on pointer operands much
6758/// like \see checkArithmeticOpPointerOperand. However, it has special logic
6759/// for emitting a single diagnostic even for operations where both LHS and RHS
6760/// are (potentially problematic) pointers.
6761///
6762/// \returns True when the operand is valid to use (even if as an extension).
6763static bool checkArithmeticBinOpPointerOperands(Sema &S, SourceLocation Loc,
Richard Trieu4ae7e972011-09-06 21:13:51 +00006764 Expr *LHSExpr, Expr *RHSExpr) {
6765 bool isLHSPointer = LHSExpr->getType()->isAnyPointerType();
6766 bool isRHSPointer = RHSExpr->getType()->isAnyPointerType();
Chandler Carruthc9332212011-06-27 08:02:19 +00006767 if (!isLHSPointer && !isRHSPointer) return true;
6768
6769 QualType LHSPointeeTy, RHSPointeeTy;
Richard Trieu4ae7e972011-09-06 21:13:51 +00006770 if (isLHSPointer) LHSPointeeTy = LHSExpr->getType()->getPointeeType();
6771 if (isRHSPointer) RHSPointeeTy = RHSExpr->getType()->getPointeeType();
Chandler Carruthc9332212011-06-27 08:02:19 +00006772
6773 // Check for arithmetic on pointers to incomplete types.
6774 bool isLHSVoidPtr = isLHSPointer && LHSPointeeTy->isVoidType();
6775 bool isRHSVoidPtr = isRHSPointer && RHSPointeeTy->isVoidType();
6776 if (isLHSVoidPtr || isRHSVoidPtr) {
Richard Trieu4ae7e972011-09-06 21:13:51 +00006777 if (!isRHSVoidPtr) diagnoseArithmeticOnVoidPointer(S, Loc, LHSExpr);
6778 else if (!isLHSVoidPtr) diagnoseArithmeticOnVoidPointer(S, Loc, RHSExpr);
6779 else diagnoseArithmeticOnTwoVoidPointers(S, Loc, LHSExpr, RHSExpr);
Chandler Carruthc9332212011-06-27 08:02:19 +00006780
David Blaikiebbafb8a2012-03-11 07:00:24 +00006781 return !S.getLangOpts().CPlusPlus;
Chandler Carruthc9332212011-06-27 08:02:19 +00006782 }
6783
6784 bool isLHSFuncPtr = isLHSPointer && LHSPointeeTy->isFunctionType();
6785 bool isRHSFuncPtr = isRHSPointer && RHSPointeeTy->isFunctionType();
6786 if (isLHSFuncPtr || isRHSFuncPtr) {
Richard Trieu4ae7e972011-09-06 21:13:51 +00006787 if (!isRHSFuncPtr) diagnoseArithmeticOnFunctionPointer(S, Loc, LHSExpr);
6788 else if (!isLHSFuncPtr) diagnoseArithmeticOnFunctionPointer(S, Loc,
6789 RHSExpr);
6790 else diagnoseArithmeticOnTwoFunctionPointers(S, Loc, LHSExpr, RHSExpr);
Chandler Carruthc9332212011-06-27 08:02:19 +00006791
David Blaikiebbafb8a2012-03-11 07:00:24 +00006792 return !S.getLangOpts().CPlusPlus;
Chandler Carruthc9332212011-06-27 08:02:19 +00006793 }
6794
John McCallf2538342012-07-31 05:14:30 +00006795 if (isLHSPointer && checkArithmeticIncompletePointerType(S, Loc, LHSExpr))
6796 return false;
6797 if (isRHSPointer && checkArithmeticIncompletePointerType(S, Loc, RHSExpr))
6798 return false;
Richard Trieuaba22802011-09-02 02:15:37 +00006799
Chandler Carruthc9332212011-06-27 08:02:19 +00006800 return true;
6801}
6802
Nico Weberccec40d2012-03-02 22:01:22 +00006803/// diagnoseStringPlusInt - Emit a warning when adding an integer to a string
6804/// literal.
6805static void diagnoseStringPlusInt(Sema &Self, SourceLocation OpLoc,
6806 Expr *LHSExpr, Expr *RHSExpr) {
6807 StringLiteral* StrExpr = dyn_cast<StringLiteral>(LHSExpr->IgnoreImpCasts());
6808 Expr* IndexExpr = RHSExpr;
6809 if (!StrExpr) {
6810 StrExpr = dyn_cast<StringLiteral>(RHSExpr->IgnoreImpCasts());
6811 IndexExpr = LHSExpr;
6812 }
6813
6814 bool IsStringPlusInt = StrExpr &&
6815 IndexExpr->getType()->isIntegralOrUnscopedEnumerationType();
6816 if (!IsStringPlusInt)
6817 return;
6818
6819 llvm::APSInt index;
6820 if (IndexExpr->EvaluateAsInt(index, Self.getASTContext())) {
6821 unsigned StrLenWithNull = StrExpr->getLength() + 1;
6822 if (index.isNonNegative() &&
6823 index <= llvm::APSInt(llvm::APInt(index.getBitWidth(), StrLenWithNull),
6824 index.isUnsigned()))
6825 return;
6826 }
6827
6828 SourceRange DiagRange(LHSExpr->getLocStart(), RHSExpr->getLocEnd());
6829 Self.Diag(OpLoc, diag::warn_string_plus_int)
6830 << DiagRange << IndexExpr->IgnoreImpCasts()->getType();
6831
6832 // Only print a fixit for "str" + int, not for int + "str".
6833 if (IndexExpr == RHSExpr) {
6834 SourceLocation EndLoc = Self.PP.getLocForEndOfToken(RHSExpr->getLocEnd());
6835 Self.Diag(OpLoc, diag::note_string_plus_int_silence)
6836 << FixItHint::CreateInsertion(LHSExpr->getLocStart(), "&")
6837 << FixItHint::CreateReplacement(SourceRange(OpLoc), "[")
6838 << FixItHint::CreateInsertion(EndLoc, "]");
6839 } else
6840 Self.Diag(OpLoc, diag::note_string_plus_int_silence);
6841}
6842
Richard Trieu993f3ab2011-09-12 18:08:02 +00006843/// \brief Emit error when two pointers are incompatible.
Richard Trieub10c6312011-09-01 22:53:23 +00006844static void diagnosePointerIncompatibility(Sema &S, SourceLocation Loc,
Richard Trieu4ae7e972011-09-06 21:13:51 +00006845 Expr *LHSExpr, Expr *RHSExpr) {
6846 assert(LHSExpr->getType()->isAnyPointerType());
6847 assert(RHSExpr->getType()->isAnyPointerType());
Richard Trieub10c6312011-09-01 22:53:23 +00006848 S.Diag(Loc, diag::err_typecheck_sub_ptr_compatible)
Richard Trieu4ae7e972011-09-06 21:13:51 +00006849 << LHSExpr->getType() << RHSExpr->getType() << LHSExpr->getSourceRange()
6850 << RHSExpr->getSourceRange();
Richard Trieub10c6312011-09-01 22:53:23 +00006851}
6852
Chris Lattnerfaa54172010-01-12 21:23:57 +00006853QualType Sema::CheckAdditionOperands( // C99 6.5.6
Nico Weberccec40d2012-03-02 22:01:22 +00006854 ExprResult &LHS, ExprResult &RHS, SourceLocation Loc, unsigned Opc,
6855 QualType* CompLHSTy) {
Richard Trieuf8916e12011-09-16 00:53:10 +00006856 checkArithmeticNull(*this, LHS, RHS, Loc, /*isCompare=*/false);
6857
Richard Trieu4ae7e972011-09-06 21:13:51 +00006858 if (LHS.get()->getType()->isVectorType() ||
6859 RHS.get()->getType()->isVectorType()) {
6860 QualType compType = CheckVectorOperands(LHS, RHS, Loc, CompLHSTy);
Eli Friedman8b7b1b12009-03-28 01:22:36 +00006861 if (CompLHSTy) *CompLHSTy = compType;
6862 return compType;
6863 }
Steve Naroff7a5af782007-07-13 16:58:59 +00006864
Richard Trieu4ae7e972011-09-06 21:13:51 +00006865 QualType compType = UsualArithmeticConversions(LHS, RHS, CompLHSTy);
6866 if (LHS.isInvalid() || RHS.isInvalid())
John Wiegley01296292011-04-08 18:41:53 +00006867 return QualType();
Eli Friedman8e122982008-05-18 18:08:51 +00006868
Nico Weberccec40d2012-03-02 22:01:22 +00006869 // Diagnose "string literal" '+' int.
6870 if (Opc == BO_Add)
6871 diagnoseStringPlusInt(*this, Loc, LHS.get(), RHS.get());
6872
Steve Naroffe4718892007-04-27 18:30:00 +00006873 // handle the common case first (both operands are arithmetic).
Eli Friedman93ee5ca2012-06-16 02:19:17 +00006874 if (!compType.isNull() && compType->isArithmeticType()) {
Eli Friedman8b7b1b12009-03-28 01:22:36 +00006875 if (CompLHSTy) *CompLHSTy = compType;
Steve Naroffbe4c4d12007-08-24 19:07:16 +00006876 return compType;
Eli Friedman8b7b1b12009-03-28 01:22:36 +00006877 }
Steve Naroff218bc2b2007-05-04 21:54:46 +00006878
John McCallf2538342012-07-31 05:14:30 +00006879 // Type-checking. Ultimately the pointer's going to be in PExp;
6880 // note that we bias towards the LHS being the pointer.
6881 Expr *PExp = LHS.get(), *IExp = RHS.get();
Eli Friedman8e122982008-05-18 18:08:51 +00006882
John McCallf2538342012-07-31 05:14:30 +00006883 bool isObjCPointer;
6884 if (PExp->getType()->isPointerType()) {
6885 isObjCPointer = false;
6886 } else if (PExp->getType()->isObjCObjectPointerType()) {
6887 isObjCPointer = true;
6888 } else {
6889 std::swap(PExp, IExp);
6890 if (PExp->getType()->isPointerType()) {
6891 isObjCPointer = false;
6892 } else if (PExp->getType()->isObjCObjectPointerType()) {
6893 isObjCPointer = true;
6894 } else {
6895 return InvalidOperands(Loc, LHS, RHS);
6896 }
6897 }
6898 assert(PExp->getType()->isAnyPointerType());
Chandler Carruthc9332212011-06-27 08:02:19 +00006899
Richard Trieub420bca2011-09-12 18:37:54 +00006900 if (!IExp->getType()->isIntegerType())
6901 return InvalidOperands(Loc, LHS, RHS);
Mike Stump11289f42009-09-09 15:08:12 +00006902
Richard Trieub420bca2011-09-12 18:37:54 +00006903 if (!checkArithmeticOpPointerOperand(*this, Loc, PExp))
6904 return QualType();
Kaelyn Uhrain2e7aa5a2011-08-05 23:18:04 +00006905
John McCallf2538342012-07-31 05:14:30 +00006906 if (isObjCPointer && checkArithmeticOnObjCPointer(*this, Loc, PExp))
Richard Trieub420bca2011-09-12 18:37:54 +00006907 return QualType();
6908
6909 // Check array bounds for pointer arithemtic
6910 CheckArrayAccess(PExp, IExp);
6911
6912 if (CompLHSTy) {
6913 QualType LHSTy = Context.isPromotableBitField(LHS.get());
6914 if (LHSTy.isNull()) {
6915 LHSTy = LHS.get()->getType();
6916 if (LHSTy->isPromotableIntegerType())
6917 LHSTy = Context.getPromotedIntegerType(LHSTy);
Eli Friedman8e122982008-05-18 18:08:51 +00006918 }
Richard Trieub420bca2011-09-12 18:37:54 +00006919 *CompLHSTy = LHSTy;
Eli Friedman8e122982008-05-18 18:08:51 +00006920 }
6921
Richard Trieub420bca2011-09-12 18:37:54 +00006922 return PExp->getType();
Steve Naroff26c8ea52007-03-21 21:08:52 +00006923}
6924
Chris Lattner2a3569b2008-04-07 05:30:13 +00006925// C99 6.5.6
Richard Trieu4ae7e972011-09-06 21:13:51 +00006926QualType Sema::CheckSubtractionOperands(ExprResult &LHS, ExprResult &RHS,
Richard Trieucfc491d2011-08-02 04:35:43 +00006927 SourceLocation Loc,
6928 QualType* CompLHSTy) {
Richard Trieuf8916e12011-09-16 00:53:10 +00006929 checkArithmeticNull(*this, LHS, RHS, Loc, /*isCompare=*/false);
6930
Richard Trieu4ae7e972011-09-06 21:13:51 +00006931 if (LHS.get()->getType()->isVectorType() ||
6932 RHS.get()->getType()->isVectorType()) {
6933 QualType compType = CheckVectorOperands(LHS, RHS, Loc, CompLHSTy);
Eli Friedman8b7b1b12009-03-28 01:22:36 +00006934 if (CompLHSTy) *CompLHSTy = compType;
6935 return compType;
6936 }
Mike Stump4e1f26a2009-02-19 03:04:26 +00006937
Richard Trieu4ae7e972011-09-06 21:13:51 +00006938 QualType compType = UsualArithmeticConversions(LHS, RHS, CompLHSTy);
6939 if (LHS.isInvalid() || RHS.isInvalid())
John Wiegley01296292011-04-08 18:41:53 +00006940 return QualType();
Mike Stump4e1f26a2009-02-19 03:04:26 +00006941
Chris Lattner4d62f422007-12-09 21:53:25 +00006942 // Enforce type constraints: C99 6.5.6p3.
Mike Stump4e1f26a2009-02-19 03:04:26 +00006943
Chris Lattner4d62f422007-12-09 21:53:25 +00006944 // Handle the common case first (both operands are arithmetic).
Eli Friedman93ee5ca2012-06-16 02:19:17 +00006945 if (!compType.isNull() && compType->isArithmeticType()) {
Eli Friedman8b7b1b12009-03-28 01:22:36 +00006946 if (CompLHSTy) *CompLHSTy = compType;
Steve Naroffbe4c4d12007-08-24 19:07:16 +00006947 return compType;
Eli Friedman8b7b1b12009-03-28 01:22:36 +00006948 }
Mike Stump11289f42009-09-09 15:08:12 +00006949
Chris Lattner4d62f422007-12-09 21:53:25 +00006950 // Either ptr - int or ptr - ptr.
Richard Trieu4ae7e972011-09-06 21:13:51 +00006951 if (LHS.get()->getType()->isAnyPointerType()) {
6952 QualType lpointee = LHS.get()->getType()->getPointeeType();
Mike Stump4e1f26a2009-02-19 03:04:26 +00006953
Chris Lattner12bdebb2009-04-24 23:50:08 +00006954 // Diagnose bad cases where we step over interface counts.
John McCallf2538342012-07-31 05:14:30 +00006955 if (LHS.get()->getType()->isObjCObjectPointerType() &&
6956 checkArithmeticOnObjCPointer(*this, Loc, LHS.get()))
Chris Lattner12bdebb2009-04-24 23:50:08 +00006957 return QualType();
Mike Stump11289f42009-09-09 15:08:12 +00006958
Chris Lattner4d62f422007-12-09 21:53:25 +00006959 // The result type of a pointer-int computation is the pointer type.
Richard Trieu4ae7e972011-09-06 21:13:51 +00006960 if (RHS.get()->getType()->isIntegerType()) {
6961 if (!checkArithmeticOpPointerOperand(*this, Loc, LHS.get()))
Chandler Carruthc9332212011-06-27 08:02:19 +00006962 return QualType();
Douglas Gregorac1fb652009-03-24 19:52:54 +00006963
Kaelyn Uhrain2e7aa5a2011-08-05 23:18:04 +00006964 // Check array bounds for pointer arithemtic
Richard Smith13f67182011-12-16 19:31:14 +00006965 CheckArrayAccess(LHS.get(), RHS.get(), /*ArraySubscriptExpr*/0,
6966 /*AllowOnePastEnd*/true, /*IndexNegated*/true);
Kaelyn Uhrain2e7aa5a2011-08-05 23:18:04 +00006967
Richard Trieu4ae7e972011-09-06 21:13:51 +00006968 if (CompLHSTy) *CompLHSTy = LHS.get()->getType();
6969 return LHS.get()->getType();
Douglas Gregorac1fb652009-03-24 19:52:54 +00006970 }
Mike Stump4e1f26a2009-02-19 03:04:26 +00006971
Chris Lattner4d62f422007-12-09 21:53:25 +00006972 // Handle pointer-pointer subtractions.
Richard Trieucfc491d2011-08-02 04:35:43 +00006973 if (const PointerType *RHSPTy
Richard Trieu4ae7e972011-09-06 21:13:51 +00006974 = RHS.get()->getType()->getAs<PointerType>()) {
Eli Friedman1974e532008-02-08 01:19:44 +00006975 QualType rpointee = RHSPTy->getPointeeType();
Mike Stump4e1f26a2009-02-19 03:04:26 +00006976
David Blaikiebbafb8a2012-03-11 07:00:24 +00006977 if (getLangOpts().CPlusPlus) {
Eli Friedman168fe152009-05-16 13:54:38 +00006978 // Pointee types must be the same: C++ [expr.add]
6979 if (!Context.hasSameUnqualifiedType(lpointee, rpointee)) {
Richard Trieu4ae7e972011-09-06 21:13:51 +00006980 diagnosePointerIncompatibility(*this, Loc, LHS.get(), RHS.get());
Eli Friedman168fe152009-05-16 13:54:38 +00006981 }
6982 } else {
6983 // Pointee types must be compatible C99 6.5.6p3
6984 if (!Context.typesAreCompatible(
6985 Context.getCanonicalType(lpointee).getUnqualifiedType(),
6986 Context.getCanonicalType(rpointee).getUnqualifiedType())) {
Richard Trieu4ae7e972011-09-06 21:13:51 +00006987 diagnosePointerIncompatibility(*this, Loc, LHS.get(), RHS.get());
Eli Friedman168fe152009-05-16 13:54:38 +00006988 return QualType();
6989 }
Chris Lattner4d62f422007-12-09 21:53:25 +00006990 }
Mike Stump4e1f26a2009-02-19 03:04:26 +00006991
Chandler Carruthc9332212011-06-27 08:02:19 +00006992 if (!checkArithmeticBinOpPointerOperands(*this, Loc,
Richard Trieu4ae7e972011-09-06 21:13:51 +00006993 LHS.get(), RHS.get()))
Chandler Carruthc9332212011-06-27 08:02:19 +00006994 return QualType();
Eli Friedman8b7b1b12009-03-28 01:22:36 +00006995
Richard Trieu4ae7e972011-09-06 21:13:51 +00006996 if (CompLHSTy) *CompLHSTy = LHS.get()->getType();
Chris Lattner4d62f422007-12-09 21:53:25 +00006997 return Context.getPointerDiffType();
6998 }
6999 }
Mike Stump4e1f26a2009-02-19 03:04:26 +00007000
Richard Trieu4ae7e972011-09-06 21:13:51 +00007001 return InvalidOperands(Loc, LHS, RHS);
Steve Naroff218bc2b2007-05-04 21:54:46 +00007002}
7003
Douglas Gregor0bf31402010-10-08 23:50:27 +00007004static bool isScopedEnumerationType(QualType T) {
7005 if (const EnumType *ET = dyn_cast<EnumType>(T))
7006 return ET->getDecl()->isScoped();
7007 return false;
7008}
7009
Richard Trieue4a19fb2011-09-06 21:21:28 +00007010static void DiagnoseBadShiftValues(Sema& S, ExprResult &LHS, ExprResult &RHS,
Chandler Carruth4c6fdca2011-02-23 23:34:11 +00007011 SourceLocation Loc, unsigned Opc,
Richard Trieue4a19fb2011-09-06 21:21:28 +00007012 QualType LHSType) {
David Tweed042e0882013-01-07 16:43:27 +00007013 // OpenCL 6.3j: shift values are effectively % word size of LHS (more defined),
7014 // so skip remaining warnings as we don't want to modify values within Sema.
7015 if (S.getLangOpts().OpenCL)
7016 return;
7017
Chandler Carruth4c6fdca2011-02-23 23:34:11 +00007018 llvm::APSInt Right;
7019 // Check right/shifter operand
Richard Trieue4a19fb2011-09-06 21:21:28 +00007020 if (RHS.get()->isValueDependent() ||
7021 !RHS.get()->isIntegerConstantExpr(Right, S.Context))
Chandler Carruth4c6fdca2011-02-23 23:34:11 +00007022 return;
7023
7024 if (Right.isNegative()) {
Richard Trieue4a19fb2011-09-06 21:21:28 +00007025 S.DiagRuntimeBehavior(Loc, RHS.get(),
Ted Kremenek63657fe2011-03-01 18:09:31 +00007026 S.PDiag(diag::warn_shift_negative)
Richard Trieue4a19fb2011-09-06 21:21:28 +00007027 << RHS.get()->getSourceRange());
Chandler Carruth4c6fdca2011-02-23 23:34:11 +00007028 return;
7029 }
7030 llvm::APInt LeftBits(Right.getBitWidth(),
Richard Trieue4a19fb2011-09-06 21:21:28 +00007031 S.Context.getTypeSize(LHS.get()->getType()));
Chandler Carruth4c6fdca2011-02-23 23:34:11 +00007032 if (Right.uge(LeftBits)) {
Richard Trieue4a19fb2011-09-06 21:21:28 +00007033 S.DiagRuntimeBehavior(Loc, RHS.get(),
Ted Kremenek26bbc3d2011-03-01 19:13:22 +00007034 S.PDiag(diag::warn_shift_gt_typewidth)
Richard Trieue4a19fb2011-09-06 21:21:28 +00007035 << RHS.get()->getSourceRange());
Chandler Carruth4c6fdca2011-02-23 23:34:11 +00007036 return;
7037 }
7038 if (Opc != BO_Shl)
7039 return;
7040
7041 // When left shifting an ICE which is signed, we can check for overflow which
7042 // according to C++ has undefined behavior ([expr.shift] 5.8/2). Unsigned
7043 // integers have defined behavior modulo one more than the maximum value
7044 // representable in the result type, so never warn for those.
7045 llvm::APSInt Left;
Richard Trieue4a19fb2011-09-06 21:21:28 +00007046 if (LHS.get()->isValueDependent() ||
7047 !LHS.get()->isIntegerConstantExpr(Left, S.Context) ||
7048 LHSType->hasUnsignedIntegerRepresentation())
Chandler Carruth4c6fdca2011-02-23 23:34:11 +00007049 return;
7050 llvm::APInt ResultBits =
7051 static_cast<llvm::APInt&>(Right) + Left.getMinSignedBits();
7052 if (LeftBits.uge(ResultBits))
7053 return;
7054 llvm::APSInt Result = Left.extend(ResultBits.getLimitedValue());
7055 Result = Result.shl(Right);
7056
Ted Kremenek70f05fd2011-06-15 00:54:52 +00007057 // Print the bit representation of the signed integer as an unsigned
7058 // hexadecimal number.
Dylan Noblesmith2c1dd272012-02-05 02:13:05 +00007059 SmallString<40> HexResult;
Ted Kremenek70f05fd2011-06-15 00:54:52 +00007060 Result.toString(HexResult, 16, /*Signed =*/false, /*Literal =*/true);
7061
Chandler Carruth4c6fdca2011-02-23 23:34:11 +00007062 // If we are only missing a sign bit, this is less likely to result in actual
7063 // bugs -- if the result is cast back to an unsigned type, it will have the
7064 // expected value. Thus we place this behind a different warning that can be
7065 // turned off separately if needed.
7066 if (LeftBits == ResultBits - 1) {
Ted Kremenek70f05fd2011-06-15 00:54:52 +00007067 S.Diag(Loc, diag::warn_shift_result_sets_sign_bit)
Richard Trieue4a19fb2011-09-06 21:21:28 +00007068 << HexResult.str() << LHSType
7069 << LHS.get()->getSourceRange() << RHS.get()->getSourceRange();
Chandler Carruth4c6fdca2011-02-23 23:34:11 +00007070 return;
7071 }
7072
7073 S.Diag(Loc, diag::warn_shift_result_gt_typewidth)
Richard Trieue4a19fb2011-09-06 21:21:28 +00007074 << HexResult.str() << Result.getMinSignedBits() << LHSType
7075 << Left.getBitWidth() << LHS.get()->getSourceRange()
7076 << RHS.get()->getSourceRange();
Chandler Carruth4c6fdca2011-02-23 23:34:11 +00007077}
7078
Chris Lattner2a3569b2008-04-07 05:30:13 +00007079// C99 6.5.7
Richard Trieue4a19fb2011-09-06 21:21:28 +00007080QualType Sema::CheckShiftOperands(ExprResult &LHS, ExprResult &RHS,
Richard Trieucfc491d2011-08-02 04:35:43 +00007081 SourceLocation Loc, unsigned Opc,
Richard Trieuba63ce62011-09-09 01:45:06 +00007082 bool IsCompAssign) {
Richard Trieuf8916e12011-09-16 00:53:10 +00007083 checkArithmeticNull(*this, LHS, RHS, Loc, /*isCompare=*/false);
7084
Nate Begemane46ee9a2009-10-25 02:26:48 +00007085 // Vector shifts promote their scalar inputs to vector type.
Richard Trieue4a19fb2011-09-06 21:21:28 +00007086 if (LHS.get()->getType()->isVectorType() ||
7087 RHS.get()->getType()->isVectorType())
Richard Trieuba63ce62011-09-09 01:45:06 +00007088 return CheckVectorOperands(LHS, RHS, Loc, IsCompAssign);
Nate Begemane46ee9a2009-10-25 02:26:48 +00007089
Chris Lattner5c11c412007-12-12 05:47:28 +00007090 // Shifts don't perform usual arithmetic conversions, they just do integer
7091 // promotions on each operand. C99 6.5.7p3
Eli Friedman8b7b1b12009-03-28 01:22:36 +00007092
John McCall57cdd882010-12-16 19:28:59 +00007093 // For the LHS, do usual unary conversions, but then reset them away
7094 // if this is a compound assignment.
Richard Trieue4a19fb2011-09-06 21:21:28 +00007095 ExprResult OldLHS = LHS;
7096 LHS = UsualUnaryConversions(LHS.take());
7097 if (LHS.isInvalid())
John Wiegley01296292011-04-08 18:41:53 +00007098 return QualType();
Richard Trieue4a19fb2011-09-06 21:21:28 +00007099 QualType LHSType = LHS.get()->getType();
Richard Trieuba63ce62011-09-09 01:45:06 +00007100 if (IsCompAssign) LHS = OldLHS;
John McCall57cdd882010-12-16 19:28:59 +00007101
7102 // The RHS is simpler.
Richard Trieue4a19fb2011-09-06 21:21:28 +00007103 RHS = UsualUnaryConversions(RHS.take());
7104 if (RHS.isInvalid())
John Wiegley01296292011-04-08 18:41:53 +00007105 return QualType();
Douglas Gregor8997dac2013-04-16 15:41:08 +00007106 QualType RHSType = RHS.get()->getType();
Mike Stump4e1f26a2009-02-19 03:04:26 +00007107
Douglas Gregor8997dac2013-04-16 15:41:08 +00007108 // C99 6.5.7p2: Each of the operands shall have integer type.
7109 if (!LHSType->hasIntegerRepresentation() ||
7110 !RHSType->hasIntegerRepresentation())
7111 return InvalidOperands(Loc, LHS, RHS);
7112
7113 // C++0x: Don't allow scoped enums. FIXME: Use something better than
7114 // hasIntegerRepresentation() above instead of this.
7115 if (isScopedEnumerationType(LHSType) ||
7116 isScopedEnumerationType(RHSType)) {
7117 return InvalidOperands(Loc, LHS, RHS);
7118 }
Ryan Flynnf53fab82009-08-07 16:20:20 +00007119 // Sanity-check shift operands
Richard Trieue4a19fb2011-09-06 21:21:28 +00007120 DiagnoseBadShiftValues(*this, LHS, RHS, Loc, Opc, LHSType);
Ryan Flynnf53fab82009-08-07 16:20:20 +00007121
Chris Lattner5c11c412007-12-12 05:47:28 +00007122 // "The type of the result is that of the promoted left operand."
Richard Trieue4a19fb2011-09-06 21:21:28 +00007123 return LHSType;
Steve Naroff26c8ea52007-03-21 21:08:52 +00007124}
7125
Chandler Carruth17773fc2010-07-10 12:30:03 +00007126static bool IsWithinTemplateSpecialization(Decl *D) {
7127 if (DeclContext *DC = D->getDeclContext()) {
7128 if (isa<ClassTemplateSpecializationDecl>(DC))
7129 return true;
7130 if (FunctionDecl *FD = dyn_cast<FunctionDecl>(DC))
7131 return FD->isFunctionTemplateSpecialization();
7132 }
7133 return false;
7134}
7135
Richard Trieueea56f72011-09-02 03:48:46 +00007136/// If two different enums are compared, raise a warning.
Ted Kremenekf2ca8ec2013-01-30 19:10:21 +00007137static void checkEnumComparison(Sema &S, SourceLocation Loc, Expr *LHS,
7138 Expr *RHS) {
7139 QualType LHSStrippedType = LHS->IgnoreParenImpCasts()->getType();
7140 QualType RHSStrippedType = RHS->IgnoreParenImpCasts()->getType();
Richard Trieueea56f72011-09-02 03:48:46 +00007141
7142 const EnumType *LHSEnumType = LHSStrippedType->getAs<EnumType>();
7143 if (!LHSEnumType)
7144 return;
7145 const EnumType *RHSEnumType = RHSStrippedType->getAs<EnumType>();
7146 if (!RHSEnumType)
7147 return;
7148
7149 // Ignore anonymous enums.
7150 if (!LHSEnumType->getDecl()->getIdentifier())
7151 return;
7152 if (!RHSEnumType->getDecl()->getIdentifier())
7153 return;
7154
7155 if (S.Context.hasSameUnqualifiedType(LHSStrippedType, RHSStrippedType))
7156 return;
7157
7158 S.Diag(Loc, diag::warn_comparison_of_mixed_enum_types)
7159 << LHSStrippedType << RHSStrippedType
Ted Kremenekf2ca8ec2013-01-30 19:10:21 +00007160 << LHS->getSourceRange() << RHS->getSourceRange();
Richard Trieueea56f72011-09-02 03:48:46 +00007161}
7162
Richard Trieudd82a5c2011-09-02 02:55:45 +00007163/// \brief Diagnose bad pointer comparisons.
7164static void diagnoseDistinctPointerComparison(Sema &S, SourceLocation Loc,
Richard Trieu1762d7c2011-09-06 21:27:33 +00007165 ExprResult &LHS, ExprResult &RHS,
Richard Trieuba63ce62011-09-09 01:45:06 +00007166 bool IsError) {
7167 S.Diag(Loc, IsError ? diag::err_typecheck_comparison_of_distinct_pointers
Richard Trieudd82a5c2011-09-02 02:55:45 +00007168 : diag::ext_typecheck_comparison_of_distinct_pointers)
Richard Trieu1762d7c2011-09-06 21:27:33 +00007169 << LHS.get()->getType() << RHS.get()->getType()
7170 << LHS.get()->getSourceRange() << RHS.get()->getSourceRange();
Richard Trieudd82a5c2011-09-02 02:55:45 +00007171}
7172
7173/// \brief Returns false if the pointers are converted to a composite type,
7174/// true otherwise.
7175static bool convertPointersToCompositeType(Sema &S, SourceLocation Loc,
Richard Trieu1762d7c2011-09-06 21:27:33 +00007176 ExprResult &LHS, ExprResult &RHS) {
Richard Trieudd82a5c2011-09-02 02:55:45 +00007177 // C++ [expr.rel]p2:
7178 // [...] Pointer conversions (4.10) and qualification
7179 // conversions (4.4) are performed on pointer operands (or on
7180 // a pointer operand and a null pointer constant) to bring
7181 // them to their composite pointer type. [...]
7182 //
7183 // C++ [expr.eq]p1 uses the same notion for (in)equality
7184 // comparisons of pointers.
7185
7186 // C++ [expr.eq]p2:
7187 // In addition, pointers to members can be compared, or a pointer to
7188 // member and a null pointer constant. Pointer to member conversions
7189 // (4.11) and qualification conversions (4.4) are performed to bring
7190 // them to a common type. If one operand is a null pointer constant,
7191 // the common type is the type of the other operand. Otherwise, the
7192 // common type is a pointer to member type similar (4.4) to the type
7193 // of one of the operands, with a cv-qualification signature (4.4)
7194 // that is the union of the cv-qualification signatures of the operand
7195 // types.
7196
Richard Trieu1762d7c2011-09-06 21:27:33 +00007197 QualType LHSType = LHS.get()->getType();
7198 QualType RHSType = RHS.get()->getType();
7199 assert((LHSType->isPointerType() && RHSType->isPointerType()) ||
7200 (LHSType->isMemberPointerType() && RHSType->isMemberPointerType()));
Richard Trieudd82a5c2011-09-02 02:55:45 +00007201
7202 bool NonStandardCompositeType = false;
Richard Trieu48277e52011-09-02 21:44:27 +00007203 bool *BoolPtr = S.isSFINAEContext() ? 0 : &NonStandardCompositeType;
Richard Trieu1762d7c2011-09-06 21:27:33 +00007204 QualType T = S.FindCompositePointerType(Loc, LHS, RHS, BoolPtr);
Richard Trieudd82a5c2011-09-02 02:55:45 +00007205 if (T.isNull()) {
Richard Trieu1762d7c2011-09-06 21:27:33 +00007206 diagnoseDistinctPointerComparison(S, Loc, LHS, RHS, /*isError*/true);
Richard Trieudd82a5c2011-09-02 02:55:45 +00007207 return true;
7208 }
7209
7210 if (NonStandardCompositeType)
7211 S.Diag(Loc, diag::ext_typecheck_comparison_of_distinct_pointers_nonstandard)
Richard Trieu1762d7c2011-09-06 21:27:33 +00007212 << LHSType << RHSType << T << LHS.get()->getSourceRange()
7213 << RHS.get()->getSourceRange();
Richard Trieudd82a5c2011-09-02 02:55:45 +00007214
Richard Trieu1762d7c2011-09-06 21:27:33 +00007215 LHS = S.ImpCastExprToType(LHS.take(), T, CK_BitCast);
7216 RHS = S.ImpCastExprToType(RHS.take(), T, CK_BitCast);
Richard Trieudd82a5c2011-09-02 02:55:45 +00007217 return false;
7218}
7219
7220static void diagnoseFunctionPointerToVoidComparison(Sema &S, SourceLocation Loc,
Richard Trieu1762d7c2011-09-06 21:27:33 +00007221 ExprResult &LHS,
7222 ExprResult &RHS,
Richard Trieuba63ce62011-09-09 01:45:06 +00007223 bool IsError) {
7224 S.Diag(Loc, IsError ? diag::err_typecheck_comparison_of_fptr_to_void
7225 : diag::ext_typecheck_comparison_of_fptr_to_void)
Richard Trieu1762d7c2011-09-06 21:27:33 +00007226 << LHS.get()->getType() << RHS.get()->getType()
7227 << LHS.get()->getSourceRange() << RHS.get()->getSourceRange();
Richard Trieudd82a5c2011-09-02 02:55:45 +00007228}
7229
Jordan Rosed49a33e2012-06-08 21:14:25 +00007230static bool isObjCObjectLiteral(ExprResult &E) {
Jordan Rosee2028132012-11-09 23:55:21 +00007231 switch (E.get()->IgnoreParenImpCasts()->getStmtClass()) {
Jordan Rosed49a33e2012-06-08 21:14:25 +00007232 case Stmt::ObjCArrayLiteralClass:
7233 case Stmt::ObjCDictionaryLiteralClass:
7234 case Stmt::ObjCStringLiteralClass:
7235 case Stmt::ObjCBoxedExprClass:
7236 return true;
7237 default:
7238 // Note that ObjCBoolLiteral is NOT an object literal!
7239 return false;
7240 }
7241}
7242
Jordan Rose7660f782012-07-17 17:46:40 +00007243static bool hasIsEqualMethod(Sema &S, const Expr *LHS, const Expr *RHS) {
Benjamin Kramer25c05102013-02-15 15:17:50 +00007244 const ObjCObjectPointerType *Type =
7245 LHS->getType()->getAs<ObjCObjectPointerType>();
7246
7247 // If this is not actually an Objective-C object, bail out.
7248 if (!Type)
Jordan Rose7660f782012-07-17 17:46:40 +00007249 return false;
Benjamin Kramer25c05102013-02-15 15:17:50 +00007250
7251 // Get the LHS object's interface type.
7252 QualType InterfaceType = Type->getPointeeType();
7253 if (const ObjCObjectType *iQFaceTy =
7254 InterfaceType->getAsObjCQualifiedInterfaceType())
7255 InterfaceType = iQFaceTy->getBaseType();
Jordan Rose7660f782012-07-17 17:46:40 +00007256
7257 // If the RHS isn't an Objective-C object, bail out.
7258 if (!RHS->getType()->isObjCObjectPointerType())
7259 return false;
7260
7261 // Try to find the -isEqual: method.
7262 Selector IsEqualSel = S.NSAPIObj->getIsEqualSelector();
7263 ObjCMethodDecl *Method = S.LookupMethodInObjectType(IsEqualSel,
7264 InterfaceType,
7265 /*instance=*/true);
7266 if (!Method) {
7267 if (Type->isObjCIdType()) {
7268 // For 'id', just check the global pool.
7269 Method = S.LookupInstanceMethodInGlobalPool(IsEqualSel, SourceRange(),
7270 /*receiverId=*/true,
7271 /*warn=*/false);
7272 } else {
7273 // Check protocols.
Benjamin Kramer25c05102013-02-15 15:17:50 +00007274 Method = S.LookupMethodInQualifiedType(IsEqualSel, Type,
Jordan Rose7660f782012-07-17 17:46:40 +00007275 /*instance=*/true);
7276 }
7277 }
7278
7279 if (!Method)
7280 return false;
7281
7282 QualType T = Method->param_begin()[0]->getType();
7283 if (!T->isObjCObjectPointerType())
7284 return false;
7285
7286 QualType R = Method->getResultType();
7287 if (!R->isScalarType())
7288 return false;
7289
7290 return true;
7291}
7292
Ted Kremenek01a33f82012-12-21 21:59:36 +00007293Sema::ObjCLiteralKind Sema::CheckLiteralKind(Expr *FromE) {
7294 FromE = FromE->IgnoreParenImpCasts();
7295 switch (FromE->getStmtClass()) {
7296 default:
7297 break;
7298 case Stmt::ObjCStringLiteralClass:
7299 // "string literal"
7300 return LK_String;
7301 case Stmt::ObjCArrayLiteralClass:
7302 // "array literal"
7303 return LK_Array;
7304 case Stmt::ObjCDictionaryLiteralClass:
7305 // "dictionary literal"
7306 return LK_Dictionary;
Ted Kremenek64873352012-12-21 22:46:35 +00007307 case Stmt::BlockExprClass:
7308 return LK_Block;
Ted Kremenek01a33f82012-12-21 21:59:36 +00007309 case Stmt::ObjCBoxedExprClass: {
Ted Kremenek44c2a2a2012-12-21 21:59:39 +00007310 Expr *Inner = cast<ObjCBoxedExpr>(FromE)->getSubExpr()->IgnoreParens();
Ted Kremenek01a33f82012-12-21 21:59:36 +00007311 switch (Inner->getStmtClass()) {
7312 case Stmt::IntegerLiteralClass:
7313 case Stmt::FloatingLiteralClass:
7314 case Stmt::CharacterLiteralClass:
7315 case Stmt::ObjCBoolLiteralExprClass:
7316 case Stmt::CXXBoolLiteralExprClass:
7317 // "numeric literal"
7318 return LK_Numeric;
7319 case Stmt::ImplicitCastExprClass: {
7320 CastKind CK = cast<CastExpr>(Inner)->getCastKind();
7321 // Boolean literals can be represented by implicit casts.
7322 if (CK == CK_IntegralToBoolean || CK == CK_IntegralCast)
7323 return LK_Numeric;
7324 break;
7325 }
7326 default:
7327 break;
7328 }
7329 return LK_Boxed;
7330 }
7331 }
7332 return LK_None;
7333}
7334
Jordan Rose7660f782012-07-17 17:46:40 +00007335static void diagnoseObjCLiteralComparison(Sema &S, SourceLocation Loc,
7336 ExprResult &LHS, ExprResult &RHS,
7337 BinaryOperator::Opcode Opc){
Jordan Rose63ffaa82012-07-17 17:46:48 +00007338 Expr *Literal;
7339 Expr *Other;
7340 if (isObjCObjectLiteral(LHS)) {
7341 Literal = LHS.get();
7342 Other = RHS.get();
7343 } else {
7344 Literal = RHS.get();
7345 Other = LHS.get();
7346 }
7347
7348 // Don't warn on comparisons against nil.
7349 Other = Other->IgnoreParenCasts();
7350 if (Other->isNullPointerConstant(S.getASTContext(),
7351 Expr::NPC_ValueDependentIsNotNull))
7352 return;
Jordan Rosed49a33e2012-06-08 21:14:25 +00007353
Jordan Roseea70bf72012-07-17 17:46:44 +00007354 // This should be kept in sync with warn_objc_literal_comparison.
Ted Kremenek01a33f82012-12-21 21:59:36 +00007355 // LK_String should always be after the other literals, since it has its own
7356 // warning flag.
7357 Sema::ObjCLiteralKind LiteralKind = S.CheckLiteralKind(Literal);
Ted Kremenek64873352012-12-21 22:46:35 +00007358 assert(LiteralKind != Sema::LK_Block);
Ted Kremenek01a33f82012-12-21 21:59:36 +00007359 if (LiteralKind == Sema::LK_None) {
Jordan Rosed49a33e2012-06-08 21:14:25 +00007360 llvm_unreachable("Unknown Objective-C object literal kind");
7361 }
7362
Ted Kremenek01a33f82012-12-21 21:59:36 +00007363 if (LiteralKind == Sema::LK_String)
Jordan Roseea70bf72012-07-17 17:46:44 +00007364 S.Diag(Loc, diag::warn_objc_string_literal_comparison)
7365 << Literal->getSourceRange();
7366 else
7367 S.Diag(Loc, diag::warn_objc_literal_comparison)
7368 << LiteralKind << Literal->getSourceRange();
Jordan Rosed49a33e2012-06-08 21:14:25 +00007369
Jordan Rose7660f782012-07-17 17:46:40 +00007370 if (BinaryOperator::isEqualityOp(Opc) &&
7371 hasIsEqualMethod(S, LHS.get(), RHS.get())) {
7372 SourceLocation Start = LHS.get()->getLocStart();
7373 SourceLocation End = S.PP.getLocForEndOfToken(RHS.get()->getLocEnd());
Fariborz Jahanian4dca1d32013-02-01 20:04:49 +00007374 CharSourceRange OpRange =
7375 CharSourceRange::getCharRange(Loc, S.PP.getLocForEndOfToken(Loc));
Jordan Rosef9198032012-07-09 16:54:44 +00007376
Jordan Rose7660f782012-07-17 17:46:40 +00007377 S.Diag(Loc, diag::note_objc_literal_comparison_isequal)
7378 << FixItHint::CreateInsertion(Start, Opc == BO_EQ ? "[" : "![")
Fariborz Jahanian4dca1d32013-02-01 20:04:49 +00007379 << FixItHint::CreateReplacement(OpRange, " isEqual:")
Jordan Rose7660f782012-07-17 17:46:40 +00007380 << FixItHint::CreateInsertion(End, "]");
Jordan Rosed49a33e2012-06-08 21:14:25 +00007381 }
Jordan Rosed49a33e2012-06-08 21:14:25 +00007382}
7383
Richard Trieubb4b8942013-06-10 18:52:07 +00007384static void diagnoseLogicalNotOnLHSofComparison(Sema &S, ExprResult &LHS,
7385 ExprResult &RHS,
7386 SourceLocation Loc,
7387 unsigned OpaqueOpc) {
7388 // This checking requires bools.
7389 if (!S.getLangOpts().Bool) return;
7390
7391 // Check that left hand side is !something.
Richard Trieu949abc32013-07-04 00:50:18 +00007392 UnaryOperator *UO = dyn_cast<UnaryOperator>(LHS.get()->IgnoreImpCasts());
Richard Trieubb4b8942013-06-10 18:52:07 +00007393 if (!UO || UO->getOpcode() != UO_LNot) return;
7394
7395 // Only check if the right hand side is non-bool arithmetic type.
7396 if (RHS.get()->getType()->isBooleanType()) return;
7397
7398 // Make sure that the something in !something is not bool.
7399 Expr *SubExpr = UO->getSubExpr()->IgnoreImpCasts();
7400 if (SubExpr->getType()->isBooleanType()) return;
7401
7402 // Emit warning.
7403 S.Diag(UO->getOperatorLoc(), diag::warn_logical_not_on_lhs_of_comparison)
7404 << Loc;
7405
7406 // First note suggest !(x < y)
7407 SourceLocation FirstOpen = SubExpr->getLocStart();
7408 SourceLocation FirstClose = RHS.get()->getLocEnd();
7409 FirstClose = S.getPreprocessor().getLocForEndOfToken(FirstClose);
Eli Friedmanef0b4a32013-07-22 23:09:39 +00007410 if (FirstClose.isInvalid())
7411 FirstOpen = SourceLocation();
Richard Trieubb4b8942013-06-10 18:52:07 +00007412 S.Diag(UO->getOperatorLoc(), diag::note_logical_not_fix)
7413 << FixItHint::CreateInsertion(FirstOpen, "(")
7414 << FixItHint::CreateInsertion(FirstClose, ")");
7415
7416 // Second note suggests (!x) < y
7417 SourceLocation SecondOpen = LHS.get()->getLocStart();
7418 SourceLocation SecondClose = LHS.get()->getLocEnd();
7419 SecondClose = S.getPreprocessor().getLocForEndOfToken(SecondClose);
Eli Friedmanef0b4a32013-07-22 23:09:39 +00007420 if (SecondClose.isInvalid())
7421 SecondOpen = SourceLocation();
Richard Trieubb4b8942013-06-10 18:52:07 +00007422 S.Diag(UO->getOperatorLoc(), diag::note_logical_not_silence_with_parens)
7423 << FixItHint::CreateInsertion(SecondOpen, "(")
7424 << FixItHint::CreateInsertion(SecondClose, ")");
7425}
7426
Douglas Gregor5b07c7e2009-05-04 06:07:12 +00007427// C99 6.5.8, C++ [expr.rel]
Richard Trieub80728f2011-09-06 21:43:51 +00007428QualType Sema::CheckCompareOperands(ExprResult &LHS, ExprResult &RHS,
Richard Trieucfc491d2011-08-02 04:35:43 +00007429 SourceLocation Loc, unsigned OpaqueOpc,
Richard Trieuba63ce62011-09-09 01:45:06 +00007430 bool IsRelational) {
Richard Trieuf8916e12011-09-16 00:53:10 +00007431 checkArithmeticNull(*this, LHS, RHS, Loc, /*isCompare=*/true);
7432
John McCalle3027922010-08-25 11:45:40 +00007433 BinaryOperatorKind Opc = (BinaryOperatorKind) OpaqueOpc;
Douglas Gregor7a5bc762009-04-06 18:45:53 +00007434
Chris Lattner9a152e22009-12-05 05:40:13 +00007435 // Handle vector comparisons separately.
Richard Trieub80728f2011-09-06 21:43:51 +00007436 if (LHS.get()->getType()->isVectorType() ||
7437 RHS.get()->getType()->isVectorType())
Richard Trieuba63ce62011-09-09 01:45:06 +00007438 return CheckVectorCompareOperands(LHS, RHS, Loc, IsRelational);
Mike Stump4e1f26a2009-02-19 03:04:26 +00007439
Richard Trieub80728f2011-09-06 21:43:51 +00007440 QualType LHSType = LHS.get()->getType();
7441 QualType RHSType = RHS.get()->getType();
Benjamin Kramera66aaa92011-09-03 08:46:20 +00007442
Richard Trieub80728f2011-09-06 21:43:51 +00007443 Expr *LHSStripped = LHS.get()->IgnoreParenImpCasts();
7444 Expr *RHSStripped = RHS.get()->IgnoreParenImpCasts();
Chandler Carruth712563b2011-02-17 08:37:06 +00007445
Ted Kremenekf2ca8ec2013-01-30 19:10:21 +00007446 checkEnumComparison(*this, Loc, LHS.get(), RHS.get());
Richard Trieubb4b8942013-06-10 18:52:07 +00007447 diagnoseLogicalNotOnLHSofComparison(*this, LHS, RHS, Loc, OpaqueOpc);
Chandler Carruth712563b2011-02-17 08:37:06 +00007448
Richard Trieub80728f2011-09-06 21:43:51 +00007449 if (!LHSType->hasFloatingRepresentation() &&
Richard Trieuba63ce62011-09-09 01:45:06 +00007450 !(LHSType->isBlockPointerType() && IsRelational) &&
Richard Trieub80728f2011-09-06 21:43:51 +00007451 !LHS.get()->getLocStart().isMacroID() &&
7452 !RHS.get()->getLocStart().isMacroID()) {
Chris Lattner222b8bd2009-03-08 19:39:53 +00007453 // For non-floating point types, check for self-comparisons of the form
7454 // x == x, x != x, x < x, etc. These always evaluate to a constant, and
7455 // often indicate logic errors in the program.
Chandler Carruth65a38182010-07-12 06:23:38 +00007456 //
7457 // NOTE: Don't warn about comparison expressions resulting from macro
7458 // expansion. Also don't warn about comparisons which are only self
7459 // comparisons within a template specialization. The warnings should catch
7460 // obvious cases in the definition of the template anyways. The idea is to
7461 // warn when the typed comparison operator will always evaluate to the same
7462 // result.
Chandler Carruth17773fc2010-07-10 12:30:03 +00007463 if (DeclRefExpr* DRL = dyn_cast<DeclRefExpr>(LHSStripped)) {
Douglas Gregorec170db2010-06-08 19:50:34 +00007464 if (DeclRefExpr* DRR = dyn_cast<DeclRefExpr>(RHSStripped)) {
Ted Kremenek853734e2010-09-16 00:03:01 +00007465 if (DRL->getDecl() == DRR->getDecl() &&
Chandler Carruth17773fc2010-07-10 12:30:03 +00007466 !IsWithinTemplateSpecialization(DRL->getDecl())) {
Ted Kremenek3427fac2011-02-23 01:52:04 +00007467 DiagRuntimeBehavior(Loc, 0, PDiag(diag::warn_comparison_always)
Douglas Gregorec170db2010-06-08 19:50:34 +00007468 << 0 // self-
John McCalle3027922010-08-25 11:45:40 +00007469 << (Opc == BO_EQ
7470 || Opc == BO_LE
7471 || Opc == BO_GE));
Richard Trieub80728f2011-09-06 21:43:51 +00007472 } else if (LHSType->isArrayType() && RHSType->isArrayType() &&
Douglas Gregorec170db2010-06-08 19:50:34 +00007473 !DRL->getDecl()->getType()->isReferenceType() &&
7474 !DRR->getDecl()->getType()->isReferenceType()) {
7475 // what is it always going to eval to?
7476 char always_evals_to;
7477 switch(Opc) {
John McCalle3027922010-08-25 11:45:40 +00007478 case BO_EQ: // e.g. array1 == array2
Douglas Gregorec170db2010-06-08 19:50:34 +00007479 always_evals_to = 0; // false
7480 break;
John McCalle3027922010-08-25 11:45:40 +00007481 case BO_NE: // e.g. array1 != array2
Douglas Gregorec170db2010-06-08 19:50:34 +00007482 always_evals_to = 1; // true
7483 break;
7484 default:
7485 // best we can say is 'a constant'
7486 always_evals_to = 2; // e.g. array1 <= array2
7487 break;
7488 }
Ted Kremenek3427fac2011-02-23 01:52:04 +00007489 DiagRuntimeBehavior(Loc, 0, PDiag(diag::warn_comparison_always)
Douglas Gregorec170db2010-06-08 19:50:34 +00007490 << 1 // array
7491 << always_evals_to);
7492 }
7493 }
Chandler Carruth17773fc2010-07-10 12:30:03 +00007494 }
Mike Stump11289f42009-09-09 15:08:12 +00007495
Chris Lattner222b8bd2009-03-08 19:39:53 +00007496 if (isa<CastExpr>(LHSStripped))
7497 LHSStripped = LHSStripped->IgnoreParenCasts();
7498 if (isa<CastExpr>(RHSStripped))
7499 RHSStripped = RHSStripped->IgnoreParenCasts();
Mike Stump11289f42009-09-09 15:08:12 +00007500
Chris Lattner222b8bd2009-03-08 19:39:53 +00007501 // Warn about comparisons against a string constant (unless the other
7502 // operand is null), the user probably wants strcmp.
Douglas Gregor7a5bc762009-04-06 18:45:53 +00007503 Expr *literalString = 0;
7504 Expr *literalStringStripped = 0;
Chris Lattner222b8bd2009-03-08 19:39:53 +00007505 if ((isa<StringLiteral>(LHSStripped) || isa<ObjCEncodeExpr>(LHSStripped)) &&
Kovarththanan Rajaratnamba2c6522010-03-13 10:17:05 +00007506 !RHSStripped->isNullPointerConstant(Context,
Douglas Gregor56751b52009-09-25 04:25:58 +00007507 Expr::NPC_ValueDependentIsNull)) {
Richard Trieub80728f2011-09-06 21:43:51 +00007508 literalString = LHS.get();
Douglas Gregor7a5bc762009-04-06 18:45:53 +00007509 literalStringStripped = LHSStripped;
Mike Stump12b8ce12009-08-04 21:02:39 +00007510 } else if ((isa<StringLiteral>(RHSStripped) ||
7511 isa<ObjCEncodeExpr>(RHSStripped)) &&
Kovarththanan Rajaratnamba2c6522010-03-13 10:17:05 +00007512 !LHSStripped->isNullPointerConstant(Context,
Douglas Gregor56751b52009-09-25 04:25:58 +00007513 Expr::NPC_ValueDependentIsNull)) {
Richard Trieub80728f2011-09-06 21:43:51 +00007514 literalString = RHS.get();
Douglas Gregor7a5bc762009-04-06 18:45:53 +00007515 literalStringStripped = RHSStripped;
7516 }
7517
7518 if (literalString) {
Ted Kremenek3427fac2011-02-23 01:52:04 +00007519 DiagRuntimeBehavior(Loc, 0,
Douglas Gregor49862b82010-01-12 23:18:54 +00007520 PDiag(diag::warn_stringcompare)
7521 << isa<ObjCEncodeExpr>(literalStringStripped)
Ted Kremenek800b66b2010-04-09 20:26:53 +00007522 << literalString->getSourceRange());
Douglas Gregor7a5bc762009-04-06 18:45:53 +00007523 }
Ted Kremeneke451eae2007-10-29 16:58:49 +00007524 }
Mike Stump4e1f26a2009-02-19 03:04:26 +00007525
Douglas Gregorec170db2010-06-08 19:50:34 +00007526 // C99 6.5.8p3 / C99 6.5.9p4
Eli Friedmane6d33952013-07-08 20:20:06 +00007527 UsualArithmeticConversions(LHS, RHS);
7528 if (LHS.isInvalid() || RHS.isInvalid())
7529 return QualType();
Douglas Gregorec170db2010-06-08 19:50:34 +00007530
Richard Trieub80728f2011-09-06 21:43:51 +00007531 LHSType = LHS.get()->getType();
7532 RHSType = RHS.get()->getType();
Douglas Gregorec170db2010-06-08 19:50:34 +00007533
Douglas Gregorca63811b2008-11-19 03:25:36 +00007534 // The result of comparisons is 'bool' in C++, 'int' in C.
Argyrios Kyrtzidis1bdd6882011-02-18 20:55:15 +00007535 QualType ResultTy = Context.getLogicalOperationType();
Douglas Gregorca63811b2008-11-19 03:25:36 +00007536
Richard Trieuba63ce62011-09-09 01:45:06 +00007537 if (IsRelational) {
Richard Trieub80728f2011-09-06 21:43:51 +00007538 if (LHSType->isRealType() && RHSType->isRealType())
Douglas Gregorca63811b2008-11-19 03:25:36 +00007539 return ResultTy;
Chris Lattnerb620c342007-08-26 01:18:55 +00007540 } else {
Ted Kremeneke2763b02007-10-29 17:13:39 +00007541 // Check for comparisons of floating point operands using != and ==.
Richard Trieub80728f2011-09-06 21:43:51 +00007542 if (LHSType->hasFloatingRepresentation())
7543 CheckFloatComparison(Loc, LHS.get(), RHS.get());
Mike Stump4e1f26a2009-02-19 03:04:26 +00007544
Richard Trieub80728f2011-09-06 21:43:51 +00007545 if (LHSType->isArithmeticType() && RHSType->isArithmeticType())
Douglas Gregorca63811b2008-11-19 03:25:36 +00007546 return ResultTy;
Chris Lattnerb620c342007-08-26 01:18:55 +00007547 }
Mike Stump4e1f26a2009-02-19 03:04:26 +00007548
Richard Trieub80728f2011-09-06 21:43:51 +00007549 bool LHSIsNull = LHS.get()->isNullPointerConstant(Context,
Douglas Gregor56751b52009-09-25 04:25:58 +00007550 Expr::NPC_ValueDependentIsNull);
Richard Trieub80728f2011-09-06 21:43:51 +00007551 bool RHSIsNull = RHS.get()->isNullPointerConstant(Context,
Douglas Gregor56751b52009-09-25 04:25:58 +00007552 Expr::NPC_ValueDependentIsNull);
Mike Stump4e1f26a2009-02-19 03:04:26 +00007553
Douglas Gregorf267edd2010-06-15 21:38:40 +00007554 // All of the following pointer-related warnings are GCC extensions, except
7555 // when handling null pointer constants.
Richard Trieub80728f2011-09-06 21:43:51 +00007556 if (LHSType->isPointerType() && RHSType->isPointerType()) { // C99 6.5.8p2
Chris Lattner3a0702e2008-04-03 05:07:25 +00007557 QualType LCanPointeeTy =
John McCall9320b872011-09-09 05:25:32 +00007558 LHSType->castAs<PointerType>()->getPointeeType().getCanonicalType();
Chris Lattner3a0702e2008-04-03 05:07:25 +00007559 QualType RCanPointeeTy =
John McCall9320b872011-09-09 05:25:32 +00007560 RHSType->castAs<PointerType>()->getPointeeType().getCanonicalType();
Mike Stump4e1f26a2009-02-19 03:04:26 +00007561
David Blaikiebbafb8a2012-03-11 07:00:24 +00007562 if (getLangOpts().CPlusPlus) {
Eli Friedman16c209612009-08-23 00:27:47 +00007563 if (LCanPointeeTy == RCanPointeeTy)
7564 return ResultTy;
Richard Trieuba63ce62011-09-09 01:45:06 +00007565 if (!IsRelational &&
Fariborz Jahanianffc420c2009-12-21 18:19:17 +00007566 (LCanPointeeTy->isVoidType() || RCanPointeeTy->isVoidType())) {
7567 // Valid unless comparison between non-null pointer and function pointer
7568 // This is a gcc extension compatibility comparison.
Douglas Gregorf267edd2010-06-15 21:38:40 +00007569 // In a SFINAE context, we treat this as a hard error to maintain
7570 // conformance with the C++ standard.
Fariborz Jahanianffc420c2009-12-21 18:19:17 +00007571 if ((LCanPointeeTy->isFunctionType() || RCanPointeeTy->isFunctionType())
7572 && !LHSIsNull && !RHSIsNull) {
Richard Trieudd82a5c2011-09-02 02:55:45 +00007573 diagnoseFunctionPointerToVoidComparison(
David Blaikie3a3c4e02013-02-21 06:05:05 +00007574 *this, Loc, LHS, RHS, /*isError*/ (bool)isSFINAEContext());
Douglas Gregorf267edd2010-06-15 21:38:40 +00007575
7576 if (isSFINAEContext())
7577 return QualType();
7578
Richard Trieub80728f2011-09-06 21:43:51 +00007579 RHS = ImpCastExprToType(RHS.take(), LHSType, CK_BitCast);
Fariborz Jahanianffc420c2009-12-21 18:19:17 +00007580 return ResultTy;
7581 }
7582 }
Anders Carlssona95069c2010-11-04 03:17:43 +00007583
Richard Trieub80728f2011-09-06 21:43:51 +00007584 if (convertPointersToCompositeType(*this, Loc, LHS, RHS))
Douglas Gregor5b07c7e2009-05-04 06:07:12 +00007585 return QualType();
Richard Trieudd82a5c2011-09-02 02:55:45 +00007586 else
7587 return ResultTy;
Douglas Gregor5b07c7e2009-05-04 06:07:12 +00007588 }
Eli Friedman16c209612009-08-23 00:27:47 +00007589 // C99 6.5.9p2 and C99 6.5.8p2
7590 if (Context.typesAreCompatible(LCanPointeeTy.getUnqualifiedType(),
7591 RCanPointeeTy.getUnqualifiedType())) {
7592 // Valid unless a relational comparison of function pointers
Richard Trieuba63ce62011-09-09 01:45:06 +00007593 if (IsRelational && LCanPointeeTy->isFunctionType()) {
Eli Friedman16c209612009-08-23 00:27:47 +00007594 Diag(Loc, diag::ext_typecheck_ordered_comparison_of_function_pointers)
Richard Trieub80728f2011-09-06 21:43:51 +00007595 << LHSType << RHSType << LHS.get()->getSourceRange()
7596 << RHS.get()->getSourceRange();
Eli Friedman16c209612009-08-23 00:27:47 +00007597 }
Richard Trieuba63ce62011-09-09 01:45:06 +00007598 } else if (!IsRelational &&
Eli Friedman16c209612009-08-23 00:27:47 +00007599 (LCanPointeeTy->isVoidType() || RCanPointeeTy->isVoidType())) {
7600 // Valid unless comparison between non-null pointer and function pointer
7601 if ((LCanPointeeTy->isFunctionType() || RCanPointeeTy->isFunctionType())
Richard Trieudd82a5c2011-09-02 02:55:45 +00007602 && !LHSIsNull && !RHSIsNull)
Richard Trieub80728f2011-09-06 21:43:51 +00007603 diagnoseFunctionPointerToVoidComparison(*this, Loc, LHS, RHS,
Richard Trieudd82a5c2011-09-02 02:55:45 +00007604 /*isError*/false);
Eli Friedman16c209612009-08-23 00:27:47 +00007605 } else {
7606 // Invalid
Richard Trieub80728f2011-09-06 21:43:51 +00007607 diagnoseDistinctPointerComparison(*this, Loc, LHS, RHS, /*isError*/false);
Steve Naroff75c17232007-06-13 21:41:08 +00007608 }
John McCall7684dde2011-03-11 04:25:25 +00007609 if (LCanPointeeTy != RCanPointeeTy) {
7610 if (LHSIsNull && !RHSIsNull)
Richard Trieub80728f2011-09-06 21:43:51 +00007611 LHS = ImpCastExprToType(LHS.take(), RHSType, CK_BitCast);
John McCall7684dde2011-03-11 04:25:25 +00007612 else
Richard Trieub80728f2011-09-06 21:43:51 +00007613 RHS = ImpCastExprToType(RHS.take(), LHSType, CK_BitCast);
John McCall7684dde2011-03-11 04:25:25 +00007614 }
Douglas Gregorca63811b2008-11-19 03:25:36 +00007615 return ResultTy;
Steve Naroffcdee44c2007-08-16 21:48:38 +00007616 }
Mike Stump11289f42009-09-09 15:08:12 +00007617
David Blaikiebbafb8a2012-03-11 07:00:24 +00007618 if (getLangOpts().CPlusPlus) {
Anders Carlssona95069c2010-11-04 03:17:43 +00007619 // Comparison of nullptr_t with itself.
Richard Trieub80728f2011-09-06 21:43:51 +00007620 if (LHSType->isNullPtrType() && RHSType->isNullPtrType())
Anders Carlssona95069c2010-11-04 03:17:43 +00007621 return ResultTy;
7622
Mike Stump11289f42009-09-09 15:08:12 +00007623 // Comparison of pointers with null pointer constants and equality
Douglas Gregorb00b10e2009-08-24 17:42:35 +00007624 // comparisons of member pointers to null pointer constants.
Mike Stump11289f42009-09-09 15:08:12 +00007625 if (RHSIsNull &&
Richard Trieub80728f2011-09-06 21:43:51 +00007626 ((LHSType->isAnyPointerType() || LHSType->isNullPtrType()) ||
Richard Trieuba63ce62011-09-09 01:45:06 +00007627 (!IsRelational &&
Richard Trieub80728f2011-09-06 21:43:51 +00007628 (LHSType->isMemberPointerType() || LHSType->isBlockPointerType())))) {
7629 RHS = ImpCastExprToType(RHS.take(), LHSType,
7630 LHSType->isMemberPointerType()
John McCalle3027922010-08-25 11:45:40 +00007631 ? CK_NullToMemberPointer
John McCalle84af4e2010-11-13 01:35:44 +00007632 : CK_NullToPointer);
Sebastian Redl576fd422009-05-10 18:38:11 +00007633 return ResultTy;
7634 }
Douglas Gregorb00b10e2009-08-24 17:42:35 +00007635 if (LHSIsNull &&
Richard Trieub80728f2011-09-06 21:43:51 +00007636 ((RHSType->isAnyPointerType() || RHSType->isNullPtrType()) ||
Richard Trieuba63ce62011-09-09 01:45:06 +00007637 (!IsRelational &&
Richard Trieub80728f2011-09-06 21:43:51 +00007638 (RHSType->isMemberPointerType() || RHSType->isBlockPointerType())))) {
7639 LHS = ImpCastExprToType(LHS.take(), RHSType,
7640 RHSType->isMemberPointerType()
John McCalle3027922010-08-25 11:45:40 +00007641 ? CK_NullToMemberPointer
John McCalle84af4e2010-11-13 01:35:44 +00007642 : CK_NullToPointer);
Sebastian Redl576fd422009-05-10 18:38:11 +00007643 return ResultTy;
7644 }
Douglas Gregorb00b10e2009-08-24 17:42:35 +00007645
7646 // Comparison of member pointers.
Richard Trieuba63ce62011-09-09 01:45:06 +00007647 if (!IsRelational &&
Richard Trieub80728f2011-09-06 21:43:51 +00007648 LHSType->isMemberPointerType() && RHSType->isMemberPointerType()) {
7649 if (convertPointersToCompositeType(*this, Loc, LHS, RHS))
Douglas Gregorb00b10e2009-08-24 17:42:35 +00007650 return QualType();
Richard Trieudd82a5c2011-09-02 02:55:45 +00007651 else
7652 return ResultTy;
Douglas Gregorb00b10e2009-08-24 17:42:35 +00007653 }
Douglas Gregor48e6bbf2011-03-01 17:16:20 +00007654
7655 // Handle scoped enumeration types specifically, since they don't promote
7656 // to integers.
Richard Trieub80728f2011-09-06 21:43:51 +00007657 if (LHS.get()->getType()->isEnumeralType() &&
7658 Context.hasSameUnqualifiedType(LHS.get()->getType(),
7659 RHS.get()->getType()))
Douglas Gregor48e6bbf2011-03-01 17:16:20 +00007660 return ResultTy;
Sebastian Redl576fd422009-05-10 18:38:11 +00007661 }
Mike Stump11289f42009-09-09 15:08:12 +00007662
Steve Naroff081c7422008-09-04 15:10:53 +00007663 // Handle block pointer types.
Richard Trieuba63ce62011-09-09 01:45:06 +00007664 if (!IsRelational && LHSType->isBlockPointerType() &&
Richard Trieub80728f2011-09-06 21:43:51 +00007665 RHSType->isBlockPointerType()) {
John McCall9320b872011-09-09 05:25:32 +00007666 QualType lpointee = LHSType->castAs<BlockPointerType>()->getPointeeType();
7667 QualType rpointee = RHSType->castAs<BlockPointerType>()->getPointeeType();
Mike Stump4e1f26a2009-02-19 03:04:26 +00007668
Steve Naroff081c7422008-09-04 15:10:53 +00007669 if (!LHSIsNull && !RHSIsNull &&
Eli Friedmana6638ca2009-06-08 05:08:54 +00007670 !Context.typesAreCompatible(lpointee, rpointee)) {
Chris Lattner377d1f82008-11-18 22:52:51 +00007671 Diag(Loc, diag::err_typecheck_comparison_of_distinct_blocks)
Richard Trieub80728f2011-09-06 21:43:51 +00007672 << LHSType << RHSType << LHS.get()->getSourceRange()
7673 << RHS.get()->getSourceRange();
Steve Naroff081c7422008-09-04 15:10:53 +00007674 }
Richard Trieub80728f2011-09-06 21:43:51 +00007675 RHS = ImpCastExprToType(RHS.take(), LHSType, CK_BitCast);
Douglas Gregorca63811b2008-11-19 03:25:36 +00007676 return ResultTy;
Steve Naroff081c7422008-09-04 15:10:53 +00007677 }
John Wiegley01296292011-04-08 18:41:53 +00007678
Steve Naroffe18f94c2008-09-28 01:11:11 +00007679 // Allow block pointers to be compared with null pointer constants.
Richard Trieuba63ce62011-09-09 01:45:06 +00007680 if (!IsRelational
Richard Trieub80728f2011-09-06 21:43:51 +00007681 && ((LHSType->isBlockPointerType() && RHSType->isPointerType())
7682 || (LHSType->isPointerType() && RHSType->isBlockPointerType()))) {
Steve Naroffe18f94c2008-09-28 01:11:11 +00007683 if (!LHSIsNull && !RHSIsNull) {
Richard Trieub80728f2011-09-06 21:43:51 +00007684 if (!((RHSType->isPointerType() && RHSType->castAs<PointerType>()
Mike Stump1b821b42009-05-07 03:14:14 +00007685 ->getPointeeType()->isVoidType())
Richard Trieub80728f2011-09-06 21:43:51 +00007686 || (LHSType->isPointerType() && LHSType->castAs<PointerType>()
Mike Stump1b821b42009-05-07 03:14:14 +00007687 ->getPointeeType()->isVoidType())))
7688 Diag(Loc, diag::err_typecheck_comparison_of_distinct_blocks)
Richard Trieub80728f2011-09-06 21:43:51 +00007689 << LHSType << RHSType << LHS.get()->getSourceRange()
7690 << RHS.get()->getSourceRange();
Steve Naroffe18f94c2008-09-28 01:11:11 +00007691 }
John McCall7684dde2011-03-11 04:25:25 +00007692 if (LHSIsNull && !RHSIsNull)
John McCall9320b872011-09-09 05:25:32 +00007693 LHS = ImpCastExprToType(LHS.take(), RHSType,
7694 RHSType->isPointerType() ? CK_BitCast
7695 : CK_AnyPointerToBlockPointerCast);
John McCall7684dde2011-03-11 04:25:25 +00007696 else
John McCall9320b872011-09-09 05:25:32 +00007697 RHS = ImpCastExprToType(RHS.take(), LHSType,
7698 LHSType->isPointerType() ? CK_BitCast
7699 : CK_AnyPointerToBlockPointerCast);
Douglas Gregorca63811b2008-11-19 03:25:36 +00007700 return ResultTy;
Steve Naroffe18f94c2008-09-28 01:11:11 +00007701 }
Steve Naroff081c7422008-09-04 15:10:53 +00007702
Richard Trieub80728f2011-09-06 21:43:51 +00007703 if (LHSType->isObjCObjectPointerType() ||
7704 RHSType->isObjCObjectPointerType()) {
7705 const PointerType *LPT = LHSType->getAs<PointerType>();
7706 const PointerType *RPT = RHSType->getAs<PointerType>();
John McCall7684dde2011-03-11 04:25:25 +00007707 if (LPT || RPT) {
7708 bool LPtrToVoid = LPT ? LPT->getPointeeType()->isVoidType() : false;
7709 bool RPtrToVoid = RPT ? RPT->getPointeeType()->isVoidType() : false;
Mike Stump4e1f26a2009-02-19 03:04:26 +00007710
Steve Naroff753567f2008-11-17 19:49:16 +00007711 if (!LPtrToVoid && !RPtrToVoid &&
Richard Trieub80728f2011-09-06 21:43:51 +00007712 !Context.typesAreCompatible(LHSType, RHSType)) {
7713 diagnoseDistinctPointerComparison(*this, Loc, LHS, RHS,
Richard Trieudd82a5c2011-09-02 02:55:45 +00007714 /*isError*/false);
Steve Naroff1d4a9a32008-10-27 10:33:19 +00007715 }
Fariborz Jahanian374089e2013-07-31 17:12:26 +00007716 if (LHSIsNull && !RHSIsNull) {
7717 Expr *E = LHS.take();
7718 if (getLangOpts().ObjCAutoRefCount)
7719 CheckObjCARCConversion(SourceRange(), RHSType, E, CCK_ImplicitConversion);
7720 LHS = ImpCastExprToType(E, RHSType,
John McCall9320b872011-09-09 05:25:32 +00007721 RPT ? CK_BitCast :CK_CPointerToObjCPointerCast);
Fariborz Jahanian374089e2013-07-31 17:12:26 +00007722 }
7723 else {
7724 Expr *E = RHS.take();
7725 if (getLangOpts().ObjCAutoRefCount)
7726 CheckObjCARCConversion(SourceRange(), LHSType, E, CCK_ImplicitConversion);
7727 RHS = ImpCastExprToType(E, LHSType,
John McCall9320b872011-09-09 05:25:32 +00007728 LPT ? CK_BitCast :CK_CPointerToObjCPointerCast);
Fariborz Jahanian374089e2013-07-31 17:12:26 +00007729 }
Douglas Gregorca63811b2008-11-19 03:25:36 +00007730 return ResultTy;
Steve Naroffea54d9e2008-10-20 18:19:10 +00007731 }
Richard Trieub80728f2011-09-06 21:43:51 +00007732 if (LHSType->isObjCObjectPointerType() &&
7733 RHSType->isObjCObjectPointerType()) {
7734 if (!Context.areComparableObjCPointerTypes(LHSType, RHSType))
7735 diagnoseDistinctPointerComparison(*this, Loc, LHS, RHS,
Richard Trieudd82a5c2011-09-02 02:55:45 +00007736 /*isError*/false);
Jordan Rosed49a33e2012-06-08 21:14:25 +00007737 if (isObjCObjectLiteral(LHS) || isObjCObjectLiteral(RHS))
Jordan Rose7660f782012-07-17 17:46:40 +00007738 diagnoseObjCLiteralComparison(*this, Loc, LHS, RHS, Opc);
Jordan Rosed49a33e2012-06-08 21:14:25 +00007739
John McCall7684dde2011-03-11 04:25:25 +00007740 if (LHSIsNull && !RHSIsNull)
Richard Trieub80728f2011-09-06 21:43:51 +00007741 LHS = ImpCastExprToType(LHS.take(), RHSType, CK_BitCast);
John McCall7684dde2011-03-11 04:25:25 +00007742 else
Richard Trieub80728f2011-09-06 21:43:51 +00007743 RHS = ImpCastExprToType(RHS.take(), LHSType, CK_BitCast);
Douglas Gregorca63811b2008-11-19 03:25:36 +00007744 return ResultTy;
Steve Naroffb788d9b2008-06-03 14:04:54 +00007745 }
Fariborz Jahanian134cbef2007-12-20 01:06:58 +00007746 }
Richard Trieub80728f2011-09-06 21:43:51 +00007747 if ((LHSType->isAnyPointerType() && RHSType->isIntegerType()) ||
7748 (LHSType->isIntegerType() && RHSType->isAnyPointerType())) {
Chris Lattnerd99bd522009-08-23 00:03:44 +00007749 unsigned DiagID = 0;
Douglas Gregorf267edd2010-06-15 21:38:40 +00007750 bool isError = false;
Douglas Gregor0064c592012-09-14 04:35:37 +00007751 if (LangOpts.DebuggerSupport) {
7752 // Under a debugger, allow the comparison of pointers to integers,
7753 // since users tend to want to compare addresses.
7754 } else if ((LHSIsNull && LHSType->isIntegerType()) ||
Richard Trieub80728f2011-09-06 21:43:51 +00007755 (RHSIsNull && RHSType->isIntegerType())) {
David Blaikiebbafb8a2012-03-11 07:00:24 +00007756 if (IsRelational && !getLangOpts().CPlusPlus)
Chris Lattnerd99bd522009-08-23 00:03:44 +00007757 DiagID = diag::ext_typecheck_ordered_comparison_of_pointer_and_zero;
David Blaikiebbafb8a2012-03-11 07:00:24 +00007758 } else if (IsRelational && !getLangOpts().CPlusPlus)
Chris Lattnerd99bd522009-08-23 00:03:44 +00007759 DiagID = diag::ext_typecheck_ordered_comparison_of_pointer_integer;
David Blaikiebbafb8a2012-03-11 07:00:24 +00007760 else if (getLangOpts().CPlusPlus) {
Douglas Gregorf267edd2010-06-15 21:38:40 +00007761 DiagID = diag::err_typecheck_comparison_of_pointer_integer;
7762 isError = true;
7763 } else
Chris Lattnerd99bd522009-08-23 00:03:44 +00007764 DiagID = diag::ext_typecheck_comparison_of_pointer_integer;
Mike Stump11289f42009-09-09 15:08:12 +00007765
Chris Lattnerd99bd522009-08-23 00:03:44 +00007766 if (DiagID) {
Chris Lattnerf8344db2009-08-22 18:58:31 +00007767 Diag(Loc, DiagID)
Richard Trieub80728f2011-09-06 21:43:51 +00007768 << LHSType << RHSType << LHS.get()->getSourceRange()
7769 << RHS.get()->getSourceRange();
Douglas Gregorf267edd2010-06-15 21:38:40 +00007770 if (isError)
7771 return QualType();
Chris Lattnerf8344db2009-08-22 18:58:31 +00007772 }
Douglas Gregorf267edd2010-06-15 21:38:40 +00007773
Richard Trieub80728f2011-09-06 21:43:51 +00007774 if (LHSType->isIntegerType())
7775 LHS = ImpCastExprToType(LHS.take(), RHSType,
John McCalle84af4e2010-11-13 01:35:44 +00007776 LHSIsNull ? CK_NullToPointer : CK_IntegralToPointer);
Chris Lattnerd99bd522009-08-23 00:03:44 +00007777 else
Richard Trieub80728f2011-09-06 21:43:51 +00007778 RHS = ImpCastExprToType(RHS.take(), LHSType,
John McCalle84af4e2010-11-13 01:35:44 +00007779 RHSIsNull ? CK_NullToPointer : CK_IntegralToPointer);
Douglas Gregorca63811b2008-11-19 03:25:36 +00007780 return ResultTy;
Steve Naroff043d45d2007-05-15 02:32:35 +00007781 }
Douglas Gregorf267edd2010-06-15 21:38:40 +00007782
Steve Naroff4b191572008-09-04 16:56:14 +00007783 // Handle block pointers.
Richard Trieuba63ce62011-09-09 01:45:06 +00007784 if (!IsRelational && RHSIsNull
Richard Trieub80728f2011-09-06 21:43:51 +00007785 && LHSType->isBlockPointerType() && RHSType->isIntegerType()) {
7786 RHS = ImpCastExprToType(RHS.take(), LHSType, CK_NullToPointer);
Douglas Gregorca63811b2008-11-19 03:25:36 +00007787 return ResultTy;
Steve Naroff4b191572008-09-04 16:56:14 +00007788 }
Richard Trieuba63ce62011-09-09 01:45:06 +00007789 if (!IsRelational && LHSIsNull
Richard Trieub80728f2011-09-06 21:43:51 +00007790 && LHSType->isIntegerType() && RHSType->isBlockPointerType()) {
7791 LHS = ImpCastExprToType(LHS.take(), RHSType, CK_NullToPointer);
Douglas Gregorca63811b2008-11-19 03:25:36 +00007792 return ResultTy;
Steve Naroff4b191572008-09-04 16:56:14 +00007793 }
Douglas Gregor48e6bbf2011-03-01 17:16:20 +00007794
Richard Trieub80728f2011-09-06 21:43:51 +00007795 return InvalidOperands(Loc, LHS, RHS);
Steve Naroff26c8ea52007-03-21 21:08:52 +00007796}
7797
Tanya Lattner20248222012-01-16 21:02:28 +00007798
7799// Return a signed type that is of identical size and number of elements.
7800// For floating point vectors, return an integer type of identical size
7801// and number of elements.
7802QualType Sema::GetSignedVectorType(QualType V) {
7803 const VectorType *VTy = V->getAs<VectorType>();
7804 unsigned TypeSize = Context.getTypeSize(VTy->getElementType());
7805 if (TypeSize == Context.getTypeSize(Context.CharTy))
7806 return Context.getExtVectorType(Context.CharTy, VTy->getNumElements());
7807 else if (TypeSize == Context.getTypeSize(Context.ShortTy))
7808 return Context.getExtVectorType(Context.ShortTy, VTy->getNumElements());
7809 else if (TypeSize == Context.getTypeSize(Context.IntTy))
7810 return Context.getExtVectorType(Context.IntTy, VTy->getNumElements());
7811 else if (TypeSize == Context.getTypeSize(Context.LongTy))
7812 return Context.getExtVectorType(Context.LongTy, VTy->getNumElements());
7813 assert(TypeSize == Context.getTypeSize(Context.LongLongTy) &&
7814 "Unhandled vector element size in vector compare");
7815 return Context.getExtVectorType(Context.LongLongTy, VTy->getNumElements());
7816}
7817
Nate Begeman191a6b12008-07-14 18:02:46 +00007818/// CheckVectorCompareOperands - vector comparisons are a clang extension that
Mike Stump4e1f26a2009-02-19 03:04:26 +00007819/// operates on extended vector types. Instead of producing an IntTy result,
Nate Begeman191a6b12008-07-14 18:02:46 +00007820/// like a scalar comparison, a vector comparison produces a vector of integer
7821/// types.
Richard Trieubcce2f72011-09-07 01:19:57 +00007822QualType Sema::CheckVectorCompareOperands(ExprResult &LHS, ExprResult &RHS,
Chris Lattner326f7572008-11-18 01:30:42 +00007823 SourceLocation Loc,
Richard Trieuba63ce62011-09-09 01:45:06 +00007824 bool IsRelational) {
Nate Begeman191a6b12008-07-14 18:02:46 +00007825 // Check to make sure we're operating on vectors of the same type and width,
7826 // Allowing one side to be a scalar of element type.
Richard Trieubcce2f72011-09-07 01:19:57 +00007827 QualType vType = CheckVectorOperands(LHS, RHS, Loc, /*isCompAssign*/false);
Nate Begeman191a6b12008-07-14 18:02:46 +00007828 if (vType.isNull())
7829 return vType;
Mike Stump4e1f26a2009-02-19 03:04:26 +00007830
Richard Trieubcce2f72011-09-07 01:19:57 +00007831 QualType LHSType = LHS.get()->getType();
Mike Stump4e1f26a2009-02-19 03:04:26 +00007832
Anton Yartsev530deb92011-03-27 15:36:07 +00007833 // If AltiVec, the comparison results in a numeric type, i.e.
7834 // bool for C++, int for C
Anton Yartsev93900c72011-03-28 21:00:05 +00007835 if (vType->getAs<VectorType>()->getVectorKind() == VectorType::AltiVecVector)
Anton Yartsev530deb92011-03-27 15:36:07 +00007836 return Context.getLogicalOperationType();
7837
Nate Begeman191a6b12008-07-14 18:02:46 +00007838 // For non-floating point types, check for self-comparisons of the form
7839 // x == x, x != x, x < x, etc. These always evaluate to a constant, and
7840 // often indicate logic errors in the program.
Richard Trieubcce2f72011-09-07 01:19:57 +00007841 if (!LHSType->hasFloatingRepresentation()) {
Richard Smith508ebf32011-10-28 03:31:48 +00007842 if (DeclRefExpr* DRL
7843 = dyn_cast<DeclRefExpr>(LHS.get()->IgnoreParenImpCasts()))
7844 if (DeclRefExpr* DRR
7845 = dyn_cast<DeclRefExpr>(RHS.get()->IgnoreParenImpCasts()))
Nate Begeman191a6b12008-07-14 18:02:46 +00007846 if (DRL->getDecl() == DRR->getDecl())
Ted Kremenek3427fac2011-02-23 01:52:04 +00007847 DiagRuntimeBehavior(Loc, 0,
Douglas Gregorec170db2010-06-08 19:50:34 +00007848 PDiag(diag::warn_comparison_always)
7849 << 0 // self-
7850 << 2 // "a constant"
7851 );
Nate Begeman191a6b12008-07-14 18:02:46 +00007852 }
Mike Stump4e1f26a2009-02-19 03:04:26 +00007853
Nate Begeman191a6b12008-07-14 18:02:46 +00007854 // Check for comparisons of floating point operands using != and ==.
Richard Trieuba63ce62011-09-09 01:45:06 +00007855 if (!IsRelational && LHSType->hasFloatingRepresentation()) {
David Blaikieca043222012-01-16 05:16:03 +00007856 assert (RHS.get()->getType()->hasFloatingRepresentation());
Richard Trieubcce2f72011-09-07 01:19:57 +00007857 CheckFloatComparison(Loc, LHS.get(), RHS.get());
Nate Begeman191a6b12008-07-14 18:02:46 +00007858 }
Tanya Lattner20248222012-01-16 21:02:28 +00007859
7860 // Return a signed type for the vector.
7861 return GetSignedVectorType(LHSType);
7862}
Mike Stump4e1f26a2009-02-19 03:04:26 +00007863
Tanya Lattner3dd33b22012-01-19 01:16:16 +00007864QualType Sema::CheckVectorLogicalOperands(ExprResult &LHS, ExprResult &RHS,
7865 SourceLocation Loc) {
Tanya Lattner20248222012-01-16 21:02:28 +00007866 // Ensure that either both operands are of the same vector type, or
7867 // one operand is of a vector type and the other is of its element type.
7868 QualType vType = CheckVectorOperands(LHS, RHS, Loc, false);
Joey Gouly7d00f002013-02-21 11:49:56 +00007869 if (vType.isNull())
7870 return InvalidOperands(Loc, LHS, RHS);
7871 if (getLangOpts().OpenCL && getLangOpts().OpenCLVersion < 120 &&
7872 vType->hasFloatingRepresentation())
Tanya Lattner20248222012-01-16 21:02:28 +00007873 return InvalidOperands(Loc, LHS, RHS);
7874
7875 return GetSignedVectorType(LHS.get()->getType());
Nate Begeman191a6b12008-07-14 18:02:46 +00007876}
7877
Steve Naroff218bc2b2007-05-04 21:54:46 +00007878inline QualType Sema::CheckBitwiseOperands(
Richard Trieuba63ce62011-09-09 01:45:06 +00007879 ExprResult &LHS, ExprResult &RHS, SourceLocation Loc, bool IsCompAssign) {
Richard Trieuf8916e12011-09-16 00:53:10 +00007880 checkArithmeticNull(*this, LHS, RHS, Loc, /*isCompare=*/false);
7881
Richard Trieubcce2f72011-09-07 01:19:57 +00007882 if (LHS.get()->getType()->isVectorType() ||
7883 RHS.get()->getType()->isVectorType()) {
7884 if (LHS.get()->getType()->hasIntegerRepresentation() &&
7885 RHS.get()->getType()->hasIntegerRepresentation())
Richard Trieuba63ce62011-09-09 01:45:06 +00007886 return CheckVectorOperands(LHS, RHS, Loc, IsCompAssign);
Douglas Gregor5cc2c8b2010-07-23 15:58:24 +00007887
Richard Trieubcce2f72011-09-07 01:19:57 +00007888 return InvalidOperands(Loc, LHS, RHS);
Douglas Gregor5cc2c8b2010-07-23 15:58:24 +00007889 }
Steve Naroffb8ea4fb2007-07-13 23:32:42 +00007890
Richard Trieubcce2f72011-09-07 01:19:57 +00007891 ExprResult LHSResult = Owned(LHS), RHSResult = Owned(RHS);
7892 QualType compType = UsualArithmeticConversions(LHSResult, RHSResult,
Richard Trieuba63ce62011-09-09 01:45:06 +00007893 IsCompAssign);
Richard Trieubcce2f72011-09-07 01:19:57 +00007894 if (LHSResult.isInvalid() || RHSResult.isInvalid())
John Wiegley01296292011-04-08 18:41:53 +00007895 return QualType();
Richard Trieubcce2f72011-09-07 01:19:57 +00007896 LHS = LHSResult.take();
7897 RHS = RHSResult.take();
Mike Stump4e1f26a2009-02-19 03:04:26 +00007898
Eli Friedman93ee5ca2012-06-16 02:19:17 +00007899 if (!compType.isNull() && compType->isIntegralOrUnscopedEnumerationType())
Steve Naroffbe4c4d12007-08-24 19:07:16 +00007900 return compType;
Richard Trieubcce2f72011-09-07 01:19:57 +00007901 return InvalidOperands(Loc, LHS, RHS);
Steve Naroff26c8ea52007-03-21 21:08:52 +00007902}
7903
Steve Naroff218bc2b2007-05-04 21:54:46 +00007904inline QualType Sema::CheckLogicalOperands( // C99 6.5.[13,14]
Richard Trieubcce2f72011-09-07 01:19:57 +00007905 ExprResult &LHS, ExprResult &RHS, SourceLocation Loc, unsigned Opc) {
Chris Lattner8406c512010-07-13 19:41:32 +00007906
Tanya Lattner20248222012-01-16 21:02:28 +00007907 // Check vector operands differently.
7908 if (LHS.get()->getType()->isVectorType() || RHS.get()->getType()->isVectorType())
7909 return CheckVectorLogicalOperands(LHS, RHS, Loc);
7910
Chris Lattner8406c512010-07-13 19:41:32 +00007911 // Diagnose cases where the user write a logical and/or but probably meant a
7912 // bitwise one. We do this when the LHS is a non-bool integer and the RHS
7913 // is a constant.
Richard Trieubcce2f72011-09-07 01:19:57 +00007914 if (LHS.get()->getType()->isIntegerType() &&
7915 !LHS.get()->getType()->isBooleanType() &&
7916 RHS.get()->getType()->isIntegerType() && !RHS.get()->isValueDependent() &&
Richard Trieucfe39262011-07-15 00:00:51 +00007917 // Don't warn in macros or template instantiations.
7918 !Loc.isMacroID() && ActiveTemplateInstantiations.empty()) {
Chris Lattner938533d2010-07-24 01:10:11 +00007919 // If the RHS can be constant folded, and if it constant folds to something
7920 // that isn't 0 or 1 (which indicate a potential logical operation that
7921 // happened to fold to true/false) then warn.
Chandler Carruthe54ff6c2011-05-31 05:41:42 +00007922 // Parens on the RHS are ignored.
Richard Smith00ab3ae2011-10-16 23:01:09 +00007923 llvm::APSInt Result;
7924 if (RHS.get()->EvaluateAsInt(Result, Context))
David Blaikiebbafb8a2012-03-11 07:00:24 +00007925 if ((getLangOpts().Bool && !RHS.get()->getType()->isBooleanType()) ||
Richard Smith00ab3ae2011-10-16 23:01:09 +00007926 (Result != 0 && Result != 1)) {
Chandler Carruthe54ff6c2011-05-31 05:41:42 +00007927 Diag(Loc, diag::warn_logical_instead_of_bitwise)
Richard Trieubcce2f72011-09-07 01:19:57 +00007928 << RHS.get()->getSourceRange()
Matt Beaumont-Gay0a0ba9d2011-08-15 17:50:06 +00007929 << (Opc == BO_LAnd ? "&&" : "||");
7930 // Suggest replacing the logical operator with the bitwise version
7931 Diag(Loc, diag::note_logical_instead_of_bitwise_change_operator)
7932 << (Opc == BO_LAnd ? "&" : "|")
7933 << FixItHint::CreateReplacement(SourceRange(
7934 Loc, Lexer::getLocForEndOfToken(Loc, 0, getSourceManager(),
David Blaikiebbafb8a2012-03-11 07:00:24 +00007935 getLangOpts())),
Matt Beaumont-Gay0a0ba9d2011-08-15 17:50:06 +00007936 Opc == BO_LAnd ? "&" : "|");
7937 if (Opc == BO_LAnd)
7938 // Suggest replacing "Foo() && kNonZero" with "Foo()"
7939 Diag(Loc, diag::note_logical_instead_of_bitwise_remove_constant)
7940 << FixItHint::CreateRemoval(
7941 SourceRange(
Richard Trieubcce2f72011-09-07 01:19:57 +00007942 Lexer::getLocForEndOfToken(LHS.get()->getLocEnd(),
Matt Beaumont-Gay0a0ba9d2011-08-15 17:50:06 +00007943 0, getSourceManager(),
David Blaikiebbafb8a2012-03-11 07:00:24 +00007944 getLangOpts()),
Richard Trieubcce2f72011-09-07 01:19:57 +00007945 RHS.get()->getLocEnd()));
Matt Beaumont-Gay0a0ba9d2011-08-15 17:50:06 +00007946 }
Chris Lattner938533d2010-07-24 01:10:11 +00007947 }
Joey Gouly7d00f002013-02-21 11:49:56 +00007948
David Blaikiebbafb8a2012-03-11 07:00:24 +00007949 if (!Context.getLangOpts().CPlusPlus) {
Joey Gouly7d00f002013-02-21 11:49:56 +00007950 // OpenCL v1.1 s6.3.g: The logical operators and (&&), or (||) do
7951 // not operate on the built-in scalar and vector float types.
7952 if (Context.getLangOpts().OpenCL &&
7953 Context.getLangOpts().OpenCLVersion < 120) {
7954 if (LHS.get()->getType()->isFloatingType() ||
7955 RHS.get()->getType()->isFloatingType())
7956 return InvalidOperands(Loc, LHS, RHS);
7957 }
7958
Richard Trieubcce2f72011-09-07 01:19:57 +00007959 LHS = UsualUnaryConversions(LHS.take());
7960 if (LHS.isInvalid())
John Wiegley01296292011-04-08 18:41:53 +00007961 return QualType();
Mike Stump4e1f26a2009-02-19 03:04:26 +00007962
Richard Trieubcce2f72011-09-07 01:19:57 +00007963 RHS = UsualUnaryConversions(RHS.take());
7964 if (RHS.isInvalid())
John Wiegley01296292011-04-08 18:41:53 +00007965 return QualType();
7966
Richard Trieubcce2f72011-09-07 01:19:57 +00007967 if (!LHS.get()->getType()->isScalarType() ||
7968 !RHS.get()->getType()->isScalarType())
7969 return InvalidOperands(Loc, LHS, RHS);
Kovarththanan Rajaratnamba2c6522010-03-13 10:17:05 +00007970
Anders Carlsson2e7bc112009-11-23 21:47:44 +00007971 return Context.IntTy;
Anders Carlsson35a99d92009-10-16 01:44:21 +00007972 }
Kovarththanan Rajaratnamba2c6522010-03-13 10:17:05 +00007973
John McCall4a2429a2010-06-04 00:29:51 +00007974 // The following is safe because we only use this method for
7975 // non-overloadable operands.
7976
Anders Carlsson2e7bc112009-11-23 21:47:44 +00007977 // C++ [expr.log.and]p1
7978 // C++ [expr.log.or]p1
John McCall4a2429a2010-06-04 00:29:51 +00007979 // The operands are both contextually converted to type bool.
Richard Trieubcce2f72011-09-07 01:19:57 +00007980 ExprResult LHSRes = PerformContextuallyConvertToBool(LHS.get());
7981 if (LHSRes.isInvalid())
7982 return InvalidOperands(Loc, LHS, RHS);
Benjamin Kramer62b95d82012-08-23 21:35:17 +00007983 LHS = LHSRes;
John Wiegley01296292011-04-08 18:41:53 +00007984
Richard Trieubcce2f72011-09-07 01:19:57 +00007985 ExprResult RHSRes = PerformContextuallyConvertToBool(RHS.get());
7986 if (RHSRes.isInvalid())
7987 return InvalidOperands(Loc, LHS, RHS);
Benjamin Kramer62b95d82012-08-23 21:35:17 +00007988 RHS = RHSRes;
Kovarththanan Rajaratnamba2c6522010-03-13 10:17:05 +00007989
Anders Carlsson2e7bc112009-11-23 21:47:44 +00007990 // C++ [expr.log.and]p2
7991 // C++ [expr.log.or]p2
7992 // The result is a bool.
7993 return Context.BoolTy;
Steve Naroffae4143e2007-04-26 20:39:23 +00007994}
7995
Fariborz Jahanian071caef2011-03-26 19:48:30 +00007996static bool IsReadonlyMessage(Expr *E, Sema &S) {
John McCall526ab472011-10-25 17:37:35 +00007997 const MemberExpr *ME = dyn_cast<MemberExpr>(E);
7998 if (!ME) return false;
7999 if (!isa<FieldDecl>(ME->getMemberDecl())) return false;
8000 ObjCMessageExpr *Base =
8001 dyn_cast<ObjCMessageExpr>(ME->getBase()->IgnoreParenImpCasts());
8002 if (!Base) return false;
8003 return Base->getMethodDecl() != 0;
Fariborz Jahanian071caef2011-03-26 19:48:30 +00008004}
8005
John McCall5fa2ef42012-03-13 00:37:01 +00008006/// Is the given expression (which must be 'const') a reference to a
8007/// variable which was originally non-const, but which has become
8008/// 'const' due to being captured within a block?
8009enum NonConstCaptureKind { NCCK_None, NCCK_Block, NCCK_Lambda };
8010static NonConstCaptureKind isReferenceToNonConstCapture(Sema &S, Expr *E) {
8011 assert(E->isLValue() && E->getType().isConstQualified());
8012 E = E->IgnoreParens();
8013
8014 // Must be a reference to a declaration from an enclosing scope.
8015 DeclRefExpr *DRE = dyn_cast<DeclRefExpr>(E);
8016 if (!DRE) return NCCK_None;
8017 if (!DRE->refersToEnclosingLocal()) return NCCK_None;
8018
8019 // The declaration must be a variable which is not declared 'const'.
8020 VarDecl *var = dyn_cast<VarDecl>(DRE->getDecl());
8021 if (!var) return NCCK_None;
8022 if (var->getType().isConstQualified()) return NCCK_None;
8023 assert(var->hasLocalStorage() && "capture added 'const' to non-local?");
8024
8025 // Decide whether the first capture was for a block or a lambda.
8026 DeclContext *DC = S.CurContext;
8027 while (DC->getParent() != var->getDeclContext())
8028 DC = DC->getParent();
8029 return (isa<BlockDecl>(DC) ? NCCK_Block : NCCK_Lambda);
8030}
8031
Chris Lattner30bd3272008-11-18 01:22:49 +00008032/// CheckForModifiableLvalue - Verify that E is a modifiable lvalue. If not,
8033/// emit an error and return true. If so, return false.
8034static bool CheckForModifiableLvalue(Expr *E, SourceLocation Loc, Sema &S) {
Fariborz Jahanianca5c5972012-04-10 17:30:10 +00008035 assert(!E->hasPlaceholderType(BuiltinType::PseudoObject));
Daniel Dunbarc2223ab2009-04-15 00:08:05 +00008036 SourceLocation OrigLoc = Loc;
Mike Stump11289f42009-09-09 15:08:12 +00008037 Expr::isModifiableLvalueResult IsLV = E->isModifiableLvalue(S.Context,
Daniel Dunbarc2223ab2009-04-15 00:08:05 +00008038 &Loc);
Eli Friedmanaa205c42013-06-27 01:36:36 +00008039 if (IsLV == Expr::MLV_ClassTemporary && IsReadonlyMessage(E, S))
Fariborz Jahanian071caef2011-03-26 19:48:30 +00008040 IsLV = Expr::MLV_InvalidMessageExpression;
Chris Lattner30bd3272008-11-18 01:22:49 +00008041 if (IsLV == Expr::MLV_Valid)
8042 return false;
Mike Stump4e1f26a2009-02-19 03:04:26 +00008043
Chris Lattner30bd3272008-11-18 01:22:49 +00008044 unsigned Diag = 0;
8045 bool NeedType = false;
8046 switch (IsLV) { // C99 6.5.16p2
John McCall31168b02011-06-15 23:02:42 +00008047 case Expr::MLV_ConstQualified:
8048 Diag = diag::err_typecheck_assign_const;
8049
John McCall5fa2ef42012-03-13 00:37:01 +00008050 // Use a specialized diagnostic when we're assigning to an object
8051 // from an enclosing function or block.
8052 if (NonConstCaptureKind NCCK = isReferenceToNonConstCapture(S, E)) {
8053 if (NCCK == NCCK_Block)
8054 Diag = diag::err_block_decl_ref_not_modifiable_lvalue;
8055 else
8056 Diag = diag::err_lambda_decl_ref_not_modifiable_lvalue;
8057 break;
8058 }
8059
John McCalld4631322011-06-17 06:42:21 +00008060 // In ARC, use some specialized diagnostics for occasions where we
8061 // infer 'const'. These are always pseudo-strong variables.
David Blaikiebbafb8a2012-03-11 07:00:24 +00008062 if (S.getLangOpts().ObjCAutoRefCount) {
John McCall31168b02011-06-15 23:02:42 +00008063 DeclRefExpr *declRef = dyn_cast<DeclRefExpr>(E->IgnoreParenCasts());
8064 if (declRef && isa<VarDecl>(declRef->getDecl())) {
8065 VarDecl *var = cast<VarDecl>(declRef->getDecl());
8066
John McCalld4631322011-06-17 06:42:21 +00008067 // Use the normal diagnostic if it's pseudo-__strong but the
8068 // user actually wrote 'const'.
8069 if (var->isARCPseudoStrong() &&
8070 (!var->getTypeSourceInfo() ||
8071 !var->getTypeSourceInfo()->getType().isConstQualified())) {
8072 // There are two pseudo-strong cases:
8073 // - self
John McCall31168b02011-06-15 23:02:42 +00008074 ObjCMethodDecl *method = S.getCurMethodDecl();
8075 if (method && var == method->getSelfDecl())
Ted Kremenek1fcdaa92011-11-14 21:59:25 +00008076 Diag = method->isClassMethod()
8077 ? diag::err_typecheck_arc_assign_self_class_method
8078 : diag::err_typecheck_arc_assign_self;
John McCalld4631322011-06-17 06:42:21 +00008079
8080 // - fast enumeration variables
8081 else
John McCall31168b02011-06-15 23:02:42 +00008082 Diag = diag::err_typecheck_arr_assign_enumeration;
John McCalld4631322011-06-17 06:42:21 +00008083
John McCall31168b02011-06-15 23:02:42 +00008084 SourceRange Assign;
8085 if (Loc != OrigLoc)
8086 Assign = SourceRange(OrigLoc, OrigLoc);
8087 S.Diag(Loc, Diag) << E->getSourceRange() << Assign;
8088 // We need to preserve the AST regardless, so migration tool
8089 // can do its job.
8090 return false;
8091 }
8092 }
8093 }
8094
8095 break;
Mike Stump4e1f26a2009-02-19 03:04:26 +00008096 case Expr::MLV_ArrayType:
Richard Smitheb3cad52012-06-04 22:27:30 +00008097 case Expr::MLV_ArrayTemporary:
Chris Lattner30bd3272008-11-18 01:22:49 +00008098 Diag = diag::err_typecheck_array_not_modifiable_lvalue;
8099 NeedType = true;
8100 break;
Mike Stump4e1f26a2009-02-19 03:04:26 +00008101 case Expr::MLV_NotObjectType:
Chris Lattner30bd3272008-11-18 01:22:49 +00008102 Diag = diag::err_typecheck_non_object_not_modifiable_lvalue;
8103 NeedType = true;
8104 break;
Chris Lattner9b3bbe92008-11-17 19:51:54 +00008105 case Expr::MLV_LValueCast:
Chris Lattner30bd3272008-11-18 01:22:49 +00008106 Diag = diag::err_typecheck_lvalue_casts_not_supported;
8107 break;
Douglas Gregorb154fdc2010-02-16 21:39:57 +00008108 case Expr::MLV_Valid:
8109 llvm_unreachable("did not take early return for MLV_Valid");
Chris Lattner9bad62c2008-01-04 18:04:52 +00008110 case Expr::MLV_InvalidExpression:
Douglas Gregorb154fdc2010-02-16 21:39:57 +00008111 case Expr::MLV_MemberFunction:
8112 case Expr::MLV_ClassTemporary:
Chris Lattner30bd3272008-11-18 01:22:49 +00008113 Diag = diag::err_typecheck_expression_not_modifiable_lvalue;
8114 break;
Chris Lattner9bad62c2008-01-04 18:04:52 +00008115 case Expr::MLV_IncompleteType:
8116 case Expr::MLV_IncompleteVoidType:
Douglas Gregored0cfbd2009-03-09 16:13:40 +00008117 return S.RequireCompleteType(Loc, E->getType(),
Douglas Gregor7bfb2d02012-05-04 16:32:21 +00008118 diag::err_typecheck_incomplete_type_not_modifiable_lvalue, E);
Chris Lattner9bad62c2008-01-04 18:04:52 +00008119 case Expr::MLV_DuplicateVectorComponents:
Chris Lattner30bd3272008-11-18 01:22:49 +00008120 Diag = diag::err_typecheck_duplicate_vector_components_not_mlvalue;
8121 break;
Fariborz Jahanian5118c412008-11-22 20:25:50 +00008122 case Expr::MLV_NoSetterProperty:
John McCall526ab472011-10-25 17:37:35 +00008123 llvm_unreachable("readonly properties should be processed differently");
Fariborz Jahanian071caef2011-03-26 19:48:30 +00008124 case Expr::MLV_InvalidMessageExpression:
8125 Diag = diag::error_readonly_message_assignment;
8126 break;
Fariborz Jahaniane8d28902009-12-15 23:59:41 +00008127 case Expr::MLV_SubObjCPropertySetting:
8128 Diag = diag::error_no_subobject_property_setting;
8129 break;
Steve Naroff218bc2b2007-05-04 21:54:46 +00008130 }
Steve Naroffad373bd2007-07-31 12:34:36 +00008131
Daniel Dunbarc2223ab2009-04-15 00:08:05 +00008132 SourceRange Assign;
8133 if (Loc != OrigLoc)
8134 Assign = SourceRange(OrigLoc, OrigLoc);
Chris Lattner30bd3272008-11-18 01:22:49 +00008135 if (NeedType)
Daniel Dunbarc2223ab2009-04-15 00:08:05 +00008136 S.Diag(Loc, Diag) << E->getType() << E->getSourceRange() << Assign;
Chris Lattner30bd3272008-11-18 01:22:49 +00008137 else
Mike Stump11289f42009-09-09 15:08:12 +00008138 S.Diag(Loc, Diag) << E->getSourceRange() << Assign;
Chris Lattner30bd3272008-11-18 01:22:49 +00008139 return true;
8140}
8141
Nico Weberb8124d12012-07-03 02:03:06 +00008142static void CheckIdentityFieldAssignment(Expr *LHSExpr, Expr *RHSExpr,
8143 SourceLocation Loc,
8144 Sema &Sema) {
8145 // C / C++ fields
Nico Weber33fd5232012-06-28 23:53:12 +00008146 MemberExpr *ML = dyn_cast<MemberExpr>(LHSExpr);
8147 MemberExpr *MR = dyn_cast<MemberExpr>(RHSExpr);
8148 if (ML && MR && ML->getMemberDecl() == MR->getMemberDecl()) {
8149 if (isa<CXXThisExpr>(ML->getBase()) && isa<CXXThisExpr>(MR->getBase()))
Nico Weberb8124d12012-07-03 02:03:06 +00008150 Sema.Diag(Loc, diag::warn_identity_field_assign) << 0;
Nico Weber33fd5232012-06-28 23:53:12 +00008151 }
Chris Lattner30bd3272008-11-18 01:22:49 +00008152
Nico Weberb8124d12012-07-03 02:03:06 +00008153 // Objective-C instance variables
Nico Weber33fd5232012-06-28 23:53:12 +00008154 ObjCIvarRefExpr *OL = dyn_cast<ObjCIvarRefExpr>(LHSExpr);
8155 ObjCIvarRefExpr *OR = dyn_cast<ObjCIvarRefExpr>(RHSExpr);
8156 if (OL && OR && OL->getDecl() == OR->getDecl()) {
8157 DeclRefExpr *RL = dyn_cast<DeclRefExpr>(OL->getBase()->IgnoreImpCasts());
8158 DeclRefExpr *RR = dyn_cast<DeclRefExpr>(OR->getBase()->IgnoreImpCasts());
8159 if (RL && RR && RL->getDecl() == RR->getDecl())
Nico Weberb8124d12012-07-03 02:03:06 +00008160 Sema.Diag(Loc, diag::warn_identity_field_assign) << 1;
Nico Weber33fd5232012-06-28 23:53:12 +00008161 }
8162}
Chris Lattner30bd3272008-11-18 01:22:49 +00008163
8164// C99 6.5.16.1
Richard Trieuda4f43a62011-09-07 01:33:52 +00008165QualType Sema::CheckAssignmentOperands(Expr *LHSExpr, ExprResult &RHS,
Chris Lattner326f7572008-11-18 01:30:42 +00008166 SourceLocation Loc,
8167 QualType CompoundType) {
John McCall526ab472011-10-25 17:37:35 +00008168 assert(!LHSExpr->hasPlaceholderType(BuiltinType::PseudoObject));
8169
Chris Lattner326f7572008-11-18 01:30:42 +00008170 // Verify that LHS is a modifiable lvalue, and emit error if not.
Richard Trieuda4f43a62011-09-07 01:33:52 +00008171 if (CheckForModifiableLvalue(LHSExpr, Loc, *this))
Chris Lattner30bd3272008-11-18 01:22:49 +00008172 return QualType();
Chris Lattner326f7572008-11-18 01:30:42 +00008173
Richard Trieuda4f43a62011-09-07 01:33:52 +00008174 QualType LHSType = LHSExpr->getType();
Richard Trieucfc491d2011-08-02 04:35:43 +00008175 QualType RHSType = CompoundType.isNull() ? RHS.get()->getType() :
8176 CompoundType;
Chris Lattner9bad62c2008-01-04 18:04:52 +00008177 AssignConvertType ConvTy;
Chris Lattner326f7572008-11-18 01:30:42 +00008178 if (CompoundType.isNull()) {
Nico Weber33fd5232012-06-28 23:53:12 +00008179 Expr *RHSCheck = RHS.get();
8180
Nico Weberb8124d12012-07-03 02:03:06 +00008181 CheckIdentityFieldAssignment(LHSExpr, RHSCheck, Loc, *this);
Nico Weber33fd5232012-06-28 23:53:12 +00008182
Fariborz Jahanianbe21aa32010-06-07 22:02:01 +00008183 QualType LHSTy(LHSType);
Fariborz Jahanianbe21aa32010-06-07 22:02:01 +00008184 ConvTy = CheckSingleAssignmentConstraints(LHSTy, RHS);
John Wiegley01296292011-04-08 18:41:53 +00008185 if (RHS.isInvalid())
8186 return QualType();
Fariborz Jahanian255c0952009-01-13 23:34:40 +00008187 // Special case of NSObject attributes on c-style pointer types.
8188 if (ConvTy == IncompatiblePointer &&
8189 ((Context.isObjCNSObjectType(LHSType) &&
Steve Naroff79d12152009-07-16 15:41:00 +00008190 RHSType->isObjCObjectPointerType()) ||
Fariborz Jahanian255c0952009-01-13 23:34:40 +00008191 (Context.isObjCNSObjectType(RHSType) &&
Steve Naroff79d12152009-07-16 15:41:00 +00008192 LHSType->isObjCObjectPointerType())))
Fariborz Jahanian255c0952009-01-13 23:34:40 +00008193 ConvTy = Compatible;
Mike Stump4e1f26a2009-02-19 03:04:26 +00008194
John McCall7decc9e2010-11-18 06:31:45 +00008195 if (ConvTy == Compatible &&
Fariborz Jahaniane2a77762012-01-24 19:40:13 +00008196 LHSType->isObjCObjectType())
Fariborz Jahanian3c4225a2012-01-24 18:05:45 +00008197 Diag(Loc, diag::err_objc_object_assignment)
8198 << LHSType;
John McCall7decc9e2010-11-18 06:31:45 +00008199
Chris Lattnerea714382008-08-21 18:04:13 +00008200 // If the RHS is a unary plus or minus, check to see if they = and + are
8201 // right next to each other. If so, the user may have typo'd "x =+ 4"
8202 // instead of "x += 4".
Chris Lattnerea714382008-08-21 18:04:13 +00008203 if (ImplicitCastExpr *ICE = dyn_cast<ImplicitCastExpr>(RHSCheck))
8204 RHSCheck = ICE->getSubExpr();
8205 if (UnaryOperator *UO = dyn_cast<UnaryOperator>(RHSCheck)) {
John McCalle3027922010-08-25 11:45:40 +00008206 if ((UO->getOpcode() == UO_Plus ||
8207 UO->getOpcode() == UO_Minus) &&
Chris Lattner326f7572008-11-18 01:30:42 +00008208 Loc.isFileID() && UO->getOperatorLoc().isFileID() &&
Chris Lattnerea714382008-08-21 18:04:13 +00008209 // Only if the two operators are exactly adjacent.
Argyrios Kyrtzidise6e67de2011-09-19 20:40:19 +00008210 Loc.getLocWithOffset(1) == UO->getOperatorLoc() &&
Chris Lattner36c39c92009-03-08 06:51:10 +00008211 // And there is a space or other character before the subexpr of the
8212 // unary +/-. We don't want to warn on "x=-1".
Argyrios Kyrtzidise6e67de2011-09-19 20:40:19 +00008213 Loc.getLocWithOffset(2) != UO->getSubExpr()->getLocStart() &&
Chris Lattnered9f14c2009-03-09 07:11:10 +00008214 UO->getSubExpr()->getLocStart().isFileID()) {
Chris Lattner29e812b2008-11-20 06:06:08 +00008215 Diag(Loc, diag::warn_not_compound_assign)
John McCalle3027922010-08-25 11:45:40 +00008216 << (UO->getOpcode() == UO_Plus ? "+" : "-")
Chris Lattner29e812b2008-11-20 06:06:08 +00008217 << SourceRange(UO->getOperatorLoc(), UO->getOperatorLoc());
Chris Lattner36c39c92009-03-08 06:51:10 +00008218 }
Chris Lattnerea714382008-08-21 18:04:13 +00008219 }
John McCall31168b02011-06-15 23:02:42 +00008220
8221 if (ConvTy == Compatible) {
Jordan Rosefa9e4ba2012-09-15 02:48:31 +00008222 if (LHSType.getObjCLifetime() == Qualifiers::OCL_Strong) {
8223 // Warn about retain cycles where a block captures the LHS, but
8224 // not if the LHS is a simple variable into which the block is
8225 // being stored...unless that variable can be captured by reference!
8226 const Expr *InnerLHS = LHSExpr->IgnoreParenCasts();
8227 const DeclRefExpr *DRE = dyn_cast<DeclRefExpr>(InnerLHS);
8228 if (!DRE || DRE->getDecl()->hasAttr<BlocksAttr>())
8229 checkRetainCycles(LHSExpr, RHS.get());
8230
Jordan Rosed3934582012-09-28 22:21:30 +00008231 // It is safe to assign a weak reference into a strong variable.
8232 // Although this code can still have problems:
8233 // id x = self.weakProp;
8234 // id y = self.weakProp;
8235 // we do not warn to warn spuriously when 'x' and 'y' are on separate
8236 // paths through the function. This should be revisited if
8237 // -Wrepeated-use-of-weak is made flow-sensitive.
8238 DiagnosticsEngine::Level Level =
8239 Diags.getDiagnosticLevel(diag::warn_arc_repeated_use_of_weak,
8240 RHS.get()->getLocStart());
8241 if (Level != DiagnosticsEngine::Ignored)
8242 getCurFunction()->markSafeWeakUse(RHS.get());
8243
Jordan Rosefa9e4ba2012-09-15 02:48:31 +00008244 } else if (getLangOpts().ObjCAutoRefCount) {
Richard Trieuda4f43a62011-09-07 01:33:52 +00008245 checkUnsafeExprAssigns(Loc, LHSExpr, RHS.get());
Jordan Rosefa9e4ba2012-09-15 02:48:31 +00008246 }
John McCall31168b02011-06-15 23:02:42 +00008247 }
Chris Lattnerea714382008-08-21 18:04:13 +00008248 } else {
8249 // Compound assignment "x += y"
Douglas Gregorc03a1082011-01-28 02:26:04 +00008250 ConvTy = CheckAssignmentConstraints(Loc, LHSType, RHSType);
Chris Lattnerea714382008-08-21 18:04:13 +00008251 }
Chris Lattner9bad62c2008-01-04 18:04:52 +00008252
Chris Lattner326f7572008-11-18 01:30:42 +00008253 if (DiagnoseAssignmentResult(ConvTy, Loc, LHSType, RHSType,
John Wiegley01296292011-04-08 18:41:53 +00008254 RHS.get(), AA_Assigning))
Chris Lattner9bad62c2008-01-04 18:04:52 +00008255 return QualType();
Mike Stump4e1f26a2009-02-19 03:04:26 +00008256
Richard Trieuda4f43a62011-09-07 01:33:52 +00008257 CheckForNullPointerDereference(*this, LHSExpr);
Kaelyn Uhrain2e7aa5a2011-08-05 23:18:04 +00008258
Steve Naroff98cf3e92007-06-06 18:38:38 +00008259 // C99 6.5.16p3: The type of an assignment expression is the type of the
8260 // left operand unless the left operand has qualified type, in which case
Mike Stump4e1f26a2009-02-19 03:04:26 +00008261 // it is the unqualified version of the type of the left operand.
Steve Naroff98cf3e92007-06-06 18:38:38 +00008262 // C99 6.5.16.1p2: In simple assignment, the value of the right operand
8263 // is converted to the type of the assignment expression (above).
Chris Lattnerf17bd422007-08-30 17:45:32 +00008264 // C++ 5.17p1: the type of the assignment expression is that of its left
Douglas Gregord2c2d172009-05-02 00:36:19 +00008265 // operand.
David Blaikiebbafb8a2012-03-11 07:00:24 +00008266 return (getLangOpts().CPlusPlus
John McCall01cbf2d2010-10-12 02:19:57 +00008267 ? LHSType : LHSType.getUnqualifiedType());
Steve Naroffae4143e2007-04-26 20:39:23 +00008268}
8269
Chris Lattner326f7572008-11-18 01:30:42 +00008270// C99 6.5.17
John Wiegley01296292011-04-08 18:41:53 +00008271static QualType CheckCommaOperands(Sema &S, ExprResult &LHS, ExprResult &RHS,
John McCall4bc41ae2010-11-18 19:01:18 +00008272 SourceLocation Loc) {
John McCall3aef3d82011-04-10 19:13:55 +00008273 LHS = S.CheckPlaceholderExpr(LHS.take());
8274 RHS = S.CheckPlaceholderExpr(RHS.take());
John Wiegley01296292011-04-08 18:41:53 +00008275 if (LHS.isInvalid() || RHS.isInvalid())
Douglas Gregor0124e9b2010-11-09 21:07:58 +00008276 return QualType();
8277
John McCall73d36182010-10-12 07:14:40 +00008278 // C's comma performs lvalue conversion (C99 6.3.2.1) on both its
8279 // operands, but not unary promotions.
8280 // C++'s comma does not do any conversions at all (C++ [expr.comma]p1).
Eli Friedmanba961a92009-03-23 00:24:07 +00008281
John McCall34376a62010-12-04 03:47:34 +00008282 // So we treat the LHS as a ignored value, and in C++ we allow the
8283 // containing site to determine what should be done with the RHS.
John Wiegley01296292011-04-08 18:41:53 +00008284 LHS = S.IgnoredValueConversions(LHS.take());
8285 if (LHS.isInvalid())
8286 return QualType();
John McCall34376a62010-12-04 03:47:34 +00008287
Eli Friedmanc11535c2012-05-24 00:47:05 +00008288 S.DiagnoseUnusedExprResult(LHS.get());
8289
David Blaikiebbafb8a2012-03-11 07:00:24 +00008290 if (!S.getLangOpts().CPlusPlus) {
John Wiegley01296292011-04-08 18:41:53 +00008291 RHS = S.DefaultFunctionArrayLvalueConversion(RHS.take());
8292 if (RHS.isInvalid())
8293 return QualType();
8294 if (!RHS.get()->getType()->isVoidType())
Richard Trieucfc491d2011-08-02 04:35:43 +00008295 S.RequireCompleteType(Loc, RHS.get()->getType(),
8296 diag::err_incomplete_type);
John McCall73d36182010-10-12 07:14:40 +00008297 }
Eli Friedmanba961a92009-03-23 00:24:07 +00008298
John Wiegley01296292011-04-08 18:41:53 +00008299 return RHS.get()->getType();
Steve Naroff95af0132007-03-30 23:47:58 +00008300}
8301
Steve Naroff7a5af782007-07-13 16:58:59 +00008302/// CheckIncrementDecrementOperand - unlike most "Check" methods, this routine
8303/// doesn't need to call UsualUnaryConversions or UsualArithmeticConversions.
John McCall4bc41ae2010-11-18 19:01:18 +00008304static QualType CheckIncrementDecrementOperand(Sema &S, Expr *Op,
8305 ExprValueKind &VK,
8306 SourceLocation OpLoc,
Richard Trieuba63ce62011-09-09 01:45:06 +00008307 bool IsInc, bool IsPrefix) {
Sebastian Redl8d2ccae2009-02-26 14:39:58 +00008308 if (Op->isTypeDependent())
John McCall4bc41ae2010-11-18 19:01:18 +00008309 return S.Context.DependentTy;
Sebastian Redl8d2ccae2009-02-26 14:39:58 +00008310
Chris Lattner6b0cf142008-11-21 07:05:48 +00008311 QualType ResType = Op->getType();
David Chisnallfa35df62012-01-16 17:27:18 +00008312 // Atomic types can be used for increment / decrement where the non-atomic
8313 // versions can, so ignore the _Atomic() specifier for the purpose of
8314 // checking.
8315 if (const AtomicType *ResAtomicType = ResType->getAs<AtomicType>())
8316 ResType = ResAtomicType->getValueType();
8317
Chris Lattner6b0cf142008-11-21 07:05:48 +00008318 assert(!ResType.isNull() && "no type for increment/decrement expression");
Steve Naroffd50c88e2007-04-05 21:15:20 +00008319
David Blaikiebbafb8a2012-03-11 07:00:24 +00008320 if (S.getLangOpts().CPlusPlus && ResType->isBooleanType()) {
Sebastian Redle10c2c32008-12-20 09:35:34 +00008321 // Decrement of bool is not allowed.
Richard Trieuba63ce62011-09-09 01:45:06 +00008322 if (!IsInc) {
John McCall4bc41ae2010-11-18 19:01:18 +00008323 S.Diag(OpLoc, diag::err_decrement_bool) << Op->getSourceRange();
Sebastian Redle10c2c32008-12-20 09:35:34 +00008324 return QualType();
8325 }
8326 // Increment of bool sets it to true, but is deprecated.
John McCall4bc41ae2010-11-18 19:01:18 +00008327 S.Diag(OpLoc, diag::warn_increment_bool) << Op->getSourceRange();
Sebastian Redle10c2c32008-12-20 09:35:34 +00008328 } else if (ResType->isRealType()) {
Chris Lattner6b0cf142008-11-21 07:05:48 +00008329 // OK!
John McCallf2538342012-07-31 05:14:30 +00008330 } else if (ResType->isPointerType()) {
Chris Lattner6b0cf142008-11-21 07:05:48 +00008331 // C99 6.5.2.4p2, 6.5.6p2
Chandler Carruthc9332212011-06-27 08:02:19 +00008332 if (!checkArithmeticOpPointerOperand(S, OpLoc, Op))
Douglas Gregordd430f72009-01-19 19:26:10 +00008333 return QualType();
John McCallf2538342012-07-31 05:14:30 +00008334 } else if (ResType->isObjCObjectPointerType()) {
8335 // On modern runtimes, ObjC pointer arithmetic is forbidden.
8336 // Otherwise, we just need a complete type.
8337 if (checkArithmeticIncompletePointerType(S, OpLoc, Op) ||
8338 checkArithmeticOnObjCPointer(S, OpLoc, Op))
8339 return QualType();
Eli Friedman090addd2010-01-03 00:20:48 +00008340 } else if (ResType->isAnyComplexType()) {
Chris Lattner6b0cf142008-11-21 07:05:48 +00008341 // C99 does not support ++/-- on complex types, we allow as an extension.
John McCall4bc41ae2010-11-18 19:01:18 +00008342 S.Diag(OpLoc, diag::ext_integer_increment_complex)
Chris Lattner1e5665e2008-11-24 06:25:27 +00008343 << ResType << Op->getSourceRange();
John McCall36226622010-10-12 02:09:17 +00008344 } else if (ResType->isPlaceholderType()) {
John McCall3aef3d82011-04-10 19:13:55 +00008345 ExprResult PR = S.CheckPlaceholderExpr(Op);
John McCall36226622010-10-12 02:09:17 +00008346 if (PR.isInvalid()) return QualType();
John McCall4bc41ae2010-11-18 19:01:18 +00008347 return CheckIncrementDecrementOperand(S, PR.take(), VK, OpLoc,
Richard Trieuba63ce62011-09-09 01:45:06 +00008348 IsInc, IsPrefix);
David Blaikiebbafb8a2012-03-11 07:00:24 +00008349 } else if (S.getLangOpts().AltiVec && ResType->isVectorType()) {
Anton Yartsev85129b82011-02-07 02:17:30 +00008350 // OK! ( C/C++ Language Extensions for CBEA(Version 2.6) 10.3 )
Chris Lattner6b0cf142008-11-21 07:05:48 +00008351 } else {
John McCall4bc41ae2010-11-18 19:01:18 +00008352 S.Diag(OpLoc, diag::err_typecheck_illegal_increment_decrement)
Richard Trieuba63ce62011-09-09 01:45:06 +00008353 << ResType << int(IsInc) << Op->getSourceRange();
Chris Lattner6b0cf142008-11-21 07:05:48 +00008354 return QualType();
Steve Naroff46ba1eb2007-04-03 23:13:13 +00008355 }
Mike Stump4e1f26a2009-02-19 03:04:26 +00008356 // At this point, we know we have a real, complex or pointer type.
Steve Naroff9e1e5512007-08-23 21:37:33 +00008357 // Now make sure the operand is a modifiable lvalue.
John McCall4bc41ae2010-11-18 19:01:18 +00008358 if (CheckForModifiableLvalue(Op, OpLoc, S))
Steve Naroff35d85152007-05-07 00:24:15 +00008359 return QualType();
Alexis Huntc46382e2010-04-28 23:02:27 +00008360 // In C++, a prefix increment is the same type as the operand. Otherwise
8361 // (in C or with postfix), the increment is the unqualified type of the
8362 // operand.
David Blaikiebbafb8a2012-03-11 07:00:24 +00008363 if (IsPrefix && S.getLangOpts().CPlusPlus) {
John McCall4bc41ae2010-11-18 19:01:18 +00008364 VK = VK_LValue;
8365 return ResType;
8366 } else {
8367 VK = VK_RValue;
8368 return ResType.getUnqualifiedType();
8369 }
Steve Naroff26c8ea52007-03-21 21:08:52 +00008370}
Fariborz Jahanian805b74e2010-09-14 23:02:38 +00008371
8372
Anders Carlsson806700f2008-02-01 07:15:58 +00008373/// getPrimaryDecl - Helper function for CheckAddressOfOperand().
Steve Naroff47500512007-04-19 23:00:49 +00008374/// This routine allows us to typecheck complex/recursive expressions
Daniel Dunbarb692ef42008-08-04 20:02:37 +00008375/// where the declaration is needed for type checking. We only need to
8376/// handle cases when the expression references a function designator
8377/// or is an lvalue. Here are some examples:
8378/// - &(x) => x
8379/// - &*****f => f for f a function designator.
8380/// - &s.xx => s
8381/// - &s.zz[1].yy -> s, if zz is an array
8382/// - *(x + 1) -> x, if x is an array
8383/// - &"123"[2] -> 0
8384/// - & __real__ x -> x
John McCallf3a88602011-02-03 08:15:49 +00008385static ValueDecl *getPrimaryDecl(Expr *E) {
Chris Lattner24d5bfe2008-04-02 04:24:33 +00008386 switch (E->getStmtClass()) {
Steve Naroff47500512007-04-19 23:00:49 +00008387 case Stmt::DeclRefExprClass:
Chris Lattner24d5bfe2008-04-02 04:24:33 +00008388 return cast<DeclRefExpr>(E)->getDecl();
Steve Naroff47500512007-04-19 23:00:49 +00008389 case Stmt::MemberExprClass:
Eli Friedman3a1e6922009-04-20 08:23:18 +00008390 // If this is an arrow operator, the address is an offset from
8391 // the base's value, so the object the base refers to is
8392 // irrelevant.
Chris Lattner24d5bfe2008-04-02 04:24:33 +00008393 if (cast<MemberExpr>(E)->isArrow())
Chris Lattner48d52842007-11-16 17:46:48 +00008394 return 0;
Eli Friedman3a1e6922009-04-20 08:23:18 +00008395 // Otherwise, the expression refers to a part of the base
Chris Lattner24d5bfe2008-04-02 04:24:33 +00008396 return getPrimaryDecl(cast<MemberExpr>(E)->getBase());
Anders Carlsson806700f2008-02-01 07:15:58 +00008397 case Stmt::ArraySubscriptExprClass: {
Mike Stump87c57ac2009-05-16 07:39:55 +00008398 // FIXME: This code shouldn't be necessary! We should catch the implicit
8399 // promotion of register arrays earlier.
Eli Friedman3a1e6922009-04-20 08:23:18 +00008400 Expr* Base = cast<ArraySubscriptExpr>(E)->getBase();
8401 if (ImplicitCastExpr* ICE = dyn_cast<ImplicitCastExpr>(Base)) {
8402 if (ICE->getSubExpr()->getType()->isArrayType())
8403 return getPrimaryDecl(ICE->getSubExpr());
8404 }
8405 return 0;
Anders Carlsson806700f2008-02-01 07:15:58 +00008406 }
Daniel Dunbarb692ef42008-08-04 20:02:37 +00008407 case Stmt::UnaryOperatorClass: {
8408 UnaryOperator *UO = cast<UnaryOperator>(E);
Mike Stump4e1f26a2009-02-19 03:04:26 +00008409
Daniel Dunbarb692ef42008-08-04 20:02:37 +00008410 switch(UO->getOpcode()) {
John McCalle3027922010-08-25 11:45:40 +00008411 case UO_Real:
8412 case UO_Imag:
8413 case UO_Extension:
Daniel Dunbarb692ef42008-08-04 20:02:37 +00008414 return getPrimaryDecl(UO->getSubExpr());
8415 default:
8416 return 0;
8417 }
8418 }
Steve Naroff47500512007-04-19 23:00:49 +00008419 case Stmt::ParenExprClass:
Chris Lattner24d5bfe2008-04-02 04:24:33 +00008420 return getPrimaryDecl(cast<ParenExpr>(E)->getSubExpr());
Chris Lattner48d52842007-11-16 17:46:48 +00008421 case Stmt::ImplicitCastExprClass:
Eli Friedman3a1e6922009-04-20 08:23:18 +00008422 // If the result of an implicit cast is an l-value, we care about
8423 // the sub-expression; otherwise, the result here doesn't matter.
Chris Lattner24d5bfe2008-04-02 04:24:33 +00008424 return getPrimaryDecl(cast<ImplicitCastExpr>(E)->getSubExpr());
Steve Naroff47500512007-04-19 23:00:49 +00008425 default:
8426 return 0;
8427 }
8428}
8429
Richard Trieu5f376f62011-09-07 21:46:33 +00008430namespace {
8431 enum {
8432 AO_Bit_Field = 0,
8433 AO_Vector_Element = 1,
8434 AO_Property_Expansion = 2,
8435 AO_Register_Variable = 3,
8436 AO_No_Error = 4
8437 };
8438}
Richard Trieu3fd7bb82011-09-02 00:47:55 +00008439/// \brief Diagnose invalid operand for address of operations.
8440///
8441/// \param Type The type of operand which cannot have its address taken.
Richard Trieu3fd7bb82011-09-02 00:47:55 +00008442static void diagnoseAddressOfInvalidType(Sema &S, SourceLocation Loc,
8443 Expr *E, unsigned Type) {
8444 S.Diag(Loc, diag::err_typecheck_address_of) << Type << E->getSourceRange();
8445}
8446
Steve Naroff47500512007-04-19 23:00:49 +00008447/// CheckAddressOfOperand - The operand of & must be either a function
Mike Stump4e1f26a2009-02-19 03:04:26 +00008448/// designator or an lvalue designating an object. If it is an lvalue, the
Steve Naroff47500512007-04-19 23:00:49 +00008449/// object cannot be declared with storage class register or be a bit field.
Mike Stump4e1f26a2009-02-19 03:04:26 +00008450/// Note: The usual conversions are *not* applied to the operand of the &
Steve Naroffa78fe7e2007-05-16 19:47:19 +00008451/// operator (C99 6.3.2.1p[2-4]), and its result is never an lvalue.
Mike Stump4e1f26a2009-02-19 03:04:26 +00008452/// In C++, the operand might be an overloaded function name, in which case
Douglas Gregorcd695e52008-11-10 20:40:00 +00008453/// we allow the '&' but retain the overloaded-function type.
Richard Smithaf9de912013-07-11 02:26:56 +00008454QualType Sema::CheckAddressOfOperand(ExprResult &OrigOp, SourceLocation OpLoc) {
John McCall526ab472011-10-25 17:37:35 +00008455 if (const BuiltinType *PTy = OrigOp.get()->getType()->getAsPlaceholderType()){
8456 if (PTy->getKind() == BuiltinType::Overload) {
David Majnemer0f328442013-07-05 06:23:33 +00008457 Expr *E = OrigOp.get()->IgnoreParens();
8458 if (!isa<OverloadExpr>(E)) {
8459 assert(cast<UnaryOperator>(E)->getOpcode() == UO_AddrOf);
Richard Smithaf9de912013-07-11 02:26:56 +00008460 Diag(OpLoc, diag::err_typecheck_invalid_lvalue_addrof_addrof_function)
John McCall526ab472011-10-25 17:37:35 +00008461 << OrigOp.get()->getSourceRange();
8462 return QualType();
8463 }
David Majnemer66ad5742013-06-11 03:56:29 +00008464
David Majnemer0f328442013-07-05 06:23:33 +00008465 OverloadExpr *Ovl = cast<OverloadExpr>(E);
David Majnemer66ad5742013-06-11 03:56:29 +00008466 if (isa<UnresolvedMemberExpr>(Ovl))
Richard Smithaf9de912013-07-11 02:26:56 +00008467 if (!ResolveSingleFunctionTemplateSpecialization(Ovl)) {
8468 Diag(OpLoc, diag::err_invalid_form_pointer_member_function)
David Majnemer66ad5742013-06-11 03:56:29 +00008469 << OrigOp.get()->getSourceRange();
8470 return QualType();
8471 }
8472
Richard Smithaf9de912013-07-11 02:26:56 +00008473 return Context.OverloadTy;
John McCall526ab472011-10-25 17:37:35 +00008474 }
8475
8476 if (PTy->getKind() == BuiltinType::UnknownAny)
Richard Smithaf9de912013-07-11 02:26:56 +00008477 return Context.UnknownAnyTy;
John McCall526ab472011-10-25 17:37:35 +00008478
8479 if (PTy->getKind() == BuiltinType::BoundMember) {
Richard Smithaf9de912013-07-11 02:26:56 +00008480 Diag(OpLoc, diag::err_invalid_form_pointer_member_function)
John McCall526ab472011-10-25 17:37:35 +00008481 << OrigOp.get()->getSourceRange();
Douglas Gregor668d3622011-10-09 19:10:41 +00008482 return QualType();
8483 }
John McCall526ab472011-10-25 17:37:35 +00008484
Richard Smithaf9de912013-07-11 02:26:56 +00008485 OrigOp = CheckPlaceholderExpr(OrigOp.take());
John McCall526ab472011-10-25 17:37:35 +00008486 if (OrigOp.isInvalid()) return QualType();
John McCall0009fcc2011-04-26 20:42:42 +00008487 }
John McCall8d08b9b2010-08-27 09:08:28 +00008488
John McCall526ab472011-10-25 17:37:35 +00008489 if (OrigOp.get()->isTypeDependent())
Richard Smithaf9de912013-07-11 02:26:56 +00008490 return Context.DependentTy;
John McCall526ab472011-10-25 17:37:35 +00008491
8492 assert(!OrigOp.get()->getType()->isPlaceholderType());
John McCall36226622010-10-12 02:09:17 +00008493
John McCall8d08b9b2010-08-27 09:08:28 +00008494 // Make sure to ignore parentheses in subsequent checks
John McCall526ab472011-10-25 17:37:35 +00008495 Expr *op = OrigOp.get()->IgnoreParens();
Douglas Gregor19b8c4f2008-12-17 22:52:20 +00008496
Richard Smithaf9de912013-07-11 02:26:56 +00008497 if (getLangOpts().C99) {
Steve Naroff826e91a2008-01-13 17:10:08 +00008498 // Implement C99-only parts of addressof rules.
8499 if (UnaryOperator* uOp = dyn_cast<UnaryOperator>(op)) {
John McCalle3027922010-08-25 11:45:40 +00008500 if (uOp->getOpcode() == UO_Deref)
Steve Naroff826e91a2008-01-13 17:10:08 +00008501 // Per C99 6.5.3.2, the address of a deref always returns a valid result
8502 // (assuming the deref expression is valid).
8503 return uOp->getSubExpr()->getType();
8504 }
8505 // Technically, there should be a check for array subscript
8506 // expressions here, but the result of one is always an lvalue anyway.
8507 }
John McCallf3a88602011-02-03 08:15:49 +00008508 ValueDecl *dcl = getPrimaryDecl(op);
Richard Smithaf9de912013-07-11 02:26:56 +00008509 Expr::LValueClassification lval = op->ClassifyLValue(Context);
Richard Trieu5f376f62011-09-07 21:46:33 +00008510 unsigned AddressOfError = AO_No_Error;
Nuno Lopes17f345f2008-12-16 22:59:47 +00008511
Richard Smithc084bd282013-02-02 02:14:45 +00008512 if (lval == Expr::LV_ClassTemporary || lval == Expr::LV_ArrayTemporary) {
Richard Smithaf9de912013-07-11 02:26:56 +00008513 bool sfinae = (bool)isSFINAEContext();
8514 Diag(OpLoc, isSFINAEContext() ? diag::err_typecheck_addrof_temporary
8515 : diag::ext_typecheck_addrof_temporary)
Douglas Gregorb154fdc2010-02-16 21:39:57 +00008516 << op->getType() << op->getSourceRange();
John McCall4bc41ae2010-11-18 19:01:18 +00008517 if (sfinae)
Douglas Gregorb154fdc2010-02-16 21:39:57 +00008518 return QualType();
Richard Smith9f8400e2013-05-01 19:00:39 +00008519 // Materialize the temporary as an lvalue so that we can take its address.
Richard Smithaf9de912013-07-11 02:26:56 +00008520 OrigOp = op = new (Context)
Richard Smithe6c01442013-06-05 00:46:14 +00008521 MaterializeTemporaryExpr(op->getType(), OrigOp.take(), true, 0);
John McCall8d08b9b2010-08-27 09:08:28 +00008522 } else if (isa<ObjCSelectorExpr>(op)) {
Richard Smithaf9de912013-07-11 02:26:56 +00008523 return Context.getPointerType(op->getType());
John McCall8d08b9b2010-08-27 09:08:28 +00008524 } else if (lval == Expr::LV_MemberFunction) {
8525 // If it's an instance method, make a member pointer.
8526 // The expression must have exactly the form &A::foo.
8527
8528 // If the underlying expression isn't a decl ref, give up.
8529 if (!isa<DeclRefExpr>(op)) {
Richard Smithaf9de912013-07-11 02:26:56 +00008530 Diag(OpLoc, diag::err_invalid_form_pointer_member_function)
John McCall526ab472011-10-25 17:37:35 +00008531 << OrigOp.get()->getSourceRange();
John McCall8d08b9b2010-08-27 09:08:28 +00008532 return QualType();
8533 }
8534 DeclRefExpr *DRE = cast<DeclRefExpr>(op);
8535 CXXMethodDecl *MD = cast<CXXMethodDecl>(DRE->getDecl());
8536
8537 // The id-expression was parenthesized.
John McCall526ab472011-10-25 17:37:35 +00008538 if (OrigOp.get() != DRE) {
Richard Smithaf9de912013-07-11 02:26:56 +00008539 Diag(OpLoc, diag::err_parens_pointer_member_function)
John McCall526ab472011-10-25 17:37:35 +00008540 << OrigOp.get()->getSourceRange();
John McCall8d08b9b2010-08-27 09:08:28 +00008541
8542 // The method was named without a qualifier.
8543 } else if (!DRE->getQualifier()) {
David Blaikiec2ff8e12012-10-11 22:55:07 +00008544 if (MD->getParent()->getName().empty())
Richard Smithaf9de912013-07-11 02:26:56 +00008545 Diag(OpLoc, diag::err_unqualified_pointer_member_function)
David Blaikiec2ff8e12012-10-11 22:55:07 +00008546 << op->getSourceRange();
8547 else {
8548 SmallString<32> Str;
8549 StringRef Qual = (MD->getParent()->getName() + "::").toStringRef(Str);
Richard Smithaf9de912013-07-11 02:26:56 +00008550 Diag(OpLoc, diag::err_unqualified_pointer_member_function)
David Blaikiec2ff8e12012-10-11 22:55:07 +00008551 << op->getSourceRange()
8552 << FixItHint::CreateInsertion(op->getSourceRange().getBegin(), Qual);
8553 }
John McCall8d08b9b2010-08-27 09:08:28 +00008554 }
8555
Richard Smithaf9de912013-07-11 02:26:56 +00008556 return Context.getMemberPointerType(op->getType(),
8557 Context.getTypeDeclType(MD->getParent()).getTypePtr());
John McCall8d08b9b2010-08-27 09:08:28 +00008558 } else if (lval != Expr::LV_Valid && lval != Expr::LV_IncompleteVoidType) {
Eli Friedmance7f9002009-05-16 23:27:50 +00008559 // C99 6.5.3.2p1
Eli Friedman3a1e6922009-04-20 08:23:18 +00008560 // The operand must be either an l-value or a function designator
Eli Friedmance7f9002009-05-16 23:27:50 +00008561 if (!op->getType()->isFunctionType()) {
John McCall526ab472011-10-25 17:37:35 +00008562 // Use a special diagnostic for loads from property references.
John McCallfe96e0b2011-11-06 09:01:30 +00008563 if (isa<PseudoObjectExpr>(op)) {
John McCall526ab472011-10-25 17:37:35 +00008564 AddressOfError = AO_Property_Expansion;
8565 } else {
Richard Smithaf9de912013-07-11 02:26:56 +00008566 Diag(OpLoc, diag::err_typecheck_invalid_lvalue_addrof)
Richard Smithc084bd282013-02-02 02:14:45 +00008567 << op->getType() << op->getSourceRange();
John McCall526ab472011-10-25 17:37:35 +00008568 return QualType();
8569 }
Steve Naroff35d85152007-05-07 00:24:15 +00008570 }
John McCall086a4642010-11-24 05:12:34 +00008571 } else if (op->getObjectKind() == OK_BitField) { // C99 6.5.3.2p1
Eli Friedman3a1e6922009-04-20 08:23:18 +00008572 // The operand cannot be a bit-field
Richard Trieu5f376f62011-09-07 21:46:33 +00008573 AddressOfError = AO_Bit_Field;
John McCall086a4642010-11-24 05:12:34 +00008574 } else if (op->getObjectKind() == OK_VectorComponent) {
Eli Friedman3a1e6922009-04-20 08:23:18 +00008575 // The operand cannot be an element of a vector
Richard Trieu5f376f62011-09-07 21:46:33 +00008576 AddressOfError = AO_Vector_Element;
Steve Naroffb96e4ab62008-02-29 23:30:25 +00008577 } else if (dcl) { // C99 6.5.3.2p1
Mike Stump4e1f26a2009-02-19 03:04:26 +00008578 // We have an lvalue with a decl. Make sure the decl is not declared
Steve Naroff47500512007-04-19 23:00:49 +00008579 // with the register storage-class specifier.
8580 if (const VarDecl *vd = dyn_cast<VarDecl>(dcl)) {
Fariborz Jahaniane0fd5a92010-08-24 22:21:48 +00008581 // in C++ it is not error to take address of a register
8582 // variable (c++03 7.1.1P3)
John McCall8e7d6562010-08-26 03:08:43 +00008583 if (vd->getStorageClass() == SC_Register &&
Richard Smithaf9de912013-07-11 02:26:56 +00008584 !getLangOpts().CPlusPlus) {
Richard Trieu5f376f62011-09-07 21:46:33 +00008585 AddressOfError = AO_Register_Variable;
Steve Naroff35d85152007-05-07 00:24:15 +00008586 }
John McCalld14a8642009-11-21 08:51:07 +00008587 } else if (isa<FunctionTemplateDecl>(dcl)) {
Richard Smithaf9de912013-07-11 02:26:56 +00008588 return Context.OverloadTy;
John McCallf3a88602011-02-03 08:15:49 +00008589 } else if (isa<FieldDecl>(dcl) || isa<IndirectFieldDecl>(dcl)) {
Douglas Gregor9aa8b552008-12-10 21:26:49 +00008590 // Okay: we can take the address of a field.
Sebastian Redl3d3f75a2009-02-03 20:19:35 +00008591 // Could be a pointer to member, though, if there is an explicit
8592 // scope qualifier for the class.
Douglas Gregor4bd90e52009-10-23 18:54:35 +00008593 if (isa<DeclRefExpr>(op) && cast<DeclRefExpr>(op)->getQualifier()) {
Sebastian Redl3d3f75a2009-02-03 20:19:35 +00008594 DeclContext *Ctx = dcl->getDeclContext();
Anders Carlsson0b675f52009-07-08 21:45:58 +00008595 if (Ctx && Ctx->isRecord()) {
John McCallf3a88602011-02-03 08:15:49 +00008596 if (dcl->getType()->isReferenceType()) {
Richard Smithaf9de912013-07-11 02:26:56 +00008597 Diag(OpLoc,
8598 diag::err_cannot_form_pointer_to_member_of_reference_type)
John McCallf3a88602011-02-03 08:15:49 +00008599 << dcl->getDeclName() << dcl->getType();
Anders Carlsson0b675f52009-07-08 21:45:58 +00008600 return QualType();
8601 }
Mike Stump11289f42009-09-09 15:08:12 +00008602
Argyrios Kyrtzidis8322b422011-01-31 07:04:29 +00008603 while (cast<RecordDecl>(Ctx)->isAnonymousStructOrUnion())
8604 Ctx = Ctx->getParent();
Richard Smithaf9de912013-07-11 02:26:56 +00008605 return Context.getMemberPointerType(op->getType(),
8606 Context.getTypeDeclType(cast<RecordDecl>(Ctx)).getTypePtr());
Anders Carlsson0b675f52009-07-08 21:45:58 +00008607 }
Sebastian Redl3d3f75a2009-02-03 20:19:35 +00008608 }
Eli Friedman755c0c92011-08-26 20:28:17 +00008609 } else if (!isa<FunctionDecl>(dcl) && !isa<NonTypeTemplateParmDecl>(dcl))
David Blaikie83d382b2011-09-23 05:06:16 +00008610 llvm_unreachable("Unknown/unexpected decl type");
Steve Naroff47500512007-04-19 23:00:49 +00008611 }
Sebastian Redl18f8ff62009-02-04 21:23:32 +00008612
Richard Trieu5f376f62011-09-07 21:46:33 +00008613 if (AddressOfError != AO_No_Error) {
Richard Smithaf9de912013-07-11 02:26:56 +00008614 diagnoseAddressOfInvalidType(*this, OpLoc, op, AddressOfError);
Richard Trieu5f376f62011-09-07 21:46:33 +00008615 return QualType();
8616 }
8617
Eli Friedmance7f9002009-05-16 23:27:50 +00008618 if (lval == Expr::LV_IncompleteVoidType) {
8619 // Taking the address of a void variable is technically illegal, but we
8620 // allow it in cases which are otherwise valid.
8621 // Example: "extern void x; void* y = &x;".
Richard Smithaf9de912013-07-11 02:26:56 +00008622 Diag(OpLoc, diag::ext_typecheck_addrof_void) << op->getSourceRange();
Eli Friedmance7f9002009-05-16 23:27:50 +00008623 }
8624
Steve Naroff47500512007-04-19 23:00:49 +00008625 // If the operand has type "type", the result has type "pointer to type".
Douglas Gregor0bdcb8a2010-07-29 16:05:45 +00008626 if (op->getType()->isObjCObjectType())
Richard Smithaf9de912013-07-11 02:26:56 +00008627 return Context.getObjCObjectPointerType(op->getType());
8628 return Context.getPointerType(op->getType());
Steve Naroff47500512007-04-19 23:00:49 +00008629}
8630
Chris Lattner9156f1b2010-07-05 19:17:26 +00008631/// CheckIndirectionOperand - Type check unary indirection (prefix '*').
John McCall4bc41ae2010-11-18 19:01:18 +00008632static QualType CheckIndirectionOperand(Sema &S, Expr *Op, ExprValueKind &VK,
8633 SourceLocation OpLoc) {
Sebastian Redl8d2ccae2009-02-26 14:39:58 +00008634 if (Op->isTypeDependent())
John McCall4bc41ae2010-11-18 19:01:18 +00008635 return S.Context.DependentTy;
Sebastian Redl8d2ccae2009-02-26 14:39:58 +00008636
John Wiegley01296292011-04-08 18:41:53 +00008637 ExprResult ConvResult = S.UsualUnaryConversions(Op);
8638 if (ConvResult.isInvalid())
8639 return QualType();
8640 Op = ConvResult.take();
Chris Lattner9156f1b2010-07-05 19:17:26 +00008641 QualType OpTy = Op->getType();
8642 QualType Result;
Argyrios Kyrtzidis69a2c922011-05-02 18:21:19 +00008643
8644 if (isa<CXXReinterpretCastExpr>(Op)) {
8645 QualType OpOrigType = Op->IgnoreParenCasts()->getType();
8646 S.CheckCompatibleReinterpretCast(OpOrigType, OpTy, /*IsDereference*/true,
8647 Op->getSourceRange());
8648 }
8649
Chris Lattner9156f1b2010-07-05 19:17:26 +00008650 // Note that per both C89 and C99, indirection is always legal, even if OpTy
8651 // is an incomplete type or void. It would be possible to warn about
8652 // dereferencing a void pointer, but it's completely well-defined, and such a
8653 // warning is unlikely to catch any mistakes.
8654 if (const PointerType *PT = OpTy->getAs<PointerType>())
8655 Result = PT->getPointeeType();
8656 else if (const ObjCObjectPointerType *OPT =
8657 OpTy->getAs<ObjCObjectPointerType>())
8658 Result = OPT->getPointeeType();
John McCall36226622010-10-12 02:09:17 +00008659 else {
John McCall3aef3d82011-04-10 19:13:55 +00008660 ExprResult PR = S.CheckPlaceholderExpr(Op);
John McCall36226622010-10-12 02:09:17 +00008661 if (PR.isInvalid()) return QualType();
John McCall4bc41ae2010-11-18 19:01:18 +00008662 if (PR.take() != Op)
8663 return CheckIndirectionOperand(S, PR.take(), VK, OpLoc);
John McCall36226622010-10-12 02:09:17 +00008664 }
Mike Stump4e1f26a2009-02-19 03:04:26 +00008665
Chris Lattner9156f1b2010-07-05 19:17:26 +00008666 if (Result.isNull()) {
John McCall4bc41ae2010-11-18 19:01:18 +00008667 S.Diag(OpLoc, diag::err_typecheck_indirection_requires_pointer)
Chris Lattner9156f1b2010-07-05 19:17:26 +00008668 << OpTy << Op->getSourceRange();
8669 return QualType();
8670 }
John McCall4bc41ae2010-11-18 19:01:18 +00008671
8672 // Dereferences are usually l-values...
8673 VK = VK_LValue;
8674
8675 // ...except that certain expressions are never l-values in C.
David Blaikiebbafb8a2012-03-11 07:00:24 +00008676 if (!S.getLangOpts().CPlusPlus && Result.isCForbiddenLValueType())
John McCall4bc41ae2010-11-18 19:01:18 +00008677 VK = VK_RValue;
Chris Lattner9156f1b2010-07-05 19:17:26 +00008678
8679 return Result;
Steve Naroff1926c832007-04-24 00:23:05 +00008680}
Steve Naroff218bc2b2007-05-04 21:54:46 +00008681
John McCalle3027922010-08-25 11:45:40 +00008682static inline BinaryOperatorKind ConvertTokenKindToBinaryOpcode(
Steve Naroff218bc2b2007-05-04 21:54:46 +00008683 tok::TokenKind Kind) {
John McCalle3027922010-08-25 11:45:40 +00008684 BinaryOperatorKind Opc;
Steve Naroff218bc2b2007-05-04 21:54:46 +00008685 switch (Kind) {
David Blaikie83d382b2011-09-23 05:06:16 +00008686 default: llvm_unreachable("Unknown binop!");
John McCalle3027922010-08-25 11:45:40 +00008687 case tok::periodstar: Opc = BO_PtrMemD; break;
8688 case tok::arrowstar: Opc = BO_PtrMemI; break;
8689 case tok::star: Opc = BO_Mul; break;
8690 case tok::slash: Opc = BO_Div; break;
8691 case tok::percent: Opc = BO_Rem; break;
8692 case tok::plus: Opc = BO_Add; break;
8693 case tok::minus: Opc = BO_Sub; break;
8694 case tok::lessless: Opc = BO_Shl; break;
8695 case tok::greatergreater: Opc = BO_Shr; break;
8696 case tok::lessequal: Opc = BO_LE; break;
8697 case tok::less: Opc = BO_LT; break;
8698 case tok::greaterequal: Opc = BO_GE; break;
8699 case tok::greater: Opc = BO_GT; break;
8700 case tok::exclaimequal: Opc = BO_NE; break;
8701 case tok::equalequal: Opc = BO_EQ; break;
8702 case tok::amp: Opc = BO_And; break;
8703 case tok::caret: Opc = BO_Xor; break;
8704 case tok::pipe: Opc = BO_Or; break;
8705 case tok::ampamp: Opc = BO_LAnd; break;
8706 case tok::pipepipe: Opc = BO_LOr; break;
8707 case tok::equal: Opc = BO_Assign; break;
8708 case tok::starequal: Opc = BO_MulAssign; break;
8709 case tok::slashequal: Opc = BO_DivAssign; break;
8710 case tok::percentequal: Opc = BO_RemAssign; break;
8711 case tok::plusequal: Opc = BO_AddAssign; break;
8712 case tok::minusequal: Opc = BO_SubAssign; break;
8713 case tok::lesslessequal: Opc = BO_ShlAssign; break;
8714 case tok::greatergreaterequal: Opc = BO_ShrAssign; break;
8715 case tok::ampequal: Opc = BO_AndAssign; break;
8716 case tok::caretequal: Opc = BO_XorAssign; break;
8717 case tok::pipeequal: Opc = BO_OrAssign; break;
8718 case tok::comma: Opc = BO_Comma; break;
Steve Naroff218bc2b2007-05-04 21:54:46 +00008719 }
8720 return Opc;
8721}
8722
John McCalle3027922010-08-25 11:45:40 +00008723static inline UnaryOperatorKind ConvertTokenKindToUnaryOpcode(
Steve Naroff35d85152007-05-07 00:24:15 +00008724 tok::TokenKind Kind) {
John McCalle3027922010-08-25 11:45:40 +00008725 UnaryOperatorKind Opc;
Steve Naroff35d85152007-05-07 00:24:15 +00008726 switch (Kind) {
David Blaikie83d382b2011-09-23 05:06:16 +00008727 default: llvm_unreachable("Unknown unary op!");
John McCalle3027922010-08-25 11:45:40 +00008728 case tok::plusplus: Opc = UO_PreInc; break;
8729 case tok::minusminus: Opc = UO_PreDec; break;
8730 case tok::amp: Opc = UO_AddrOf; break;
8731 case tok::star: Opc = UO_Deref; break;
8732 case tok::plus: Opc = UO_Plus; break;
8733 case tok::minus: Opc = UO_Minus; break;
8734 case tok::tilde: Opc = UO_Not; break;
8735 case tok::exclaim: Opc = UO_LNot; break;
8736 case tok::kw___real: Opc = UO_Real; break;
8737 case tok::kw___imag: Opc = UO_Imag; break;
8738 case tok::kw___extension__: Opc = UO_Extension; break;
Steve Naroff35d85152007-05-07 00:24:15 +00008739 }
8740 return Opc;
8741}
8742
Chandler Carruthe0cee6a2011-01-04 06:52:15 +00008743/// DiagnoseSelfAssignment - Emits a warning if a value is assigned to itself.
8744/// This warning is only emitted for builtin assignment operations. It is also
8745/// suppressed in the event of macro expansions.
Richard Trieuda4f43a62011-09-07 01:33:52 +00008746static void DiagnoseSelfAssignment(Sema &S, Expr *LHSExpr, Expr *RHSExpr,
Chandler Carruthe0cee6a2011-01-04 06:52:15 +00008747 SourceLocation OpLoc) {
8748 if (!S.ActiveTemplateInstantiations.empty())
8749 return;
8750 if (OpLoc.isInvalid() || OpLoc.isMacroID())
8751 return;
Richard Trieuda4f43a62011-09-07 01:33:52 +00008752 LHSExpr = LHSExpr->IgnoreParenImpCasts();
8753 RHSExpr = RHSExpr->IgnoreParenImpCasts();
8754 const DeclRefExpr *LHSDeclRef = dyn_cast<DeclRefExpr>(LHSExpr);
8755 const DeclRefExpr *RHSDeclRef = dyn_cast<DeclRefExpr>(RHSExpr);
8756 if (!LHSDeclRef || !RHSDeclRef ||
8757 LHSDeclRef->getLocation().isMacroID() ||
8758 RHSDeclRef->getLocation().isMacroID())
Chandler Carruthe0cee6a2011-01-04 06:52:15 +00008759 return;
Richard Trieuda4f43a62011-09-07 01:33:52 +00008760 const ValueDecl *LHSDecl =
8761 cast<ValueDecl>(LHSDeclRef->getDecl()->getCanonicalDecl());
8762 const ValueDecl *RHSDecl =
8763 cast<ValueDecl>(RHSDeclRef->getDecl()->getCanonicalDecl());
8764 if (LHSDecl != RHSDecl)
Chandler Carruthe0cee6a2011-01-04 06:52:15 +00008765 return;
Richard Trieuda4f43a62011-09-07 01:33:52 +00008766 if (LHSDecl->getType().isVolatileQualified())
Chandler Carruthe0cee6a2011-01-04 06:52:15 +00008767 return;
Richard Trieuda4f43a62011-09-07 01:33:52 +00008768 if (const ReferenceType *RefTy = LHSDecl->getType()->getAs<ReferenceType>())
Chandler Carruthe0cee6a2011-01-04 06:52:15 +00008769 if (RefTy->getPointeeType().isVolatileQualified())
8770 return;
8771
8772 S.Diag(OpLoc, diag::warn_self_assignment)
Richard Trieuda4f43a62011-09-07 01:33:52 +00008773 << LHSDeclRef->getType()
8774 << LHSExpr->getSourceRange() << RHSExpr->getSourceRange();
Chandler Carruthe0cee6a2011-01-04 06:52:15 +00008775}
8776
Ted Kremenekebeabab2013-04-22 22:46:52 +00008777/// Check if a bitwise-& is performed on an Objective-C pointer. This
8778/// is usually indicative of introspection within the Objective-C pointer.
8779static void checkObjCPointerIntrospection(Sema &S, ExprResult &L, ExprResult &R,
8780 SourceLocation OpLoc) {
8781 if (!S.getLangOpts().ObjC1)
8782 return;
8783
8784 const Expr *ObjCPointerExpr = 0, *OtherExpr = 0;
8785 const Expr *LHS = L.get();
8786 const Expr *RHS = R.get();
8787
8788 if (LHS->IgnoreParenCasts()->getType()->isObjCObjectPointerType()) {
8789 ObjCPointerExpr = LHS;
8790 OtherExpr = RHS;
8791 }
8792 else if (RHS->IgnoreParenCasts()->getType()->isObjCObjectPointerType()) {
8793 ObjCPointerExpr = RHS;
8794 OtherExpr = LHS;
8795 }
8796
8797 // This warning is deliberately made very specific to reduce false
8798 // positives with logic that uses '&' for hashing. This logic mainly
8799 // looks for code trying to introspect into tagged pointers, which
8800 // code should generally never do.
8801 if (ObjCPointerExpr && isa<IntegerLiteral>(OtherExpr->IgnoreParenCasts())) {
Ted Kremenek009d61d2013-06-24 21:35:39 +00008802 unsigned Diag = diag::warn_objc_pointer_masking;
8803 // Determine if we are introspecting the result of performSelectorXXX.
8804 const Expr *Ex = ObjCPointerExpr->IgnoreParenCasts();
8805 // Special case messages to -performSelector and friends, which
8806 // can return non-pointer values boxed in a pointer value.
8807 // Some clients may wish to silence warnings in this subcase.
8808 if (const ObjCMessageExpr *ME = dyn_cast<ObjCMessageExpr>(Ex)) {
8809 Selector S = ME->getSelector();
8810 StringRef SelArg0 = S.getNameForSlot(0);
8811 if (SelArg0.startswith("performSelector"))
8812 Diag = diag::warn_objc_pointer_masking_performSelector;
8813 }
8814
8815 S.Diag(OpLoc, Diag)
Ted Kremenekebeabab2013-04-22 22:46:52 +00008816 << ObjCPointerExpr->getSourceRange();
8817 }
8818}
8819
Douglas Gregor7d5fc7e2008-11-06 23:29:22 +00008820/// CreateBuiltinBinOp - Creates a new built-in binary operation with
8821/// operator @p Opc at location @c TokLoc. This routine only supports
8822/// built-in operations; ActOnBinOp handles overloaded operators.
John McCalldadc5752010-08-24 06:29:42 +00008823ExprResult Sema::CreateBuiltinBinOp(SourceLocation OpLoc,
Argyrios Kyrtzidis7a808c02011-01-05 20:09:36 +00008824 BinaryOperatorKind Opc,
Richard Trieu4a287fb2011-09-07 01:49:20 +00008825 Expr *LHSExpr, Expr *RHSExpr) {
Richard Smith2bf7fdb2013-01-02 11:42:31 +00008826 if (getLangOpts().CPlusPlus11 && isa<InitListExpr>(RHSExpr)) {
Sebastian Redl67766732012-02-27 20:34:02 +00008827 // The syntax only allows initializer lists on the RHS of assignment,
8828 // so we don't need to worry about accepting invalid code for
8829 // non-assignment operators.
8830 // C++11 5.17p9:
8831 // The meaning of x = {v} [...] is that of x = T(v) [...]. The meaning
8832 // of x = {} is x = T().
8833 InitializationKind Kind =
8834 InitializationKind::CreateDirectList(RHSExpr->getLocStart());
8835 InitializedEntity Entity =
8836 InitializedEntity::InitializeTemporary(LHSExpr->getType());
Dmitri Gribenko8f8930f2013-05-03 15:05:50 +00008837 InitializationSequence InitSeq(*this, Entity, Kind, RHSExpr);
Benjamin Kramercc4c49d2012-08-23 23:38:35 +00008838 ExprResult Init = InitSeq.Perform(*this, Entity, Kind, RHSExpr);
Sebastian Redl67766732012-02-27 20:34:02 +00008839 if (Init.isInvalid())
8840 return Init;
8841 RHSExpr = Init.take();
8842 }
8843
Richard Trieu4a287fb2011-09-07 01:49:20 +00008844 ExprResult LHS = Owned(LHSExpr), RHS = Owned(RHSExpr);
Eli Friedman8b7b1b12009-03-28 01:22:36 +00008845 QualType ResultTy; // Result type of the binary operator.
Eli Friedman8b7b1b12009-03-28 01:22:36 +00008846 // The following two variables are used for compound assignment operators
8847 QualType CompLHSTy; // Type of LHS after promotions for computation
8848 QualType CompResultTy; // Type of computation result
John McCall7decc9e2010-11-18 06:31:45 +00008849 ExprValueKind VK = VK_RValue;
8850 ExprObjectKind OK = OK_Ordinary;
Douglas Gregor7d5fc7e2008-11-06 23:29:22 +00008851
8852 switch (Opc) {
John McCalle3027922010-08-25 11:45:40 +00008853 case BO_Assign:
Richard Trieu4a287fb2011-09-07 01:49:20 +00008854 ResultTy = CheckAssignmentOperands(LHS.get(), RHS, OpLoc, QualType());
David Blaikiebbafb8a2012-03-11 07:00:24 +00008855 if (getLangOpts().CPlusPlus &&
Richard Trieu4a287fb2011-09-07 01:49:20 +00008856 LHS.get()->getObjectKind() != OK_ObjCProperty) {
8857 VK = LHS.get()->getValueKind();
8858 OK = LHS.get()->getObjectKind();
John McCall7decc9e2010-11-18 06:31:45 +00008859 }
Chandler Carruthe0cee6a2011-01-04 06:52:15 +00008860 if (!ResultTy.isNull())
Richard Trieu4a287fb2011-09-07 01:49:20 +00008861 DiagnoseSelfAssignment(*this, LHS.get(), RHS.get(), OpLoc);
Douglas Gregor7d5fc7e2008-11-06 23:29:22 +00008862 break;
John McCalle3027922010-08-25 11:45:40 +00008863 case BO_PtrMemD:
8864 case BO_PtrMemI:
Richard Trieu4a287fb2011-09-07 01:49:20 +00008865 ResultTy = CheckPointerToMemberOperands(LHS, RHS, VK, OpLoc,
John McCalle3027922010-08-25 11:45:40 +00008866 Opc == BO_PtrMemI);
Sebastian Redl112a97662009-02-07 00:15:38 +00008867 break;
John McCalle3027922010-08-25 11:45:40 +00008868 case BO_Mul:
8869 case BO_Div:
Richard Trieu4a287fb2011-09-07 01:49:20 +00008870 ResultTy = CheckMultiplyDivideOperands(LHS, RHS, OpLoc, false,
John McCalle3027922010-08-25 11:45:40 +00008871 Opc == BO_Div);
Douglas Gregor7d5fc7e2008-11-06 23:29:22 +00008872 break;
John McCalle3027922010-08-25 11:45:40 +00008873 case BO_Rem:
Richard Trieu4a287fb2011-09-07 01:49:20 +00008874 ResultTy = CheckRemainderOperands(LHS, RHS, OpLoc);
Douglas Gregor7d5fc7e2008-11-06 23:29:22 +00008875 break;
John McCalle3027922010-08-25 11:45:40 +00008876 case BO_Add:
Nico Weberccec40d2012-03-02 22:01:22 +00008877 ResultTy = CheckAdditionOperands(LHS, RHS, OpLoc, Opc);
Douglas Gregor7d5fc7e2008-11-06 23:29:22 +00008878 break;
John McCalle3027922010-08-25 11:45:40 +00008879 case BO_Sub:
Richard Trieu4a287fb2011-09-07 01:49:20 +00008880 ResultTy = CheckSubtractionOperands(LHS, RHS, OpLoc);
Douglas Gregor7d5fc7e2008-11-06 23:29:22 +00008881 break;
John McCalle3027922010-08-25 11:45:40 +00008882 case BO_Shl:
8883 case BO_Shr:
Richard Trieu4a287fb2011-09-07 01:49:20 +00008884 ResultTy = CheckShiftOperands(LHS, RHS, OpLoc, Opc);
Douglas Gregor7d5fc7e2008-11-06 23:29:22 +00008885 break;
John McCalle3027922010-08-25 11:45:40 +00008886 case BO_LE:
8887 case BO_LT:
8888 case BO_GE:
8889 case BO_GT:
Richard Trieu4a287fb2011-09-07 01:49:20 +00008890 ResultTy = CheckCompareOperands(LHS, RHS, OpLoc, Opc, true);
Douglas Gregor7d5fc7e2008-11-06 23:29:22 +00008891 break;
John McCalle3027922010-08-25 11:45:40 +00008892 case BO_EQ:
8893 case BO_NE:
Richard Trieu4a287fb2011-09-07 01:49:20 +00008894 ResultTy = CheckCompareOperands(LHS, RHS, OpLoc, Opc, false);
Douglas Gregor7d5fc7e2008-11-06 23:29:22 +00008895 break;
John McCalle3027922010-08-25 11:45:40 +00008896 case BO_And:
Ted Kremenekebeabab2013-04-22 22:46:52 +00008897 checkObjCPointerIntrospection(*this, LHS, RHS, OpLoc);
John McCalle3027922010-08-25 11:45:40 +00008898 case BO_Xor:
8899 case BO_Or:
Richard Trieu4a287fb2011-09-07 01:49:20 +00008900 ResultTy = CheckBitwiseOperands(LHS, RHS, OpLoc);
Douglas Gregor7d5fc7e2008-11-06 23:29:22 +00008901 break;
John McCalle3027922010-08-25 11:45:40 +00008902 case BO_LAnd:
8903 case BO_LOr:
Richard Trieu4a287fb2011-09-07 01:49:20 +00008904 ResultTy = CheckLogicalOperands(LHS, RHS, OpLoc, Opc);
Douglas Gregor7d5fc7e2008-11-06 23:29:22 +00008905 break;
John McCalle3027922010-08-25 11:45:40 +00008906 case BO_MulAssign:
8907 case BO_DivAssign:
Richard Trieu4a287fb2011-09-07 01:49:20 +00008908 CompResultTy = CheckMultiplyDivideOperands(LHS, RHS, OpLoc, true,
John McCall7decc9e2010-11-18 06:31:45 +00008909 Opc == BO_DivAssign);
Eli Friedman8b7b1b12009-03-28 01:22:36 +00008910 CompLHSTy = CompResultTy;
Richard Trieu4a287fb2011-09-07 01:49:20 +00008911 if (!CompResultTy.isNull() && !LHS.isInvalid() && !RHS.isInvalid())
8912 ResultTy = CheckAssignmentOperands(LHS.get(), RHS, OpLoc, CompResultTy);
Douglas Gregor7d5fc7e2008-11-06 23:29:22 +00008913 break;
John McCalle3027922010-08-25 11:45:40 +00008914 case BO_RemAssign:
Richard Trieu4a287fb2011-09-07 01:49:20 +00008915 CompResultTy = CheckRemainderOperands(LHS, RHS, OpLoc, true);
Eli Friedman8b7b1b12009-03-28 01:22:36 +00008916 CompLHSTy = CompResultTy;
Richard Trieu4a287fb2011-09-07 01:49:20 +00008917 if (!CompResultTy.isNull() && !LHS.isInvalid() && !RHS.isInvalid())
8918 ResultTy = CheckAssignmentOperands(LHS.get(), RHS, OpLoc, CompResultTy);
Douglas Gregor7d5fc7e2008-11-06 23:29:22 +00008919 break;
John McCalle3027922010-08-25 11:45:40 +00008920 case BO_AddAssign:
Nico Weberccec40d2012-03-02 22:01:22 +00008921 CompResultTy = CheckAdditionOperands(LHS, RHS, OpLoc, Opc, &CompLHSTy);
Richard Trieu4a287fb2011-09-07 01:49:20 +00008922 if (!CompResultTy.isNull() && !LHS.isInvalid() && !RHS.isInvalid())
8923 ResultTy = CheckAssignmentOperands(LHS.get(), RHS, OpLoc, CompResultTy);
Douglas Gregor7d5fc7e2008-11-06 23:29:22 +00008924 break;
John McCalle3027922010-08-25 11:45:40 +00008925 case BO_SubAssign:
Richard Trieu4a287fb2011-09-07 01:49:20 +00008926 CompResultTy = CheckSubtractionOperands(LHS, RHS, OpLoc, &CompLHSTy);
8927 if (!CompResultTy.isNull() && !LHS.isInvalid() && !RHS.isInvalid())
8928 ResultTy = CheckAssignmentOperands(LHS.get(), RHS, OpLoc, CompResultTy);
Douglas Gregor7d5fc7e2008-11-06 23:29:22 +00008929 break;
John McCalle3027922010-08-25 11:45:40 +00008930 case BO_ShlAssign:
8931 case BO_ShrAssign:
Richard Trieu4a287fb2011-09-07 01:49:20 +00008932 CompResultTy = CheckShiftOperands(LHS, RHS, OpLoc, Opc, true);
Eli Friedman8b7b1b12009-03-28 01:22:36 +00008933 CompLHSTy = CompResultTy;
Richard Trieu4a287fb2011-09-07 01:49:20 +00008934 if (!CompResultTy.isNull() && !LHS.isInvalid() && !RHS.isInvalid())
8935 ResultTy = CheckAssignmentOperands(LHS.get(), RHS, OpLoc, CompResultTy);
Douglas Gregor7d5fc7e2008-11-06 23:29:22 +00008936 break;
John McCalle3027922010-08-25 11:45:40 +00008937 case BO_AndAssign:
8938 case BO_XorAssign:
8939 case BO_OrAssign:
Richard Trieu4a287fb2011-09-07 01:49:20 +00008940 CompResultTy = CheckBitwiseOperands(LHS, RHS, OpLoc, true);
Eli Friedman8b7b1b12009-03-28 01:22:36 +00008941 CompLHSTy = CompResultTy;
Richard Trieu4a287fb2011-09-07 01:49:20 +00008942 if (!CompResultTy.isNull() && !LHS.isInvalid() && !RHS.isInvalid())
8943 ResultTy = CheckAssignmentOperands(LHS.get(), RHS, OpLoc, CompResultTy);
Douglas Gregor7d5fc7e2008-11-06 23:29:22 +00008944 break;
John McCalle3027922010-08-25 11:45:40 +00008945 case BO_Comma:
Richard Trieu4a287fb2011-09-07 01:49:20 +00008946 ResultTy = CheckCommaOperands(*this, LHS, RHS, OpLoc);
David Blaikiebbafb8a2012-03-11 07:00:24 +00008947 if (getLangOpts().CPlusPlus && !RHS.isInvalid()) {
Richard Trieu4a287fb2011-09-07 01:49:20 +00008948 VK = RHS.get()->getValueKind();
8949 OK = RHS.get()->getObjectKind();
John McCall7decc9e2010-11-18 06:31:45 +00008950 }
Douglas Gregor7d5fc7e2008-11-06 23:29:22 +00008951 break;
8952 }
Richard Trieu4a287fb2011-09-07 01:49:20 +00008953 if (ResultTy.isNull() || LHS.isInvalid() || RHS.isInvalid())
Sebastian Redlb5d49352009-01-19 22:31:54 +00008954 return ExprError();
Kaelyn Uhrain2e7aa5a2011-08-05 23:18:04 +00008955
8956 // Check for array bounds violations for both sides of the BinaryOperator
Richard Trieu4a287fb2011-09-07 01:49:20 +00008957 CheckArrayAccess(LHS.get());
8958 CheckArrayAccess(RHS.get());
Kaelyn Uhrain2e7aa5a2011-08-05 23:18:04 +00008959
Fariborz Jahanian06bb7f72013-03-28 19:50:55 +00008960 if (const ObjCIsaExpr *OISA = dyn_cast<ObjCIsaExpr>(LHS.get()->IgnoreParenCasts())) {
8961 NamedDecl *ObjectSetClass = LookupSingleName(TUScope,
8962 &Context.Idents.get("object_setClass"),
8963 SourceLocation(), LookupOrdinaryName);
8964 if (ObjectSetClass && isa<ObjCIsaExpr>(LHS.get())) {
8965 SourceLocation RHSLocEnd = PP.getLocForEndOfToken(RHS.get()->getLocEnd());
8966 Diag(LHS.get()->getExprLoc(), diag::warn_objc_isa_assign) <<
8967 FixItHint::CreateInsertion(LHS.get()->getLocStart(), "object_setClass(") <<
8968 FixItHint::CreateReplacement(SourceRange(OISA->getOpLoc(), OpLoc), ",") <<
8969 FixItHint::CreateInsertion(RHSLocEnd, ")");
8970 }
8971 else
8972 Diag(LHS.get()->getExprLoc(), diag::warn_objc_isa_assign);
8973 }
Fariborz Jahanian3b602ce2013-03-28 23:39:11 +00008974 else if (const ObjCIvarRefExpr *OIRE =
8975 dyn_cast<ObjCIvarRefExpr>(LHS.get()->IgnoreParenCasts()))
Fariborz Jahanianf12ff4df2013-04-02 18:57:54 +00008976 DiagnoseDirectIsaAccess(*this, OIRE, OpLoc, RHS.get());
Fariborz Jahanian3b602ce2013-03-28 23:39:11 +00008977
Eli Friedman8b7b1b12009-03-28 01:22:36 +00008978 if (CompResultTy.isNull())
Richard Trieu4a287fb2011-09-07 01:49:20 +00008979 return Owned(new (Context) BinaryOperator(LHS.take(), RHS.take(), Opc,
Lang Hames5de91cc2012-10-02 04:45:10 +00008980 ResultTy, VK, OK, OpLoc,
8981 FPFeatures.fp_contract));
David Blaikiebbafb8a2012-03-11 07:00:24 +00008982 if (getLangOpts().CPlusPlus && LHS.get()->getObjectKind() !=
Richard Trieucfc491d2011-08-02 04:35:43 +00008983 OK_ObjCProperty) {
John McCall7decc9e2010-11-18 06:31:45 +00008984 VK = VK_LValue;
Richard Trieu4a287fb2011-09-07 01:49:20 +00008985 OK = LHS.get()->getObjectKind();
John McCall7decc9e2010-11-18 06:31:45 +00008986 }
Richard Trieu4a287fb2011-09-07 01:49:20 +00008987 return Owned(new (Context) CompoundAssignOperator(LHS.take(), RHS.take(), Opc,
John Wiegley01296292011-04-08 18:41:53 +00008988 ResultTy, VK, OK, CompLHSTy,
Lang Hames5de91cc2012-10-02 04:45:10 +00008989 CompResultTy, OpLoc,
8990 FPFeatures.fp_contract));
Douglas Gregor7d5fc7e2008-11-06 23:29:22 +00008991}
8992
Sebastian Redl44615072009-10-27 12:10:02 +00008993/// DiagnoseBitwisePrecedence - Emit a warning when bitwise and comparison
8994/// operators are mixed in a way that suggests that the programmer forgot that
8995/// comparison operators have higher precedence. The most typical example of
8996/// such code is "flags & 0x0020 != 0", which is equivalent to "flags & 1".
John McCalle3027922010-08-25 11:45:40 +00008997static void DiagnoseBitwisePrecedence(Sema &Self, BinaryOperatorKind Opc,
Richard Trieu4a287fb2011-09-07 01:49:20 +00008998 SourceLocation OpLoc, Expr *LHSExpr,
8999 Expr *RHSExpr) {
Eli Friedman37feb2d2012-11-15 00:29:07 +00009000 BinaryOperator *LHSBO = dyn_cast<BinaryOperator>(LHSExpr);
9001 BinaryOperator *RHSBO = dyn_cast<BinaryOperator>(RHSExpr);
Sebastian Redl43028242009-10-26 15:24:15 +00009002
Eli Friedman37feb2d2012-11-15 00:29:07 +00009003 // Check that one of the sides is a comparison operator.
9004 bool isLeftComp = LHSBO && LHSBO->isComparisonOp();
9005 bool isRightComp = RHSBO && RHSBO->isComparisonOp();
9006 if (!isLeftComp && !isRightComp)
Sebastian Redl43028242009-10-26 15:24:15 +00009007 return;
9008
9009 // Bitwise operations are sometimes used as eager logical ops.
9010 // Don't diagnose this.
Eli Friedman37feb2d2012-11-15 00:29:07 +00009011 bool isLeftBitwise = LHSBO && LHSBO->isBitwiseOp();
9012 bool isRightBitwise = RHSBO && RHSBO->isBitwiseOp();
9013 if ((isLeftComp || isLeftBitwise) && (isRightComp || isRightBitwise))
Sebastian Redl43028242009-10-26 15:24:15 +00009014 return;
9015
Richard Trieu4a287fb2011-09-07 01:49:20 +00009016 SourceRange DiagRange = isLeftComp ? SourceRange(LHSExpr->getLocStart(),
9017 OpLoc)
9018 : SourceRange(OpLoc, RHSExpr->getLocEnd());
Eli Friedman37feb2d2012-11-15 00:29:07 +00009019 StringRef OpStr = isLeftComp ? LHSBO->getOpcodeStr() : RHSBO->getOpcodeStr();
Richard Trieu73088052011-08-10 22:41:34 +00009020 SourceRange ParensRange = isLeftComp ?
Eli Friedman37feb2d2012-11-15 00:29:07 +00009021 SourceRange(LHSBO->getRHS()->getLocStart(), RHSExpr->getLocEnd())
9022 : SourceRange(LHSExpr->getLocStart(), RHSBO->getLHS()->getLocStart());
Richard Trieu73088052011-08-10 22:41:34 +00009023
9024 Self.Diag(OpLoc, diag::warn_precedence_bitwise_rel)
Eli Friedman37feb2d2012-11-15 00:29:07 +00009025 << DiagRange << BinaryOperator::getOpcodeStr(Opc) << OpStr;
Richard Trieu73088052011-08-10 22:41:34 +00009026 SuggestParentheses(Self, OpLoc,
David Blaikiedac86fd2012-10-08 01:19:49 +00009027 Self.PDiag(diag::note_precedence_silence) << OpStr,
Nico Webercdfb1ae2012-06-03 07:07:00 +00009028 (isLeftComp ? LHSExpr : RHSExpr)->getSourceRange());
Richard Trieu73088052011-08-10 22:41:34 +00009029 SuggestParentheses(Self, OpLoc,
Eli Friedman37feb2d2012-11-15 00:29:07 +00009030 Self.PDiag(diag::note_precedence_bitwise_first)
9031 << BinaryOperator::getOpcodeStr(Opc),
Richard Trieu73088052011-08-10 22:41:34 +00009032 ParensRange);
Sebastian Redl43028242009-10-26 15:24:15 +00009033}
9034
Argyrios Kyrtzidis01bf7772011-06-20 18:41:26 +00009035/// \brief It accepts a '&' expr that is inside a '|' one.
9036/// Emit a diagnostic together with a fixit hint that wraps the '&' expression
9037/// in parentheses.
9038static void
9039EmitDiagnosticForBitwiseAndInBitwiseOr(Sema &Self, SourceLocation OpLoc,
9040 BinaryOperator *Bop) {
9041 assert(Bop->getOpcode() == BO_And);
9042 Self.Diag(Bop->getOperatorLoc(), diag::warn_bitwise_and_in_bitwise_or)
9043 << Bop->getSourceRange() << OpLoc;
9044 SuggestParentheses(Self, Bop->getOperatorLoc(),
David Blaikiedac86fd2012-10-08 01:19:49 +00009045 Self.PDiag(diag::note_precedence_silence)
9046 << Bop->getOpcodeStr(),
Argyrios Kyrtzidis01bf7772011-06-20 18:41:26 +00009047 Bop->getSourceRange());
9048}
9049
Argyrios Kyrtzidis14a96622010-11-17 18:26:36 +00009050/// \brief It accepts a '&&' expr that is inside a '||' one.
9051/// Emit a diagnostic together with a fixit hint that wraps the '&&' expression
9052/// in parentheses.
9053static void
9054EmitDiagnosticForLogicalAndInLogicalOr(Sema &Self, SourceLocation OpLoc,
Argyrios Kyrtzidisad8b4d42011-04-22 19:16:27 +00009055 BinaryOperator *Bop) {
9056 assert(Bop->getOpcode() == BO_LAnd);
Chandler Carruthb00e8c02011-06-16 01:05:14 +00009057 Self.Diag(Bop->getOperatorLoc(), diag::warn_logical_and_in_logical_or)
9058 << Bop->getSourceRange() << OpLoc;
Argyrios Kyrtzidisad8b4d42011-04-22 19:16:27 +00009059 SuggestParentheses(Self, Bop->getOperatorLoc(),
David Blaikiedac86fd2012-10-08 01:19:49 +00009060 Self.PDiag(diag::note_precedence_silence)
9061 << Bop->getOpcodeStr(),
Chandler Carruthb00e8c02011-06-16 01:05:14 +00009062 Bop->getSourceRange());
Argyrios Kyrtzidis14a96622010-11-17 18:26:36 +00009063}
9064
9065/// \brief Returns true if the given expression can be evaluated as a constant
9066/// 'true'.
9067static bool EvaluatesAsTrue(Sema &S, Expr *E) {
9068 bool Res;
9069 return E->EvaluateAsBooleanCondition(Res, S.getASTContext()) && Res;
9070}
9071
Argyrios Kyrtzidis56e879d2010-11-17 19:18:19 +00009072/// \brief Returns true if the given expression can be evaluated as a constant
9073/// 'false'.
9074static bool EvaluatesAsFalse(Sema &S, Expr *E) {
9075 bool Res;
9076 return E->EvaluateAsBooleanCondition(Res, S.getASTContext()) && !Res;
9077}
9078
Argyrios Kyrtzidis14a96622010-11-17 18:26:36 +00009079/// \brief Look for '&&' in the left hand of a '||' expr.
9080static void DiagnoseLogicalAndInLogicalOrLHS(Sema &S, SourceLocation OpLoc,
Richard Trieuf9bd0f52011-09-07 02:02:10 +00009081 Expr *LHSExpr, Expr *RHSExpr) {
9082 if (BinaryOperator *Bop = dyn_cast<BinaryOperator>(LHSExpr)) {
Argyrios Kyrtzidisf89a56c2010-11-16 21:00:12 +00009083 if (Bop->getOpcode() == BO_LAnd) {
Argyrios Kyrtzidis56e879d2010-11-17 19:18:19 +00009084 // If it's "a && b || 0" don't warn since the precedence doesn't matter.
Richard Trieuf9bd0f52011-09-07 02:02:10 +00009085 if (EvaluatesAsFalse(S, RHSExpr))
Argyrios Kyrtzidis56e879d2010-11-17 19:18:19 +00009086 return;
Argyrios Kyrtzidis14a96622010-11-17 18:26:36 +00009087 // If it's "1 && a || b" don't warn since the precedence doesn't matter.
9088 if (!EvaluatesAsTrue(S, Bop->getLHS()))
9089 return EmitDiagnosticForLogicalAndInLogicalOr(S, OpLoc, Bop);
9090 } else if (Bop->getOpcode() == BO_LOr) {
9091 if (BinaryOperator *RBop = dyn_cast<BinaryOperator>(Bop->getRHS())) {
9092 // If it's "a || b && 1 || c" we didn't warn earlier for
9093 // "a || b && 1", but warn now.
9094 if (RBop->getOpcode() == BO_LAnd && EvaluatesAsTrue(S, RBop->getRHS()))
9095 return EmitDiagnosticForLogicalAndInLogicalOr(S, OpLoc, RBop);
9096 }
9097 }
9098 }
9099}
9100
9101/// \brief Look for '&&' in the right hand of a '||' expr.
9102static void DiagnoseLogicalAndInLogicalOrRHS(Sema &S, SourceLocation OpLoc,
Richard Trieuf9bd0f52011-09-07 02:02:10 +00009103 Expr *LHSExpr, Expr *RHSExpr) {
9104 if (BinaryOperator *Bop = dyn_cast<BinaryOperator>(RHSExpr)) {
Argyrios Kyrtzidis14a96622010-11-17 18:26:36 +00009105 if (Bop->getOpcode() == BO_LAnd) {
Argyrios Kyrtzidis56e879d2010-11-17 19:18:19 +00009106 // If it's "0 || a && b" don't warn since the precedence doesn't matter.
Richard Trieuf9bd0f52011-09-07 02:02:10 +00009107 if (EvaluatesAsFalse(S, LHSExpr))
Argyrios Kyrtzidis56e879d2010-11-17 19:18:19 +00009108 return;
Argyrios Kyrtzidis14a96622010-11-17 18:26:36 +00009109 // If it's "a || b && 1" don't warn since the precedence doesn't matter.
9110 if (!EvaluatesAsTrue(S, Bop->getRHS()))
9111 return EmitDiagnosticForLogicalAndInLogicalOr(S, OpLoc, Bop);
Argyrios Kyrtzidisf89a56c2010-11-16 21:00:12 +00009112 }
9113 }
9114}
9115
Argyrios Kyrtzidis01bf7772011-06-20 18:41:26 +00009116/// \brief Look for '&' in the left or right hand of a '|' expr.
9117static void DiagnoseBitwiseAndInBitwiseOr(Sema &S, SourceLocation OpLoc,
9118 Expr *OrArg) {
9119 if (BinaryOperator *Bop = dyn_cast<BinaryOperator>(OrArg)) {
9120 if (Bop->getOpcode() == BO_And)
9121 return EmitDiagnosticForBitwiseAndInBitwiseOr(S, OpLoc, Bop);
9122 }
9123}
9124
David Blaikie15f17cb2012-10-05 00:41:03 +00009125static void DiagnoseAdditionInShift(Sema &S, SourceLocation OpLoc,
David Blaikie82d3ab92012-10-19 18:26:06 +00009126 Expr *SubExpr, StringRef Shift) {
David Blaikie15f17cb2012-10-05 00:41:03 +00009127 if (BinaryOperator *Bop = dyn_cast<BinaryOperator>(SubExpr)) {
9128 if (Bop->getOpcode() == BO_Add || Bop->getOpcode() == BO_Sub) {
David Blaikiedac86fd2012-10-08 01:19:49 +00009129 StringRef Op = Bop->getOpcodeStr();
David Blaikie15f17cb2012-10-05 00:41:03 +00009130 S.Diag(Bop->getOperatorLoc(), diag::warn_addition_in_bitshift)
David Blaikie82d3ab92012-10-19 18:26:06 +00009131 << Bop->getSourceRange() << OpLoc << Shift << Op;
David Blaikie15f17cb2012-10-05 00:41:03 +00009132 SuggestParentheses(S, Bop->getOperatorLoc(),
David Blaikiedac86fd2012-10-08 01:19:49 +00009133 S.PDiag(diag::note_precedence_silence) << Op,
David Blaikie15f17cb2012-10-05 00:41:03 +00009134 Bop->getSourceRange());
9135 }
9136 }
9137}
9138
Richard Trieufe042e62013-04-17 02:12:45 +00009139static void DiagnoseShiftCompare(Sema &S, SourceLocation OpLoc,
9140 Expr *LHSExpr, Expr *RHSExpr) {
9141 CXXOperatorCallExpr *OCE = dyn_cast<CXXOperatorCallExpr>(LHSExpr);
9142 if (!OCE)
9143 return;
9144
9145 FunctionDecl *FD = OCE->getDirectCallee();
9146 if (!FD || !FD->isOverloadedOperator())
9147 return;
9148
9149 OverloadedOperatorKind Kind = FD->getOverloadedOperator();
9150 if (Kind != OO_LessLess && Kind != OO_GreaterGreater)
9151 return;
9152
9153 S.Diag(OpLoc, diag::warn_overloaded_shift_in_comparison)
9154 << LHSExpr->getSourceRange() << RHSExpr->getSourceRange()
9155 << (Kind == OO_LessLess);
Richard Trieufe042e62013-04-17 02:12:45 +00009156 SuggestParentheses(S, OCE->getOperatorLoc(),
9157 S.PDiag(diag::note_precedence_silence)
9158 << (Kind == OO_LessLess ? "<<" : ">>"),
9159 OCE->getSourceRange());
Richard Trieue0894972013-04-18 01:04:37 +00009160 SuggestParentheses(S, OpLoc,
9161 S.PDiag(diag::note_evaluate_comparison_first),
9162 SourceRange(OCE->getArg(1)->getLocStart(),
9163 RHSExpr->getLocEnd()));
Richard Trieufe042e62013-04-17 02:12:45 +00009164}
9165
Sebastian Redl43028242009-10-26 15:24:15 +00009166/// DiagnoseBinOpPrecedence - Emit warnings for expressions with tricky
Argyrios Kyrtzidisf89a56c2010-11-16 21:00:12 +00009167/// precedence.
John McCalle3027922010-08-25 11:45:40 +00009168static void DiagnoseBinOpPrecedence(Sema &Self, BinaryOperatorKind Opc,
Richard Trieuf9bd0f52011-09-07 02:02:10 +00009169 SourceLocation OpLoc, Expr *LHSExpr,
9170 Expr *RHSExpr){
Argyrios Kyrtzidisf89a56c2010-11-16 21:00:12 +00009171 // Diagnose "arg1 'bitwise' arg2 'eq' arg3".
Sebastian Redl44615072009-10-27 12:10:02 +00009172 if (BinaryOperator::isBitwiseOp(Opc))
Richard Trieuf9bd0f52011-09-07 02:02:10 +00009173 DiagnoseBitwisePrecedence(Self, Opc, OpLoc, LHSExpr, RHSExpr);
Argyrios Kyrtzidis01bf7772011-06-20 18:41:26 +00009174
9175 // Diagnose "arg1 & arg2 | arg3"
9176 if (Opc == BO_Or && !OpLoc.isMacroID()/* Don't warn in macros. */) {
Richard Trieuf9bd0f52011-09-07 02:02:10 +00009177 DiagnoseBitwiseAndInBitwiseOr(Self, OpLoc, LHSExpr);
9178 DiagnoseBitwiseAndInBitwiseOr(Self, OpLoc, RHSExpr);
Argyrios Kyrtzidis01bf7772011-06-20 18:41:26 +00009179 }
Argyrios Kyrtzidisf89a56c2010-11-16 21:00:12 +00009180
Argyrios Kyrtzidis14a96622010-11-17 18:26:36 +00009181 // Warn about arg1 || arg2 && arg3, as GCC 4.3+ does.
9182 // We don't warn for 'assert(a || b && "bad")' since this is safe.
Argyrios Kyrtzidisb94e5a32010-11-17 18:54:22 +00009183 if (Opc == BO_LOr && !OpLoc.isMacroID()/* Don't warn in macros. */) {
Richard Trieuf9bd0f52011-09-07 02:02:10 +00009184 DiagnoseLogicalAndInLogicalOrLHS(Self, OpLoc, LHSExpr, RHSExpr);
9185 DiagnoseLogicalAndInLogicalOrRHS(Self, OpLoc, LHSExpr, RHSExpr);
Argyrios Kyrtzidisf89a56c2010-11-16 21:00:12 +00009186 }
David Blaikie15f17cb2012-10-05 00:41:03 +00009187
9188 if ((Opc == BO_Shl && LHSExpr->getType()->isIntegralType(Self.getASTContext()))
9189 || Opc == BO_Shr) {
David Blaikie82d3ab92012-10-19 18:26:06 +00009190 StringRef Shift = BinaryOperator::getOpcodeStr(Opc);
9191 DiagnoseAdditionInShift(Self, OpLoc, LHSExpr, Shift);
9192 DiagnoseAdditionInShift(Self, OpLoc, RHSExpr, Shift);
David Blaikie15f17cb2012-10-05 00:41:03 +00009193 }
Richard Trieufe042e62013-04-17 02:12:45 +00009194
9195 // Warn on overloaded shift operators and comparisons, such as:
9196 // cout << 5 == 4;
9197 if (BinaryOperator::isComparisonOp(Opc))
9198 DiagnoseShiftCompare(Self, OpLoc, LHSExpr, RHSExpr);
Sebastian Redl43028242009-10-26 15:24:15 +00009199}
9200
Steve Naroff218bc2b2007-05-04 21:54:46 +00009201// Binary Operators. 'Tok' is the token for the operator.
John McCalldadc5752010-08-24 06:29:42 +00009202ExprResult Sema::ActOnBinOp(Scope *S, SourceLocation TokLoc,
John McCalle3027922010-08-25 11:45:40 +00009203 tok::TokenKind Kind,
Richard Trieuf9bd0f52011-09-07 02:02:10 +00009204 Expr *LHSExpr, Expr *RHSExpr) {
John McCalle3027922010-08-25 11:45:40 +00009205 BinaryOperatorKind Opc = ConvertTokenKindToBinaryOpcode(Kind);
Richard Trieuf9bd0f52011-09-07 02:02:10 +00009206 assert((LHSExpr != 0) && "ActOnBinOp(): missing left expression");
9207 assert((RHSExpr != 0) && "ActOnBinOp(): missing right expression");
Steve Naroff218bc2b2007-05-04 21:54:46 +00009208
Sebastian Redl43028242009-10-26 15:24:15 +00009209 // Emit warnings for tricky precedence issues, e.g. "bitfield & 0x4 == 0"
Richard Trieuf9bd0f52011-09-07 02:02:10 +00009210 DiagnoseBinOpPrecedence(*this, Opc, TokLoc, LHSExpr, RHSExpr);
Sebastian Redl43028242009-10-26 15:24:15 +00009211
Richard Trieuf9bd0f52011-09-07 02:02:10 +00009212 return BuildBinOp(S, TokLoc, Opc, LHSExpr, RHSExpr);
Douglas Gregor5287f092009-11-05 00:51:44 +00009213}
9214
John McCall526ab472011-10-25 17:37:35 +00009215/// Build an overloaded binary operator expression in the given scope.
9216static ExprResult BuildOverloadedBinOp(Sema &S, Scope *Sc, SourceLocation OpLoc,
9217 BinaryOperatorKind Opc,
9218 Expr *LHS, Expr *RHS) {
9219 // Find all of the overloaded operators visible from this
9220 // point. We perform both an operator-name lookup from the local
9221 // scope and an argument-dependent lookup based on the types of
9222 // the arguments.
9223 UnresolvedSet<16> Functions;
9224 OverloadedOperatorKind OverOp
9225 = BinaryOperator::getOverloadedOperator(Opc);
9226 if (Sc && OverOp != OO_None)
9227 S.LookupOverloadedOperatorName(OverOp, Sc, LHS->getType(),
9228 RHS->getType(), Functions);
9229
9230 // Build the (potentially-overloaded, potentially-dependent)
9231 // binary operation.
9232 return S.CreateOverloadedBinOp(OpLoc, Opc, Functions, LHS, RHS);
9233}
9234
John McCalldadc5752010-08-24 06:29:42 +00009235ExprResult Sema::BuildBinOp(Scope *S, SourceLocation OpLoc,
John McCalle3027922010-08-25 11:45:40 +00009236 BinaryOperatorKind Opc,
Richard Trieuf9bd0f52011-09-07 02:02:10 +00009237 Expr *LHSExpr, Expr *RHSExpr) {
John McCall9a43e122011-10-28 01:04:34 +00009238 // We want to end up calling one of checkPseudoObjectAssignment
9239 // (if the LHS is a pseudo-object), BuildOverloadedBinOp (if
9240 // both expressions are overloadable or either is type-dependent),
9241 // or CreateBuiltinBinOp (in any other case). We also want to get
9242 // any placeholder types out of the way.
9243
John McCall526ab472011-10-25 17:37:35 +00009244 // Handle pseudo-objects in the LHS.
9245 if (const BuiltinType *pty = LHSExpr->getType()->getAsPlaceholderType()) {
9246 // Assignments with a pseudo-object l-value need special analysis.
9247 if (pty->getKind() == BuiltinType::PseudoObject &&
9248 BinaryOperator::isAssignmentOp(Opc))
9249 return checkPseudoObjectAssignment(S, OpLoc, Opc, LHSExpr, RHSExpr);
9250
9251 // Don't resolve overloads if the other type is overloadable.
9252 if (pty->getKind() == BuiltinType::Overload) {
9253 // We can't actually test that if we still have a placeholder,
9254 // though. Fortunately, none of the exceptions we see in that
John McCall9a43e122011-10-28 01:04:34 +00009255 // code below are valid when the LHS is an overload set. Note
9256 // that an overload set can be dependently-typed, but it never
9257 // instantiates to having an overloadable type.
John McCall526ab472011-10-25 17:37:35 +00009258 ExprResult resolvedRHS = CheckPlaceholderExpr(RHSExpr);
9259 if (resolvedRHS.isInvalid()) return ExprError();
9260 RHSExpr = resolvedRHS.take();
9261
John McCall9a43e122011-10-28 01:04:34 +00009262 if (RHSExpr->isTypeDependent() ||
9263 RHSExpr->getType()->isOverloadableType())
John McCall526ab472011-10-25 17:37:35 +00009264 return BuildOverloadedBinOp(*this, S, OpLoc, Opc, LHSExpr, RHSExpr);
9265 }
9266
9267 ExprResult LHS = CheckPlaceholderExpr(LHSExpr);
9268 if (LHS.isInvalid()) return ExprError();
9269 LHSExpr = LHS.take();
9270 }
9271
9272 // Handle pseudo-objects in the RHS.
9273 if (const BuiltinType *pty = RHSExpr->getType()->getAsPlaceholderType()) {
9274 // An overload in the RHS can potentially be resolved by the type
9275 // being assigned to.
John McCall9a43e122011-10-28 01:04:34 +00009276 if (Opc == BO_Assign && pty->getKind() == BuiltinType::Overload) {
9277 if (LHSExpr->isTypeDependent() || RHSExpr->isTypeDependent())
9278 return BuildOverloadedBinOp(*this, S, OpLoc, Opc, LHSExpr, RHSExpr);
9279
Eli Friedman419b1ff2012-01-17 21:27:43 +00009280 if (LHSExpr->getType()->isOverloadableType())
9281 return BuildOverloadedBinOp(*this, S, OpLoc, Opc, LHSExpr, RHSExpr);
9282
John McCall526ab472011-10-25 17:37:35 +00009283 return CreateBuiltinBinOp(OpLoc, Opc, LHSExpr, RHSExpr);
John McCall9a43e122011-10-28 01:04:34 +00009284 }
John McCall526ab472011-10-25 17:37:35 +00009285
9286 // Don't resolve overloads if the other type is overloadable.
9287 if (pty->getKind() == BuiltinType::Overload &&
9288 LHSExpr->getType()->isOverloadableType())
9289 return BuildOverloadedBinOp(*this, S, OpLoc, Opc, LHSExpr, RHSExpr);
9290
9291 ExprResult resolvedRHS = CheckPlaceholderExpr(RHSExpr);
9292 if (!resolvedRHS.isUsable()) return ExprError();
9293 RHSExpr = resolvedRHS.take();
9294 }
9295
David Blaikiebbafb8a2012-03-11 07:00:24 +00009296 if (getLangOpts().CPlusPlus) {
John McCall9a43e122011-10-28 01:04:34 +00009297 // If either expression is type-dependent, always build an
9298 // overloaded op.
9299 if (LHSExpr->isTypeDependent() || RHSExpr->isTypeDependent())
9300 return BuildOverloadedBinOp(*this, S, OpLoc, Opc, LHSExpr, RHSExpr);
Kovarththanan Rajaratnamba2c6522010-03-13 10:17:05 +00009301
John McCall9a43e122011-10-28 01:04:34 +00009302 // Otherwise, build an overloaded op if either expression has an
9303 // overloadable type.
9304 if (LHSExpr->getType()->isOverloadableType() ||
9305 RHSExpr->getType()->isOverloadableType())
John McCall526ab472011-10-25 17:37:35 +00009306 return BuildOverloadedBinOp(*this, S, OpLoc, Opc, LHSExpr, RHSExpr);
Sebastian Redlb5d49352009-01-19 22:31:54 +00009307 }
Kovarththanan Rajaratnamba2c6522010-03-13 10:17:05 +00009308
Douglas Gregor7d5fc7e2008-11-06 23:29:22 +00009309 // Build a built-in binary operation.
Richard Trieuf9bd0f52011-09-07 02:02:10 +00009310 return CreateBuiltinBinOp(OpLoc, Opc, LHSExpr, RHSExpr);
Steve Naroff218bc2b2007-05-04 21:54:46 +00009311}
9312
John McCalldadc5752010-08-24 06:29:42 +00009313ExprResult Sema::CreateBuiltinUnaryOp(SourceLocation OpLoc,
Argyrios Kyrtzidis7a808c02011-01-05 20:09:36 +00009314 UnaryOperatorKind Opc,
John Wiegley01296292011-04-08 18:41:53 +00009315 Expr *InputExpr) {
9316 ExprResult Input = Owned(InputExpr);
John McCall7decc9e2010-11-18 06:31:45 +00009317 ExprValueKind VK = VK_RValue;
9318 ExprObjectKind OK = OK_Ordinary;
Steve Naroff35d85152007-05-07 00:24:15 +00009319 QualType resultType;
9320 switch (Opc) {
John McCalle3027922010-08-25 11:45:40 +00009321 case UO_PreInc:
9322 case UO_PreDec:
9323 case UO_PostInc:
9324 case UO_PostDec:
John Wiegley01296292011-04-08 18:41:53 +00009325 resultType = CheckIncrementDecrementOperand(*this, Input.get(), VK, OpLoc,
John McCalle3027922010-08-25 11:45:40 +00009326 Opc == UO_PreInc ||
9327 Opc == UO_PostInc,
9328 Opc == UO_PreInc ||
9329 Opc == UO_PreDec);
Steve Naroff35d85152007-05-07 00:24:15 +00009330 break;
John McCalle3027922010-08-25 11:45:40 +00009331 case UO_AddrOf:
Richard Smithaf9de912013-07-11 02:26:56 +00009332 resultType = CheckAddressOfOperand(Input, OpLoc);
Steve Naroff35d85152007-05-07 00:24:15 +00009333 break;
John McCall31996342011-04-07 08:22:57 +00009334 case UO_Deref: {
John Wiegley01296292011-04-08 18:41:53 +00009335 Input = DefaultFunctionArrayLvalueConversion(Input.take());
Eli Friedman34866c72012-08-31 00:14:07 +00009336 if (Input.isInvalid()) return ExprError();
John Wiegley01296292011-04-08 18:41:53 +00009337 resultType = CheckIndirectionOperand(*this, Input.get(), VK, OpLoc);
Steve Naroff35d85152007-05-07 00:24:15 +00009338 break;
John McCall31996342011-04-07 08:22:57 +00009339 }
John McCalle3027922010-08-25 11:45:40 +00009340 case UO_Plus:
9341 case UO_Minus:
John Wiegley01296292011-04-08 18:41:53 +00009342 Input = UsualUnaryConversions(Input.take());
9343 if (Input.isInvalid()) return ExprError();
9344 resultType = Input.get()->getType();
Sebastian Redl8d2ccae2009-02-26 14:39:58 +00009345 if (resultType->isDependentType())
9346 break;
Douglas Gregora3208f92010-06-22 23:41:02 +00009347 if (resultType->isArithmeticType() || // C99 6.5.3.3p1
9348 resultType->isVectorType())
Douglas Gregord08452f2008-11-19 15:42:04 +00009349 break;
David Blaikiebbafb8a2012-03-11 07:00:24 +00009350 else if (getLangOpts().CPlusPlus && // C++ [expr.unary.op]p6-7
Douglas Gregord08452f2008-11-19 15:42:04 +00009351 resultType->isEnumeralType())
9352 break;
David Blaikiebbafb8a2012-03-11 07:00:24 +00009353 else if (getLangOpts().CPlusPlus && // C++ [expr.unary.op]p6
John McCalle3027922010-08-25 11:45:40 +00009354 Opc == UO_Plus &&
Douglas Gregord08452f2008-11-19 15:42:04 +00009355 resultType->isPointerType())
9356 break;
9357
Sebastian Redlc215cfc2009-01-19 00:08:26 +00009358 return ExprError(Diag(OpLoc, diag::err_typecheck_unary_expr)
John Wiegley01296292011-04-08 18:41:53 +00009359 << resultType << Input.get()->getSourceRange());
9360
John McCalle3027922010-08-25 11:45:40 +00009361 case UO_Not: // bitwise complement
John Wiegley01296292011-04-08 18:41:53 +00009362 Input = UsualUnaryConversions(Input.take());
Joey Gouly7d00f002013-02-21 11:49:56 +00009363 if (Input.isInvalid())
9364 return ExprError();
John Wiegley01296292011-04-08 18:41:53 +00009365 resultType = Input.get()->getType();
Sebastian Redl8d2ccae2009-02-26 14:39:58 +00009366 if (resultType->isDependentType())
9367 break;
Chris Lattner0d707612008-07-25 23:52:49 +00009368 // C99 6.5.3.3p1. We allow complex int and float as a GCC extension.
9369 if (resultType->isComplexType() || resultType->isComplexIntegerType())
9370 // C99 does not support '~' for complex conjugation.
Chris Lattner29e812b2008-11-20 06:06:08 +00009371 Diag(OpLoc, diag::ext_integer_complement_complex)
Joey Gouly7d00f002013-02-21 11:49:56 +00009372 << resultType << Input.get()->getSourceRange();
John McCall36226622010-10-12 02:09:17 +00009373 else if (resultType->hasIntegerRepresentation())
9374 break;
Joey Gouly7d00f002013-02-21 11:49:56 +00009375 else if (resultType->isExtVectorType()) {
9376 if (Context.getLangOpts().OpenCL) {
9377 // OpenCL v1.1 s6.3.f: The bitwise operator not (~) does not operate
9378 // on vector float types.
9379 QualType T = resultType->getAs<ExtVectorType>()->getElementType();
9380 if (!T->isIntegerType())
9381 return ExprError(Diag(OpLoc, diag::err_typecheck_unary_expr)
9382 << resultType << Input.get()->getSourceRange());
9383 }
9384 break;
9385 } else {
Sebastian Redlc215cfc2009-01-19 00:08:26 +00009386 return ExprError(Diag(OpLoc, diag::err_typecheck_unary_expr)
Joey Gouly7d00f002013-02-21 11:49:56 +00009387 << resultType << Input.get()->getSourceRange());
John McCall36226622010-10-12 02:09:17 +00009388 }
Steve Naroff35d85152007-05-07 00:24:15 +00009389 break;
John Wiegley01296292011-04-08 18:41:53 +00009390
John McCalle3027922010-08-25 11:45:40 +00009391 case UO_LNot: // logical negation
Steve Naroff71b59a92007-06-04 22:22:31 +00009392 // Unlike +/-/~, integer promotions aren't done here (C99 6.5.3.3p5).
John Wiegley01296292011-04-08 18:41:53 +00009393 Input = DefaultFunctionArrayLvalueConversion(Input.take());
9394 if (Input.isInvalid()) return ExprError();
9395 resultType = Input.get()->getType();
Anton Korobeynikovf0c267e2011-10-14 23:23:15 +00009396
9397 // Though we still have to promote half FP to float...
Joey Goulydd7f4562013-01-23 11:56:20 +00009398 if (resultType->isHalfType() && !Context.getLangOpts().NativeHalfType) {
Anton Korobeynikovf0c267e2011-10-14 23:23:15 +00009399 Input = ImpCastExprToType(Input.take(), Context.FloatTy, CK_FloatingCast).take();
9400 resultType = Context.FloatTy;
9401 }
9402
Sebastian Redl8d2ccae2009-02-26 14:39:58 +00009403 if (resultType->isDependentType())
9404 break;
Abramo Bagnara7ccce982011-04-07 09:26:19 +00009405 if (resultType->isScalarType()) {
9406 // C99 6.5.3.3p1: ok, fallthrough;
David Blaikiebbafb8a2012-03-11 07:00:24 +00009407 if (Context.getLangOpts().CPlusPlus) {
Abramo Bagnara7ccce982011-04-07 09:26:19 +00009408 // C++03 [expr.unary.op]p8, C++0x [expr.unary.op]p9:
9409 // operand contextually converted to bool.
John Wiegley01296292011-04-08 18:41:53 +00009410 Input = ImpCastExprToType(Input.take(), Context.BoolTy,
9411 ScalarTypeToBooleanCastKind(resultType));
Joey Gouly7d00f002013-02-21 11:49:56 +00009412 } else if (Context.getLangOpts().OpenCL &&
9413 Context.getLangOpts().OpenCLVersion < 120) {
9414 // OpenCL v1.1 6.3.h: The logical operator not (!) does not
9415 // operate on scalar float types.
9416 if (!resultType->isIntegerType())
9417 return ExprError(Diag(OpLoc, diag::err_typecheck_unary_expr)
9418 << resultType << Input.get()->getSourceRange());
Abramo Bagnara7ccce982011-04-07 09:26:19 +00009419 }
Tanya Lattner3dd33b22012-01-19 01:16:16 +00009420 } else if (resultType->isExtVectorType()) {
Joey Gouly7d00f002013-02-21 11:49:56 +00009421 if (Context.getLangOpts().OpenCL &&
9422 Context.getLangOpts().OpenCLVersion < 120) {
9423 // OpenCL v1.1 6.3.h: The logical operator not (!) does not
9424 // operate on vector float types.
9425 QualType T = resultType->getAs<ExtVectorType>()->getElementType();
9426 if (!T->isIntegerType())
9427 return ExprError(Diag(OpLoc, diag::err_typecheck_unary_expr)
9428 << resultType << Input.get()->getSourceRange());
9429 }
Tanya Lattner20248222012-01-16 21:02:28 +00009430 // Vector logical not returns the signed variant of the operand type.
9431 resultType = GetSignedVectorType(resultType);
9432 break;
John McCall36226622010-10-12 02:09:17 +00009433 } else {
Sebastian Redlc215cfc2009-01-19 00:08:26 +00009434 return ExprError(Diag(OpLoc, diag::err_typecheck_unary_expr)
John Wiegley01296292011-04-08 18:41:53 +00009435 << resultType << Input.get()->getSourceRange());
John McCall36226622010-10-12 02:09:17 +00009436 }
Douglas Gregordb8c6fd2010-09-20 17:13:33 +00009437
Chris Lattnerbe31ed82007-06-02 19:11:33 +00009438 // LNot always has type int. C99 6.5.3.3p5.
Sebastian Redlc215cfc2009-01-19 00:08:26 +00009439 // In C++, it's bool. C++ 5.3.1p8
Argyrios Kyrtzidis1bdd6882011-02-18 20:55:15 +00009440 resultType = Context.getLogicalOperationType();
Steve Naroff35d85152007-05-07 00:24:15 +00009441 break;
John McCalle3027922010-08-25 11:45:40 +00009442 case UO_Real:
9443 case UO_Imag:
John McCall4bc41ae2010-11-18 19:01:18 +00009444 resultType = CheckRealImagOperand(*this, Input, OpLoc, Opc == UO_Real);
Richard Smith0b6b8e42012-02-18 20:53:32 +00009445 // _Real maps ordinary l-values into ordinary l-values. _Imag maps ordinary
9446 // complex l-values to ordinary l-values and all other values to r-values.
John Wiegley01296292011-04-08 18:41:53 +00009447 if (Input.isInvalid()) return ExprError();
Richard Smith0b6b8e42012-02-18 20:53:32 +00009448 if (Opc == UO_Real || Input.get()->getType()->isAnyComplexType()) {
9449 if (Input.get()->getValueKind() != VK_RValue &&
9450 Input.get()->getObjectKind() == OK_Ordinary)
9451 VK = Input.get()->getValueKind();
David Blaikiebbafb8a2012-03-11 07:00:24 +00009452 } else if (!getLangOpts().CPlusPlus) {
Richard Smith0b6b8e42012-02-18 20:53:32 +00009453 // In C, a volatile scalar is read by __imag. In C++, it is not.
9454 Input = DefaultLvalueConversion(Input.take());
9455 }
Chris Lattner30b5dd02007-08-24 21:16:53 +00009456 break;
John McCalle3027922010-08-25 11:45:40 +00009457 case UO_Extension:
John Wiegley01296292011-04-08 18:41:53 +00009458 resultType = Input.get()->getType();
9459 VK = Input.get()->getValueKind();
9460 OK = Input.get()->getObjectKind();
Steve Naroff043d45d2007-05-15 02:32:35 +00009461 break;
Steve Naroff35d85152007-05-07 00:24:15 +00009462 }
John Wiegley01296292011-04-08 18:41:53 +00009463 if (resultType.isNull() || Input.isInvalid())
Sebastian Redlc215cfc2009-01-19 00:08:26 +00009464 return ExprError();
Douglas Gregor084d8552009-03-13 23:49:33 +00009465
Kaelyn Uhrain2e7aa5a2011-08-05 23:18:04 +00009466 // Check for array bounds violations in the operand of the UnaryOperator,
9467 // except for the '*' and '&' operators that have to be handled specially
9468 // by CheckArrayAccess (as there are special cases like &array[arraysize]
9469 // that are explicitly defined as valid by the standard).
9470 if (Opc != UO_AddrOf && Opc != UO_Deref)
9471 CheckArrayAccess(Input.get());
9472
John Wiegley01296292011-04-08 18:41:53 +00009473 return Owned(new (Context) UnaryOperator(Input.take(), Opc, resultType,
John McCall7decc9e2010-11-18 06:31:45 +00009474 VK, OK, OpLoc));
Steve Naroff35d85152007-05-07 00:24:15 +00009475}
Chris Lattnereefa10e2007-05-28 06:56:27 +00009476
Douglas Gregor72341032011-12-14 21:23:13 +00009477/// \brief Determine whether the given expression is a qualified member
9478/// access expression, of a form that could be turned into a pointer to member
9479/// with the address-of operator.
9480static bool isQualifiedMemberAccess(Expr *E) {
9481 if (DeclRefExpr *DRE = dyn_cast<DeclRefExpr>(E)) {
9482 if (!DRE->getQualifier())
9483 return false;
9484
9485 ValueDecl *VD = DRE->getDecl();
9486 if (!VD->isCXXClassMember())
9487 return false;
9488
9489 if (isa<FieldDecl>(VD) || isa<IndirectFieldDecl>(VD))
9490 return true;
9491 if (CXXMethodDecl *Method = dyn_cast<CXXMethodDecl>(VD))
9492 return Method->isInstance();
9493
9494 return false;
9495 }
9496
9497 if (UnresolvedLookupExpr *ULE = dyn_cast<UnresolvedLookupExpr>(E)) {
9498 if (!ULE->getQualifier())
9499 return false;
9500
9501 for (UnresolvedLookupExpr::decls_iterator D = ULE->decls_begin(),
9502 DEnd = ULE->decls_end();
9503 D != DEnd; ++D) {
9504 if (CXXMethodDecl *Method = dyn_cast<CXXMethodDecl>(*D)) {
9505 if (Method->isInstance())
9506 return true;
9507 } else {
9508 // Overload set does not contain methods.
9509 break;
9510 }
9511 }
9512
9513 return false;
9514 }
9515
9516 return false;
9517}
9518
John McCalldadc5752010-08-24 06:29:42 +00009519ExprResult Sema::BuildUnaryOp(Scope *S, SourceLocation OpLoc,
Richard Trieuba63ce62011-09-09 01:45:06 +00009520 UnaryOperatorKind Opc, Expr *Input) {
John McCall526ab472011-10-25 17:37:35 +00009521 // First things first: handle placeholders so that the
9522 // overloaded-operator check considers the right type.
9523 if (const BuiltinType *pty = Input->getType()->getAsPlaceholderType()) {
9524 // Increment and decrement of pseudo-object references.
9525 if (pty->getKind() == BuiltinType::PseudoObject &&
9526 UnaryOperator::isIncrementDecrementOp(Opc))
9527 return checkPseudoObjectIncDec(S, OpLoc, Opc, Input);
9528
9529 // extension is always a builtin operator.
9530 if (Opc == UO_Extension)
9531 return CreateBuiltinUnaryOp(OpLoc, Opc, Input);
9532
9533 // & gets special logic for several kinds of placeholder.
9534 // The builtin code knows what to do.
9535 if (Opc == UO_AddrOf &&
9536 (pty->getKind() == BuiltinType::Overload ||
9537 pty->getKind() == BuiltinType::UnknownAny ||
9538 pty->getKind() == BuiltinType::BoundMember))
9539 return CreateBuiltinUnaryOp(OpLoc, Opc, Input);
9540
9541 // Anything else needs to be handled now.
9542 ExprResult Result = CheckPlaceholderExpr(Input);
9543 if (Result.isInvalid()) return ExprError();
9544 Input = Result.take();
9545 }
9546
David Blaikiebbafb8a2012-03-11 07:00:24 +00009547 if (getLangOpts().CPlusPlus && Input->getType()->isOverloadableType() &&
Douglas Gregor72341032011-12-14 21:23:13 +00009548 UnaryOperator::getOverloadedOperator(Opc) != OO_None &&
9549 !(Opc == UO_AddrOf && isQualifiedMemberAccess(Input))) {
Douglas Gregor084d8552009-03-13 23:49:33 +00009550 // Find all of the overloaded operators visible from this
9551 // point. We perform both an operator-name lookup from the local
9552 // scope and an argument-dependent lookup based on the types of
9553 // the arguments.
John McCall4c4c1df2010-01-26 03:27:55 +00009554 UnresolvedSet<16> Functions;
Douglas Gregor084d8552009-03-13 23:49:33 +00009555 OverloadedOperatorKind OverOp = UnaryOperator::getOverloadedOperator(Opc);
John McCall4c4c1df2010-01-26 03:27:55 +00009556 if (S && OverOp != OO_None)
9557 LookupOverloadedOperatorName(OverOp, S, Input->getType(), QualType(),
9558 Functions);
Kovarththanan Rajaratnamba2c6522010-03-13 10:17:05 +00009559
John McCallb268a282010-08-23 23:25:46 +00009560 return CreateOverloadedUnaryOp(OpLoc, Opc, Functions, Input);
Douglas Gregor084d8552009-03-13 23:49:33 +00009561 }
Kovarththanan Rajaratnamba2c6522010-03-13 10:17:05 +00009562
John McCallb268a282010-08-23 23:25:46 +00009563 return CreateBuiltinUnaryOp(OpLoc, Opc, Input);
Douglas Gregor084d8552009-03-13 23:49:33 +00009564}
9565
Douglas Gregor5287f092009-11-05 00:51:44 +00009566// Unary Operators. 'Tok' is the token for the operator.
John McCalldadc5752010-08-24 06:29:42 +00009567ExprResult Sema::ActOnUnaryOp(Scope *S, SourceLocation OpLoc,
John McCall424cec92011-01-19 06:33:43 +00009568 tok::TokenKind Op, Expr *Input) {
John McCallb268a282010-08-23 23:25:46 +00009569 return BuildUnaryOp(S, OpLoc, ConvertTokenKindToUnaryOpcode(Op), Input);
Douglas Gregor5287f092009-11-05 00:51:44 +00009570}
9571
Steve Naroff66356bd2007-09-16 14:56:35 +00009572/// ActOnAddrLabel - Parse the GNU address of label extension: "&&foo".
Chris Lattnerc8e630e2011-02-17 07:39:24 +00009573ExprResult Sema::ActOnAddrLabel(SourceLocation OpLoc, SourceLocation LabLoc,
Chris Lattnercab02a62011-02-17 20:34:02 +00009574 LabelDecl *TheDecl) {
Chris Lattnerc8e630e2011-02-17 07:39:24 +00009575 TheDecl->setUsed();
Chris Lattnereefa10e2007-05-28 06:56:27 +00009576 // Create the AST node. The address of a label always has type 'void*'.
Chris Lattnerc8e630e2011-02-17 07:39:24 +00009577 return Owned(new (Context) AddrLabelExpr(OpLoc, LabLoc, TheDecl,
Sebastian Redl6d4256c2009-03-15 17:47:39 +00009578 Context.getPointerType(Context.VoidTy)));
Chris Lattnereefa10e2007-05-28 06:56:27 +00009579}
9580
John McCall31168b02011-06-15 23:02:42 +00009581/// Given the last statement in a statement-expression, check whether
9582/// the result is a producing expression (like a call to an
9583/// ns_returns_retained function) and, if so, rebuild it to hoist the
9584/// release out of the full-expression. Otherwise, return null.
9585/// Cannot fail.
Richard Trieuba63ce62011-09-09 01:45:06 +00009586static Expr *maybeRebuildARCConsumingStmt(Stmt *Statement) {
John McCall31168b02011-06-15 23:02:42 +00009587 // Should always be wrapped with one of these.
Richard Trieuba63ce62011-09-09 01:45:06 +00009588 ExprWithCleanups *cleanups = dyn_cast<ExprWithCleanups>(Statement);
John McCall31168b02011-06-15 23:02:42 +00009589 if (!cleanups) return 0;
9590
9591 ImplicitCastExpr *cast = dyn_cast<ImplicitCastExpr>(cleanups->getSubExpr());
John McCall2d637d22011-09-10 06:18:15 +00009592 if (!cast || cast->getCastKind() != CK_ARCConsumeObject)
John McCall31168b02011-06-15 23:02:42 +00009593 return 0;
9594
9595 // Splice out the cast. This shouldn't modify any interesting
9596 // features of the statement.
9597 Expr *producer = cast->getSubExpr();
9598 assert(producer->getType() == cast->getType());
9599 assert(producer->getValueKind() == cast->getValueKind());
9600 cleanups->setSubExpr(producer);
9601 return cleanups;
9602}
9603
John McCall3abee492012-04-04 01:27:53 +00009604void Sema::ActOnStartStmtExpr() {
9605 PushExpressionEvaluationContext(ExprEvalContexts.back().Context);
9606}
9607
9608void Sema::ActOnStmtExprError() {
John McCalled7b2782012-04-06 18:20:53 +00009609 // Note that function is also called by TreeTransform when leaving a
9610 // StmtExpr scope without rebuilding anything.
9611
John McCall3abee492012-04-04 01:27:53 +00009612 DiscardCleanupsInEvaluationContext();
9613 PopExpressionEvaluationContext();
9614}
9615
John McCalldadc5752010-08-24 06:29:42 +00009616ExprResult
John McCallb268a282010-08-23 23:25:46 +00009617Sema::ActOnStmtExpr(SourceLocation LPLoc, Stmt *SubStmt,
Sebastian Redl6d4256c2009-03-15 17:47:39 +00009618 SourceLocation RPLoc) { // "({..})"
Chris Lattner366727f2007-07-24 16:58:17 +00009619 assert(SubStmt && isa<CompoundStmt>(SubStmt) && "Invalid action invocation!");
9620 CompoundStmt *Compound = cast<CompoundStmt>(SubStmt);
9621
John McCall3abee492012-04-04 01:27:53 +00009622 if (hasAnyUnrecoverableErrorsInThisFunction())
9623 DiscardCleanupsInEvaluationContext();
9624 assert(!ExprNeedsCleanups && "cleanups within StmtExpr not correctly bound!");
9625 PopExpressionEvaluationContext();
9626
Douglas Gregor6cf3f3c2010-03-10 04:54:39 +00009627 bool isFileScope
9628 = (getCurFunctionOrMethodDecl() == 0) && (getCurBlock() == 0);
Chris Lattnera69b0762009-04-25 19:11:05 +00009629 if (isFileScope)
Sebastian Redl6d4256c2009-03-15 17:47:39 +00009630 return ExprError(Diag(LPLoc, diag::err_stmtexpr_file_scope));
Eli Friedman52cc0162009-01-24 23:09:00 +00009631
Chris Lattner366727f2007-07-24 16:58:17 +00009632 // FIXME: there are a variety of strange constraints to enforce here, for
9633 // example, it is not possible to goto into a stmt expression apparently.
9634 // More semantic analysis is needed.
Mike Stump4e1f26a2009-02-19 03:04:26 +00009635
Chris Lattner366727f2007-07-24 16:58:17 +00009636 // If there are sub stmts in the compound stmt, take the type of the last one
9637 // as the type of the stmtexpr.
9638 QualType Ty = Context.VoidTy;
Fariborz Jahanian56143ae2010-10-25 23:27:26 +00009639 bool StmtExprMayBindToTemp = false;
Chris Lattner944d3062008-07-26 19:51:01 +00009640 if (!Compound->body_empty()) {
9641 Stmt *LastStmt = Compound->body_back();
Fariborz Jahanian56143ae2010-10-25 23:27:26 +00009642 LabelStmt *LastLabelStmt = 0;
Chris Lattner944d3062008-07-26 19:51:01 +00009643 // If LastStmt is a label, skip down through into the body.
Fariborz Jahanian56143ae2010-10-25 23:27:26 +00009644 while (LabelStmt *Label = dyn_cast<LabelStmt>(LastStmt)) {
9645 LastLabelStmt = Label;
Chris Lattner944d3062008-07-26 19:51:01 +00009646 LastStmt = Label->getSubStmt();
Fariborz Jahanian56143ae2010-10-25 23:27:26 +00009647 }
John McCall31168b02011-06-15 23:02:42 +00009648
John Wiegley01296292011-04-08 18:41:53 +00009649 if (Expr *LastE = dyn_cast<Expr>(LastStmt)) {
John McCall34376a62010-12-04 03:47:34 +00009650 // Do function/array conversion on the last expression, but not
9651 // lvalue-to-rvalue. However, initialize an unqualified type.
John Wiegley01296292011-04-08 18:41:53 +00009652 ExprResult LastExpr = DefaultFunctionArrayConversion(LastE);
9653 if (LastExpr.isInvalid())
9654 return ExprError();
9655 Ty = LastExpr.get()->getType().getUnqualifiedType();
John McCall34376a62010-12-04 03:47:34 +00009656
John Wiegley01296292011-04-08 18:41:53 +00009657 if (!Ty->isDependentType() && !LastExpr.get()->isTypeDependent()) {
John McCall31168b02011-06-15 23:02:42 +00009658 // In ARC, if the final expression ends in a consume, splice
9659 // the consume out and bind it later. In the alternate case
9660 // (when dealing with a retainable type), the result
9661 // initialization will create a produce. In both cases the
9662 // result will be +1, and we'll need to balance that out with
9663 // a bind.
9664 if (Expr *rebuiltLastStmt
9665 = maybeRebuildARCConsumingStmt(LastExpr.get())) {
9666 LastExpr = rebuiltLastStmt;
9667 } else {
9668 LastExpr = PerformCopyInitialization(
Fariborz Jahanian56143ae2010-10-25 23:27:26 +00009669 InitializedEntity::InitializeResult(LPLoc,
9670 Ty,
9671 false),
9672 SourceLocation(),
John McCall31168b02011-06-15 23:02:42 +00009673 LastExpr);
9674 }
9675
John Wiegley01296292011-04-08 18:41:53 +00009676 if (LastExpr.isInvalid())
Fariborz Jahanian56143ae2010-10-25 23:27:26 +00009677 return ExprError();
John Wiegley01296292011-04-08 18:41:53 +00009678 if (LastExpr.get() != 0) {
Fariborz Jahanian56143ae2010-10-25 23:27:26 +00009679 if (!LastLabelStmt)
John Wiegley01296292011-04-08 18:41:53 +00009680 Compound->setLastStmt(LastExpr.take());
Fariborz Jahanian56143ae2010-10-25 23:27:26 +00009681 else
John Wiegley01296292011-04-08 18:41:53 +00009682 LastLabelStmt->setSubStmt(LastExpr.take());
Fariborz Jahanian56143ae2010-10-25 23:27:26 +00009683 StmtExprMayBindToTemp = true;
9684 }
9685 }
9686 }
Chris Lattner944d3062008-07-26 19:51:01 +00009687 }
Mike Stump4e1f26a2009-02-19 03:04:26 +00009688
Eli Friedmanba961a92009-03-23 00:24:07 +00009689 // FIXME: Check that expression type is complete/non-abstract; statement
9690 // expressions are not lvalues.
Fariborz Jahanian56143ae2010-10-25 23:27:26 +00009691 Expr *ResStmtExpr = new (Context) StmtExpr(Compound, Ty, LPLoc, RPLoc);
9692 if (StmtExprMayBindToTemp)
9693 return MaybeBindToTemporary(ResStmtExpr);
9694 return Owned(ResStmtExpr);
Chris Lattner366727f2007-07-24 16:58:17 +00009695}
Steve Naroff78864672007-08-01 22:05:33 +00009696
John McCalldadc5752010-08-24 06:29:42 +00009697ExprResult Sema::BuildBuiltinOffsetOf(SourceLocation BuiltinLoc,
John McCall36226622010-10-12 02:09:17 +00009698 TypeSourceInfo *TInfo,
9699 OffsetOfComponent *CompPtr,
9700 unsigned NumComponents,
9701 SourceLocation RParenLoc) {
Douglas Gregor882211c2010-04-28 22:16:22 +00009702 QualType ArgTy = TInfo->getType();
Sebastian Redl8d2ccae2009-02-26 14:39:58 +00009703 bool Dependent = ArgTy->isDependentType();
Abramo Bagnara1108e7b2010-05-20 10:00:11 +00009704 SourceRange TypeRange = TInfo->getTypeLoc().getLocalSourceRange();
Douglas Gregor882211c2010-04-28 22:16:22 +00009705
Chris Lattnerf17bd422007-08-30 17:45:32 +00009706 // We must have at least one component that refers to the type, and the first
9707 // one is known to be a field designator. Verify that the ArgTy represents
9708 // a struct/union/class.
Sebastian Redl8d2ccae2009-02-26 14:39:58 +00009709 if (!Dependent && !ArgTy->isRecordType())
Douglas Gregor882211c2010-04-28 22:16:22 +00009710 return ExprError(Diag(BuiltinLoc, diag::err_offsetof_record_type)
9711 << ArgTy << TypeRange);
9712
9713 // Type must be complete per C99 7.17p3 because a declaring a variable
9714 // with an incomplete type would be ill-formed.
9715 if (!Dependent
9716 && RequireCompleteType(BuiltinLoc, ArgTy,
Douglas Gregor7bfb2d02012-05-04 16:32:21 +00009717 diag::err_offsetof_incomplete_type, TypeRange))
Douglas Gregor882211c2010-04-28 22:16:22 +00009718 return ExprError();
9719
Chris Lattner78502cf2007-08-31 21:49:13 +00009720 // offsetof with non-identifier designators (e.g. "offsetof(x, a.b[c])") are a
9721 // GCC extension, diagnose them.
Eli Friedman988a16b2009-02-27 06:44:11 +00009722 // FIXME: This diagnostic isn't actually visible because the location is in
9723 // a system header!
Chris Lattner78502cf2007-08-31 21:49:13 +00009724 if (NumComponents != 1)
Chris Lattnerf490e152008-11-19 05:27:50 +00009725 Diag(BuiltinLoc, diag::ext_offsetof_extended_field_designator)
9726 << SourceRange(CompPtr[1].LocStart, CompPtr[NumComponents-1].LocEnd);
Douglas Gregor882211c2010-04-28 22:16:22 +00009727
9728 bool DidWarnAboutNonPOD = false;
9729 QualType CurrentType = ArgTy;
9730 typedef OffsetOfExpr::OffsetOfNode OffsetOfNode;
Chris Lattner0e62c1c2011-07-23 10:55:15 +00009731 SmallVector<OffsetOfNode, 4> Comps;
9732 SmallVector<Expr*, 4> Exprs;
Douglas Gregor882211c2010-04-28 22:16:22 +00009733 for (unsigned i = 0; i != NumComponents; ++i) {
9734 const OffsetOfComponent &OC = CompPtr[i];
9735 if (OC.isBrackets) {
9736 // Offset of an array sub-field. TODO: Should we allow vector elements?
9737 if (!CurrentType->isDependentType()) {
9738 const ArrayType *AT = Context.getAsArrayType(CurrentType);
9739 if(!AT)
9740 return ExprError(Diag(OC.LocEnd, diag::err_offsetof_array_type)
9741 << CurrentType);
9742 CurrentType = AT->getElementType();
9743 } else
9744 CurrentType = Context.DependentTy;
9745
Richard Smith9fcc5c32011-10-17 23:29:39 +00009746 ExprResult IdxRval = DefaultLvalueConversion(static_cast<Expr*>(OC.U.E));
9747 if (IdxRval.isInvalid())
9748 return ExprError();
9749 Expr *Idx = IdxRval.take();
9750
Douglas Gregor882211c2010-04-28 22:16:22 +00009751 // The expression must be an integral expression.
9752 // FIXME: An integral constant expression?
Douglas Gregor882211c2010-04-28 22:16:22 +00009753 if (!Idx->isTypeDependent() && !Idx->isValueDependent() &&
9754 !Idx->getType()->isIntegerType())
9755 return ExprError(Diag(Idx->getLocStart(),
9756 diag::err_typecheck_subscript_not_integer)
9757 << Idx->getSourceRange());
Richard Smitheda612882011-10-17 05:48:07 +00009758
Douglas Gregor882211c2010-04-28 22:16:22 +00009759 // Record this array index.
9760 Comps.push_back(OffsetOfNode(OC.LocStart, Exprs.size(), OC.LocEnd));
Richard Smith9fcc5c32011-10-17 23:29:39 +00009761 Exprs.push_back(Idx);
Douglas Gregor882211c2010-04-28 22:16:22 +00009762 continue;
9763 }
9764
9765 // Offset of a field.
9766 if (CurrentType->isDependentType()) {
9767 // We have the offset of a field, but we can't look into the dependent
9768 // type. Just record the identifier of the field.
9769 Comps.push_back(OffsetOfNode(OC.LocStart, OC.U.IdentInfo, OC.LocEnd));
9770 CurrentType = Context.DependentTy;
9771 continue;
9772 }
9773
9774 // We need to have a complete type to look into.
9775 if (RequireCompleteType(OC.LocStart, CurrentType,
9776 diag::err_offsetof_incomplete_type))
9777 return ExprError();
9778
9779 // Look for the designated field.
9780 const RecordType *RC = CurrentType->getAs<RecordType>();
9781 if (!RC)
9782 return ExprError(Diag(OC.LocEnd, diag::err_offsetof_record_type)
9783 << CurrentType);
9784 RecordDecl *RD = RC->getDecl();
9785
9786 // C++ [lib.support.types]p5:
9787 // The macro offsetof accepts a restricted set of type arguments in this
9788 // International Standard. type shall be a POD structure or a POD union
9789 // (clause 9).
Benjamin Kramer9e7876b2012-04-28 11:14:51 +00009790 // C++11 [support.types]p4:
9791 // If type is not a standard-layout class (Clause 9), the results are
9792 // undefined.
Douglas Gregor882211c2010-04-28 22:16:22 +00009793 if (CXXRecordDecl *CRD = dyn_cast<CXXRecordDecl>(RD)) {
Richard Smith2bf7fdb2013-01-02 11:42:31 +00009794 bool IsSafe = LangOpts.CPlusPlus11? CRD->isStandardLayout() : CRD->isPOD();
Benjamin Kramer9e7876b2012-04-28 11:14:51 +00009795 unsigned DiagID =
Richard Smith2bf7fdb2013-01-02 11:42:31 +00009796 LangOpts.CPlusPlus11? diag::warn_offsetof_non_standardlayout_type
Benjamin Kramer9e7876b2012-04-28 11:14:51 +00009797 : diag::warn_offsetof_non_pod_type;
9798
9799 if (!IsSafe && !DidWarnAboutNonPOD &&
Ted Kremenek55ae3192011-02-23 01:51:43 +00009800 DiagRuntimeBehavior(BuiltinLoc, 0,
Benjamin Kramer9e7876b2012-04-28 11:14:51 +00009801 PDiag(DiagID)
Douglas Gregor882211c2010-04-28 22:16:22 +00009802 << SourceRange(CompPtr[0].LocStart, OC.LocEnd)
9803 << CurrentType))
9804 DidWarnAboutNonPOD = true;
9805 }
9806
9807 // Look for the field.
9808 LookupResult R(*this, OC.U.IdentInfo, OC.LocStart, LookupMemberName);
9809 LookupQualifiedName(R, RD);
9810 FieldDecl *MemberDecl = R.getAsSingle<FieldDecl>();
Francois Pichet783dd6e2010-11-21 06:08:52 +00009811 IndirectFieldDecl *IndirectMemberDecl = 0;
9812 if (!MemberDecl) {
Benjamin Kramer39593702010-11-21 14:11:41 +00009813 if ((IndirectMemberDecl = R.getAsSingle<IndirectFieldDecl>()))
Francois Pichet783dd6e2010-11-21 06:08:52 +00009814 MemberDecl = IndirectMemberDecl->getAnonField();
9815 }
9816
Douglas Gregor882211c2010-04-28 22:16:22 +00009817 if (!MemberDecl)
9818 return ExprError(Diag(BuiltinLoc, diag::err_no_member)
9819 << OC.U.IdentInfo << RD << SourceRange(OC.LocStart,
9820 OC.LocEnd));
9821
Douglas Gregor10982ea2010-04-28 22:36:06 +00009822 // C99 7.17p3:
9823 // (If the specified member is a bit-field, the behavior is undefined.)
9824 //
9825 // We diagnose this as an error.
Richard Smithcaf33902011-10-10 18:28:20 +00009826 if (MemberDecl->isBitField()) {
Douglas Gregor10982ea2010-04-28 22:36:06 +00009827 Diag(OC.LocEnd, diag::err_offsetof_bitfield)
9828 << MemberDecl->getDeclName()
9829 << SourceRange(BuiltinLoc, RParenLoc);
9830 Diag(MemberDecl->getLocation(), diag::note_bitfield_decl);
9831 return ExprError();
9832 }
Eli Friedman74ef7cf2010-08-05 10:11:36 +00009833
9834 RecordDecl *Parent = MemberDecl->getParent();
Francois Pichet783dd6e2010-11-21 06:08:52 +00009835 if (IndirectMemberDecl)
9836 Parent = cast<RecordDecl>(IndirectMemberDecl->getDeclContext());
Eli Friedman74ef7cf2010-08-05 10:11:36 +00009837
Douglas Gregord1702062010-04-29 00:18:15 +00009838 // If the member was found in a base class, introduce OffsetOfNodes for
9839 // the base class indirections.
9840 CXXBasePaths Paths(/*FindAmbiguities=*/true, /*RecordPaths=*/true,
9841 /*DetectVirtual=*/false);
Eli Friedman74ef7cf2010-08-05 10:11:36 +00009842 if (IsDerivedFrom(CurrentType, Context.getTypeDeclType(Parent), Paths)) {
Douglas Gregord1702062010-04-29 00:18:15 +00009843 CXXBasePath &Path = Paths.front();
9844 for (CXXBasePath::iterator B = Path.begin(), BEnd = Path.end();
9845 B != BEnd; ++B)
9846 Comps.push_back(OffsetOfNode(B->Base));
9847 }
Eli Friedman74ef7cf2010-08-05 10:11:36 +00009848
Francois Pichet783dd6e2010-11-21 06:08:52 +00009849 if (IndirectMemberDecl) {
9850 for (IndirectFieldDecl::chain_iterator FI =
9851 IndirectMemberDecl->chain_begin(),
9852 FEnd = IndirectMemberDecl->chain_end(); FI != FEnd; FI++) {
9853 assert(isa<FieldDecl>(*FI));
9854 Comps.push_back(OffsetOfNode(OC.LocStart,
9855 cast<FieldDecl>(*FI), OC.LocEnd));
9856 }
9857 } else
Douglas Gregor882211c2010-04-28 22:16:22 +00009858 Comps.push_back(OffsetOfNode(OC.LocStart, MemberDecl, OC.LocEnd));
Francois Pichet783dd6e2010-11-21 06:08:52 +00009859
Douglas Gregor882211c2010-04-28 22:16:22 +00009860 CurrentType = MemberDecl->getType().getNonReferenceType();
9861 }
9862
9863 return Owned(OffsetOfExpr::Create(Context, Context.getSizeType(), BuiltinLoc,
Benjamin Kramerc215e762012-08-24 11:54:20 +00009864 TInfo, Comps, Exprs, RParenLoc));
Douglas Gregor882211c2010-04-28 22:16:22 +00009865}
Mike Stump4e1f26a2009-02-19 03:04:26 +00009866
John McCalldadc5752010-08-24 06:29:42 +00009867ExprResult Sema::ActOnBuiltinOffsetOf(Scope *S,
John McCall36226622010-10-12 02:09:17 +00009868 SourceLocation BuiltinLoc,
9869 SourceLocation TypeLoc,
Richard Trieuba63ce62011-09-09 01:45:06 +00009870 ParsedType ParsedArgTy,
John McCall36226622010-10-12 02:09:17 +00009871 OffsetOfComponent *CompPtr,
9872 unsigned NumComponents,
Richard Trieuba63ce62011-09-09 01:45:06 +00009873 SourceLocation RParenLoc) {
John McCall36226622010-10-12 02:09:17 +00009874
Douglas Gregor882211c2010-04-28 22:16:22 +00009875 TypeSourceInfo *ArgTInfo;
Richard Trieuba63ce62011-09-09 01:45:06 +00009876 QualType ArgTy = GetTypeFromParser(ParsedArgTy, &ArgTInfo);
Douglas Gregor882211c2010-04-28 22:16:22 +00009877 if (ArgTy.isNull())
9878 return ExprError();
9879
Eli Friedman06dcfd92010-08-05 10:15:45 +00009880 if (!ArgTInfo)
9881 ArgTInfo = Context.getTrivialTypeSourceInfo(ArgTy, TypeLoc);
9882
9883 return BuildBuiltinOffsetOf(BuiltinLoc, ArgTInfo, CompPtr, NumComponents,
Richard Trieuba63ce62011-09-09 01:45:06 +00009884 RParenLoc);
Chris Lattnerf17bd422007-08-30 17:45:32 +00009885}
9886
9887
John McCalldadc5752010-08-24 06:29:42 +00009888ExprResult Sema::ActOnChooseExpr(SourceLocation BuiltinLoc,
John McCall36226622010-10-12 02:09:17 +00009889 Expr *CondExpr,
9890 Expr *LHSExpr, Expr *RHSExpr,
9891 SourceLocation RPLoc) {
Steve Naroff9efdabc2007-08-03 21:21:27 +00009892 assert((CondExpr && LHSExpr && RHSExpr) && "Missing type argument(s)");
9893
John McCall7decc9e2010-11-18 06:31:45 +00009894 ExprValueKind VK = VK_RValue;
9895 ExprObjectKind OK = OK_Ordinary;
Sebastian Redl8d2ccae2009-02-26 14:39:58 +00009896 QualType resType;
Douglas Gregor56751b52009-09-25 04:25:58 +00009897 bool ValueDependent = false;
Eli Friedman75807f22013-07-20 00:40:58 +00009898 bool CondIsTrue = false;
Douglas Gregor0df91122009-05-19 22:43:30 +00009899 if (CondExpr->isTypeDependent() || CondExpr->isValueDependent()) {
Sebastian Redl8d2ccae2009-02-26 14:39:58 +00009900 resType = Context.DependentTy;
Douglas Gregor56751b52009-09-25 04:25:58 +00009901 ValueDependent = true;
Sebastian Redl8d2ccae2009-02-26 14:39:58 +00009902 } else {
9903 // The conditional expression is required to be a constant expression.
9904 llvm::APSInt condEval(32);
Douglas Gregore2b37442012-05-04 22:38:52 +00009905 ExprResult CondICE
9906 = VerifyIntegerConstantExpression(CondExpr, &condEval,
9907 diag::err_typecheck_choose_expr_requires_constant, false);
Richard Smithf4c51d92012-02-04 09:53:13 +00009908 if (CondICE.isInvalid())
9909 return ExprError();
9910 CondExpr = CondICE.take();
Eli Friedman75807f22013-07-20 00:40:58 +00009911 CondIsTrue = condEval.getZExtValue();
Steve Naroff9efdabc2007-08-03 21:21:27 +00009912
Sebastian Redl8d2ccae2009-02-26 14:39:58 +00009913 // If the condition is > zero, then the AST type is the same as the LSHExpr.
Eli Friedman75807f22013-07-20 00:40:58 +00009914 Expr *ActiveExpr = CondIsTrue ? LHSExpr : RHSExpr;
John McCall7decc9e2010-11-18 06:31:45 +00009915
9916 resType = ActiveExpr->getType();
9917 ValueDependent = ActiveExpr->isValueDependent();
9918 VK = ActiveExpr->getValueKind();
9919 OK = ActiveExpr->getObjectKind();
Sebastian Redl8d2ccae2009-02-26 14:39:58 +00009920 }
9921
Sebastian Redl6d4256c2009-03-15 17:47:39 +00009922 return Owned(new (Context) ChooseExpr(BuiltinLoc, CondExpr, LHSExpr, RHSExpr,
Eli Friedman75807f22013-07-20 00:40:58 +00009923 resType, VK, OK, RPLoc, CondIsTrue,
Douglas Gregor56751b52009-09-25 04:25:58 +00009924 resType->isDependentType(),
9925 ValueDependent));
Steve Naroff9efdabc2007-08-03 21:21:27 +00009926}
9927
Steve Naroffc540d662008-09-03 18:15:37 +00009928//===----------------------------------------------------------------------===//
9929// Clang Extensions.
9930//===----------------------------------------------------------------------===//
9931
9932/// ActOnBlockStart - This callback is invoked when a block literal is started.
Richard Trieuba63ce62011-09-09 01:45:06 +00009933void Sema::ActOnBlockStart(SourceLocation CaretLoc, Scope *CurScope) {
Douglas Gregor9a28e842010-03-01 23:15:13 +00009934 BlockDecl *Block = BlockDecl::Create(Context, CurContext, CaretLoc);
Eli Friedman7e346a82013-07-01 20:22:57 +00009935
9936 {
9937 Decl *ManglingContextDecl;
9938 if (MangleNumberingContext *MCtx =
9939 getCurrentMangleNumberContext(Block->getDeclContext(),
9940 ManglingContextDecl)) {
9941 unsigned ManglingNumber = MCtx->getManglingNumber(Block);
9942 Block->setBlockMangling(ManglingNumber, ManglingContextDecl);
9943 }
9944 }
9945
Richard Trieuba63ce62011-09-09 01:45:06 +00009946 PushBlockScope(CurScope, Block);
Douglas Gregor9a28e842010-03-01 23:15:13 +00009947 CurContext->addDecl(Block);
Richard Trieuba63ce62011-09-09 01:45:06 +00009948 if (CurScope)
9949 PushDeclContext(CurScope, Block);
Fariborz Jahanian1babe772010-07-09 18:44:02 +00009950 else
9951 CurContext = Block;
John McCallf1a3c2a2011-11-11 03:19:12 +00009952
Eli Friedman34b49062012-01-26 03:00:14 +00009953 getCurBlock()->HasImplicitReturnType = true;
9954
John McCallf1a3c2a2011-11-11 03:19:12 +00009955 // Enter a new evaluation context to insulate the block from any
9956 // cleanups from the enclosing full-expression.
9957 PushExpressionEvaluationContext(PotentiallyEvaluated);
Steve Naroff1d95e5a2008-10-10 01:28:17 +00009958}
9959
Douglas Gregor7efd007c2012-06-15 16:59:29 +00009960void Sema::ActOnBlockArguments(SourceLocation CaretLoc, Declarator &ParamInfo,
9961 Scope *CurScope) {
Mike Stumpf70bcf72009-05-07 18:43:07 +00009962 assert(ParamInfo.getIdentifier()==0 && "block-id should have no identifier!");
John McCall3882ace2011-01-05 12:14:39 +00009963 assert(ParamInfo.getContext() == Declarator::BlockLiteralContext);
Douglas Gregor9a28e842010-03-01 23:15:13 +00009964 BlockScopeInfo *CurBlock = getCurBlock();
Kovarththanan Rajaratnamba2c6522010-03-13 10:17:05 +00009965
John McCall8cb7bdf2010-06-04 23:28:52 +00009966 TypeSourceInfo *Sig = GetTypeForDeclarator(ParamInfo, CurScope);
John McCall8cb7bdf2010-06-04 23:28:52 +00009967 QualType T = Sig->getType();
Mike Stump82f071f2009-02-04 22:31:32 +00009968
Douglas Gregor7efd007c2012-06-15 16:59:29 +00009969 // FIXME: We should allow unexpanded parameter packs here, but that would,
9970 // in turn, make the block expression contain unexpanded parameter packs.
9971 if (DiagnoseUnexpandedParameterPack(CaretLoc, Sig, UPPC_Block)) {
9972 // Drop the parameters.
9973 FunctionProtoType::ExtProtoInfo EPI;
9974 EPI.HasTrailingReturn = false;
9975 EPI.TypeQuals |= DeclSpec::TQ_const;
Dmitri Gribenko44ebbd52013-05-05 00:41:58 +00009976 T = Context.getFunctionType(Context.DependentTy, None, EPI);
Douglas Gregor7efd007c2012-06-15 16:59:29 +00009977 Sig = Context.getTrivialTypeSourceInfo(T);
9978 }
9979
John McCall3882ace2011-01-05 12:14:39 +00009980 // GetTypeForDeclarator always produces a function type for a block
9981 // literal signature. Furthermore, it is always a FunctionProtoType
9982 // unless the function was written with a typedef.
9983 assert(T->isFunctionType() &&
9984 "GetTypeForDeclarator made a non-function block signature");
9985
9986 // Look for an explicit signature in that function type.
9987 FunctionProtoTypeLoc ExplicitSignature;
9988
9989 TypeLoc tmp = Sig->getTypeLoc().IgnoreParens();
David Blaikie6adc78e2013-02-18 22:06:02 +00009990 if ((ExplicitSignature = tmp.getAs<FunctionProtoTypeLoc>())) {
John McCall3882ace2011-01-05 12:14:39 +00009991
9992 // Check whether that explicit signature was synthesized by
9993 // GetTypeForDeclarator. If so, don't save that as part of the
9994 // written signature.
Abramo Bagnaraf2a79d92011-03-12 11:17:06 +00009995 if (ExplicitSignature.getLocalRangeBegin() ==
9996 ExplicitSignature.getLocalRangeEnd()) {
John McCall3882ace2011-01-05 12:14:39 +00009997 // This would be much cheaper if we stored TypeLocs instead of
9998 // TypeSourceInfos.
9999 TypeLoc Result = ExplicitSignature.getResultLoc();
10000 unsigned Size = Result.getFullDataSize();
10001 Sig = Context.CreateTypeSourceInfo(Result.getType(), Size);
10002 Sig->getTypeLoc().initializeFullCopy(Result, Size);
10003
10004 ExplicitSignature = FunctionProtoTypeLoc();
10005 }
John McCalla3ccba02010-06-04 11:21:44 +000010006 }
Mike Stump11289f42009-09-09 15:08:12 +000010007
John McCall3882ace2011-01-05 12:14:39 +000010008 CurBlock->TheDecl->setSignatureAsWritten(Sig);
10009 CurBlock->FunctionType = T;
10010
10011 const FunctionType *Fn = T->getAs<FunctionType>();
10012 QualType RetTy = Fn->getResultType();
10013 bool isVariadic =
10014 (isa<FunctionProtoType>(Fn) && cast<FunctionProtoType>(Fn)->isVariadic());
10015
John McCall8e346702010-06-04 19:02:56 +000010016 CurBlock->TheDecl->setIsVariadic(isVariadic);
Douglas Gregorb92a1562010-02-03 00:27:59 +000010017
John McCalla3ccba02010-06-04 11:21:44 +000010018 // Context.DependentTy is used as a placeholder for a missing block
John McCall8e346702010-06-04 19:02:56 +000010019 // return type. TODO: what should we do with declarators like:
10020 // ^ * { ... }
10021 // If the answer is "apply template argument deduction"....
Fariborz Jahaniandd5eb9d2011-12-03 17:47:53 +000010022 if (RetTy != Context.DependentTy) {
John McCalla3ccba02010-06-04 11:21:44 +000010023 CurBlock->ReturnType = RetTy;
Fariborz Jahaniandd5eb9d2011-12-03 17:47:53 +000010024 CurBlock->TheDecl->setBlockMissingReturnType(false);
Eli Friedman34b49062012-01-26 03:00:14 +000010025 CurBlock->HasImplicitReturnType = false;
Fariborz Jahaniandd5eb9d2011-12-03 17:47:53 +000010026 }
Mike Stump4e1f26a2009-02-19 03:04:26 +000010027
John McCalla3ccba02010-06-04 11:21:44 +000010028 // Push block parameters from the declarator if we had them.
Chris Lattner0e62c1c2011-07-23 10:55:15 +000010029 SmallVector<ParmVarDecl*, 8> Params;
John McCall3882ace2011-01-05 12:14:39 +000010030 if (ExplicitSignature) {
10031 for (unsigned I = 0, E = ExplicitSignature.getNumArgs(); I != E; ++I) {
10032 ParmVarDecl *Param = ExplicitSignature.getArg(I);
Fariborz Jahanian5ec502e2010-02-12 21:53:14 +000010033 if (Param->getIdentifier() == 0 &&
10034 !Param->isImplicit() &&
10035 !Param->isInvalidDecl() &&
David Blaikiebbafb8a2012-03-11 07:00:24 +000010036 !getLangOpts().CPlusPlus)
Fariborz Jahanian5ec502e2010-02-12 21:53:14 +000010037 Diag(Param->getLocation(), diag::err_parameter_name_omitted);
John McCall8e346702010-06-04 19:02:56 +000010038 Params.push_back(Param);
Fariborz Jahanian5ec502e2010-02-12 21:53:14 +000010039 }
John McCalla3ccba02010-06-04 11:21:44 +000010040
10041 // Fake up parameter variables if we have a typedef, like
10042 // ^ fntype { ... }
10043 } else if (const FunctionProtoType *Fn = T->getAs<FunctionProtoType>()) {
10044 for (FunctionProtoType::arg_type_iterator
10045 I = Fn->arg_type_begin(), E = Fn->arg_type_end(); I != E; ++I) {
10046 ParmVarDecl *Param =
10047 BuildParmVarDeclForTypedef(CurBlock->TheDecl,
Daniel Dunbar62ee6412012-03-09 18:35:03 +000010048 ParamInfo.getLocStart(),
John McCalla3ccba02010-06-04 11:21:44 +000010049 *I);
John McCall8e346702010-06-04 19:02:56 +000010050 Params.push_back(Param);
John McCalla3ccba02010-06-04 11:21:44 +000010051 }
Steve Naroffc540d662008-09-03 18:15:37 +000010052 }
John McCalla3ccba02010-06-04 11:21:44 +000010053
John McCall8e346702010-06-04 19:02:56 +000010054 // Set the parameters on the block decl.
Douglas Gregorb524d902010-11-01 18:37:59 +000010055 if (!Params.empty()) {
David Blaikie9c70e042011-09-21 18:16:56 +000010056 CurBlock->TheDecl->setParams(Params);
Douglas Gregorb524d902010-11-01 18:37:59 +000010057 CheckParmsForFunctionDef(CurBlock->TheDecl->param_begin(),
10058 CurBlock->TheDecl->param_end(),
10059 /*CheckParameterNames=*/false);
10060 }
10061
John McCalla3ccba02010-06-04 11:21:44 +000010062 // Finally we can process decl attributes.
Douglas Gregor758a8692009-06-17 21:51:59 +000010063 ProcessDeclAttributes(CurScope, CurBlock->TheDecl, ParamInfo);
John McCalldf8b37c2010-03-22 09:20:08 +000010064
Eli Friedman7e346a82013-07-01 20:22:57 +000010065 // Put the parameter variables in scope.
Steve Naroff1d95e5a2008-10-10 01:28:17 +000010066 for (BlockDecl::param_iterator AI = CurBlock->TheDecl->param_begin(),
John McCallf7b2fb52010-01-22 00:28:27 +000010067 E = CurBlock->TheDecl->param_end(); AI != E; ++AI) {
10068 (*AI)->setOwningFunction(CurBlock->TheDecl);
10069
Steve Naroff1d95e5a2008-10-10 01:28:17 +000010070 // If this has an identifier, add it to the scope stack.
John McCalldf8b37c2010-03-22 09:20:08 +000010071 if ((*AI)->getIdentifier()) {
Argyrios Kyrtzidis1cb0de12010-12-15 18:44:22 +000010072 CheckShadow(CurBlock->TheScope, *AI);
John McCalldf8b37c2010-03-22 09:20:08 +000010073
Steve Naroff1d95e5a2008-10-10 01:28:17 +000010074 PushOnScopeChains(*AI, CurBlock->TheScope);
John McCalldf8b37c2010-03-22 09:20:08 +000010075 }
John McCallf7b2fb52010-01-22 00:28:27 +000010076 }
Steve Naroffc540d662008-09-03 18:15:37 +000010077}
10078
10079/// ActOnBlockError - If there is an error parsing a block, this callback
10080/// is invoked to pop the information about the block from the action impl.
10081void Sema::ActOnBlockError(SourceLocation CaretLoc, Scope *CurScope) {
John McCallf1a3c2a2011-11-11 03:19:12 +000010082 // Leave the expression-evaluation context.
10083 DiscardCleanupsInEvaluationContext();
10084 PopExpressionEvaluationContext();
10085
Steve Naroffc540d662008-09-03 18:15:37 +000010086 // Pop off CurBlock, handle nested blocks.
Chris Lattner41b86942009-04-21 22:38:46 +000010087 PopDeclContext();
Eli Friedman71c80552012-01-05 03:35:19 +000010088 PopFunctionScopeInfo();
Steve Naroffc540d662008-09-03 18:15:37 +000010089}
10090
10091/// ActOnBlockStmtExpr - This is called when the body of a block statement
10092/// literal was successfully completed. ^(int x){...}
John McCalldadc5752010-08-24 06:29:42 +000010093ExprResult Sema::ActOnBlockStmtExpr(SourceLocation CaretLoc,
Chris Lattner60f84492011-02-17 23:58:47 +000010094 Stmt *Body, Scope *CurScope) {
Chris Lattner9eac9312009-03-27 04:18:06 +000010095 // If blocks are disabled, emit an error.
10096 if (!LangOpts.Blocks)
10097 Diag(CaretLoc, diag::err_blocks_disable);
Mike Stump11289f42009-09-09 15:08:12 +000010098
John McCallf1a3c2a2011-11-11 03:19:12 +000010099 // Leave the expression-evaluation context.
John McCall85110b42012-03-08 22:00:17 +000010100 if (hasAnyUnrecoverableErrorsInThisFunction())
10101 DiscardCleanupsInEvaluationContext();
John McCallf1a3c2a2011-11-11 03:19:12 +000010102 assert(!ExprNeedsCleanups && "cleanups within block not correctly bound!");
10103 PopExpressionEvaluationContext();
10104
Douglas Gregor9a28e842010-03-01 23:15:13 +000010105 BlockScopeInfo *BSI = cast<BlockScopeInfo>(FunctionScopes.back());
Jordan Rosed39e5f12012-07-02 21:19:23 +000010106
10107 if (BSI->HasImplicitReturnType)
10108 deduceClosureReturnType(*BSI);
10109
Steve Naroff1d95e5a2008-10-10 01:28:17 +000010110 PopDeclContext();
10111
Steve Naroffc540d662008-09-03 18:15:37 +000010112 QualType RetTy = Context.VoidTy;
Fariborz Jahanian3fd73102009-06-19 23:37:08 +000010113 if (!BSI->ReturnType.isNull())
10114 RetTy = BSI->ReturnType;
Mike Stump4e1f26a2009-02-19 03:04:26 +000010115
Mike Stump3bf1ab42009-07-28 22:04:01 +000010116 bool NoReturn = BSI->TheDecl->getAttr<NoReturnAttr>();
Steve Naroffc540d662008-09-03 18:15:37 +000010117 QualType BlockTy;
John McCall8e346702010-06-04 19:02:56 +000010118
John McCallc63de662011-02-02 13:00:07 +000010119 // Set the captured variables on the block.
Eli Friedman20139d32012-01-11 02:36:31 +000010120 // FIXME: Share capture structure between BlockDecl and CapturingScopeInfo!
10121 SmallVector<BlockDecl::Capture, 4> Captures;
10122 for (unsigned i = 0, e = BSI->Captures.size(); i != e; i++) {
10123 CapturingScopeInfo::Capture &Cap = BSI->Captures[i];
10124 if (Cap.isThisCapture())
10125 continue;
Eli Friedman24af8502012-02-03 22:47:37 +000010126 BlockDecl::Capture NewCap(Cap.getVariable(), Cap.isBlockCapture(),
Richard Smithba71c082013-05-16 06:20:58 +000010127 Cap.isNested(), Cap.getInitExpr());
Eli Friedman20139d32012-01-11 02:36:31 +000010128 Captures.push_back(NewCap);
10129 }
10130 BSI->TheDecl->setCaptures(Context, Captures.begin(), Captures.end(),
10131 BSI->CXXThisCaptureIndex != 0);
John McCallc63de662011-02-02 13:00:07 +000010132
John McCall8e346702010-06-04 19:02:56 +000010133 // If the user wrote a function type in some form, try to use that.
10134 if (!BSI->FunctionType.isNull()) {
10135 const FunctionType *FTy = BSI->FunctionType->getAs<FunctionType>();
10136
10137 FunctionType::ExtInfo Ext = FTy->getExtInfo();
10138 if (NoReturn && !Ext.getNoReturn()) Ext = Ext.withNoReturn(true);
10139
10140 // Turn protoless block types into nullary block types.
10141 if (isa<FunctionNoProtoType>(FTy)) {
John McCalldb40c7f2010-12-14 08:05:40 +000010142 FunctionProtoType::ExtProtoInfo EPI;
10143 EPI.ExtInfo = Ext;
Dmitri Gribenko44ebbd52013-05-05 00:41:58 +000010144 BlockTy = Context.getFunctionType(RetTy, None, EPI);
John McCall8e346702010-06-04 19:02:56 +000010145
10146 // Otherwise, if we don't need to change anything about the function type,
10147 // preserve its sugar structure.
10148 } else if (FTy->getResultType() == RetTy &&
10149 (!NoReturn || FTy->getNoReturnAttr())) {
10150 BlockTy = BSI->FunctionType;
10151
10152 // Otherwise, make the minimal modifications to the function type.
10153 } else {
10154 const FunctionProtoType *FPT = cast<FunctionProtoType>(FTy);
John McCalldb40c7f2010-12-14 08:05:40 +000010155 FunctionProtoType::ExtProtoInfo EPI = FPT->getExtProtoInfo();
10156 EPI.TypeQuals = 0; // FIXME: silently?
10157 EPI.ExtInfo = Ext;
Reid Kleckner896b32f2013-06-10 20:51:09 +000010158 BlockTy = Context.getFunctionType(RetTy, FPT->getArgTypes(), EPI);
John McCall8e346702010-06-04 19:02:56 +000010159 }
10160
10161 // If we don't have a function type, just build one from nothing.
10162 } else {
John McCalldb40c7f2010-12-14 08:05:40 +000010163 FunctionProtoType::ExtProtoInfo EPI;
John McCall31168b02011-06-15 23:02:42 +000010164 EPI.ExtInfo = FunctionType::ExtInfo().withNoReturn(NoReturn);
Dmitri Gribenko44ebbd52013-05-05 00:41:58 +000010165 BlockTy = Context.getFunctionType(RetTy, None, EPI);
John McCall8e346702010-06-04 19:02:56 +000010166 }
Mike Stump4e1f26a2009-02-19 03:04:26 +000010167
John McCall8e346702010-06-04 19:02:56 +000010168 DiagnoseUnusedParameters(BSI->TheDecl->param_begin(),
10169 BSI->TheDecl->param_end());
Steve Naroffc540d662008-09-03 18:15:37 +000010170 BlockTy = Context.getBlockPointerType(BlockTy);
Mike Stump4e1f26a2009-02-19 03:04:26 +000010171
Chris Lattner45542ea2009-04-19 05:28:12 +000010172 // If needed, diagnose invalid gotos and switches in the block.
John McCall31168b02011-06-15 23:02:42 +000010173 if (getCurFunction()->NeedsScopeChecking() &&
Douglas Gregor5d944db2012-08-17 05:12:08 +000010174 !hasAnyUnrecoverableErrorsInThisFunction() &&
10175 !PP.isCodeCompletionEnabled())
John McCallb268a282010-08-23 23:25:46 +000010176 DiagnoseInvalidJumps(cast<CompoundStmt>(Body));
Mike Stump11289f42009-09-09 15:08:12 +000010177
Chris Lattner60f84492011-02-17 23:58:47 +000010178 BSI->TheDecl->setBody(cast<CompoundStmt>(Body));
Kovarththanan Rajaratnamba2c6522010-03-13 10:17:05 +000010179
Jordan Rosed39e5f12012-07-02 21:19:23 +000010180 // Try to apply the named return value optimization. We have to check again
10181 // if we can do this, though, because blocks keep return statements around
10182 // to deduce an implicit return type.
10183 if (getLangOpts().CPlusPlus && RetTy->isRecordType() &&
10184 !BSI->TheDecl->isDependentContext())
10185 computeNRVO(Body, getCurBlock());
Douglas Gregor49695f02011-09-06 20:46:03 +000010186
Benjamin Kramera4fb8362011-07-12 14:11:05 +000010187 BlockExpr *Result = new (Context) BlockExpr(BSI->TheDecl, BlockTy);
10188 const AnalysisBasedWarnings::Policy &WP = AnalysisWarnings.getDefaultPolicy();
Eli Friedman71c80552012-01-05 03:35:19 +000010189 PopFunctionScopeInfo(&WP, Result->getBlockDecl(), Result);
Benjamin Kramera4fb8362011-07-12 14:11:05 +000010190
John McCall28fc7092011-11-10 05:35:25 +000010191 // If the block isn't obviously global, i.e. it captures anything at
John McCalld2393872012-04-13 01:08:17 +000010192 // all, then we need to do a few things in the surrounding context:
John McCall28fc7092011-11-10 05:35:25 +000010193 if (Result->getBlockDecl()->hasCaptures()) {
John McCalld2393872012-04-13 01:08:17 +000010194 // First, this expression has a new cleanup object.
John McCall28fc7092011-11-10 05:35:25 +000010195 ExprCleanupObjects.push_back(Result->getBlockDecl());
10196 ExprNeedsCleanups = true;
John McCalld2393872012-04-13 01:08:17 +000010197
10198 // It also gets a branch-protected scope if any of the captured
10199 // variables needs destruction.
10200 for (BlockDecl::capture_const_iterator
10201 ci = Result->getBlockDecl()->capture_begin(),
10202 ce = Result->getBlockDecl()->capture_end(); ci != ce; ++ci) {
10203 const VarDecl *var = ci->getVariable();
10204 if (var->getType().isDestructedType() != QualType::DK_none) {
10205 getCurFunction()->setHasBranchProtectedScope();
10206 break;
10207 }
10208 }
John McCall28fc7092011-11-10 05:35:25 +000010209 }
Fariborz Jahanian197c68c2012-03-06 18:41:35 +000010210
Douglas Gregor9a28e842010-03-01 23:15:13 +000010211 return Owned(Result);
Steve Naroffc540d662008-09-03 18:15:37 +000010212}
10213
John McCalldadc5752010-08-24 06:29:42 +000010214ExprResult Sema::ActOnVAArg(SourceLocation BuiltinLoc,
Richard Trieuba63ce62011-09-09 01:45:06 +000010215 Expr *E, ParsedType Ty,
Sebastian Redl6d4256c2009-03-15 17:47:39 +000010216 SourceLocation RPLoc) {
Abramo Bagnara27db2392010-08-10 10:06:15 +000010217 TypeSourceInfo *TInfo;
Richard Trieuba63ce62011-09-09 01:45:06 +000010218 GetTypeFromParser(Ty, &TInfo);
10219 return BuildVAArgExpr(BuiltinLoc, E, TInfo, RPLoc);
Abramo Bagnara27db2392010-08-10 10:06:15 +000010220}
10221
John McCalldadc5752010-08-24 06:29:42 +000010222ExprResult Sema::BuildVAArgExpr(SourceLocation BuiltinLoc,
John McCall7decc9e2010-11-18 06:31:45 +000010223 Expr *E, TypeSourceInfo *TInfo,
10224 SourceLocation RPLoc) {
Chris Lattner56382aa2009-04-05 15:49:53 +000010225 Expr *OrigExpr = E;
Mike Stump11289f42009-09-09 15:08:12 +000010226
Eli Friedman121ba0c2008-08-09 23:32:40 +000010227 // Get the va_list type
10228 QualType VaListType = Context.getBuiltinVaListType();
Eli Friedmane2cad652009-05-16 12:46:54 +000010229 if (VaListType->isArrayType()) {
10230 // Deal with implicit array decay; for example, on x86-64,
10231 // va_list is an array, but it's supposed to decay to
10232 // a pointer for va_arg.
Eli Friedman121ba0c2008-08-09 23:32:40 +000010233 VaListType = Context.getArrayDecayedType(VaListType);
Eli Friedmane2cad652009-05-16 12:46:54 +000010234 // Make sure the input expression also decays appropriately.
John Wiegley01296292011-04-08 18:41:53 +000010235 ExprResult Result = UsualUnaryConversions(E);
10236 if (Result.isInvalid())
10237 return ExprError();
10238 E = Result.take();
Logan Chien29574892012-10-20 06:11:33 +000010239 } else if (VaListType->isRecordType() && getLangOpts().CPlusPlus) {
10240 // If va_list is a record type and we are compiling in C++ mode,
10241 // check the argument using reference binding.
10242 InitializedEntity Entity
10243 = InitializedEntity::InitializeParameter(Context,
10244 Context.getLValueReferenceType(VaListType), false);
10245 ExprResult Init = PerformCopyInitialization(Entity, SourceLocation(), E);
10246 if (Init.isInvalid())
10247 return ExprError();
10248 E = Init.takeAs<Expr>();
Eli Friedmane2cad652009-05-16 12:46:54 +000010249 } else {
10250 // Otherwise, the va_list argument must be an l-value because
10251 // it is modified by va_arg.
Mike Stump11289f42009-09-09 15:08:12 +000010252 if (!E->isTypeDependent() &&
Douglas Gregorad3150c2009-05-19 23:10:31 +000010253 CheckForModifiableLvalue(E, BuiltinLoc, *this))
Eli Friedmane2cad652009-05-16 12:46:54 +000010254 return ExprError();
10255 }
Eli Friedman121ba0c2008-08-09 23:32:40 +000010256
Douglas Gregorad3150c2009-05-19 23:10:31 +000010257 if (!E->isTypeDependent() &&
10258 !Context.hasSameType(VaListType, E->getType())) {
Sebastian Redl6d4256c2009-03-15 17:47:39 +000010259 return ExprError(Diag(E->getLocStart(),
10260 diag::err_first_argument_to_va_arg_not_of_type_va_list)
Chris Lattner56382aa2009-04-05 15:49:53 +000010261 << OrigExpr->getType() << E->getSourceRange());
Chris Lattner3f5cd772009-04-05 00:59:53 +000010262 }
Mike Stump4e1f26a2009-02-19 03:04:26 +000010263
David Majnemerc75d1a12011-06-14 05:17:32 +000010264 if (!TInfo->getType()->isDependentType()) {
10265 if (RequireCompleteType(TInfo->getTypeLoc().getBeginLoc(), TInfo->getType(),
Douglas Gregor7bfb2d02012-05-04 16:32:21 +000010266 diag::err_second_parameter_to_va_arg_incomplete,
10267 TInfo->getTypeLoc()))
David Majnemerc75d1a12011-06-14 05:17:32 +000010268 return ExprError();
David Majnemer254a5c02011-06-13 06:37:03 +000010269
David Majnemerc75d1a12011-06-14 05:17:32 +000010270 if (RequireNonAbstractType(TInfo->getTypeLoc().getBeginLoc(),
Douglas Gregorae298422012-05-04 17:09:59 +000010271 TInfo->getType(),
10272 diag::err_second_parameter_to_va_arg_abstract,
10273 TInfo->getTypeLoc()))
David Majnemerc75d1a12011-06-14 05:17:32 +000010274 return ExprError();
10275
Douglas Gregor7e1eb932011-07-30 06:45:27 +000010276 if (!TInfo->getType().isPODType(Context)) {
David Majnemerc75d1a12011-06-14 05:17:32 +000010277 Diag(TInfo->getTypeLoc().getBeginLoc(),
Douglas Gregor7e1eb932011-07-30 06:45:27 +000010278 TInfo->getType()->isObjCLifetimeType()
10279 ? diag::warn_second_parameter_to_va_arg_ownership_qualified
10280 : diag::warn_second_parameter_to_va_arg_not_pod)
David Majnemerc75d1a12011-06-14 05:17:32 +000010281 << TInfo->getType()
10282 << TInfo->getTypeLoc().getSourceRange();
Douglas Gregor7e1eb932011-07-30 06:45:27 +000010283 }
Eli Friedman6290ae42011-07-11 21:45:59 +000010284
10285 // Check for va_arg where arguments of the given type will be promoted
10286 // (i.e. this va_arg is guaranteed to have undefined behavior).
10287 QualType PromoteType;
10288 if (TInfo->getType()->isPromotableIntegerType()) {
10289 PromoteType = Context.getPromotedIntegerType(TInfo->getType());
10290 if (Context.typesAreCompatible(PromoteType, TInfo->getType()))
10291 PromoteType = QualType();
10292 }
10293 if (TInfo->getType()->isSpecificBuiltinType(BuiltinType::Float))
10294 PromoteType = Context.DoubleTy;
10295 if (!PromoteType.isNull())
Ted Kremeneka0461692013-01-08 01:50:40 +000010296 DiagRuntimeBehavior(TInfo->getTypeLoc().getBeginLoc(), E,
10297 PDiag(diag::warn_second_parameter_to_va_arg_never_compatible)
10298 << TInfo->getType()
10299 << PromoteType
10300 << TInfo->getTypeLoc().getSourceRange());
David Majnemerc75d1a12011-06-14 05:17:32 +000010301 }
Mike Stump4e1f26a2009-02-19 03:04:26 +000010302
Abramo Bagnara27db2392010-08-10 10:06:15 +000010303 QualType T = TInfo->getType().getNonLValueExprType(Context);
10304 return Owned(new (Context) VAArgExpr(BuiltinLoc, E, TInfo, RPLoc, T));
Anders Carlsson7e13ab82007-10-15 20:28:48 +000010305}
10306
John McCalldadc5752010-08-24 06:29:42 +000010307ExprResult Sema::ActOnGNUNullExpr(SourceLocation TokenLoc) {
Douglas Gregor3be4b122008-11-29 04:51:27 +000010308 // The type of __null will be int or long, depending on the size of
10309 // pointers on the target.
10310 QualType Ty;
Douglas Gregore8bbc122011-09-02 00:18:52 +000010311 unsigned pw = Context.getTargetInfo().getPointerWidth(0);
10312 if (pw == Context.getTargetInfo().getIntWidth())
Douglas Gregor3be4b122008-11-29 04:51:27 +000010313 Ty = Context.IntTy;
Douglas Gregore8bbc122011-09-02 00:18:52 +000010314 else if (pw == Context.getTargetInfo().getLongWidth())
Douglas Gregor3be4b122008-11-29 04:51:27 +000010315 Ty = Context.LongTy;
Douglas Gregore8bbc122011-09-02 00:18:52 +000010316 else if (pw == Context.getTargetInfo().getLongLongWidth())
NAKAMURA Takumi0d13fd32011-01-19 00:11:41 +000010317 Ty = Context.LongLongTy;
10318 else {
David Blaikie83d382b2011-09-23 05:06:16 +000010319 llvm_unreachable("I don't know size of pointer!");
NAKAMURA Takumi0d13fd32011-01-19 00:11:41 +000010320 }
Douglas Gregor3be4b122008-11-29 04:51:27 +000010321
Sebastian Redl6d4256c2009-03-15 17:47:39 +000010322 return Owned(new (Context) GNUNullExpr(Ty, TokenLoc));
Douglas Gregor3be4b122008-11-29 04:51:27 +000010323}
10324
Alexis Huntc46382e2010-04-28 23:02:27 +000010325static void MakeObjCStringLiteralFixItHint(Sema& SemaRef, QualType DstType,
Fariborz Jahanian286fcf62013-06-10 23:51:51 +000010326 Expr *SrcExpr, FixItHint &Hint,
10327 bool &IsNSString) {
David Blaikiebbafb8a2012-03-11 07:00:24 +000010328 if (!SemaRef.getLangOpts().ObjC1)
Anders Carlssonace5d072009-11-10 04:46:30 +000010329 return;
Kovarththanan Rajaratnamba2c6522010-03-13 10:17:05 +000010330
Anders Carlssonace5d072009-11-10 04:46:30 +000010331 const ObjCObjectPointerType *PT = DstType->getAs<ObjCObjectPointerType>();
10332 if (!PT)
10333 return;
10334
10335 // Check if the destination is of type 'id'.
10336 if (!PT->isObjCIdType()) {
10337 // Check if the destination is the 'NSString' interface.
10338 const ObjCInterfaceDecl *ID = PT->getInterfaceDecl();
10339 if (!ID || !ID->getIdentifier()->isStr("NSString"))
10340 return;
Fariborz Jahanian286fcf62013-06-10 23:51:51 +000010341 IsNSString = true;
Anders Carlssonace5d072009-11-10 04:46:30 +000010342 }
Kovarththanan Rajaratnamba2c6522010-03-13 10:17:05 +000010343
John McCallfe96e0b2011-11-06 09:01:30 +000010344 // Ignore any parens, implicit casts (should only be
10345 // array-to-pointer decays), and not-so-opaque values. The last is
10346 // important for making this trigger for property assignments.
10347 SrcExpr = SrcExpr->IgnoreParenImpCasts();
10348 if (OpaqueValueExpr *OV = dyn_cast<OpaqueValueExpr>(SrcExpr))
10349 if (OV->getSourceExpr())
10350 SrcExpr = OV->getSourceExpr()->IgnoreParenImpCasts();
10351
10352 StringLiteral *SL = dyn_cast<StringLiteral>(SrcExpr);
Douglas Gregorfb65e592011-07-27 05:40:30 +000010353 if (!SL || !SL->isAscii())
Anders Carlssonace5d072009-11-10 04:46:30 +000010354 return;
Kovarththanan Rajaratnamba2c6522010-03-13 10:17:05 +000010355
Douglas Gregora771f462010-03-31 17:46:05 +000010356 Hint = FixItHint::CreateInsertion(SL->getLocStart(), "@");
Anders Carlssonace5d072009-11-10 04:46:30 +000010357}
10358
Chris Lattner9bad62c2008-01-04 18:04:52 +000010359bool Sema::DiagnoseAssignmentResult(AssignConvertType ConvTy,
10360 SourceLocation Loc,
10361 QualType DstType, QualType SrcType,
Douglas Gregor4f4946a2010-04-22 00:20:18 +000010362 Expr *SrcExpr, AssignmentAction Action,
10363 bool *Complained) {
10364 if (Complained)
10365 *Complained = false;
10366
Chris Lattner9bad62c2008-01-04 18:04:52 +000010367 // Decode the result (notice that AST's are still created for extensions).
Douglas Gregor33823722011-06-11 01:09:30 +000010368 bool CheckInferredResultType = false;
Chris Lattner9bad62c2008-01-04 18:04:52 +000010369 bool isInvalid = false;
Eli Friedman381f4312012-02-29 20:59:56 +000010370 unsigned DiagKind = 0;
Douglas Gregora771f462010-03-31 17:46:05 +000010371 FixItHint Hint;
Anna Zaks3b402712011-07-28 19:51:27 +000010372 ConversionFixItGenerator ConvHints;
10373 bool MayHaveConvFixit = false;
Richard Trieucaff2472011-11-23 22:32:32 +000010374 bool MayHaveFunctionDiff = false;
Fariborz Jahanian286fcf62013-06-10 23:51:51 +000010375 bool IsNSString = false;
Kovarththanan Rajaratnamba2c6522010-03-13 10:17:05 +000010376
Chris Lattner9bad62c2008-01-04 18:04:52 +000010377 switch (ConvTy) {
Fariborz Jahanian268fec12012-07-17 18:00:08 +000010378 case Compatible:
Daniel Dunbarbd847cc2012-10-15 22:23:53 +000010379 DiagnoseAssignmentEnum(DstType, SrcType, SrcExpr);
10380 return false;
Fariborz Jahanian268fec12012-07-17 18:00:08 +000010381
Chris Lattner940cfeb2008-01-04 18:22:42 +000010382 case PointerToInt:
Chris Lattner9bad62c2008-01-04 18:04:52 +000010383 DiagKind = diag::ext_typecheck_convert_pointer_int;
Anna Zaks3b402712011-07-28 19:51:27 +000010384 ConvHints.tryToFixConversion(SrcExpr, SrcType, DstType, *this);
10385 MayHaveConvFixit = true;
Chris Lattner9bad62c2008-01-04 18:04:52 +000010386 break;
Chris Lattner940cfeb2008-01-04 18:22:42 +000010387 case IntToPointer:
10388 DiagKind = diag::ext_typecheck_convert_int_pointer;
Anna Zaks3b402712011-07-28 19:51:27 +000010389 ConvHints.tryToFixConversion(SrcExpr, SrcType, DstType, *this);
10390 MayHaveConvFixit = true;
Chris Lattner940cfeb2008-01-04 18:22:42 +000010391 break;
Chris Lattner9bad62c2008-01-04 18:04:52 +000010392 case IncompatiblePointer:
Fariborz Jahanian286fcf62013-06-10 23:51:51 +000010393 MakeObjCStringLiteralFixItHint(*this, DstType, SrcExpr, Hint, IsNSString);
Chris Lattner9bad62c2008-01-04 18:04:52 +000010394 DiagKind = diag::ext_typecheck_convert_incompatible_pointer;
Douglas Gregor33823722011-06-11 01:09:30 +000010395 CheckInferredResultType = DstType->isObjCObjectPointerType() &&
10396 SrcType->isObjCObjectPointerType();
Anna Zaks3b402712011-07-28 19:51:27 +000010397 if (Hint.isNull() && !CheckInferredResultType) {
10398 ConvHints.tryToFixConversion(SrcExpr, SrcType, DstType, *this);
10399 }
Fariborz Jahanian3beec202013-04-30 00:30:48 +000010400 else if (CheckInferredResultType) {
10401 SrcType = SrcType.getUnqualifiedType();
10402 DstType = DstType.getUnqualifiedType();
10403 }
Fariborz Jahanian286fcf62013-06-10 23:51:51 +000010404 else if (IsNSString && !Hint.isNull())
10405 DiagKind = diag::warn_missing_atsign_prefix;
Anna Zaks3b402712011-07-28 19:51:27 +000010406 MayHaveConvFixit = true;
Chris Lattner9bad62c2008-01-04 18:04:52 +000010407 break;
Eli Friedman80160bd2009-03-22 23:59:44 +000010408 case IncompatiblePointerSign:
10409 DiagKind = diag::ext_typecheck_convert_incompatible_pointer_sign;
10410 break;
Chris Lattner9bad62c2008-01-04 18:04:52 +000010411 case FunctionVoidPointer:
10412 DiagKind = diag::ext_typecheck_convert_pointer_void_func;
10413 break;
John McCall4fff8f62011-02-01 00:10:29 +000010414 case IncompatiblePointerDiscardsQualifiers: {
John McCall71de91c2011-02-01 23:28:01 +000010415 // Perform array-to-pointer decay if necessary.
10416 if (SrcType->isArrayType()) SrcType = Context.getArrayDecayedType(SrcType);
10417
John McCall4fff8f62011-02-01 00:10:29 +000010418 Qualifiers lhq = SrcType->getPointeeType().getQualifiers();
10419 Qualifiers rhq = DstType->getPointeeType().getQualifiers();
10420 if (lhq.getAddressSpace() != rhq.getAddressSpace()) {
10421 DiagKind = diag::err_typecheck_incompatible_address_space;
10422 break;
John McCall31168b02011-06-15 23:02:42 +000010423
10424
10425 } else if (lhq.getObjCLifetime() != rhq.getObjCLifetime()) {
Argyrios Kyrtzidiscff00d92011-06-24 00:08:59 +000010426 DiagKind = diag::err_typecheck_incompatible_ownership;
John McCall31168b02011-06-15 23:02:42 +000010427 break;
John McCall4fff8f62011-02-01 00:10:29 +000010428 }
10429
10430 llvm_unreachable("unknown error case for discarding qualifiers!");
10431 // fallthrough
10432 }
Chris Lattner9bad62c2008-01-04 18:04:52 +000010433 case CompatiblePointerDiscardsQualifiers:
Douglas Gregoraa1e21d2008-09-12 00:47:35 +000010434 // If the qualifiers lost were because we were applying the
10435 // (deprecated) C++ conversion from a string literal to a char*
10436 // (or wchar_t*), then there was no error (C++ 4.2p2). FIXME:
10437 // Ideally, this check would be performed in
John McCallaba90822011-01-31 23:13:11 +000010438 // checkPointerTypesForAssignment. However, that would require a
Douglas Gregoraa1e21d2008-09-12 00:47:35 +000010439 // bit of refactoring (so that the second argument is an
10440 // expression, rather than a type), which should be done as part
John McCallaba90822011-01-31 23:13:11 +000010441 // of a larger effort to fix checkPointerTypesForAssignment for
Douglas Gregoraa1e21d2008-09-12 00:47:35 +000010442 // C++ semantics.
David Blaikiebbafb8a2012-03-11 07:00:24 +000010443 if (getLangOpts().CPlusPlus &&
Douglas Gregoraa1e21d2008-09-12 00:47:35 +000010444 IsStringLiteralToNonConstPointerConversion(SrcExpr, DstType))
10445 return false;
Chris Lattner9bad62c2008-01-04 18:04:52 +000010446 DiagKind = diag::ext_typecheck_convert_discards_qualifiers;
10447 break;
Alexis Hunt6f3de502009-11-08 07:46:34 +000010448 case IncompatibleNestedPointerQualifiers:
Fariborz Jahanianb98dade2009-11-09 22:16:37 +000010449 DiagKind = diag::ext_nested_pointer_qualifier_mismatch;
Fariborz Jahaniand7aa9d82009-11-07 20:20:40 +000010450 break;
Steve Naroff081c7422008-09-04 15:10:53 +000010451 case IntToBlockPointer:
10452 DiagKind = diag::err_int_to_block_pointer;
10453 break;
10454 case IncompatibleBlockPointer:
Mike Stumpd79b5a82009-04-21 22:51:42 +000010455 DiagKind = diag::err_typecheck_convert_incompatible_block_pointer;
Steve Naroff081c7422008-09-04 15:10:53 +000010456 break;
Steve Naroff8afa9892008-10-14 22:18:38 +000010457 case IncompatibleObjCQualifiedId:
Mike Stump4e1f26a2009-02-19 03:04:26 +000010458 // FIXME: Diagnose the problem in ObjCQualifiedIdTypesAreCompatible, since
Steve Naroff8afa9892008-10-14 22:18:38 +000010459 // it can give a more specific diagnostic.
10460 DiagKind = diag::warn_incompatible_qualified_id;
10461 break;
Anders Carlssondb5a9b62009-01-30 23:17:46 +000010462 case IncompatibleVectors:
10463 DiagKind = diag::warn_incompatible_vectors;
10464 break;
Fariborz Jahanian6f472e82011-07-07 18:55:47 +000010465 case IncompatibleObjCWeakRef:
10466 DiagKind = diag::err_arc_weak_unavailable_assign;
10467 break;
Chris Lattner9bad62c2008-01-04 18:04:52 +000010468 case Incompatible:
10469 DiagKind = diag::err_typecheck_convert_incompatible;
Anna Zaks3b402712011-07-28 19:51:27 +000010470 ConvHints.tryToFixConversion(SrcExpr, SrcType, DstType, *this);
10471 MayHaveConvFixit = true;
Chris Lattner9bad62c2008-01-04 18:04:52 +000010472 isInvalid = true;
Richard Trieucaff2472011-11-23 22:32:32 +000010473 MayHaveFunctionDiff = true;
Chris Lattner9bad62c2008-01-04 18:04:52 +000010474 break;
10475 }
Mike Stump4e1f26a2009-02-19 03:04:26 +000010476
Douglas Gregorc68e1402010-04-09 00:35:39 +000010477 QualType FirstType, SecondType;
10478 switch (Action) {
10479 case AA_Assigning:
10480 case AA_Initializing:
10481 // The destination type comes first.
10482 FirstType = DstType;
10483 SecondType = SrcType;
10484 break;
Alexis Huntc46382e2010-04-28 23:02:27 +000010485
Douglas Gregorc68e1402010-04-09 00:35:39 +000010486 case AA_Returning:
10487 case AA_Passing:
10488 case AA_Converting:
10489 case AA_Sending:
10490 case AA_Casting:
10491 // The source type comes first.
10492 FirstType = SrcType;
10493 SecondType = DstType;
10494 break;
10495 }
Alexis Huntc46382e2010-04-28 23:02:27 +000010496
Anna Zaks3b402712011-07-28 19:51:27 +000010497 PartialDiagnostic FDiag = PDiag(DiagKind);
10498 FDiag << FirstType << SecondType << Action << SrcExpr->getSourceRange();
10499
10500 // If we can fix the conversion, suggest the FixIts.
10501 assert(ConvHints.isNull() || Hint.isNull());
10502 if (!ConvHints.isNull()) {
Benjamin Kramer490afa62012-01-14 21:05:10 +000010503 for (std::vector<FixItHint>::iterator HI = ConvHints.Hints.begin(),
10504 HE = ConvHints.Hints.end(); HI != HE; ++HI)
Anna Zaks3b402712011-07-28 19:51:27 +000010505 FDiag << *HI;
10506 } else {
10507 FDiag << Hint;
10508 }
10509 if (MayHaveConvFixit) { FDiag << (unsigned) (ConvHints.Kind); }
10510
Richard Trieucaff2472011-11-23 22:32:32 +000010511 if (MayHaveFunctionDiff)
10512 HandleFunctionTypeMismatch(FDiag, SecondType, FirstType);
10513
Anna Zaks3b402712011-07-28 19:51:27 +000010514 Diag(Loc, FDiag);
10515
Richard Trieucaff2472011-11-23 22:32:32 +000010516 if (SecondType == Context.OverloadTy)
10517 NoteAllOverloadCandidates(OverloadExpr::find(SrcExpr).Expression,
10518 FirstType);
10519
Douglas Gregor33823722011-06-11 01:09:30 +000010520 if (CheckInferredResultType)
10521 EmitRelatedResultTypeNote(SrcExpr);
John McCall5ec7e7d2013-03-19 07:04:25 +000010522
10523 if (Action == AA_Returning && ConvTy == IncompatiblePointer)
10524 EmitRelatedResultTypeNoteForReturn(DstType);
Douglas Gregor33823722011-06-11 01:09:30 +000010525
Douglas Gregor4f4946a2010-04-22 00:20:18 +000010526 if (Complained)
10527 *Complained = true;
Chris Lattner9bad62c2008-01-04 18:04:52 +000010528 return isInvalid;
10529}
Anders Carlssone54e8a12008-11-30 19:50:32 +000010530
Richard Smithf4c51d92012-02-04 09:53:13 +000010531ExprResult Sema::VerifyIntegerConstantExpression(Expr *E,
10532 llvm::APSInt *Result) {
Douglas Gregore2b37442012-05-04 22:38:52 +000010533 class SimpleICEDiagnoser : public VerifyICEDiagnoser {
10534 public:
10535 virtual void diagnoseNotICE(Sema &S, SourceLocation Loc, SourceRange SR) {
10536 S.Diag(Loc, diag::err_expr_not_ice) << S.LangOpts.CPlusPlus << SR;
10537 }
10538 } Diagnoser;
10539
10540 return VerifyIntegerConstantExpression(E, Result, Diagnoser);
10541}
10542
10543ExprResult Sema::VerifyIntegerConstantExpression(Expr *E,
10544 llvm::APSInt *Result,
10545 unsigned DiagID,
10546 bool AllowFold) {
10547 class IDDiagnoser : public VerifyICEDiagnoser {
10548 unsigned DiagID;
10549
10550 public:
10551 IDDiagnoser(unsigned DiagID)
10552 : VerifyICEDiagnoser(DiagID == 0), DiagID(DiagID) { }
10553
10554 virtual void diagnoseNotICE(Sema &S, SourceLocation Loc, SourceRange SR) {
10555 S.Diag(Loc, DiagID) << SR;
10556 }
10557 } Diagnoser(DiagID);
10558
10559 return VerifyIntegerConstantExpression(E, Result, Diagnoser, AllowFold);
10560}
10561
10562void Sema::VerifyICEDiagnoser::diagnoseFold(Sema &S, SourceLocation Loc,
10563 SourceRange SR) {
10564 S.Diag(Loc, diag::ext_expr_not_ice) << SR << S.LangOpts.CPlusPlus;
Richard Smithf4c51d92012-02-04 09:53:13 +000010565}
10566
Benjamin Kramer33adaae2012-04-18 14:22:41 +000010567ExprResult
10568Sema::VerifyIntegerConstantExpression(Expr *E, llvm::APSInt *Result,
Douglas Gregore2b37442012-05-04 22:38:52 +000010569 VerifyICEDiagnoser &Diagnoser,
10570 bool AllowFold) {
Daniel Dunbar62ee6412012-03-09 18:35:03 +000010571 SourceLocation DiagLoc = E->getLocStart();
Richard Smithf4c51d92012-02-04 09:53:13 +000010572
Richard Smith2bf7fdb2013-01-02 11:42:31 +000010573 if (getLangOpts().CPlusPlus11) {
Richard Smithf4c51d92012-02-04 09:53:13 +000010574 // C++11 [expr.const]p5:
10575 // If an expression of literal class type is used in a context where an
10576 // integral constant expression is required, then that class type shall
10577 // have a single non-explicit conversion function to an integral or
10578 // unscoped enumeration type
10579 ExprResult Converted;
Richard Smithccc11812013-05-21 19:05:48 +000010580 class CXX11ConvertDiagnoser : public ICEConvertDiagnoser {
10581 public:
10582 CXX11ConvertDiagnoser(bool Silent)
10583 : ICEConvertDiagnoser(/*AllowScopedEnumerations*/false,
10584 Silent, true) {}
Douglas Gregore2b37442012-05-04 22:38:52 +000010585
Richard Smithccc11812013-05-21 19:05:48 +000010586 virtual SemaDiagnosticBuilder diagnoseNotInt(Sema &S, SourceLocation Loc,
10587 QualType T) {
10588 return S.Diag(Loc, diag::err_ice_not_integral) << T;
10589 }
10590
10591 virtual SemaDiagnosticBuilder diagnoseIncomplete(
10592 Sema &S, SourceLocation Loc, QualType T) {
10593 return S.Diag(Loc, diag::err_ice_incomplete_type) << T;
10594 }
10595
10596 virtual SemaDiagnosticBuilder diagnoseExplicitConv(
10597 Sema &S, SourceLocation Loc, QualType T, QualType ConvTy) {
10598 return S.Diag(Loc, diag::err_ice_explicit_conversion) << T << ConvTy;
10599 }
10600
10601 virtual SemaDiagnosticBuilder noteExplicitConv(
10602 Sema &S, CXXConversionDecl *Conv, QualType ConvTy) {
10603 return S.Diag(Conv->getLocation(), diag::note_ice_conversion_here)
10604 << ConvTy->isEnumeralType() << ConvTy;
10605 }
10606
10607 virtual SemaDiagnosticBuilder diagnoseAmbiguous(
10608 Sema &S, SourceLocation Loc, QualType T) {
10609 return S.Diag(Loc, diag::err_ice_ambiguous_conversion) << T;
10610 }
10611
10612 virtual SemaDiagnosticBuilder noteAmbiguous(
10613 Sema &S, CXXConversionDecl *Conv, QualType ConvTy) {
10614 return S.Diag(Conv->getLocation(), diag::note_ice_conversion_here)
10615 << ConvTy->isEnumeralType() << ConvTy;
10616 }
10617
10618 virtual SemaDiagnosticBuilder diagnoseConversion(
10619 Sema &S, SourceLocation Loc, QualType T, QualType ConvTy) {
10620 llvm_unreachable("conversion functions are permitted");
10621 }
10622 } ConvertDiagnoser(Diagnoser.Suppress);
10623
10624 Converted = PerformContextualImplicitConversion(DiagLoc, E,
10625 ConvertDiagnoser);
Richard Smithf4c51d92012-02-04 09:53:13 +000010626 if (Converted.isInvalid())
10627 return Converted;
10628 E = Converted.take();
10629 if (!E->getType()->isIntegralOrUnscopedEnumerationType())
10630 return ExprError();
10631 } else if (!E->getType()->isIntegralOrUnscopedEnumerationType()) {
10632 // An ICE must be of integral or unscoped enumeration type.
Douglas Gregore2b37442012-05-04 22:38:52 +000010633 if (!Diagnoser.Suppress)
10634 Diagnoser.diagnoseNotICE(*this, DiagLoc, E->getSourceRange());
Richard Smithf4c51d92012-02-04 09:53:13 +000010635 return ExprError();
10636 }
10637
Richard Smith902ca212011-12-14 23:32:26 +000010638 // Circumvent ICE checking in C++11 to avoid evaluating the expression twice
10639 // in the non-ICE case.
Richard Smith2bf7fdb2013-01-02 11:42:31 +000010640 if (!getLangOpts().CPlusPlus11 && E->isIntegerConstantExpr(Context)) {
Richard Smithf4c51d92012-02-04 09:53:13 +000010641 if (Result)
10642 *Result = E->EvaluateKnownConstInt(Context);
10643 return Owned(E);
Eli Friedmanbb967cc2009-04-25 22:26:58 +000010644 }
10645
Anders Carlssone54e8a12008-11-30 19:50:32 +000010646 Expr::EvalResult EvalResult;
Dmitri Gribenkof8579502013-01-12 19:30:44 +000010647 SmallVector<PartialDiagnosticAt, 8> Notes;
Richard Smith92b1ce02011-12-12 09:28:41 +000010648 EvalResult.Diag = &Notes;
Anders Carlssone54e8a12008-11-30 19:50:32 +000010649
Richard Smith902ca212011-12-14 23:32:26 +000010650 // Try to evaluate the expression, and produce diagnostics explaining why it's
10651 // not a constant expression as a side-effect.
10652 bool Folded = E->EvaluateAsRValue(EvalResult, Context) &&
10653 EvalResult.Val.isInt() && !EvalResult.HasSideEffects;
10654
10655 // In C++11, we can rely on diagnostics being produced for any expression
10656 // which is not a constant expression. If no diagnostics were produced, then
10657 // this is a constant expression.
Richard Smith2bf7fdb2013-01-02 11:42:31 +000010658 if (Folded && getLangOpts().CPlusPlus11 && Notes.empty()) {
Richard Smith902ca212011-12-14 23:32:26 +000010659 if (Result)
10660 *Result = EvalResult.Val.getInt();
Richard Smithf4c51d92012-02-04 09:53:13 +000010661 return Owned(E);
10662 }
10663
10664 // If our only note is the usual "invalid subexpression" note, just point
10665 // the caret at its location rather than producing an essentially
10666 // redundant note.
10667 if (Notes.size() == 1 && Notes[0].second.getDiagID() ==
10668 diag::note_invalid_subexpr_in_const_expr) {
10669 DiagLoc = Notes[0].first;
10670 Notes.clear();
Richard Smith902ca212011-12-14 23:32:26 +000010671 }
10672
10673 if (!Folded || !AllowFold) {
Douglas Gregore2b37442012-05-04 22:38:52 +000010674 if (!Diagnoser.Suppress) {
10675 Diagnoser.diagnoseNotICE(*this, DiagLoc, E->getSourceRange());
Richard Smith92b1ce02011-12-12 09:28:41 +000010676 for (unsigned I = 0, N = Notes.size(); I != N; ++I)
10677 Diag(Notes[I].first, Notes[I].second);
Anders Carlssone54e8a12008-11-30 19:50:32 +000010678 }
Mike Stump4e1f26a2009-02-19 03:04:26 +000010679
Richard Smithf4c51d92012-02-04 09:53:13 +000010680 return ExprError();
Anders Carlssone54e8a12008-11-30 19:50:32 +000010681 }
10682
Douglas Gregore2b37442012-05-04 22:38:52 +000010683 Diagnoser.diagnoseFold(*this, DiagLoc, E->getSourceRange());
Richard Smith2ec40612012-01-15 03:51:30 +000010684 for (unsigned I = 0, N = Notes.size(); I != N; ++I)
10685 Diag(Notes[I].first, Notes[I].second);
Mike Stump4e1f26a2009-02-19 03:04:26 +000010686
Anders Carlssone54e8a12008-11-30 19:50:32 +000010687 if (Result)
10688 *Result = EvalResult.Val.getInt();
Richard Smithf4c51d92012-02-04 09:53:13 +000010689 return Owned(E);
Anders Carlssone54e8a12008-11-30 19:50:32 +000010690}
Douglas Gregorc9c02ed2009-06-19 23:52:42 +000010691
Eli Friedman456f0182012-01-20 01:26:23 +000010692namespace {
10693 // Handle the case where we conclude a expression which we speculatively
10694 // considered to be unevaluated is actually evaluated.
10695 class TransformToPE : public TreeTransform<TransformToPE> {
10696 typedef TreeTransform<TransformToPE> BaseTransform;
10697
10698 public:
10699 TransformToPE(Sema &SemaRef) : BaseTransform(SemaRef) { }
10700
10701 // Make sure we redo semantic analysis
10702 bool AlwaysRebuild() { return true; }
10703
Eli Friedman5f0ca242012-02-06 23:29:57 +000010704 // Make sure we handle LabelStmts correctly.
10705 // FIXME: This does the right thing, but maybe we need a more general
10706 // fix to TreeTransform?
10707 StmtResult TransformLabelStmt(LabelStmt *S) {
10708 S->getDecl()->setStmt(0);
10709 return BaseTransform::TransformLabelStmt(S);
10710 }
10711
Eli Friedman456f0182012-01-20 01:26:23 +000010712 // We need to special-case DeclRefExprs referring to FieldDecls which
10713 // are not part of a member pointer formation; normal TreeTransforming
10714 // doesn't catch this case because of the way we represent them in the AST.
10715 // FIXME: This is a bit ugly; is it really the best way to handle this
10716 // case?
10717 //
10718 // Error on DeclRefExprs referring to FieldDecls.
10719 ExprResult TransformDeclRefExpr(DeclRefExpr *E) {
10720 if (isa<FieldDecl>(E->getDecl()) &&
David Blaikie131fcb42012-08-06 22:47:24 +000010721 !SemaRef.isUnevaluatedContext())
Eli Friedman456f0182012-01-20 01:26:23 +000010722 return SemaRef.Diag(E->getLocation(),
10723 diag::err_invalid_non_static_member_use)
10724 << E->getDecl() << E->getSourceRange();
10725
10726 return BaseTransform::TransformDeclRefExpr(E);
10727 }
10728
10729 // Exception: filter out member pointer formation
10730 ExprResult TransformUnaryOperator(UnaryOperator *E) {
10731 if (E->getOpcode() == UO_AddrOf && E->getType()->isMemberPointerType())
10732 return E;
10733
10734 return BaseTransform::TransformUnaryOperator(E);
10735 }
10736
Douglas Gregor89625492012-02-09 08:14:43 +000010737 ExprResult TransformLambdaExpr(LambdaExpr *E) {
10738 // Lambdas never need to be transformed.
10739 return E;
10740 }
Eli Friedman456f0182012-01-20 01:26:23 +000010741 };
Eli Friedmanfbc0dff2012-01-18 01:05:54 +000010742}
10743
Benjamin Kramerd81108f2012-11-14 15:08:31 +000010744ExprResult Sema::TransformToPotentiallyEvaluated(Expr *E) {
John McCallf413f5e2013-05-03 00:10:13 +000010745 assert(isUnevaluatedContext() &&
Eli Friedmane4f22df2012-02-29 04:03:55 +000010746 "Should only transform unevaluated expressions");
Eli Friedman456f0182012-01-20 01:26:23 +000010747 ExprEvalContexts.back().Context =
10748 ExprEvalContexts[ExprEvalContexts.size()-2].Context;
John McCallf413f5e2013-05-03 00:10:13 +000010749 if (isUnevaluatedContext())
Eli Friedman456f0182012-01-20 01:26:23 +000010750 return E;
10751 return TransformToPE(*this).TransformExpr(E);
Eli Friedmanfbc0dff2012-01-18 01:05:54 +000010752}
10753
Douglas Gregorff790f12009-11-26 00:44:06 +000010754void
Douglas Gregor7fcbd902012-02-21 00:37:24 +000010755Sema::PushExpressionEvaluationContext(ExpressionEvaluationContext NewContext,
Richard Smithfd555f62012-02-22 02:04:18 +000010756 Decl *LambdaContextDecl,
10757 bool IsDecltype) {
Douglas Gregorff790f12009-11-26 00:44:06 +000010758 ExprEvalContexts.push_back(
John McCall31168b02011-06-15 23:02:42 +000010759 ExpressionEvaluationContextRecord(NewContext,
John McCall28fc7092011-11-10 05:35:25 +000010760 ExprCleanupObjects.size(),
Douglas Gregor7fcbd902012-02-21 00:37:24 +000010761 ExprNeedsCleanups,
Richard Smithfd555f62012-02-22 02:04:18 +000010762 LambdaContextDecl,
10763 IsDecltype));
John McCall31168b02011-06-15 23:02:42 +000010764 ExprNeedsCleanups = false;
Eli Friedman3bda6b12012-02-02 23:15:15 +000010765 if (!MaybeODRUseExprs.empty())
10766 std::swap(MaybeODRUseExprs, ExprEvalContexts.back().SavedMaybeODRUseExprs);
Douglas Gregor0b6a6242009-06-22 20:57:11 +000010767}
10768
Eli Friedman15681d62012-09-26 04:34:21 +000010769void
10770Sema::PushExpressionEvaluationContext(ExpressionEvaluationContext NewContext,
10771 ReuseLambdaContextDecl_t,
10772 bool IsDecltype) {
Eli Friedman7e346a82013-07-01 20:22:57 +000010773 Decl *ClosureContextDecl = ExprEvalContexts.back().ManglingContextDecl;
10774 PushExpressionEvaluationContext(NewContext, ClosureContextDecl, IsDecltype);
Eli Friedman15681d62012-09-26 04:34:21 +000010775}
10776
Richard Trieucfc491d2011-08-02 04:35:43 +000010777void Sema::PopExpressionEvaluationContext() {
Eli Friedmanfa0df832012-02-02 03:46:19 +000010778 ExpressionEvaluationContextRecord& Rec = ExprEvalContexts.back();
Douglas Gregor0b6a6242009-06-22 20:57:11 +000010779
Douglas Gregor89625492012-02-09 08:14:43 +000010780 if (!Rec.Lambdas.empty()) {
John McCallf413f5e2013-05-03 00:10:13 +000010781 if (Rec.isUnevaluated()) {
Douglas Gregor89625492012-02-09 08:14:43 +000010782 // C++11 [expr.prim.lambda]p2:
10783 // A lambda-expression shall not appear in an unevaluated operand
10784 // (Clause 5).
10785 for (unsigned I = 0, N = Rec.Lambdas.size(); I != N; ++I)
10786 Diag(Rec.Lambdas[I]->getLocStart(),
10787 diag::err_lambda_unevaluated_operand);
10788 } else {
10789 // Mark the capture expressions odr-used. This was deferred
10790 // during lambda expression creation.
10791 for (unsigned I = 0, N = Rec.Lambdas.size(); I != N; ++I) {
10792 LambdaExpr *Lambda = Rec.Lambdas[I];
10793 for (LambdaExpr::capture_init_iterator
10794 C = Lambda->capture_init_begin(),
10795 CEnd = Lambda->capture_init_end();
10796 C != CEnd; ++C) {
10797 MarkDeclarationsReferencedInExpr(*C);
10798 }
10799 }
10800 }
10801 }
10802
Douglas Gregorff790f12009-11-26 00:44:06 +000010803 // When are coming out of an unevaluated context, clear out any
10804 // temporaries that we may have created as part of the evaluation of
10805 // the expression in that context: they aren't relevant because they
10806 // will never be constructed.
John McCallf413f5e2013-05-03 00:10:13 +000010807 if (Rec.isUnevaluated() || Rec.Context == ConstantEvaluated) {
John McCall28fc7092011-11-10 05:35:25 +000010808 ExprCleanupObjects.erase(ExprCleanupObjects.begin() + Rec.NumCleanupObjects,
10809 ExprCleanupObjects.end());
John McCall31168b02011-06-15 23:02:42 +000010810 ExprNeedsCleanups = Rec.ParentNeedsCleanups;
Eli Friedman3bda6b12012-02-02 23:15:15 +000010811 CleanupVarDeclMarking();
10812 std::swap(MaybeODRUseExprs, Rec.SavedMaybeODRUseExprs);
John McCall31168b02011-06-15 23:02:42 +000010813 // Otherwise, merge the contexts together.
10814 } else {
10815 ExprNeedsCleanups |= Rec.ParentNeedsCleanups;
Eli Friedman3bda6b12012-02-02 23:15:15 +000010816 MaybeODRUseExprs.insert(Rec.SavedMaybeODRUseExprs.begin(),
10817 Rec.SavedMaybeODRUseExprs.end());
John McCall31168b02011-06-15 23:02:42 +000010818 }
Eli Friedmanfa0df832012-02-02 03:46:19 +000010819
10820 // Pop the current expression evaluation context off the stack.
10821 ExprEvalContexts.pop_back();
Douglas Gregor0b6a6242009-06-22 20:57:11 +000010822}
Douglas Gregorc9c02ed2009-06-19 23:52:42 +000010823
John McCall31168b02011-06-15 23:02:42 +000010824void Sema::DiscardCleanupsInEvaluationContext() {
John McCall28fc7092011-11-10 05:35:25 +000010825 ExprCleanupObjects.erase(
10826 ExprCleanupObjects.begin() + ExprEvalContexts.back().NumCleanupObjects,
10827 ExprCleanupObjects.end());
John McCall31168b02011-06-15 23:02:42 +000010828 ExprNeedsCleanups = false;
Eli Friedman3bda6b12012-02-02 23:15:15 +000010829 MaybeODRUseExprs.clear();
John McCall31168b02011-06-15 23:02:42 +000010830}
10831
Eli Friedmane0afc982012-01-21 01:01:51 +000010832ExprResult Sema::HandleExprEvaluationContextForTypeof(Expr *E) {
10833 if (!E->getType()->isVariablyModifiedType())
10834 return E;
Benjamin Kramerd81108f2012-11-14 15:08:31 +000010835 return TransformToPotentiallyEvaluated(E);
Eli Friedmane0afc982012-01-21 01:01:51 +000010836}
10837
Benjamin Kramerbf8da9d2012-02-06 11:13:08 +000010838static bool IsPotentiallyEvaluatedContext(Sema &SemaRef) {
Douglas Gregorc9c02ed2009-06-19 23:52:42 +000010839 // Do not mark anything as "used" within a dependent context; wait for
10840 // an instantiation.
Eli Friedmanfa0df832012-02-02 03:46:19 +000010841 if (SemaRef.CurContext->isDependentContext())
10842 return false;
Mike Stump11289f42009-09-09 15:08:12 +000010843
Eli Friedmanfa0df832012-02-02 03:46:19 +000010844 switch (SemaRef.ExprEvalContexts.back().Context) {
10845 case Sema::Unevaluated:
John McCallf413f5e2013-05-03 00:10:13 +000010846 case Sema::UnevaluatedAbstract:
Douglas Gregor0b6a6242009-06-22 20:57:11 +000010847 // We are in an expression that is not potentially evaluated; do nothing.
Eli Friedman02b58512012-01-21 04:44:06 +000010848 // (Depending on how you read the standard, we actually do need to do
10849 // something here for null pointer constants, but the standard's
10850 // definition of a null pointer constant is completely crazy.)
Eli Friedmanfa0df832012-02-02 03:46:19 +000010851 return false;
Mike Stump11289f42009-09-09 15:08:12 +000010852
Eli Friedmanfa0df832012-02-02 03:46:19 +000010853 case Sema::ConstantEvaluated:
10854 case Sema::PotentiallyEvaluated:
Eli Friedman02b58512012-01-21 04:44:06 +000010855 // We are in a potentially evaluated expression (or a constant-expression
10856 // in C++03); we need to do implicit template instantiation, implicitly
10857 // define class members, and mark most declarations as used.
Eli Friedmanfa0df832012-02-02 03:46:19 +000010858 return true;
Mike Stump11289f42009-09-09 15:08:12 +000010859
Eli Friedmanfa0df832012-02-02 03:46:19 +000010860 case Sema::PotentiallyEvaluatedIfUsed:
Douglas Gregor8a01b2a2010-09-11 20:24:53 +000010861 // Referenced declarations will only be used if the construct in the
10862 // containing expression is used.
Eli Friedmanfa0df832012-02-02 03:46:19 +000010863 return false;
Douglas Gregor0b6a6242009-06-22 20:57:11 +000010864 }
Matt Beaumont-Gay248bc722012-02-02 18:35:35 +000010865 llvm_unreachable("Invalid context");
Eli Friedmanfa0df832012-02-02 03:46:19 +000010866}
10867
10868/// \brief Mark a function referenced, and check whether it is odr-used
10869/// (C++ [basic.def.odr]p2, C99 6.9p3)
10870void Sema::MarkFunctionReferenced(SourceLocation Loc, FunctionDecl *Func) {
10871 assert(Func && "No function?");
10872
10873 Func->setReferenced();
10874
Richard Smithe10d3042012-11-07 01:14:25 +000010875 // C++11 [basic.def.odr]p3:
10876 // A function whose name appears as a potentially-evaluated expression is
10877 // odr-used if it is the unique lookup result or the selected member of a
10878 // set of overloaded functions [...].
10879 //
10880 // We (incorrectly) mark overload resolution as an unevaluated context, so we
10881 // can just check that here. Skip the rest of this function if we've already
10882 // marked the function as used.
10883 if (Func->isUsed(false) || !IsPotentiallyEvaluatedContext(*this)) {
10884 // C++11 [temp.inst]p3:
10885 // Unless a function template specialization has been explicitly
10886 // instantiated or explicitly specialized, the function template
10887 // specialization is implicitly instantiated when the specialization is
10888 // referenced in a context that requires a function definition to exist.
10889 //
10890 // We consider constexpr function templates to be referenced in a context
10891 // that requires a definition to exist whenever they are referenced.
10892 //
10893 // FIXME: This instantiates constexpr functions too frequently. If this is
10894 // really an unevaluated context (and we're not just in the definition of a
10895 // function template or overload resolution or other cases which we
10896 // incorrectly consider to be unevaluated contexts), and we're not in a
10897 // subexpression which we actually need to evaluate (for instance, a
10898 // template argument, array bound or an expression in a braced-init-list),
10899 // we are not permitted to instantiate this constexpr function definition.
10900 //
10901 // FIXME: This also implicitly defines special members too frequently. They
10902 // are only supposed to be implicitly defined if they are odr-used, but they
10903 // are not odr-used from constant expressions in unevaluated contexts.
10904 // However, they cannot be referenced if they are deleted, and they are
10905 // deleted whenever the implicit definition of the special member would
10906 // fail.
10907 if (!Func->isConstexpr() || Func->getBody())
10908 return;
10909 CXXMethodDecl *MD = dyn_cast<CXXMethodDecl>(Func);
10910 if (!Func->isImplicitlyInstantiable() && (!MD || MD->isUserProvided()))
10911 return;
10912 }
Mike Stump11289f42009-09-09 15:08:12 +000010913
Douglas Gregorc9c02ed2009-06-19 23:52:42 +000010914 // Note that this declaration has been used.
Eli Friedmanfa0df832012-02-02 03:46:19 +000010915 if (CXXConstructorDecl *Constructor = dyn_cast<CXXConstructorDecl>(Func)) {
Richard Smith273c4e92012-02-26 07:51:39 +000010916 if (Constructor->isDefaulted() && !Constructor->isDeleted()) {
Sebastian Redl22653ba2011-08-30 19:58:05 +000010917 if (Constructor->isDefaultConstructor()) {
10918 if (Constructor->isTrivial())
10919 return;
10920 if (!Constructor->isUsed(false))
10921 DefineImplicitDefaultConstructor(Loc, Constructor);
10922 } else if (Constructor->isCopyConstructor()) {
10923 if (!Constructor->isUsed(false))
10924 DefineImplicitCopyConstructor(Loc, Constructor);
10925 } else if (Constructor->isMoveConstructor()) {
10926 if (!Constructor->isUsed(false))
10927 DefineImplicitMoveConstructor(Loc, Constructor);
10928 }
Richard Smithc2bc61b2013-03-18 21:12:30 +000010929 } else if (Constructor->getInheritedConstructor()) {
10930 if (!Constructor->isUsed(false))
10931 DefineInheritingConstructor(Loc, Constructor);
Fariborz Jahanian477d2422009-06-22 23:34:40 +000010932 }
Kovarththanan Rajaratnamba2c6522010-03-13 10:17:05 +000010933
Douglas Gregor88d292c2010-05-13 16:44:06 +000010934 MarkVTableUsed(Loc, Constructor->getParent());
Eli Friedmanfa0df832012-02-02 03:46:19 +000010935 } else if (CXXDestructorDecl *Destructor =
10936 dyn_cast<CXXDestructorDecl>(Func)) {
Richard Smith273c4e92012-02-26 07:51:39 +000010937 if (Destructor->isDefaulted() && !Destructor->isDeleted() &&
10938 !Destructor->isUsed(false))
Fariborz Jahanian24a175b2009-06-26 23:49:16 +000010939 DefineImplicitDestructor(Loc, Destructor);
Douglas Gregor88d292c2010-05-13 16:44:06 +000010940 if (Destructor->isVirtual())
10941 MarkVTableUsed(Loc, Destructor->getParent());
Eli Friedmanfa0df832012-02-02 03:46:19 +000010942 } else if (CXXMethodDecl *MethodDecl = dyn_cast<CXXMethodDecl>(Func)) {
Richard Smith273c4e92012-02-26 07:51:39 +000010943 if (MethodDecl->isDefaulted() && !MethodDecl->isDeleted() &&
10944 MethodDecl->isOverloadedOperator() &&
Fariborz Jahanian41f79272009-06-25 21:45:19 +000010945 MethodDecl->getOverloadedOperator() == OO_Equal) {
Sebastian Redl22653ba2011-08-30 19:58:05 +000010946 if (!MethodDecl->isUsed(false)) {
10947 if (MethodDecl->isCopyAssignmentOperator())
10948 DefineImplicitCopyAssignment(Loc, MethodDecl);
10949 else
10950 DefineImplicitMoveAssignment(Loc, MethodDecl);
10951 }
Douglas Gregord3b672c2012-02-16 01:06:16 +000010952 } else if (isa<CXXConversionDecl>(MethodDecl) &&
10953 MethodDecl->getParent()->isLambda()) {
10954 CXXConversionDecl *Conversion = cast<CXXConversionDecl>(MethodDecl);
10955 if (Conversion->isLambdaToBlockPointerConversion())
10956 DefineImplicitLambdaToBlockPointerConversion(Loc, Conversion);
10957 else
10958 DefineImplicitLambdaToFunctionPointerConversion(Loc, Conversion);
Douglas Gregor88d292c2010-05-13 16:44:06 +000010959 } else if (MethodDecl->isVirtual())
10960 MarkVTableUsed(Loc, MethodDecl->getParent());
Fariborz Jahanian41f79272009-06-25 21:45:19 +000010961 }
John McCall83779672011-02-19 02:53:41 +000010962
Eli Friedmanfa0df832012-02-02 03:46:19 +000010963 // Recursive functions should be marked when used from another function.
10964 // FIXME: Is this really right?
10965 if (CurContext == Func) return;
Kovarththanan Rajaratnamba2c6522010-03-13 10:17:05 +000010966
Richard Smithd3b5c9082012-07-27 04:22:15 +000010967 // Resolve the exception specification for any function which is
Richard Smithf623c962012-04-17 00:58:00 +000010968 // used: CodeGen will need it.
Richard Smithd3729422012-04-19 00:08:28 +000010969 const FunctionProtoType *FPT = Func->getType()->getAs<FunctionProtoType>();
Richard Smithd3b5c9082012-07-27 04:22:15 +000010970 if (FPT && isUnresolvedExceptionSpec(FPT->getExceptionSpecType()))
10971 ResolveExceptionSpec(Loc, FPT);
Richard Smithf623c962012-04-17 00:58:00 +000010972
Eli Friedmanfa0df832012-02-02 03:46:19 +000010973 // Implicit instantiation of function templates and member functions of
10974 // class templates.
10975 if (Func->isImplicitlyInstantiable()) {
10976 bool AlreadyInstantiated = false;
Richard Smith4a941e22012-02-14 22:25:15 +000010977 SourceLocation PointOfInstantiation = Loc;
Eli Friedmanfa0df832012-02-02 03:46:19 +000010978 if (FunctionTemplateSpecializationInfo *SpecInfo
10979 = Func->getTemplateSpecializationInfo()) {
10980 if (SpecInfo->getPointOfInstantiation().isInvalid())
10981 SpecInfo->setPointOfInstantiation(Loc);
10982 else if (SpecInfo->getTemplateSpecializationKind()
Richard Smith4a941e22012-02-14 22:25:15 +000010983 == TSK_ImplicitInstantiation) {
Eli Friedmanfa0df832012-02-02 03:46:19 +000010984 AlreadyInstantiated = true;
Richard Smith4a941e22012-02-14 22:25:15 +000010985 PointOfInstantiation = SpecInfo->getPointOfInstantiation();
10986 }
Eli Friedmanfa0df832012-02-02 03:46:19 +000010987 } else if (MemberSpecializationInfo *MSInfo
10988 = Func->getMemberSpecializationInfo()) {
10989 if (MSInfo->getPointOfInstantiation().isInvalid())
Douglas Gregor06db9f52009-10-12 20:18:28 +000010990 MSInfo->setPointOfInstantiation(Loc);
Eli Friedmanfa0df832012-02-02 03:46:19 +000010991 else if (MSInfo->getTemplateSpecializationKind()
Richard Smith4a941e22012-02-14 22:25:15 +000010992 == TSK_ImplicitInstantiation) {
Eli Friedmanfa0df832012-02-02 03:46:19 +000010993 AlreadyInstantiated = true;
Richard Smith4a941e22012-02-14 22:25:15 +000010994 PointOfInstantiation = MSInfo->getPointOfInstantiation();
10995 }
Douglas Gregor06db9f52009-10-12 20:18:28 +000010996 }
Mike Stump11289f42009-09-09 15:08:12 +000010997
Richard Smith4a941e22012-02-14 22:25:15 +000010998 if (!AlreadyInstantiated || Func->isConstexpr()) {
Eli Friedmanfa0df832012-02-02 03:46:19 +000010999 if (isa<CXXRecordDecl>(Func->getDeclContext()) &&
Faisal Vali18d35982013-06-26 02:34:24 +000011000 cast<CXXRecordDecl>(Func->getDeclContext())->isLocalClass() &&
11001 ActiveTemplateInstantiations.size())
Richard Smith4a941e22012-02-14 22:25:15 +000011002 PendingLocalImplicitInstantiations.push_back(
11003 std::make_pair(Func, PointOfInstantiation));
11004 else if (Func->isConstexpr())
Eli Friedmanfa0df832012-02-02 03:46:19 +000011005 // Do not defer instantiations of constexpr functions, to avoid the
11006 // expression evaluator needing to call back into Sema if it sees a
11007 // call to such a function.
Richard Smith4a941e22012-02-14 22:25:15 +000011008 InstantiateFunctionDefinition(PointOfInstantiation, Func);
Argyrios Kyrtzidise5dc5b32012-02-10 20:10:44 +000011009 else {
Richard Smith4a941e22012-02-14 22:25:15 +000011010 PendingInstantiations.push_back(std::make_pair(Func,
11011 PointOfInstantiation));
Argyrios Kyrtzidise5dc5b32012-02-10 20:10:44 +000011012 // Notify the consumer that a function was implicitly instantiated.
11013 Consumer.HandleCXXImplicitFunctionInstantiation(Func);
11014 }
John McCall83779672011-02-19 02:53:41 +000011015 }
Eli Friedmanfa0df832012-02-02 03:46:19 +000011016 } else {
11017 // Walk redefinitions, as some of them may be instantiable.
11018 for (FunctionDecl::redecl_iterator i(Func->redecls_begin()),
11019 e(Func->redecls_end()); i != e; ++i) {
11020 if (!i->isUsed(false) && i->isImplicitlyInstantiable())
11021 MarkFunctionReferenced(Loc, *i);
11022 }
Sam Weinigbae69142009-09-11 03:29:30 +000011023 }
Eli Friedmanfa0df832012-02-02 03:46:19 +000011024
11025 // Keep track of used but undefined functions.
Nick Lewycky9c7eb1d2013-02-01 08:13:20 +000011026 if (!Func->isDefined()) {
Rafael Espindola0e0d0092013-03-14 03:07:35 +000011027 if (mightHaveNonExternalLinkage(Func))
Nick Lewycky9c7eb1d2013-02-01 08:13:20 +000011028 UndefinedButUsed.insert(std::make_pair(Func->getCanonicalDecl(), Loc));
11029 else if (Func->getMostRecentDecl()->isInlined() &&
11030 (LangOpts.CPlusPlus || !LangOpts.GNUInline) &&
11031 !Func->getMostRecentDecl()->hasAttr<GNUInlineAttr>())
11032 UndefinedButUsed.insert(std::make_pair(Func->getCanonicalDecl(), Loc));
Eli Friedmanfa0df832012-02-02 03:46:19 +000011033 }
11034
Rafael Espindola820fa702013-01-08 19:43:34 +000011035 // Normally the must current decl is marked used while processing the use and
11036 // any subsequent decls are marked used by decl merging. This fails with
11037 // template instantiation since marking can happen at the end of the file
11038 // and, because of the two phase lookup, this function is called with at
11039 // decl in the middle of a decl chain. We loop to maintain the invariant
11040 // that once a decl is used, all decls after it are also used.
Rafael Espindolaf26d5392013-01-08 19:58:34 +000011041 for (FunctionDecl *F = Func->getMostRecentDecl();; F = F->getPreviousDecl()) {
Rafael Espindola820fa702013-01-08 19:43:34 +000011042 F->setUsed(true);
11043 if (F == Func)
11044 break;
Rafael Espindola820fa702013-01-08 19:43:34 +000011045 }
Eli Friedmanfa0df832012-02-02 03:46:19 +000011046}
11047
Eli Friedman9bb33f52012-02-03 02:04:35 +000011048static void
11049diagnoseUncapturableValueReference(Sema &S, SourceLocation loc,
11050 VarDecl *var, DeclContext *DC) {
Eli Friedmandd053f62012-02-07 00:15:00 +000011051 DeclContext *VarDC = var->getDeclContext();
11052
Eli Friedman9bb33f52012-02-03 02:04:35 +000011053 // If the parameter still belongs to the translation unit, then
11054 // we're actually just using one parameter in the declaration of
11055 // the next.
11056 if (isa<ParmVarDecl>(var) &&
Eli Friedmandd053f62012-02-07 00:15:00 +000011057 isa<TranslationUnitDecl>(VarDC))
Eli Friedman9bb33f52012-02-03 02:04:35 +000011058 return;
11059
Eli Friedmandd053f62012-02-07 00:15:00 +000011060 // For C code, don't diagnose about capture if we're not actually in code
11061 // right now; it's impossible to write a non-constant expression outside of
11062 // function context, so we'll get other (more useful) diagnostics later.
11063 //
11064 // For C++, things get a bit more nasty... it would be nice to suppress this
11065 // diagnostic for certain cases like using a local variable in an array bound
11066 // for a member of a local class, but the correct predicate is not obvious.
David Blaikiebbafb8a2012-03-11 07:00:24 +000011067 if (!S.getLangOpts().CPlusPlus && !S.CurContext->isFunctionOrMethod())
Eli Friedman9bb33f52012-02-03 02:04:35 +000011068 return;
11069
Eli Friedmandd053f62012-02-07 00:15:00 +000011070 if (isa<CXXMethodDecl>(VarDC) &&
11071 cast<CXXRecordDecl>(VarDC->getParent())->isLambda()) {
11072 S.Diag(loc, diag::err_reference_to_local_var_in_enclosing_lambda)
11073 << var->getIdentifier();
11074 } else if (FunctionDecl *fn = dyn_cast<FunctionDecl>(VarDC)) {
11075 S.Diag(loc, diag::err_reference_to_local_var_in_enclosing_function)
11076 << var->getIdentifier() << fn->getDeclName();
11077 } else if (isa<BlockDecl>(VarDC)) {
11078 S.Diag(loc, diag::err_reference_to_local_var_in_enclosing_block)
11079 << var->getIdentifier();
11080 } else {
11081 // FIXME: Is there any other context where a local variable can be
11082 // declared?
11083 S.Diag(loc, diag::err_reference_to_local_var_in_enclosing_context)
11084 << var->getIdentifier();
11085 }
Eli Friedman9bb33f52012-02-03 02:04:35 +000011086
Eli Friedman9bb33f52012-02-03 02:04:35 +000011087 S.Diag(var->getLocation(), diag::note_local_variable_declared_here)
11088 << var->getIdentifier();
Eli Friedmandd053f62012-02-07 00:15:00 +000011089
11090 // FIXME: Add additional diagnostic info about class etc. which prevents
11091 // capture.
Eli Friedman9bb33f52012-02-03 02:04:35 +000011092}
11093
Tareq A. Siraj6dfa25a2013-04-16 19:37:38 +000011094/// \brief Capture the given variable in the captured region.
11095static ExprResult captureInCapturedRegion(Sema &S, CapturedRegionScopeInfo *RSI,
11096 VarDecl *Var, QualType FieldType,
11097 QualType DeclRefType,
11098 SourceLocation Loc,
11099 bool RefersToEnclosingLocal) {
11100 // The current implemention assumes that all variables are captured
11101 // by references. Since there is no capture by copy, no expression evaluation
11102 // will be needed.
11103 //
11104 RecordDecl *RD = RSI->TheRecordDecl;
11105
11106 FieldDecl *Field
11107 = FieldDecl::Create(S.Context, RD, Loc, Loc, 0, FieldType,
11108 S.Context.getTrivialTypeSourceInfo(FieldType, Loc),
11109 0, false, ICIS_NoInit);
11110 Field->setImplicit(true);
11111 Field->setAccess(AS_private);
11112 RD->addDecl(Field);
11113
11114 Expr *Ref = new (S.Context) DeclRefExpr(Var, RefersToEnclosingLocal,
11115 DeclRefType, VK_LValue, Loc);
11116 Var->setReferenced(true);
11117 Var->setUsed(true);
11118
11119 return Ref;
11120}
11121
Douglas Gregor81495f32012-02-12 18:42:33 +000011122/// \brief Capture the given variable in the given lambda expression.
11123static ExprResult captureInLambda(Sema &S, LambdaScopeInfo *LSI,
Douglas Gregorfdf598e2012-02-18 09:37:24 +000011124 VarDecl *Var, QualType FieldType,
11125 QualType DeclRefType,
Douglas Gregora8182f92012-05-16 17:01:33 +000011126 SourceLocation Loc,
11127 bool RefersToEnclosingLocal) {
Douglas Gregor81495f32012-02-12 18:42:33 +000011128 CXXRecordDecl *Lambda = LSI->Lambda;
Douglas Gregor81495f32012-02-12 18:42:33 +000011129
Douglas Gregorabecb9c2012-02-09 01:56:40 +000011130 // Build the non-static data member.
11131 FieldDecl *Field
11132 = FieldDecl::Create(S.Context, Lambda, Loc, Loc, 0, FieldType,
11133 S.Context.getTrivialTypeSourceInfo(FieldType, Loc),
Richard Smith2b013182012-06-10 03:12:00 +000011134 0, false, ICIS_NoInit);
Douglas Gregorabecb9c2012-02-09 01:56:40 +000011135 Field->setImplicit(true);
11136 Field->setAccess(AS_private);
Douglas Gregor3d23f7882012-02-09 02:12:34 +000011137 Lambda->addDecl(Field);
Douglas Gregorabecb9c2012-02-09 01:56:40 +000011138
11139 // C++11 [expr.prim.lambda]p21:
11140 // When the lambda-expression is evaluated, the entities that
11141 // are captured by copy are used to direct-initialize each
11142 // corresponding non-static data member of the resulting closure
11143 // object. (For array members, the array elements are
11144 // direct-initialized in increasing subscript order.) These
11145 // initializations are performed in the (unspecified) order in
11146 // which the non-static data members are declared.
Douglas Gregorabecb9c2012-02-09 01:56:40 +000011147
Douglas Gregor89625492012-02-09 08:14:43 +000011148 // Introduce a new evaluation context for the initialization, so
11149 // that temporaries introduced as part of the capture are retained
11150 // to be re-"exported" from the lambda expression itself.
John McCalleaef89b2013-03-22 02:10:40 +000011151 EnterExpressionEvaluationContext scope(S, Sema::PotentiallyEvaluated);
Douglas Gregorabecb9c2012-02-09 01:56:40 +000011152
Douglas Gregorf02455e2012-02-10 09:26:04 +000011153 // C++ [expr.prim.labda]p12:
11154 // An entity captured by a lambda-expression is odr-used (3.2) in
11155 // the scope containing the lambda-expression.
Douglas Gregora8182f92012-05-16 17:01:33 +000011156 Expr *Ref = new (S.Context) DeclRefExpr(Var, RefersToEnclosingLocal,
11157 DeclRefType, VK_LValue, Loc);
Eli Friedman23b1be92012-03-01 21:32:56 +000011158 Var->setReferenced(true);
Douglas Gregorf02455e2012-02-10 09:26:04 +000011159 Var->setUsed(true);
Douglas Gregor199cec72012-02-09 02:45:47 +000011160
11161 // When the field has array type, create index variables for each
11162 // dimension of the array. We use these index variables to subscript
11163 // the source array, and other clients (e.g., CodeGen) will perform
11164 // the necessary iteration with these index variables.
11165 SmallVector<VarDecl *, 4> IndexVariables;
Douglas Gregor199cec72012-02-09 02:45:47 +000011166 QualType BaseType = FieldType;
11167 QualType SizeType = S.Context.getSizeType();
Douglas Gregor54fcea62012-02-13 16:35:30 +000011168 LSI->ArrayIndexStarts.push_back(LSI->ArrayIndexVars.size());
Douglas Gregor199cec72012-02-09 02:45:47 +000011169 while (const ConstantArrayType *Array
11170 = S.Context.getAsConstantArrayType(BaseType)) {
Douglas Gregor199cec72012-02-09 02:45:47 +000011171 // Create the iteration variable for this array index.
11172 IdentifierInfo *IterationVarName = 0;
11173 {
11174 SmallString<8> Str;
11175 llvm::raw_svector_ostream OS(Str);
11176 OS << "__i" << IndexVariables.size();
11177 IterationVarName = &S.Context.Idents.get(OS.str());
11178 }
11179 VarDecl *IterationVar
11180 = VarDecl::Create(S.Context, S.CurContext, Loc, Loc,
11181 IterationVarName, SizeType,
11182 S.Context.getTrivialTypeSourceInfo(SizeType, Loc),
Rafael Espindola6ae7e502013-04-03 19:27:57 +000011183 SC_None);
Douglas Gregor199cec72012-02-09 02:45:47 +000011184 IndexVariables.push_back(IterationVar);
Douglas Gregor54fcea62012-02-13 16:35:30 +000011185 LSI->ArrayIndexVars.push_back(IterationVar);
11186
Douglas Gregor199cec72012-02-09 02:45:47 +000011187 // Create a reference to the iteration variable.
11188 ExprResult IterationVarRef
11189 = S.BuildDeclRefExpr(IterationVar, SizeType, VK_LValue, Loc);
11190 assert(!IterationVarRef.isInvalid() &&
11191 "Reference to invented variable cannot fail!");
11192 IterationVarRef = S.DefaultLvalueConversion(IterationVarRef.take());
11193 assert(!IterationVarRef.isInvalid() &&
11194 "Conversion of invented variable cannot fail!");
11195
11196 // Subscript the array with this iteration variable.
11197 ExprResult Subscript = S.CreateBuiltinArraySubscriptExpr(
11198 Ref, Loc, IterationVarRef.take(), Loc);
11199 if (Subscript.isInvalid()) {
11200 S.CleanupVarDeclMarking();
11201 S.DiscardCleanupsInEvaluationContext();
Douglas Gregor199cec72012-02-09 02:45:47 +000011202 return ExprError();
11203 }
11204
11205 Ref = Subscript.take();
11206 BaseType = Array->getElementType();
11207 }
11208
11209 // Construct the entity that we will be initializing. For an array, this
11210 // will be first element in the array, which may require several levels
11211 // of array-subscript entities.
11212 SmallVector<InitializedEntity, 4> Entities;
11213 Entities.reserve(1 + IndexVariables.size());
Douglas Gregor19666fb2012-02-15 16:57:26 +000011214 Entities.push_back(
11215 InitializedEntity::InitializeLambdaCapture(Var, Field, Loc));
Douglas Gregor199cec72012-02-09 02:45:47 +000011216 for (unsigned I = 0, N = IndexVariables.size(); I != N; ++I)
11217 Entities.push_back(InitializedEntity::InitializeElement(S.Context,
11218 0,
11219 Entities.back()));
11220
Douglas Gregorabecb9c2012-02-09 01:56:40 +000011221 InitializationKind InitKind
11222 = InitializationKind::CreateDirect(Loc, Loc, Loc);
Dmitri Gribenko8f8930f2013-05-03 15:05:50 +000011223 InitializationSequence Init(S, Entities.back(), InitKind, Ref);
Douglas Gregorabecb9c2012-02-09 01:56:40 +000011224 ExprResult Result(true);
Dmitri Gribenko8f8930f2013-05-03 15:05:50 +000011225 if (!Init.Diagnose(S, Entities.back(), InitKind, Ref))
Benjamin Kramercc4c49d2012-08-23 23:38:35 +000011226 Result = Init.Perform(S, Entities.back(), InitKind, Ref);
Douglas Gregorabecb9c2012-02-09 01:56:40 +000011227
11228 // If this initialization requires any cleanups (e.g., due to a
11229 // default argument to a copy constructor), note that for the
11230 // lambda.
11231 if (S.ExprNeedsCleanups)
11232 LSI->ExprNeedsCleanups = true;
11233
11234 // Exit the expression evaluation context used for the capture.
11235 S.CleanupVarDeclMarking();
11236 S.DiscardCleanupsInEvaluationContext();
Douglas Gregorabecb9c2012-02-09 01:56:40 +000011237 return Result;
Douglas Gregor199cec72012-02-09 02:45:47 +000011238}
Douglas Gregorabecb9c2012-02-09 01:56:40 +000011239
Douglas Gregorfdf598e2012-02-18 09:37:24 +000011240bool Sema::tryCaptureVariable(VarDecl *Var, SourceLocation Loc,
11241 TryCaptureKind Kind, SourceLocation EllipsisLoc,
11242 bool BuildAndDiagnose,
11243 QualType &CaptureType,
11244 QualType &DeclRefType) {
11245 bool Nested = false;
Douglas Gregor81495f32012-02-12 18:42:33 +000011246
Eli Friedman24af8502012-02-03 22:47:37 +000011247 DeclContext *DC = CurContext;
Douglas Gregorfdf598e2012-02-18 09:37:24 +000011248 if (Var->getDeclContext() == DC) return true;
11249 if (!Var->hasLocalStorage()) return true;
Eli Friedman9bb33f52012-02-03 02:04:35 +000011250
Douglas Gregor81495f32012-02-12 18:42:33 +000011251 bool HasBlocksAttr = Var->hasAttr<BlocksAttr>();
Eli Friedman9bb33f52012-02-03 02:04:35 +000011252
Douglas Gregorfdf598e2012-02-18 09:37:24 +000011253 // Walk up the stack to determine whether we can capture the variable,
11254 // performing the "simple" checks that don't depend on type. We stop when
11255 // we've either hit the declared scope of the variable or find an existing
11256 // capture of that variable.
11257 CaptureType = Var->getType();
11258 DeclRefType = CaptureType.getNonReferenceType();
11259 bool Explicit = (Kind != TryCapture_Implicit);
11260 unsigned FunctionScopesIndex = FunctionScopes.size() - 1;
Eli Friedman9bb33f52012-02-03 02:04:35 +000011261 do {
Tareq A. Siraj6dfa25a2013-04-16 19:37:38 +000011262 // Only block literals, captured statements, and lambda expressions can
11263 // capture; other scopes don't work.
Eli Friedman24af8502012-02-03 22:47:37 +000011264 DeclContext *ParentDC;
Tareq A. Siraj6dfa25a2013-04-16 19:37:38 +000011265 if (isa<BlockDecl>(DC) || isa<CapturedDecl>(DC))
Eli Friedman24af8502012-02-03 22:47:37 +000011266 ParentDC = DC->getParent();
11267 else if (isa<CXXMethodDecl>(DC) &&
Douglas Gregor81495f32012-02-12 18:42:33 +000011268 cast<CXXMethodDecl>(DC)->getOverloadedOperator() == OO_Call &&
Eli Friedman24af8502012-02-03 22:47:37 +000011269 cast<CXXRecordDecl>(DC->getParent())->isLambda())
11270 ParentDC = DC->getParent()->getParent();
Douglas Gregor81495f32012-02-12 18:42:33 +000011271 else {
Douglas Gregorfdf598e2012-02-18 09:37:24 +000011272 if (BuildAndDiagnose)
Douglas Gregor81495f32012-02-12 18:42:33 +000011273 diagnoseUncapturableValueReference(*this, Loc, Var, DC);
Douglas Gregorfdf598e2012-02-18 09:37:24 +000011274 return true;
Douglas Gregor81495f32012-02-12 18:42:33 +000011275 }
Eli Friedman9bb33f52012-02-03 02:04:35 +000011276
Eli Friedman24af8502012-02-03 22:47:37 +000011277 CapturingScopeInfo *CSI =
Douglas Gregor81495f32012-02-12 18:42:33 +000011278 cast<CapturingScopeInfo>(FunctionScopes[FunctionScopesIndex]);
Eli Friedman9bb33f52012-02-03 02:04:35 +000011279
Eli Friedman24af8502012-02-03 22:47:37 +000011280 // Check whether we've already captured it.
Richard Smithba71c082013-05-16 06:20:58 +000011281 if (CSI->isCaptured(Var)) {
11282 const CapturingScopeInfo::Capture &Cap = CSI->getCapture(Var);
11283
Douglas Gregorfdf598e2012-02-18 09:37:24 +000011284 // If we found a capture, any subcaptures are nested.
Eli Friedman9bb33f52012-02-03 02:04:35 +000011285 Nested = true;
Douglas Gregorfdf598e2012-02-18 09:37:24 +000011286
11287 // Retrieve the capture type for this variable.
Richard Smithba71c082013-05-16 06:20:58 +000011288 CaptureType = Cap.getCaptureType();
Douglas Gregorfdf598e2012-02-18 09:37:24 +000011289
11290 // Compute the type of an expression that refers to this variable.
11291 DeclRefType = CaptureType.getNonReferenceType();
11292
Douglas Gregorfdf598e2012-02-18 09:37:24 +000011293 if (Cap.isCopyCapture() &&
11294 !(isa<LambdaScopeInfo>(CSI) && cast<LambdaScopeInfo>(CSI)->Mutable))
11295 DeclRefType.addConst();
Eli Friedman9bb33f52012-02-03 02:04:35 +000011296 break;
11297 }
11298
Douglas Gregor81495f32012-02-12 18:42:33 +000011299 bool IsBlock = isa<BlockScopeInfo>(CSI);
Tareq A. Siraj6dfa25a2013-04-16 19:37:38 +000011300 bool IsLambda = isa<LambdaScopeInfo>(CSI);
Eli Friedman24af8502012-02-03 22:47:37 +000011301
11302 // Lambdas are not allowed to capture unnamed variables
11303 // (e.g. anonymous unions).
11304 // FIXME: The C++11 rule don't actually state this explicitly, but I'm
11305 // assuming that's the intent.
Douglas Gregor81495f32012-02-12 18:42:33 +000011306 if (IsLambda && !Var->getDeclName()) {
Douglas Gregorfdf598e2012-02-18 09:37:24 +000011307 if (BuildAndDiagnose) {
Douglas Gregor81495f32012-02-12 18:42:33 +000011308 Diag(Loc, diag::err_lambda_capture_anonymous_var);
11309 Diag(Var->getLocation(), diag::note_declared_at);
11310 }
Douglas Gregorfdf598e2012-02-18 09:37:24 +000011311 return true;
Eli Friedman24af8502012-02-03 22:47:37 +000011312 }
11313
11314 // Prohibit variably-modified types; they're difficult to deal with.
Douglas Gregorfdf598e2012-02-18 09:37:24 +000011315 if (Var->getType()->isVariablyModifiedType()) {
11316 if (BuildAndDiagnose) {
Douglas Gregor81495f32012-02-12 18:42:33 +000011317 if (IsBlock)
11318 Diag(Loc, diag::err_ref_vm_type);
11319 else
11320 Diag(Loc, diag::err_lambda_capture_vm_type) << Var->getDeclName();
11321 Diag(Var->getLocation(), diag::note_previous_decl)
11322 << Var->getDeclName();
11323 }
Douglas Gregorfdf598e2012-02-18 09:37:24 +000011324 return true;
Eli Friedman9bb33f52012-02-03 02:04:35 +000011325 }
Fariborz Jahanian5eae4ad2013-01-08 23:48:48 +000011326 // Prohibit structs with flexible array members too.
Fariborz Jahaniana716a342013-01-08 23:17:51 +000011327 // We cannot capture what is in the tail end of the struct.
11328 if (const RecordType *VTTy = Var->getType()->getAs<RecordType>()) {
Fariborz Jahanian14da4402013-01-09 00:09:15 +000011329 if (VTTy->getDecl()->hasFlexibleArrayMember()) {
Fariborz Jahaniana716a342013-01-08 23:17:51 +000011330 if (BuildAndDiagnose) {
11331 if (IsBlock)
11332 Diag(Loc, diag::err_ref_flexarray_type);
Fariborz Jahanian14da4402013-01-09 00:09:15 +000011333 else
11334 Diag(Loc, diag::err_lambda_capture_flexarray_type)
11335 << Var->getDeclName();
Fariborz Jahaniana716a342013-01-08 23:17:51 +000011336 Diag(Var->getLocation(), diag::note_previous_decl)
11337 << Var->getDeclName();
11338 }
11339 return true;
11340 }
11341 }
Ben Langmuir3b4c30b2013-05-09 19:17:11 +000011342 // Lambdas and captured statements are not allowed to capture __block
11343 // variables; they don't support the expected semantics.
11344 if (HasBlocksAttr && (IsLambda || isa<CapturedRegionScopeInfo>(CSI))) {
Douglas Gregorfdf598e2012-02-18 09:37:24 +000011345 if (BuildAndDiagnose) {
Ben Langmuir3b4c30b2013-05-09 19:17:11 +000011346 Diag(Loc, diag::err_capture_block_variable)
11347 << Var->getDeclName() << !IsLambda;
Douglas Gregor81495f32012-02-12 18:42:33 +000011348 Diag(Var->getLocation(), diag::note_previous_decl)
11349 << Var->getDeclName();
11350 }
Douglas Gregorfdf598e2012-02-18 09:37:24 +000011351 return true;
Eli Friedman24af8502012-02-03 22:47:37 +000011352 }
11353
Douglas Gregor81495f32012-02-12 18:42:33 +000011354 if (CSI->ImpCaptureStyle == CapturingScopeInfo::ImpCap_None && !Explicit) {
11355 // No capture-default
Douglas Gregorfdf598e2012-02-18 09:37:24 +000011356 if (BuildAndDiagnose) {
Douglas Gregor81495f32012-02-12 18:42:33 +000011357 Diag(Loc, diag::err_lambda_impcap) << Var->getDeclName();
11358 Diag(Var->getLocation(), diag::note_previous_decl)
11359 << Var->getDeclName();
11360 Diag(cast<LambdaScopeInfo>(CSI)->Lambda->getLocStart(),
11361 diag::note_lambda_decl);
11362 }
Douglas Gregorfdf598e2012-02-18 09:37:24 +000011363 return true;
Douglas Gregor81495f32012-02-12 18:42:33 +000011364 }
11365
11366 FunctionScopesIndex--;
11367 DC = ParentDC;
11368 Explicit = false;
11369 } while (!Var->getDeclContext()->Equals(DC));
11370
Douglas Gregorfdf598e2012-02-18 09:37:24 +000011371 // Walk back down the scope stack, computing the type of the capture at
11372 // each step, checking type-specific requirements, and adding captures if
11373 // requested.
11374 for (unsigned I = ++FunctionScopesIndex, N = FunctionScopes.size(); I != N;
11375 ++I) {
11376 CapturingScopeInfo *CSI = cast<CapturingScopeInfo>(FunctionScopes[I]);
Douglas Gregor812d8f62012-02-18 05:51:20 +000011377
Douglas Gregorfdf598e2012-02-18 09:37:24 +000011378 // Compute the type of the capture and of a reference to the capture within
11379 // this scope.
11380 if (isa<BlockScopeInfo>(CSI)) {
11381 Expr *CopyExpr = 0;
11382 bool ByRef = false;
11383
11384 // Blocks are not allowed to capture arrays.
11385 if (CaptureType->isArrayType()) {
11386 if (BuildAndDiagnose) {
11387 Diag(Loc, diag::err_ref_array_type);
11388 Diag(Var->getLocation(), diag::note_previous_decl)
11389 << Var->getDeclName();
11390 }
11391 return true;
11392 }
11393
John McCall67cd5e02012-03-30 05:23:48 +000011394 // Forbid the block-capture of autoreleasing variables.
11395 if (CaptureType.getObjCLifetime() == Qualifiers::OCL_Autoreleasing) {
11396 if (BuildAndDiagnose) {
11397 Diag(Loc, diag::err_arc_autoreleasing_capture)
11398 << /*block*/ 0;
11399 Diag(Var->getLocation(), diag::note_previous_decl)
11400 << Var->getDeclName();
11401 }
11402 return true;
11403 }
11404
Douglas Gregorfdf598e2012-02-18 09:37:24 +000011405 if (HasBlocksAttr || CaptureType->isReferenceType()) {
11406 // Block capture by reference does not change the capture or
11407 // declaration reference types.
11408 ByRef = true;
11409 } else {
11410 // Block capture by copy introduces 'const'.
11411 CaptureType = CaptureType.getNonReferenceType().withConst();
11412 DeclRefType = CaptureType;
11413
David Blaikiebbafb8a2012-03-11 07:00:24 +000011414 if (getLangOpts().CPlusPlus && BuildAndDiagnose) {
Douglas Gregorfdf598e2012-02-18 09:37:24 +000011415 if (const RecordType *Record = DeclRefType->getAs<RecordType>()) {
11416 // The capture logic needs the destructor, so make sure we mark it.
11417 // Usually this is unnecessary because most local variables have
11418 // their destructors marked at declaration time, but parameters are
11419 // an exception because it's technically only the call site that
11420 // actually requires the destructor.
11421 if (isa<ParmVarDecl>(Var))
11422 FinalizeVarWithDestructor(Var, Record);
Douglas Gregorc4017552012-12-01 01:01:09 +000011423
John McCalleaef89b2013-03-22 02:10:40 +000011424 // Enter a new evaluation context to insulate the copy
11425 // full-expression.
11426 EnterExpressionEvaluationContext scope(*this, PotentiallyEvaluated);
11427
Douglas Gregorfdf598e2012-02-18 09:37:24 +000011428 // According to the blocks spec, the capture of a variable from
11429 // the stack requires a const copy constructor. This is not true
11430 // of the copy/move done to move a __block variable to the heap.
Douglas Gregorc4017552012-12-01 01:01:09 +000011431 Expr *DeclRef = new (Context) DeclRefExpr(Var, Nested,
Douglas Gregorfdf598e2012-02-18 09:37:24 +000011432 DeclRefType.withConst(),
11433 VK_LValue, Loc);
Douglas Gregorc4017552012-12-01 01:01:09 +000011434
Douglas Gregorfdf598e2012-02-18 09:37:24 +000011435 ExprResult Result
11436 = PerformCopyInitialization(
11437 InitializedEntity::InitializeBlock(Var->getLocation(),
11438 CaptureType, false),
11439 Loc, Owned(DeclRef));
11440
11441 // Build a full-expression copy expression if initialization
11442 // succeeded and used a non-trivial constructor. Recover from
11443 // errors by pretending that the copy isn't necessary.
11444 if (!Result.isInvalid() &&
11445 !cast<CXXConstructExpr>(Result.get())->getConstructor()
11446 ->isTrivial()) {
11447 Result = MaybeCreateExprWithCleanups(Result);
11448 CopyExpr = Result.take();
11449 }
11450 }
11451 }
11452 }
11453
11454 // Actually capture the variable.
11455 if (BuildAndDiagnose)
11456 CSI->addCapture(Var, HasBlocksAttr, ByRef, Nested, Loc,
11457 SourceLocation(), CaptureType, CopyExpr);
11458 Nested = true;
11459 continue;
Tareq A. Siraj6dfa25a2013-04-16 19:37:38 +000011460 }
11461
11462 if (CapturedRegionScopeInfo *RSI = dyn_cast<CapturedRegionScopeInfo>(CSI)) {
11463 // By default, capture variables by reference.
11464 bool ByRef = true;
11465 // Using an LValue reference type is consistent with Lambdas (see below).
11466 CaptureType = Context.getLValueReferenceType(DeclRefType);
11467
11468 Expr *CopyExpr = 0;
11469 if (BuildAndDiagnose) {
11470 ExprResult Result = captureInCapturedRegion(*this, RSI, Var,
11471 CaptureType, DeclRefType,
11472 Loc, Nested);
11473 if (!Result.isInvalid())
11474 CopyExpr = Result.take();
11475 }
11476
11477 // Actually capture the variable.
11478 if (BuildAndDiagnose)
11479 CSI->addCapture(Var, /*isBlock*/false, ByRef, Nested, Loc,
11480 SourceLocation(), CaptureType, CopyExpr);
11481 Nested = true;
11482 continue;
11483 }
11484
Douglas Gregorfdf598e2012-02-18 09:37:24 +000011485 LambdaScopeInfo *LSI = cast<LambdaScopeInfo>(CSI);
11486
11487 // Determine whether we are capturing by reference or by value.
11488 bool ByRef = false;
11489 if (I == N - 1 && Kind != TryCapture_Implicit) {
11490 ByRef = (Kind == TryCapture_ExplicitByRef);
Eli Friedman24af8502012-02-03 22:47:37 +000011491 } else {
Douglas Gregorfdf598e2012-02-18 09:37:24 +000011492 ByRef = (LSI->ImpCaptureStyle == LambdaScopeInfo::ImpCap_LambdaByref);
Eli Friedman24af8502012-02-03 22:47:37 +000011493 }
Douglas Gregorfdf598e2012-02-18 09:37:24 +000011494
11495 // Compute the type of the field that will capture this variable.
11496 if (ByRef) {
11497 // C++11 [expr.prim.lambda]p15:
11498 // An entity is captured by reference if it is implicitly or
11499 // explicitly captured but not captured by copy. It is
11500 // unspecified whether additional unnamed non-static data
11501 // members are declared in the closure type for entities
11502 // captured by reference.
11503 //
11504 // FIXME: It is not clear whether we want to build an lvalue reference
11505 // to the DeclRefType or to CaptureType.getNonReferenceType(). GCC appears
11506 // to do the former, while EDG does the latter. Core issue 1249 will
11507 // clarify, but for now we follow GCC because it's a more permissive and
11508 // easily defensible position.
11509 CaptureType = Context.getLValueReferenceType(DeclRefType);
11510 } else {
11511 // C++11 [expr.prim.lambda]p14:
11512 // For each entity captured by copy, an unnamed non-static
11513 // data member is declared in the closure type. The
11514 // declaration order of these members is unspecified. The type
11515 // of such a data member is the type of the corresponding
11516 // captured entity if the entity is not a reference to an
11517 // object, or the referenced type otherwise. [Note: If the
11518 // captured entity is a reference to a function, the
11519 // corresponding data member is also a reference to a
11520 // function. - end note ]
11521 if (const ReferenceType *RefType = CaptureType->getAs<ReferenceType>()){
11522 if (!RefType->getPointeeType()->isFunctionType())
11523 CaptureType = RefType->getPointeeType();
Eli Friedman9bb33f52012-02-03 02:04:35 +000011524 }
John McCall67cd5e02012-03-30 05:23:48 +000011525
11526 // Forbid the lambda copy-capture of autoreleasing variables.
11527 if (CaptureType.getObjCLifetime() == Qualifiers::OCL_Autoreleasing) {
11528 if (BuildAndDiagnose) {
11529 Diag(Loc, diag::err_arc_autoreleasing_capture) << /*lambda*/ 1;
11530 Diag(Var->getLocation(), diag::note_previous_decl)
11531 << Var->getDeclName();
11532 }
11533 return true;
11534 }
Eli Friedman9bb33f52012-02-03 02:04:35 +000011535 }
11536
Douglas Gregorfdf598e2012-02-18 09:37:24 +000011537 // Capture this variable in the lambda.
11538 Expr *CopyExpr = 0;
11539 if (BuildAndDiagnose) {
11540 ExprResult Result = captureInLambda(*this, LSI, Var, CaptureType,
Douglas Gregora8182f92012-05-16 17:01:33 +000011541 DeclRefType, Loc,
Douglas Gregorc4017552012-12-01 01:01:09 +000011542 Nested);
Douglas Gregorfdf598e2012-02-18 09:37:24 +000011543 if (!Result.isInvalid())
11544 CopyExpr = Result.take();
11545 }
11546
11547 // Compute the type of a reference to this captured variable.
11548 if (ByRef)
11549 DeclRefType = CaptureType.getNonReferenceType();
11550 else {
11551 // C++ [expr.prim.lambda]p5:
11552 // The closure type for a lambda-expression has a public inline
11553 // function call operator [...]. This function call operator is
11554 // declared const (9.3.1) if and only if the lambda-expression’s
11555 // parameter-declaration-clause is not followed by mutable.
11556 DeclRefType = CaptureType.getNonReferenceType();
11557 if (!LSI->Mutable && !CaptureType->isReferenceType())
11558 DeclRefType.addConst();
11559 }
11560
11561 // Add the capture.
11562 if (BuildAndDiagnose)
11563 CSI->addCapture(Var, /*IsBlock=*/false, ByRef, Nested, Loc,
11564 EllipsisLoc, CaptureType, CopyExpr);
Eli Friedman9bb33f52012-02-03 02:04:35 +000011565 Nested = true;
11566 }
Douglas Gregorfdf598e2012-02-18 09:37:24 +000011567
11568 return false;
11569}
11570
11571bool Sema::tryCaptureVariable(VarDecl *Var, SourceLocation Loc,
11572 TryCaptureKind Kind, SourceLocation EllipsisLoc) {
11573 QualType CaptureType;
11574 QualType DeclRefType;
11575 return tryCaptureVariable(Var, Loc, Kind, EllipsisLoc,
11576 /*BuildAndDiagnose=*/true, CaptureType,
11577 DeclRefType);
11578}
11579
11580QualType Sema::getCapturedDeclRefType(VarDecl *Var, SourceLocation Loc) {
11581 QualType CaptureType;
11582 QualType DeclRefType;
11583
11584 // Determine whether we can capture this variable.
11585 if (tryCaptureVariable(Var, Loc, TryCapture_Implicit, SourceLocation(),
11586 /*BuildAndDiagnose=*/false, CaptureType, DeclRefType))
11587 return QualType();
11588
11589 return DeclRefType;
Eli Friedman9bb33f52012-02-03 02:04:35 +000011590}
11591
Eli Friedman3bda6b12012-02-02 23:15:15 +000011592static void MarkVarDeclODRUsed(Sema &SemaRef, VarDecl *Var,
11593 SourceLocation Loc) {
11594 // Keep track of used but undefined variables.
Eli Friedman130bbd02012-02-04 00:54:05 +000011595 // FIXME: We shouldn't suppress this warning for static data members.
Daniel Dunbar9d355812012-03-09 01:51:51 +000011596 if (Var->hasDefinition(SemaRef.Context) == VarDecl::DeclarationOnly &&
Rafael Espindola3ae00052013-05-13 00:12:11 +000011597 !Var->isExternallyVisible() &&
Eli Friedman130bbd02012-02-04 00:54:05 +000011598 !(Var->isStaticDataMember() && Var->hasInit())) {
Nick Lewycky9c7eb1d2013-02-01 08:13:20 +000011599 SourceLocation &old = SemaRef.UndefinedButUsed[Var->getCanonicalDecl()];
Eli Friedman3bda6b12012-02-02 23:15:15 +000011600 if (old.isInvalid()) old = Loc;
11601 }
11602
Douglas Gregorfdf598e2012-02-18 09:37:24 +000011603 SemaRef.tryCaptureVariable(Var, Loc);
Eli Friedman9bb33f52012-02-03 02:04:35 +000011604
Eli Friedman3bda6b12012-02-02 23:15:15 +000011605 Var->setUsed(true);
11606}
11607
11608void Sema::UpdateMarkingForLValueToRValue(Expr *E) {
11609 // Per C++11 [basic.def.odr], a variable is odr-used "unless it is
11610 // an object that satisfies the requirements for appearing in a
11611 // constant expression (5.19) and the lvalue-to-rvalue conversion (4.1)
11612 // is immediately applied." This function handles the lvalue-to-rvalue
11613 // conversion part.
11614 MaybeODRUseExprs.erase(E->IgnoreParens());
11615}
11616
Eli Friedmanc6237c62012-02-29 03:16:56 +000011617ExprResult Sema::ActOnConstantExpression(ExprResult Res) {
11618 if (!Res.isUsable())
11619 return Res;
11620
11621 // If a constant-expression is a reference to a variable where we delay
11622 // deciding whether it is an odr-use, just assume we will apply the
11623 // lvalue-to-rvalue conversion. In the one case where this doesn't happen
11624 // (a non-type template argument), we have special handling anyway.
11625 UpdateMarkingForLValueToRValue(Res.get());
11626 return Res;
11627}
11628
Eli Friedman3bda6b12012-02-02 23:15:15 +000011629void Sema::CleanupVarDeclMarking() {
11630 for (llvm::SmallPtrSetIterator<Expr*> i = MaybeODRUseExprs.begin(),
11631 e = MaybeODRUseExprs.end();
11632 i != e; ++i) {
11633 VarDecl *Var;
11634 SourceLocation Loc;
John McCall113bee02012-03-10 09:33:50 +000011635 if (DeclRefExpr *DRE = dyn_cast<DeclRefExpr>(*i)) {
Eli Friedman3bda6b12012-02-02 23:15:15 +000011636 Var = cast<VarDecl>(DRE->getDecl());
11637 Loc = DRE->getLocation();
11638 } else if (MemberExpr *ME = dyn_cast<MemberExpr>(*i)) {
11639 Var = cast<VarDecl>(ME->getMemberDecl());
11640 Loc = ME->getMemberLoc();
11641 } else {
11642 llvm_unreachable("Unexpcted expression");
11643 }
11644
11645 MarkVarDeclODRUsed(*this, Var, Loc);
11646 }
11647
11648 MaybeODRUseExprs.clear();
11649}
11650
11651// Mark a VarDecl referenced, and perform the necessary handling to compute
11652// odr-uses.
11653static void DoMarkVarDeclReferenced(Sema &SemaRef, SourceLocation Loc,
11654 VarDecl *Var, Expr *E) {
Eli Friedmanfa0df832012-02-02 03:46:19 +000011655 Var->setReferenced();
11656
Eli Friedman3bda6b12012-02-02 23:15:15 +000011657 if (!IsPotentiallyEvaluatedContext(SemaRef))
Eli Friedmanfa0df832012-02-02 03:46:19 +000011658 return;
11659
11660 // Implicit instantiation of static data members of class templates.
Richard Smithd3cf2382012-02-15 02:42:50 +000011661 if (Var->isStaticDataMember() && Var->getInstantiatedFromStaticDataMember()) {
Eli Friedmanfa0df832012-02-02 03:46:19 +000011662 MemberSpecializationInfo *MSInfo = Var->getMemberSpecializationInfo();
11663 assert(MSInfo && "Missing member specialization information?");
Richard Smithd3cf2382012-02-15 02:42:50 +000011664 bool AlreadyInstantiated = !MSInfo->getPointOfInstantiation().isInvalid();
11665 if (MSInfo->getTemplateSpecializationKind() == TSK_ImplicitInstantiation &&
Daniel Dunbar9d355812012-03-09 01:51:51 +000011666 (!AlreadyInstantiated ||
11667 Var->isUsableInConstantExpressions(SemaRef.Context))) {
Richard Smithd3cf2382012-02-15 02:42:50 +000011668 if (!AlreadyInstantiated) {
11669 // This is a modification of an existing AST node. Notify listeners.
11670 if (ASTMutationListener *L = SemaRef.getASTMutationListener())
11671 L->StaticDataMemberInstantiated(Var);
11672 MSInfo->setPointOfInstantiation(Loc);
11673 }
11674 SourceLocation PointOfInstantiation = MSInfo->getPointOfInstantiation();
Daniel Dunbar9d355812012-03-09 01:51:51 +000011675 if (Var->isUsableInConstantExpressions(SemaRef.Context))
Eli Friedmanfa0df832012-02-02 03:46:19 +000011676 // Do not defer instantiations of variables which could be used in a
11677 // constant expression.
Richard Smithd3cf2382012-02-15 02:42:50 +000011678 SemaRef.InstantiateStaticDataMemberDefinition(PointOfInstantiation,Var);
Eli Friedmanfa0df832012-02-02 03:46:19 +000011679 else
Richard Smithd3cf2382012-02-15 02:42:50 +000011680 SemaRef.PendingInstantiations.push_back(
11681 std::make_pair(Var, PointOfInstantiation));
Eli Friedmanfa0df832012-02-02 03:46:19 +000011682 }
11683 }
11684
Richard Smith5a1104b2012-10-20 01:38:33 +000011685 // Per C++11 [basic.def.odr], a variable is odr-used "unless it satisfies
11686 // the requirements for appearing in a constant expression (5.19) and, if
11687 // it is an object, the lvalue-to-rvalue conversion (4.1)
Eli Friedman3bda6b12012-02-02 23:15:15 +000011688 // is immediately applied." We check the first part here, and
11689 // Sema::UpdateMarkingForLValueToRValue deals with the second part.
11690 // Note that we use the C++11 definition everywhere because nothing in
Richard Smith5a1104b2012-10-20 01:38:33 +000011691 // C++03 depends on whether we get the C++03 version correct. The second
11692 // part does not apply to references, since they are not objects.
Eli Friedman3bda6b12012-02-02 23:15:15 +000011693 const VarDecl *DefVD;
Richard Smith5a1104b2012-10-20 01:38:33 +000011694 if (E && !isa<ParmVarDecl>(Var) &&
Daniel Dunbar9d355812012-03-09 01:51:51 +000011695 Var->isUsableInConstantExpressions(SemaRef.Context) &&
Richard Smith5a1104b2012-10-20 01:38:33 +000011696 Var->getAnyInitializer(DefVD) && DefVD->checkInitIsICE()) {
11697 if (!Var->getType()->isReferenceType())
11698 SemaRef.MaybeODRUseExprs.insert(E);
11699 } else
Eli Friedman3bda6b12012-02-02 23:15:15 +000011700 MarkVarDeclODRUsed(SemaRef, Var, Loc);
11701}
Eli Friedmanfa0df832012-02-02 03:46:19 +000011702
Eli Friedman3bda6b12012-02-02 23:15:15 +000011703/// \brief Mark a variable referenced, and check whether it is odr-used
11704/// (C++ [basic.def.odr]p2, C99 6.9p3). Note that this should not be
11705/// used directly for normal expressions referring to VarDecl.
11706void Sema::MarkVariableReferenced(SourceLocation Loc, VarDecl *Var) {
11707 DoMarkVarDeclReferenced(*this, Loc, Var, 0);
Eli Friedmanfa0df832012-02-02 03:46:19 +000011708}
11709
11710static void MarkExprReferenced(Sema &SemaRef, SourceLocation Loc,
Nick Lewycky45b50522013-02-02 00:25:55 +000011711 Decl *D, Expr *E, bool OdrUse) {
Eli Friedman3bda6b12012-02-02 23:15:15 +000011712 if (VarDecl *Var = dyn_cast<VarDecl>(D)) {
11713 DoMarkVarDeclReferenced(SemaRef, Loc, Var, E);
11714 return;
11715 }
11716
Nick Lewycky45b50522013-02-02 00:25:55 +000011717 SemaRef.MarkAnyDeclReferenced(Loc, D, OdrUse);
Rafael Espindola49e860b2012-06-26 17:45:31 +000011718
11719 // If this is a call to a method via a cast, also mark the method in the
11720 // derived class used in case codegen can devirtualize the call.
11721 const MemberExpr *ME = dyn_cast<MemberExpr>(E);
11722 if (!ME)
11723 return;
11724 CXXMethodDecl *MD = dyn_cast<CXXMethodDecl>(ME->getMemberDecl());
11725 if (!MD)
11726 return;
11727 const Expr *Base = ME->getBase();
Rafael Espindolab7f5a9c2012-06-27 18:18:05 +000011728 const CXXRecordDecl *MostDerivedClassDecl = Base->getBestDynamicClassType();
Rafael Espindola49e860b2012-06-26 17:45:31 +000011729 if (!MostDerivedClassDecl)
11730 return;
11731 CXXMethodDecl *DM = MD->getCorrespondingMethodInClass(MostDerivedClassDecl);
Nick Lewyckyb7444cd2013-02-14 00:55:17 +000011732 if (!DM || DM->isPure())
Rafael Espindolaa245edc2012-06-27 17:44:39 +000011733 return;
Nick Lewycky45b50522013-02-02 00:25:55 +000011734 SemaRef.MarkAnyDeclReferenced(Loc, DM, OdrUse);
Douglas Gregord3b672c2012-02-16 01:06:16 +000011735}
Eli Friedmanfa0df832012-02-02 03:46:19 +000011736
Eli Friedmanfa0df832012-02-02 03:46:19 +000011737/// \brief Perform reference-marking and odr-use handling for a DeclRefExpr.
11738void Sema::MarkDeclRefReferenced(DeclRefExpr *E) {
Nick Lewycky45b50522013-02-02 00:25:55 +000011739 // TODO: update this with DR# once a defect report is filed.
11740 // C++11 defect. The address of a pure member should not be an ODR use, even
11741 // if it's a qualified reference.
11742 bool OdrUse = true;
11743 if (CXXMethodDecl *Method = dyn_cast<CXXMethodDecl>(E->getDecl()))
Nick Lewycky192542c2013-02-05 06:20:31 +000011744 if (Method->isVirtual())
Nick Lewycky45b50522013-02-02 00:25:55 +000011745 OdrUse = false;
11746 MarkExprReferenced(*this, E->getLocation(), E->getDecl(), E, OdrUse);
Eli Friedmanfa0df832012-02-02 03:46:19 +000011747}
11748
11749/// \brief Perform reference-marking and odr-use handling for a MemberExpr.
11750void Sema::MarkMemberReferenced(MemberExpr *E) {
Nick Lewycky60bd4be2013-01-31 03:15:20 +000011751 // C++11 [basic.def.odr]p2:
Nick Lewycky35d23592013-01-31 01:34:31 +000011752 // A non-overloaded function whose name appears as a potentially-evaluated
11753 // expression or a member of a set of candidate functions, if selected by
11754 // overload resolution when referred to from a potentially-evaluated
11755 // expression, is odr-used, unless it is a pure virtual function and its
11756 // name is not explicitly qualified.
Nick Lewycky45b50522013-02-02 00:25:55 +000011757 bool OdrUse = true;
Nick Lewycky35d23592013-01-31 01:34:31 +000011758 if (!E->hasQualifier()) {
11759 if (CXXMethodDecl *Method = dyn_cast<CXXMethodDecl>(E->getMemberDecl()))
11760 if (Method->isPure())
Nick Lewycky45b50522013-02-02 00:25:55 +000011761 OdrUse = false;
Nick Lewycky35d23592013-01-31 01:34:31 +000011762 }
Nick Lewyckya096b142013-02-12 08:08:54 +000011763 SourceLocation Loc = E->getMemberLoc().isValid() ?
11764 E->getMemberLoc() : E->getLocStart();
11765 MarkExprReferenced(*this, Loc, E->getMemberDecl(), E, OdrUse);
Eli Friedmanfa0df832012-02-02 03:46:19 +000011766}
11767
Douglas Gregorf02455e2012-02-10 09:26:04 +000011768/// \brief Perform marking for a reference to an arbitrary declaration. It
Eli Friedmanfa0df832012-02-02 03:46:19 +000011769/// marks the declaration referenced, and performs odr-use checking for functions
11770/// and variables. This method should not be used when building an normal
11771/// expression which refers to a variable.
Nick Lewycky45b50522013-02-02 00:25:55 +000011772void Sema::MarkAnyDeclReferenced(SourceLocation Loc, Decl *D, bool OdrUse) {
11773 if (OdrUse) {
11774 if (VarDecl *VD = dyn_cast<VarDecl>(D)) {
11775 MarkVariableReferenced(Loc, VD);
11776 return;
11777 }
11778 if (FunctionDecl *FD = dyn_cast<FunctionDecl>(D)) {
11779 MarkFunctionReferenced(Loc, FD);
11780 return;
11781 }
11782 }
11783 D->setReferenced();
Douglas Gregorc9c02ed2009-06-19 23:52:42 +000011784}
Anders Carlsson7f84ed92009-10-09 23:51:55 +000011785
Douglas Gregor5597ab42010-05-07 23:12:07 +000011786namespace {
Chandler Carruthaf80f662010-06-09 08:17:30 +000011787 // Mark all of the declarations referenced
Douglas Gregor5597ab42010-05-07 23:12:07 +000011788 // FIXME: Not fully implemented yet! We need to have a better understanding
Chandler Carruthaf80f662010-06-09 08:17:30 +000011789 // of when we're entering
Douglas Gregor5597ab42010-05-07 23:12:07 +000011790 class MarkReferencedDecls : public RecursiveASTVisitor<MarkReferencedDecls> {
11791 Sema &S;
11792 SourceLocation Loc;
Chandler Carruthaf80f662010-06-09 08:17:30 +000011793
Douglas Gregor5597ab42010-05-07 23:12:07 +000011794 public:
11795 typedef RecursiveASTVisitor<MarkReferencedDecls> Inherited;
Chandler Carruthaf80f662010-06-09 08:17:30 +000011796
Douglas Gregor5597ab42010-05-07 23:12:07 +000011797 MarkReferencedDecls(Sema &S, SourceLocation Loc) : S(S), Loc(Loc) { }
Chandler Carruthaf80f662010-06-09 08:17:30 +000011798
11799 bool TraverseTemplateArgument(const TemplateArgument &Arg);
11800 bool TraverseRecordType(RecordType *T);
Douglas Gregor5597ab42010-05-07 23:12:07 +000011801 };
11802}
11803
Chandler Carruthaf80f662010-06-09 08:17:30 +000011804bool MarkReferencedDecls::TraverseTemplateArgument(
11805 const TemplateArgument &Arg) {
Douglas Gregor5597ab42010-05-07 23:12:07 +000011806 if (Arg.getKind() == TemplateArgument::Declaration) {
Douglas Gregor31f55dc2012-04-06 22:40:38 +000011807 if (Decl *D = Arg.getAsDecl())
Nick Lewycky45b50522013-02-02 00:25:55 +000011808 S.MarkAnyDeclReferenced(Loc, D, true);
Douglas Gregor5597ab42010-05-07 23:12:07 +000011809 }
Chandler Carruthaf80f662010-06-09 08:17:30 +000011810
11811 return Inherited::TraverseTemplateArgument(Arg);
Douglas Gregor5597ab42010-05-07 23:12:07 +000011812}
11813
Chandler Carruthaf80f662010-06-09 08:17:30 +000011814bool MarkReferencedDecls::TraverseRecordType(RecordType *T) {
Douglas Gregor5597ab42010-05-07 23:12:07 +000011815 if (ClassTemplateSpecializationDecl *Spec
11816 = dyn_cast<ClassTemplateSpecializationDecl>(T->getDecl())) {
11817 const TemplateArgumentList &Args = Spec->getTemplateArgs();
Douglas Gregor1ccc8412010-11-07 23:05:16 +000011818 return TraverseTemplateArguments(Args.data(), Args.size());
Douglas Gregor5597ab42010-05-07 23:12:07 +000011819 }
11820
Chandler Carruthc65667c2010-06-10 10:31:57 +000011821 return true;
Douglas Gregor5597ab42010-05-07 23:12:07 +000011822}
11823
11824void Sema::MarkDeclarationsReferencedInType(SourceLocation Loc, QualType T) {
11825 MarkReferencedDecls Marker(*this, Loc);
Chandler Carruthaf80f662010-06-09 08:17:30 +000011826 Marker.TraverseType(Context.getCanonicalType(T));
Douglas Gregor5597ab42010-05-07 23:12:07 +000011827}
11828
Douglas Gregor8a01b2a2010-09-11 20:24:53 +000011829namespace {
11830 /// \brief Helper class that marks all of the declarations referenced by
11831 /// potentially-evaluated subexpressions as "referenced".
11832 class EvaluatedExprMarker : public EvaluatedExprVisitor<EvaluatedExprMarker> {
11833 Sema &S;
Douglas Gregor680e9e02012-02-21 19:11:17 +000011834 bool SkipLocalVariables;
Douglas Gregor8a01b2a2010-09-11 20:24:53 +000011835
11836 public:
11837 typedef EvaluatedExprVisitor<EvaluatedExprMarker> Inherited;
11838
Douglas Gregor680e9e02012-02-21 19:11:17 +000011839 EvaluatedExprMarker(Sema &S, bool SkipLocalVariables)
11840 : Inherited(S.Context), S(S), SkipLocalVariables(SkipLocalVariables) { }
Douglas Gregor8a01b2a2010-09-11 20:24:53 +000011841
11842 void VisitDeclRefExpr(DeclRefExpr *E) {
Douglas Gregor680e9e02012-02-21 19:11:17 +000011843 // If we were asked not to visit local variables, don't.
11844 if (SkipLocalVariables) {
11845 if (VarDecl *VD = dyn_cast<VarDecl>(E->getDecl()))
11846 if (VD->hasLocalStorage())
11847 return;
11848 }
11849
Eli Friedmanfa0df832012-02-02 03:46:19 +000011850 S.MarkDeclRefReferenced(E);
Douglas Gregor8a01b2a2010-09-11 20:24:53 +000011851 }
11852
11853 void VisitMemberExpr(MemberExpr *E) {
Eli Friedmanfa0df832012-02-02 03:46:19 +000011854 S.MarkMemberReferenced(E);
Douglas Gregor32b3de52010-09-11 23:32:50 +000011855 Inherited::VisitMemberExpr(E);
Douglas Gregor8a01b2a2010-09-11 20:24:53 +000011856 }
11857
John McCall28fc7092011-11-10 05:35:25 +000011858 void VisitCXXBindTemporaryExpr(CXXBindTemporaryExpr *E) {
Eli Friedmanfa0df832012-02-02 03:46:19 +000011859 S.MarkFunctionReferenced(E->getLocStart(),
John McCall28fc7092011-11-10 05:35:25 +000011860 const_cast<CXXDestructorDecl*>(E->getTemporary()->getDestructor()));
11861 Visit(E->getSubExpr());
11862 }
11863
Douglas Gregor8a01b2a2010-09-11 20:24:53 +000011864 void VisitCXXNewExpr(CXXNewExpr *E) {
Douglas Gregor8a01b2a2010-09-11 20:24:53 +000011865 if (E->getOperatorNew())
Eli Friedmanfa0df832012-02-02 03:46:19 +000011866 S.MarkFunctionReferenced(E->getLocStart(), E->getOperatorNew());
Douglas Gregor8a01b2a2010-09-11 20:24:53 +000011867 if (E->getOperatorDelete())
Eli Friedmanfa0df832012-02-02 03:46:19 +000011868 S.MarkFunctionReferenced(E->getLocStart(), E->getOperatorDelete());
Douglas Gregor32b3de52010-09-11 23:32:50 +000011869 Inherited::VisitCXXNewExpr(E);
Douglas Gregor8a01b2a2010-09-11 20:24:53 +000011870 }
Sebastian Redl6047f072012-02-16 12:22:20 +000011871
Douglas Gregor8a01b2a2010-09-11 20:24:53 +000011872 void VisitCXXDeleteExpr(CXXDeleteExpr *E) {
11873 if (E->getOperatorDelete())
Eli Friedmanfa0df832012-02-02 03:46:19 +000011874 S.MarkFunctionReferenced(E->getLocStart(), E->getOperatorDelete());
Douglas Gregor6ed2fee2010-09-14 22:55:20 +000011875 QualType Destroyed = S.Context.getBaseElementType(E->getDestroyedType());
11876 if (const RecordType *DestroyedRec = Destroyed->getAs<RecordType>()) {
11877 CXXRecordDecl *Record = cast<CXXRecordDecl>(DestroyedRec->getDecl());
Eli Friedmanfa0df832012-02-02 03:46:19 +000011878 S.MarkFunctionReferenced(E->getLocStart(),
Douglas Gregor6ed2fee2010-09-14 22:55:20 +000011879 S.LookupDestructor(Record));
11880 }
11881
Douglas Gregor32b3de52010-09-11 23:32:50 +000011882 Inherited::VisitCXXDeleteExpr(E);
Douglas Gregor8a01b2a2010-09-11 20:24:53 +000011883 }
11884
11885 void VisitCXXConstructExpr(CXXConstructExpr *E) {
Eli Friedmanfa0df832012-02-02 03:46:19 +000011886 S.MarkFunctionReferenced(E->getLocStart(), E->getConstructor());
Douglas Gregor32b3de52010-09-11 23:32:50 +000011887 Inherited::VisitCXXConstructExpr(E);
Douglas Gregor8a01b2a2010-09-11 20:24:53 +000011888 }
11889
Douglas Gregorf0873f42010-10-19 17:17:35 +000011890 void VisitCXXDefaultArgExpr(CXXDefaultArgExpr *E) {
11891 Visit(E->getExpr());
11892 }
Eli Friedman3bda6b12012-02-02 23:15:15 +000011893
11894 void VisitImplicitCastExpr(ImplicitCastExpr *E) {
11895 Inherited::VisitImplicitCastExpr(E);
11896
11897 if (E->getCastKind() == CK_LValueToRValue)
11898 S.UpdateMarkingForLValueToRValue(E->getSubExpr());
11899 }
Douglas Gregor8a01b2a2010-09-11 20:24:53 +000011900 };
11901}
11902
11903/// \brief Mark any declarations that appear within this expression or any
11904/// potentially-evaluated subexpressions as "referenced".
Douglas Gregor680e9e02012-02-21 19:11:17 +000011905///
11906/// \param SkipLocalVariables If true, don't mark local variables as
11907/// 'referenced'.
11908void Sema::MarkDeclarationsReferencedInExpr(Expr *E,
11909 bool SkipLocalVariables) {
11910 EvaluatedExprMarker(*this, SkipLocalVariables).Visit(E);
Douglas Gregor8a01b2a2010-09-11 20:24:53 +000011911}
11912
Douglas Gregorda8cdbc2009-12-22 01:01:55 +000011913/// \brief Emit a diagnostic that describes an effect on the run-time behavior
11914/// of the program being compiled.
11915///
11916/// This routine emits the given diagnostic when the code currently being
Kovarththanan Rajaratnamba2c6522010-03-13 10:17:05 +000011917/// type-checked is "potentially evaluated", meaning that there is a
Douglas Gregorda8cdbc2009-12-22 01:01:55 +000011918/// possibility that the code will actually be executable. Code in sizeof()
11919/// expressions, code used only during overload resolution, etc., are not
11920/// potentially evaluated. This routine will suppress such diagnostics or,
11921/// in the absolutely nutty case of potentially potentially evaluated
Kovarththanan Rajaratnamba2c6522010-03-13 10:17:05 +000011922/// expressions (C++ typeid), queue the diagnostic to potentially emit it
Douglas Gregorda8cdbc2009-12-22 01:01:55 +000011923/// later.
Kovarththanan Rajaratnamba2c6522010-03-13 10:17:05 +000011924///
Douglas Gregorda8cdbc2009-12-22 01:01:55 +000011925/// This routine should be used for all diagnostics that describe the run-time
11926/// behavior of a program, such as passing a non-POD value through an ellipsis.
11927/// Failure to do so will likely result in spurious diagnostics or failures
11928/// during overload resolution or within sizeof/alignof/typeof/typeid.
Richard Trieuba63ce62011-09-09 01:45:06 +000011929bool Sema::DiagRuntimeBehavior(SourceLocation Loc, const Stmt *Statement,
Douglas Gregorda8cdbc2009-12-22 01:01:55 +000011930 const PartialDiagnostic &PD) {
John McCall31168b02011-06-15 23:02:42 +000011931 switch (ExprEvalContexts.back().Context) {
Douglas Gregorda8cdbc2009-12-22 01:01:55 +000011932 case Unevaluated:
John McCallf413f5e2013-05-03 00:10:13 +000011933 case UnevaluatedAbstract:
Douglas Gregorda8cdbc2009-12-22 01:01:55 +000011934 // The argument will never be evaluated, so don't complain.
11935 break;
Kovarththanan Rajaratnamba2c6522010-03-13 10:17:05 +000011936
Richard Smith764d2fe2011-12-20 02:08:33 +000011937 case ConstantEvaluated:
11938 // Relevant diagnostics should be produced by constant evaluation.
11939 break;
11940
Douglas Gregorda8cdbc2009-12-22 01:01:55 +000011941 case PotentiallyEvaluated:
Douglas Gregor8a01b2a2010-09-11 20:24:53 +000011942 case PotentiallyEvaluatedIfUsed:
Richard Trieuba63ce62011-09-09 01:45:06 +000011943 if (Statement && getCurFunctionOrMethodDecl()) {
Ted Kremenek3427fac2011-02-23 01:52:04 +000011944 FunctionScopes.back()->PossiblyUnreachableDiags.
Richard Trieuba63ce62011-09-09 01:45:06 +000011945 push_back(sema::PossiblyUnreachableDiag(PD, Loc, Statement));
Ted Kremenek3427fac2011-02-23 01:52:04 +000011946 }
11947 else
11948 Diag(Loc, PD);
11949
Douglas Gregorda8cdbc2009-12-22 01:01:55 +000011950 return true;
Douglas Gregorda8cdbc2009-12-22 01:01:55 +000011951 }
11952
11953 return false;
11954}
11955
Anders Carlsson7f84ed92009-10-09 23:51:55 +000011956bool Sema::CheckCallReturnType(QualType ReturnType, SourceLocation Loc,
11957 CallExpr *CE, FunctionDecl *FD) {
11958 if (ReturnType->isVoidType() || !ReturnType->isIncompleteType())
11959 return false;
11960
Richard Smithfd555f62012-02-22 02:04:18 +000011961 // If we're inside a decltype's expression, don't check for a valid return
11962 // type or construct temporaries until we know whether this is the last call.
11963 if (ExprEvalContexts.back().IsDecltype) {
11964 ExprEvalContexts.back().DelayedDecltypeCalls.push_back(CE);
11965 return false;
11966 }
11967
Douglas Gregora6c5abb2012-05-04 16:48:41 +000011968 class CallReturnIncompleteDiagnoser : public TypeDiagnoser {
Douglas Gregor7bfb2d02012-05-04 16:32:21 +000011969 FunctionDecl *FD;
11970 CallExpr *CE;
11971
11972 public:
11973 CallReturnIncompleteDiagnoser(FunctionDecl *FD, CallExpr *CE)
11974 : FD(FD), CE(CE) { }
11975
11976 virtual void diagnose(Sema &S, SourceLocation Loc, QualType T) {
11977 if (!FD) {
11978 S.Diag(Loc, diag::err_call_incomplete_return)
11979 << T << CE->getSourceRange();
11980 return;
11981 }
11982
11983 S.Diag(Loc, diag::err_call_function_incomplete_return)
11984 << CE->getSourceRange() << FD->getDeclName() << T;
11985 S.Diag(FD->getLocation(),
11986 diag::note_function_with_incomplete_return_type_declared_here)
11987 << FD->getDeclName();
11988 }
11989 } Diagnoser(FD, CE);
11990
11991 if (RequireCompleteType(Loc, ReturnType, Diagnoser))
Anders Carlsson7f84ed92009-10-09 23:51:55 +000011992 return true;
11993
11994 return false;
11995}
11996
Douglas Gregor2d4f64f2011-01-19 16:50:08 +000011997// Diagnose the s/=/==/ and s/\|=/!=/ typos. Note that adding parentheses
John McCalld5707ab2009-10-12 21:59:07 +000011998// will prevent this condition from triggering, which is what we want.
11999void Sema::DiagnoseAssignmentAsCondition(Expr *E) {
12000 SourceLocation Loc;
12001
John McCall0506e4a2009-11-11 02:41:58 +000012002 unsigned diagnostic = diag::warn_condition_is_assignment;
Douglas Gregor2d4f64f2011-01-19 16:50:08 +000012003 bool IsOrAssign = false;
John McCall0506e4a2009-11-11 02:41:58 +000012004
Chandler Carruthf87d6c02011-08-16 22:30:10 +000012005 if (BinaryOperator *Op = dyn_cast<BinaryOperator>(E)) {
Douglas Gregor2d4f64f2011-01-19 16:50:08 +000012006 if (Op->getOpcode() != BO_Assign && Op->getOpcode() != BO_OrAssign)
John McCalld5707ab2009-10-12 21:59:07 +000012007 return;
12008
Douglas Gregor2d4f64f2011-01-19 16:50:08 +000012009 IsOrAssign = Op->getOpcode() == BO_OrAssign;
12010
John McCallb0e419e2009-11-12 00:06:05 +000012011 // Greylist some idioms by putting them into a warning subcategory.
12012 if (ObjCMessageExpr *ME
12013 = dyn_cast<ObjCMessageExpr>(Op->getRHS()->IgnoreParenCasts())) {
12014 Selector Sel = ME->getSelector();
12015
John McCallb0e419e2009-11-12 00:06:05 +000012016 // self = [<foo> init...]
Jean-Daniel Dupas39655742013-07-17 18:17:14 +000012017 if (isSelfExpr(Op->getLHS()) && ME->getMethodFamily() == OMF_init)
John McCallb0e419e2009-11-12 00:06:05 +000012018 diagnostic = diag::warn_condition_is_idiomatic_assignment;
12019
12020 // <foo> = [<bar> nextObject]
Douglas Gregoraf2a6ae2011-02-18 22:29:55 +000012021 else if (Sel.isUnarySelector() && Sel.getNameForSlot(0) == "nextObject")
John McCallb0e419e2009-11-12 00:06:05 +000012022 diagnostic = diag::warn_condition_is_idiomatic_assignment;
12023 }
John McCall0506e4a2009-11-11 02:41:58 +000012024
John McCalld5707ab2009-10-12 21:59:07 +000012025 Loc = Op->getOperatorLoc();
Chandler Carruthf87d6c02011-08-16 22:30:10 +000012026 } else if (CXXOperatorCallExpr *Op = dyn_cast<CXXOperatorCallExpr>(E)) {
Douglas Gregor2d4f64f2011-01-19 16:50:08 +000012027 if (Op->getOperator() != OO_Equal && Op->getOperator() != OO_PipeEqual)
John McCalld5707ab2009-10-12 21:59:07 +000012028 return;
12029
Douglas Gregor2d4f64f2011-01-19 16:50:08 +000012030 IsOrAssign = Op->getOperator() == OO_PipeEqual;
John McCalld5707ab2009-10-12 21:59:07 +000012031 Loc = Op->getOperatorLoc();
Fariborz Jahanianf07bcc52012-08-29 17:17:11 +000012032 } else if (PseudoObjectExpr *POE = dyn_cast<PseudoObjectExpr>(E))
12033 return DiagnoseAssignmentAsCondition(POE->getSyntacticForm());
12034 else {
John McCalld5707ab2009-10-12 21:59:07 +000012035 // Not an assignment.
12036 return;
12037 }
12038
Douglas Gregor2bf2d3d2010-04-14 16:09:52 +000012039 Diag(Loc, diagnostic) << E->getSourceRange();
Douglas Gregor2d4f64f2011-01-19 16:50:08 +000012040
Daniel Dunbar62ee6412012-03-09 18:35:03 +000012041 SourceLocation Open = E->getLocStart();
Argyrios Kyrtzidise1b97c42011-04-25 23:01:29 +000012042 SourceLocation Close = PP.getLocForEndOfToken(E->getSourceRange().getEnd());
12043 Diag(Loc, diag::note_condition_assign_silence)
12044 << FixItHint::CreateInsertion(Open, "(")
12045 << FixItHint::CreateInsertion(Close, ")");
12046
Douglas Gregor2d4f64f2011-01-19 16:50:08 +000012047 if (IsOrAssign)
12048 Diag(Loc, diag::note_condition_or_assign_to_comparison)
12049 << FixItHint::CreateReplacement(Loc, "!=");
12050 else
12051 Diag(Loc, diag::note_condition_assign_to_comparison)
12052 << FixItHint::CreateReplacement(Loc, "==");
John McCalld5707ab2009-10-12 21:59:07 +000012053}
12054
Argyrios Kyrtzidis8b6ec682011-02-01 18:24:22 +000012055/// \brief Redundant parentheses over an equality comparison can indicate
12056/// that the user intended an assignment used as condition.
Richard Trieuba63ce62011-09-09 01:45:06 +000012057void Sema::DiagnoseEqualityWithExtraParens(ParenExpr *ParenE) {
Argyrios Kyrtzidisf4f82782011-02-01 22:23:56 +000012058 // Don't warn if the parens came from a macro.
Richard Trieuba63ce62011-09-09 01:45:06 +000012059 SourceLocation parenLoc = ParenE->getLocStart();
Argyrios Kyrtzidisf4f82782011-02-01 22:23:56 +000012060 if (parenLoc.isInvalid() || parenLoc.isMacroID())
12061 return;
Argyrios Kyrtzidisba699d62011-03-28 23:52:04 +000012062 // Don't warn for dependent expressions.
Richard Trieuba63ce62011-09-09 01:45:06 +000012063 if (ParenE->isTypeDependent())
Argyrios Kyrtzidisba699d62011-03-28 23:52:04 +000012064 return;
Argyrios Kyrtzidisf4f82782011-02-01 22:23:56 +000012065
Richard Trieuba63ce62011-09-09 01:45:06 +000012066 Expr *E = ParenE->IgnoreParens();
Argyrios Kyrtzidis8b6ec682011-02-01 18:24:22 +000012067
12068 if (BinaryOperator *opE = dyn_cast<BinaryOperator>(E))
Argyrios Kyrtzidis582dd682011-02-01 19:32:59 +000012069 if (opE->getOpcode() == BO_EQ &&
12070 opE->getLHS()->IgnoreParenImpCasts()->isModifiableLvalue(Context)
12071 == Expr::MLV_Valid) {
Argyrios Kyrtzidis8b6ec682011-02-01 18:24:22 +000012072 SourceLocation Loc = opE->getOperatorLoc();
Ted Kremenekc358d9f2011-02-01 22:36:09 +000012073
Ted Kremenekae022092011-02-02 02:20:30 +000012074 Diag(Loc, diag::warn_equality_with_extra_parens) << E->getSourceRange();
Daniel Dunbar62ee6412012-03-09 18:35:03 +000012075 SourceRange ParenERange = ParenE->getSourceRange();
Ted Kremenekae022092011-02-02 02:20:30 +000012076 Diag(Loc, diag::note_equality_comparison_silence)
Daniel Dunbar62ee6412012-03-09 18:35:03 +000012077 << FixItHint::CreateRemoval(ParenERange.getBegin())
12078 << FixItHint::CreateRemoval(ParenERange.getEnd());
Argyrios Kyrtzidise1b97c42011-04-25 23:01:29 +000012079 Diag(Loc, diag::note_equality_comparison_to_assign)
12080 << FixItHint::CreateReplacement(Loc, "=");
Argyrios Kyrtzidis8b6ec682011-02-01 18:24:22 +000012081 }
12082}
12083
John Wiegley01296292011-04-08 18:41:53 +000012084ExprResult Sema::CheckBooleanCondition(Expr *E, SourceLocation Loc) {
John McCalld5707ab2009-10-12 21:59:07 +000012085 DiagnoseAssignmentAsCondition(E);
Argyrios Kyrtzidis8b6ec682011-02-01 18:24:22 +000012086 if (ParenExpr *parenE = dyn_cast<ParenExpr>(E))
12087 DiagnoseEqualityWithExtraParens(parenE);
John McCalld5707ab2009-10-12 21:59:07 +000012088
John McCall0009fcc2011-04-26 20:42:42 +000012089 ExprResult result = CheckPlaceholderExpr(E);
12090 if (result.isInvalid()) return ExprError();
12091 E = result.take();
Argyrios Kyrtzidisca766292010-11-01 18:49:26 +000012092
John McCall0009fcc2011-04-26 20:42:42 +000012093 if (!E->isTypeDependent()) {
David Blaikiebbafb8a2012-03-11 07:00:24 +000012094 if (getLangOpts().CPlusPlus)
John McCall34376a62010-12-04 03:47:34 +000012095 return CheckCXXBooleanCondition(E); // C++ 6.4p4
12096
John Wiegley01296292011-04-08 18:41:53 +000012097 ExprResult ERes = DefaultFunctionArrayLvalueConversion(E);
12098 if (ERes.isInvalid())
12099 return ExprError();
12100 E = ERes.take();
John McCall29cb2fd2010-12-04 06:09:13 +000012101
12102 QualType T = E->getType();
John Wiegley01296292011-04-08 18:41:53 +000012103 if (!T->isScalarType()) { // C99 6.8.4.1p1
12104 Diag(Loc, diag::err_typecheck_statement_requires_scalar)
12105 << T << E->getSourceRange();
12106 return ExprError();
12107 }
John McCalld5707ab2009-10-12 21:59:07 +000012108 }
12109
John Wiegley01296292011-04-08 18:41:53 +000012110 return Owned(E);
John McCalld5707ab2009-10-12 21:59:07 +000012111}
Douglas Gregore60e41a2010-05-06 17:25:47 +000012112
John McCalldadc5752010-08-24 06:29:42 +000012113ExprResult Sema::ActOnBooleanCondition(Scope *S, SourceLocation Loc,
Richard Trieuba63ce62011-09-09 01:45:06 +000012114 Expr *SubExpr) {
12115 if (!SubExpr)
Douglas Gregore60e41a2010-05-06 17:25:47 +000012116 return ExprError();
John Wiegley01296292011-04-08 18:41:53 +000012117
Richard Trieuba63ce62011-09-09 01:45:06 +000012118 return CheckBooleanCondition(SubExpr, Loc);
Douglas Gregore60e41a2010-05-06 17:25:47 +000012119}
John McCall36e7fe32010-10-12 00:20:44 +000012120
John McCall31996342011-04-07 08:22:57 +000012121namespace {
John McCall2979fe02011-04-12 00:42:48 +000012122 /// A visitor for rebuilding a call to an __unknown_any expression
12123 /// to have an appropriate type.
12124 struct RebuildUnknownAnyFunction
12125 : StmtVisitor<RebuildUnknownAnyFunction, ExprResult> {
12126
12127 Sema &S;
12128
12129 RebuildUnknownAnyFunction(Sema &S) : S(S) {}
12130
12131 ExprResult VisitStmt(Stmt *S) {
12132 llvm_unreachable("unexpected statement!");
John McCall2979fe02011-04-12 00:42:48 +000012133 }
12134
Richard Trieu10162ab2011-09-09 03:59:41 +000012135 ExprResult VisitExpr(Expr *E) {
12136 S.Diag(E->getExprLoc(), diag::err_unsupported_unknown_any_call)
12137 << E->getSourceRange();
John McCall2979fe02011-04-12 00:42:48 +000012138 return ExprError();
12139 }
12140
12141 /// Rebuild an expression which simply semantically wraps another
12142 /// expression which it shares the type and value kind of.
Richard Trieu10162ab2011-09-09 03:59:41 +000012143 template <class T> ExprResult rebuildSugarExpr(T *E) {
12144 ExprResult SubResult = Visit(E->getSubExpr());
12145 if (SubResult.isInvalid()) return ExprError();
John McCall2979fe02011-04-12 00:42:48 +000012146
Richard Trieu10162ab2011-09-09 03:59:41 +000012147 Expr *SubExpr = SubResult.take();
12148 E->setSubExpr(SubExpr);
12149 E->setType(SubExpr->getType());
12150 E->setValueKind(SubExpr->getValueKind());
12151 assert(E->getObjectKind() == OK_Ordinary);
12152 return E;
John McCall2979fe02011-04-12 00:42:48 +000012153 }
12154
Richard Trieu10162ab2011-09-09 03:59:41 +000012155 ExprResult VisitParenExpr(ParenExpr *E) {
12156 return rebuildSugarExpr(E);
John McCall2979fe02011-04-12 00:42:48 +000012157 }
12158
Richard Trieu10162ab2011-09-09 03:59:41 +000012159 ExprResult VisitUnaryExtension(UnaryOperator *E) {
12160 return rebuildSugarExpr(E);
John McCall2979fe02011-04-12 00:42:48 +000012161 }
12162
Richard Trieu10162ab2011-09-09 03:59:41 +000012163 ExprResult VisitUnaryAddrOf(UnaryOperator *E) {
12164 ExprResult SubResult = Visit(E->getSubExpr());
12165 if (SubResult.isInvalid()) return ExprError();
John McCall2979fe02011-04-12 00:42:48 +000012166
Richard Trieu10162ab2011-09-09 03:59:41 +000012167 Expr *SubExpr = SubResult.take();
12168 E->setSubExpr(SubExpr);
12169 E->setType(S.Context.getPointerType(SubExpr->getType()));
12170 assert(E->getValueKind() == VK_RValue);
12171 assert(E->getObjectKind() == OK_Ordinary);
12172 return E;
John McCall2979fe02011-04-12 00:42:48 +000012173 }
12174
Richard Trieu10162ab2011-09-09 03:59:41 +000012175 ExprResult resolveDecl(Expr *E, ValueDecl *VD) {
12176 if (!isa<FunctionDecl>(VD)) return VisitExpr(E);
John McCall2979fe02011-04-12 00:42:48 +000012177
Richard Trieu10162ab2011-09-09 03:59:41 +000012178 E->setType(VD->getType());
John McCall2979fe02011-04-12 00:42:48 +000012179
Richard Trieu10162ab2011-09-09 03:59:41 +000012180 assert(E->getValueKind() == VK_RValue);
David Blaikiebbafb8a2012-03-11 07:00:24 +000012181 if (S.getLangOpts().CPlusPlus &&
Richard Trieu10162ab2011-09-09 03:59:41 +000012182 !(isa<CXXMethodDecl>(VD) &&
12183 cast<CXXMethodDecl>(VD)->isInstance()))
12184 E->setValueKind(VK_LValue);
John McCall2979fe02011-04-12 00:42:48 +000012185
Richard Trieu10162ab2011-09-09 03:59:41 +000012186 return E;
John McCall2979fe02011-04-12 00:42:48 +000012187 }
12188
Richard Trieu10162ab2011-09-09 03:59:41 +000012189 ExprResult VisitMemberExpr(MemberExpr *E) {
12190 return resolveDecl(E, E->getMemberDecl());
John McCall2979fe02011-04-12 00:42:48 +000012191 }
12192
Richard Trieu10162ab2011-09-09 03:59:41 +000012193 ExprResult VisitDeclRefExpr(DeclRefExpr *E) {
12194 return resolveDecl(E, E->getDecl());
John McCall2979fe02011-04-12 00:42:48 +000012195 }
12196 };
12197}
12198
12199/// Given a function expression of unknown-any type, try to rebuild it
12200/// to have a function type.
Richard Trieu10162ab2011-09-09 03:59:41 +000012201static ExprResult rebuildUnknownAnyFunction(Sema &S, Expr *FunctionExpr) {
12202 ExprResult Result = RebuildUnknownAnyFunction(S).Visit(FunctionExpr);
12203 if (Result.isInvalid()) return ExprError();
12204 return S.DefaultFunctionArrayConversion(Result.take());
John McCall2979fe02011-04-12 00:42:48 +000012205}
12206
12207namespace {
John McCall2d2e8702011-04-11 07:02:50 +000012208 /// A visitor for rebuilding an expression of type __unknown_anytype
12209 /// into one which resolves the type directly on the referring
12210 /// expression. Strict preservation of the original source
12211 /// structure is not a goal.
John McCall31996342011-04-07 08:22:57 +000012212 struct RebuildUnknownAnyExpr
John McCall39439732011-04-09 22:50:59 +000012213 : StmtVisitor<RebuildUnknownAnyExpr, ExprResult> {
John McCall31996342011-04-07 08:22:57 +000012214
12215 Sema &S;
12216
12217 /// The current destination type.
12218 QualType DestType;
12219
Richard Trieu10162ab2011-09-09 03:59:41 +000012220 RebuildUnknownAnyExpr(Sema &S, QualType CastType)
12221 : S(S), DestType(CastType) {}
John McCall31996342011-04-07 08:22:57 +000012222
John McCall39439732011-04-09 22:50:59 +000012223 ExprResult VisitStmt(Stmt *S) {
John McCall2d2e8702011-04-11 07:02:50 +000012224 llvm_unreachable("unexpected statement!");
John McCall31996342011-04-07 08:22:57 +000012225 }
12226
Richard Trieu10162ab2011-09-09 03:59:41 +000012227 ExprResult VisitExpr(Expr *E) {
12228 S.Diag(E->getExprLoc(), diag::err_unsupported_unknown_any_expr)
12229 << E->getSourceRange();
John McCall2d2e8702011-04-11 07:02:50 +000012230 return ExprError();
John McCall31996342011-04-07 08:22:57 +000012231 }
12232
Richard Trieu10162ab2011-09-09 03:59:41 +000012233 ExprResult VisitCallExpr(CallExpr *E);
12234 ExprResult VisitObjCMessageExpr(ObjCMessageExpr *E);
John McCall2d2e8702011-04-11 07:02:50 +000012235
John McCall39439732011-04-09 22:50:59 +000012236 /// Rebuild an expression which simply semantically wraps another
12237 /// expression which it shares the type and value kind of.
Richard Trieu10162ab2011-09-09 03:59:41 +000012238 template <class T> ExprResult rebuildSugarExpr(T *E) {
12239 ExprResult SubResult = Visit(E->getSubExpr());
12240 if (SubResult.isInvalid()) return ExprError();
12241 Expr *SubExpr = SubResult.take();
12242 E->setSubExpr(SubExpr);
12243 E->setType(SubExpr->getType());
12244 E->setValueKind(SubExpr->getValueKind());
12245 assert(E->getObjectKind() == OK_Ordinary);
12246 return E;
John McCall39439732011-04-09 22:50:59 +000012247 }
John McCall31996342011-04-07 08:22:57 +000012248
Richard Trieu10162ab2011-09-09 03:59:41 +000012249 ExprResult VisitParenExpr(ParenExpr *E) {
12250 return rebuildSugarExpr(E);
John McCall39439732011-04-09 22:50:59 +000012251 }
12252
Richard Trieu10162ab2011-09-09 03:59:41 +000012253 ExprResult VisitUnaryExtension(UnaryOperator *E) {
12254 return rebuildSugarExpr(E);
John McCall39439732011-04-09 22:50:59 +000012255 }
12256
Richard Trieu10162ab2011-09-09 03:59:41 +000012257 ExprResult VisitUnaryAddrOf(UnaryOperator *E) {
12258 const PointerType *Ptr = DestType->getAs<PointerType>();
12259 if (!Ptr) {
12260 S.Diag(E->getOperatorLoc(), diag::err_unknown_any_addrof)
12261 << E->getSourceRange();
John McCall2979fe02011-04-12 00:42:48 +000012262 return ExprError();
12263 }
Richard Trieu10162ab2011-09-09 03:59:41 +000012264 assert(E->getValueKind() == VK_RValue);
12265 assert(E->getObjectKind() == OK_Ordinary);
12266 E->setType(DestType);
John McCall2979fe02011-04-12 00:42:48 +000012267
12268 // Build the sub-expression as if it were an object of the pointee type.
Richard Trieu10162ab2011-09-09 03:59:41 +000012269 DestType = Ptr->getPointeeType();
12270 ExprResult SubResult = Visit(E->getSubExpr());
12271 if (SubResult.isInvalid()) return ExprError();
12272 E->setSubExpr(SubResult.take());
12273 return E;
John McCall2979fe02011-04-12 00:42:48 +000012274 }
12275
Richard Trieu10162ab2011-09-09 03:59:41 +000012276 ExprResult VisitImplicitCastExpr(ImplicitCastExpr *E);
John McCall39439732011-04-09 22:50:59 +000012277
Richard Trieu10162ab2011-09-09 03:59:41 +000012278 ExprResult resolveDecl(Expr *E, ValueDecl *VD);
John McCall39439732011-04-09 22:50:59 +000012279
Richard Trieu10162ab2011-09-09 03:59:41 +000012280 ExprResult VisitMemberExpr(MemberExpr *E) {
12281 return resolveDecl(E, E->getMemberDecl());
John McCall2979fe02011-04-12 00:42:48 +000012282 }
John McCall39439732011-04-09 22:50:59 +000012283
Richard Trieu10162ab2011-09-09 03:59:41 +000012284 ExprResult VisitDeclRefExpr(DeclRefExpr *E) {
12285 return resolveDecl(E, E->getDecl());
John McCall31996342011-04-07 08:22:57 +000012286 }
12287 };
12288}
12289
John McCall2d2e8702011-04-11 07:02:50 +000012290/// Rebuilds a call expression which yielded __unknown_anytype.
Richard Trieu10162ab2011-09-09 03:59:41 +000012291ExprResult RebuildUnknownAnyExpr::VisitCallExpr(CallExpr *E) {
12292 Expr *CalleeExpr = E->getCallee();
John McCall2d2e8702011-04-11 07:02:50 +000012293
12294 enum FnKind {
John McCall4adb38c2011-04-27 00:36:17 +000012295 FK_MemberFunction,
John McCall2d2e8702011-04-11 07:02:50 +000012296 FK_FunctionPointer,
12297 FK_BlockPointer
12298 };
12299
Richard Trieu10162ab2011-09-09 03:59:41 +000012300 FnKind Kind;
12301 QualType CalleeType = CalleeExpr->getType();
12302 if (CalleeType == S.Context.BoundMemberTy) {
12303 assert(isa<CXXMemberCallExpr>(E) || isa<CXXOperatorCallExpr>(E));
12304 Kind = FK_MemberFunction;
12305 CalleeType = Expr::findBoundMemberType(CalleeExpr);
12306 } else if (const PointerType *Ptr = CalleeType->getAs<PointerType>()) {
12307 CalleeType = Ptr->getPointeeType();
12308 Kind = FK_FunctionPointer;
John McCall2d2e8702011-04-11 07:02:50 +000012309 } else {
Richard Trieu10162ab2011-09-09 03:59:41 +000012310 CalleeType = CalleeType->castAs<BlockPointerType>()->getPointeeType();
12311 Kind = FK_BlockPointer;
John McCall2d2e8702011-04-11 07:02:50 +000012312 }
Richard Trieu10162ab2011-09-09 03:59:41 +000012313 const FunctionType *FnType = CalleeType->castAs<FunctionType>();
John McCall2d2e8702011-04-11 07:02:50 +000012314
12315 // Verify that this is a legal result type of a function.
12316 if (DestType->isArrayType() || DestType->isFunctionType()) {
12317 unsigned diagID = diag::err_func_returning_array_function;
Richard Trieu10162ab2011-09-09 03:59:41 +000012318 if (Kind == FK_BlockPointer)
John McCall2d2e8702011-04-11 07:02:50 +000012319 diagID = diag::err_block_returning_array_function;
12320
Richard Trieu10162ab2011-09-09 03:59:41 +000012321 S.Diag(E->getExprLoc(), diagID)
John McCall2d2e8702011-04-11 07:02:50 +000012322 << DestType->isFunctionType() << DestType;
12323 return ExprError();
12324 }
12325
12326 // Otherwise, go ahead and set DestType as the call's result.
Richard Trieu10162ab2011-09-09 03:59:41 +000012327 E->setType(DestType.getNonLValueExprType(S.Context));
12328 E->setValueKind(Expr::getValueKindForType(DestType));
12329 assert(E->getObjectKind() == OK_Ordinary);
John McCall2d2e8702011-04-11 07:02:50 +000012330
12331 // Rebuild the function type, replacing the result type with DestType.
John McCall611d9b62013-06-27 22:43:24 +000012332 const FunctionProtoType *Proto = dyn_cast<FunctionProtoType>(FnType);
12333 if (Proto) {
12334 // __unknown_anytype(...) is a special case used by the debugger when
12335 // it has no idea what a function's signature is.
12336 //
12337 // We want to build this call essentially under the K&R
12338 // unprototyped rules, but making a FunctionNoProtoType in C++
12339 // would foul up all sorts of assumptions. However, we cannot
12340 // simply pass all arguments as variadic arguments, nor can we
12341 // portably just call the function under a non-variadic type; see
12342 // the comment on IR-gen's TargetInfo::isNoProtoCallVariadic.
12343 // However, it turns out that in practice it is generally safe to
12344 // call a function declared as "A foo(B,C,D);" under the prototype
12345 // "A foo(B,C,D,...);". The only known exception is with the
12346 // Windows ABI, where any variadic function is implicitly cdecl
12347 // regardless of its normal CC. Therefore we change the parameter
12348 // types to match the types of the arguments.
12349 //
12350 // This is a hack, but it is far superior to moving the
12351 // corresponding target-specific code from IR-gen to Sema/AST.
12352
12353 ArrayRef<QualType> ParamTypes = Proto->getArgTypes();
12354 SmallVector<QualType, 8> ArgTypes;
12355 if (ParamTypes.empty() && Proto->isVariadic()) { // the special case
12356 ArgTypes.reserve(E->getNumArgs());
12357 for (unsigned i = 0, e = E->getNumArgs(); i != e; ++i) {
12358 Expr *Arg = E->getArg(i);
12359 QualType ArgType = Arg->getType();
12360 if (E->isLValue()) {
12361 ArgType = S.Context.getLValueReferenceType(ArgType);
12362 } else if (E->isXValue()) {
12363 ArgType = S.Context.getRValueReferenceType(ArgType);
12364 }
12365 ArgTypes.push_back(ArgType);
12366 }
12367 ParamTypes = ArgTypes;
12368 }
12369 DestType = S.Context.getFunctionType(DestType, ParamTypes,
Reid Kleckner896b32f2013-06-10 20:51:09 +000012370 Proto->getExtProtoInfo());
John McCall611d9b62013-06-27 22:43:24 +000012371 } else {
John McCall2d2e8702011-04-11 07:02:50 +000012372 DestType = S.Context.getFunctionNoProtoType(DestType,
Richard Trieu10162ab2011-09-09 03:59:41 +000012373 FnType->getExtInfo());
John McCall611d9b62013-06-27 22:43:24 +000012374 }
John McCall2d2e8702011-04-11 07:02:50 +000012375
12376 // Rebuild the appropriate pointer-to-function type.
Richard Trieu10162ab2011-09-09 03:59:41 +000012377 switch (Kind) {
John McCall4adb38c2011-04-27 00:36:17 +000012378 case FK_MemberFunction:
John McCall2d2e8702011-04-11 07:02:50 +000012379 // Nothing to do.
12380 break;
12381
12382 case FK_FunctionPointer:
12383 DestType = S.Context.getPointerType(DestType);
12384 break;
12385
12386 case FK_BlockPointer:
12387 DestType = S.Context.getBlockPointerType(DestType);
12388 break;
12389 }
12390
12391 // Finally, we can recurse.
Richard Trieu10162ab2011-09-09 03:59:41 +000012392 ExprResult CalleeResult = Visit(CalleeExpr);
12393 if (!CalleeResult.isUsable()) return ExprError();
12394 E->setCallee(CalleeResult.take());
John McCall2d2e8702011-04-11 07:02:50 +000012395
12396 // Bind a temporary if necessary.
Richard Trieu10162ab2011-09-09 03:59:41 +000012397 return S.MaybeBindToTemporary(E);
John McCall2d2e8702011-04-11 07:02:50 +000012398}
12399
Richard Trieu10162ab2011-09-09 03:59:41 +000012400ExprResult RebuildUnknownAnyExpr::VisitObjCMessageExpr(ObjCMessageExpr *E) {
John McCall2979fe02011-04-12 00:42:48 +000012401 // Verify that this is a legal result type of a call.
12402 if (DestType->isArrayType() || DestType->isFunctionType()) {
Richard Trieu10162ab2011-09-09 03:59:41 +000012403 S.Diag(E->getExprLoc(), diag::err_func_returning_array_function)
John McCall2979fe02011-04-12 00:42:48 +000012404 << DestType->isFunctionType() << DestType;
12405 return ExprError();
John McCall2d2e8702011-04-11 07:02:50 +000012406 }
12407
John McCall3f4138c2011-07-13 17:56:40 +000012408 // Rewrite the method result type if available.
Richard Trieu10162ab2011-09-09 03:59:41 +000012409 if (ObjCMethodDecl *Method = E->getMethodDecl()) {
12410 assert(Method->getResultType() == S.Context.UnknownAnyTy);
12411 Method->setResultType(DestType);
John McCall3f4138c2011-07-13 17:56:40 +000012412 }
John McCall2979fe02011-04-12 00:42:48 +000012413
John McCall2d2e8702011-04-11 07:02:50 +000012414 // Change the type of the message.
Richard Trieu10162ab2011-09-09 03:59:41 +000012415 E->setType(DestType.getNonReferenceType());
12416 E->setValueKind(Expr::getValueKindForType(DestType));
John McCall2d2e8702011-04-11 07:02:50 +000012417
Richard Trieu10162ab2011-09-09 03:59:41 +000012418 return S.MaybeBindToTemporary(E);
John McCall2d2e8702011-04-11 07:02:50 +000012419}
12420
Richard Trieu10162ab2011-09-09 03:59:41 +000012421ExprResult RebuildUnknownAnyExpr::VisitImplicitCastExpr(ImplicitCastExpr *E) {
John McCall2979fe02011-04-12 00:42:48 +000012422 // The only case we should ever see here is a function-to-pointer decay.
Sean Callanan2db103c2012-03-06 23:12:57 +000012423 if (E->getCastKind() == CK_FunctionToPointerDecay) {
Sean Callanan12495112012-03-06 21:34:12 +000012424 assert(E->getValueKind() == VK_RValue);
12425 assert(E->getObjectKind() == OK_Ordinary);
12426
12427 E->setType(DestType);
12428
12429 // Rebuild the sub-expression as the pointee (function) type.
12430 DestType = DestType->castAs<PointerType>()->getPointeeType();
12431
12432 ExprResult Result = Visit(E->getSubExpr());
12433 if (!Result.isUsable()) return ExprError();
12434
12435 E->setSubExpr(Result.take());
12436 return S.Owned(E);
Sean Callanan2db103c2012-03-06 23:12:57 +000012437 } else if (E->getCastKind() == CK_LValueToRValue) {
Sean Callanan12495112012-03-06 21:34:12 +000012438 assert(E->getValueKind() == VK_RValue);
12439 assert(E->getObjectKind() == OK_Ordinary);
John McCall2d2e8702011-04-11 07:02:50 +000012440
Sean Callanan12495112012-03-06 21:34:12 +000012441 assert(isa<BlockPointerType>(E->getType()));
John McCall2979fe02011-04-12 00:42:48 +000012442
Sean Callanan12495112012-03-06 21:34:12 +000012443 E->setType(DestType);
John McCall2d2e8702011-04-11 07:02:50 +000012444
Sean Callanan12495112012-03-06 21:34:12 +000012445 // The sub-expression has to be a lvalue reference, so rebuild it as such.
12446 DestType = S.Context.getLValueReferenceType(DestType);
John McCall2d2e8702011-04-11 07:02:50 +000012447
Sean Callanan12495112012-03-06 21:34:12 +000012448 ExprResult Result = Visit(E->getSubExpr());
12449 if (!Result.isUsable()) return ExprError();
12450
12451 E->setSubExpr(Result.take());
12452 return S.Owned(E);
Sean Callanan2db103c2012-03-06 23:12:57 +000012453 } else {
Sean Callanan12495112012-03-06 21:34:12 +000012454 llvm_unreachable("Unhandled cast type!");
12455 }
John McCall2d2e8702011-04-11 07:02:50 +000012456}
12457
Richard Trieu10162ab2011-09-09 03:59:41 +000012458ExprResult RebuildUnknownAnyExpr::resolveDecl(Expr *E, ValueDecl *VD) {
12459 ExprValueKind ValueKind = VK_LValue;
12460 QualType Type = DestType;
John McCall2d2e8702011-04-11 07:02:50 +000012461
12462 // We know how to make this work for certain kinds of decls:
12463
12464 // - functions
Richard Trieu10162ab2011-09-09 03:59:41 +000012465 if (FunctionDecl *FD = dyn_cast<FunctionDecl>(VD)) {
12466 if (const PointerType *Ptr = Type->getAs<PointerType>()) {
12467 DestType = Ptr->getPointeeType();
12468 ExprResult Result = resolveDecl(E, VD);
12469 if (Result.isInvalid()) return ExprError();
12470 return S.ImpCastExprToType(Result.take(), Type,
John McCall9a877fe2011-08-10 04:12:23 +000012471 CK_FunctionToPointerDecay, VK_RValue);
12472 }
12473
Richard Trieu10162ab2011-09-09 03:59:41 +000012474 if (!Type->isFunctionType()) {
12475 S.Diag(E->getExprLoc(), diag::err_unknown_any_function)
12476 << VD << E->getSourceRange();
John McCall9a877fe2011-08-10 04:12:23 +000012477 return ExprError();
12478 }
John McCall2d2e8702011-04-11 07:02:50 +000012479
Richard Trieu10162ab2011-09-09 03:59:41 +000012480 if (CXXMethodDecl *MD = dyn_cast<CXXMethodDecl>(FD))
12481 if (MD->isInstance()) {
12482 ValueKind = VK_RValue;
12483 Type = S.Context.BoundMemberTy;
John McCall4adb38c2011-04-27 00:36:17 +000012484 }
12485
John McCall2d2e8702011-04-11 07:02:50 +000012486 // Function references aren't l-values in C.
David Blaikiebbafb8a2012-03-11 07:00:24 +000012487 if (!S.getLangOpts().CPlusPlus)
Richard Trieu10162ab2011-09-09 03:59:41 +000012488 ValueKind = VK_RValue;
John McCall2d2e8702011-04-11 07:02:50 +000012489
12490 // - variables
Richard Trieu10162ab2011-09-09 03:59:41 +000012491 } else if (isa<VarDecl>(VD)) {
12492 if (const ReferenceType *RefTy = Type->getAs<ReferenceType>()) {
12493 Type = RefTy->getPointeeType();
12494 } else if (Type->isFunctionType()) {
12495 S.Diag(E->getExprLoc(), diag::err_unknown_any_var_function_type)
12496 << VD << E->getSourceRange();
John McCall2979fe02011-04-12 00:42:48 +000012497 return ExprError();
John McCall2d2e8702011-04-11 07:02:50 +000012498 }
12499
12500 // - nothing else
12501 } else {
Richard Trieu10162ab2011-09-09 03:59:41 +000012502 S.Diag(E->getExprLoc(), diag::err_unsupported_unknown_any_decl)
12503 << VD << E->getSourceRange();
John McCall2d2e8702011-04-11 07:02:50 +000012504 return ExprError();
12505 }
12506
John McCall611d9b62013-06-27 22:43:24 +000012507 // Modifying the declaration like this is friendly to IR-gen but
12508 // also really dangerous.
Richard Trieu10162ab2011-09-09 03:59:41 +000012509 VD->setType(DestType);
12510 E->setType(Type);
12511 E->setValueKind(ValueKind);
12512 return S.Owned(E);
John McCall2d2e8702011-04-11 07:02:50 +000012513}
12514
John McCall31996342011-04-07 08:22:57 +000012515/// Check a cast of an unknown-any type. We intentionally only
12516/// trigger this for C-style casts.
Richard Trieuba63ce62011-09-09 01:45:06 +000012517ExprResult Sema::checkUnknownAnyCast(SourceRange TypeRange, QualType CastType,
12518 Expr *CastExpr, CastKind &CastKind,
12519 ExprValueKind &VK, CXXCastPath &Path) {
John McCall31996342011-04-07 08:22:57 +000012520 // Rewrite the casted expression from scratch.
Richard Trieuba63ce62011-09-09 01:45:06 +000012521 ExprResult result = RebuildUnknownAnyExpr(*this, CastType).Visit(CastExpr);
John McCall39439732011-04-09 22:50:59 +000012522 if (!result.isUsable()) return ExprError();
John McCall31996342011-04-07 08:22:57 +000012523
Richard Trieuba63ce62011-09-09 01:45:06 +000012524 CastExpr = result.take();
12525 VK = CastExpr->getValueKind();
12526 CastKind = CK_NoOp;
John McCall39439732011-04-09 22:50:59 +000012527
Richard Trieuba63ce62011-09-09 01:45:06 +000012528 return CastExpr;
John McCall31996342011-04-07 08:22:57 +000012529}
12530
Douglas Gregord8fb1e32011-12-01 01:37:36 +000012531ExprResult Sema::forceUnknownAnyToType(Expr *E, QualType ToType) {
12532 return RebuildUnknownAnyExpr(*this, ToType).Visit(E);
12533}
12534
John McCallcc5788c2013-03-04 07:34:02 +000012535ExprResult Sema::checkUnknownAnyArg(SourceLocation callLoc,
12536 Expr *arg, QualType &paramType) {
12537 // If the syntactic form of the argument is not an explicit cast of
12538 // any sort, just do default argument promotion.
12539 ExplicitCastExpr *castArg = dyn_cast<ExplicitCastExpr>(arg->IgnoreParens());
12540 if (!castArg) {
12541 ExprResult result = DefaultArgumentPromotion(arg);
12542 if (result.isInvalid()) return ExprError();
12543 paramType = result.get()->getType();
12544 return result;
John McCallea0a39e2012-11-14 00:49:39 +000012545 }
12546
John McCallcc5788c2013-03-04 07:34:02 +000012547 // Otherwise, use the type that was written in the explicit cast.
12548 assert(!arg->hasPlaceholderType());
12549 paramType = castArg->getTypeAsWritten();
12550
12551 // Copy-initialize a parameter of that type.
12552 InitializedEntity entity =
12553 InitializedEntity::InitializeParameter(Context, paramType,
12554 /*consumed*/ false);
12555 return PerformCopyInitialization(entity, callLoc, Owned(arg));
John McCallea0a39e2012-11-14 00:49:39 +000012556}
12557
Richard Trieuba63ce62011-09-09 01:45:06 +000012558static ExprResult diagnoseUnknownAnyExpr(Sema &S, Expr *E) {
12559 Expr *orig = E;
John McCall2d2e8702011-04-11 07:02:50 +000012560 unsigned diagID = diag::err_uncasted_use_of_unknown_any;
John McCall31996342011-04-07 08:22:57 +000012561 while (true) {
Richard Trieuba63ce62011-09-09 01:45:06 +000012562 E = E->IgnoreParenImpCasts();
12563 if (CallExpr *call = dyn_cast<CallExpr>(E)) {
12564 E = call->getCallee();
John McCall2d2e8702011-04-11 07:02:50 +000012565 diagID = diag::err_uncasted_call_of_unknown_any;
12566 } else {
John McCall31996342011-04-07 08:22:57 +000012567 break;
John McCall2d2e8702011-04-11 07:02:50 +000012568 }
John McCall31996342011-04-07 08:22:57 +000012569 }
12570
John McCall2d2e8702011-04-11 07:02:50 +000012571 SourceLocation loc;
12572 NamedDecl *d;
Richard Trieuba63ce62011-09-09 01:45:06 +000012573 if (DeclRefExpr *ref = dyn_cast<DeclRefExpr>(E)) {
John McCall2d2e8702011-04-11 07:02:50 +000012574 loc = ref->getLocation();
12575 d = ref->getDecl();
Richard Trieuba63ce62011-09-09 01:45:06 +000012576 } else if (MemberExpr *mem = dyn_cast<MemberExpr>(E)) {
John McCall2d2e8702011-04-11 07:02:50 +000012577 loc = mem->getMemberLoc();
12578 d = mem->getMemberDecl();
Richard Trieuba63ce62011-09-09 01:45:06 +000012579 } else if (ObjCMessageExpr *msg = dyn_cast<ObjCMessageExpr>(E)) {
John McCall2d2e8702011-04-11 07:02:50 +000012580 diagID = diag::err_uncasted_call_of_unknown_any;
Argyrios Kyrtzidisa6011e22011-10-03 06:36:51 +000012581 loc = msg->getSelectorStartLoc();
John McCall2d2e8702011-04-11 07:02:50 +000012582 d = msg->getMethodDecl();
John McCallfa6f5d62011-08-31 20:57:36 +000012583 if (!d) {
12584 S.Diag(loc, diag::err_uncasted_send_to_unknown_any_method)
12585 << static_cast<unsigned>(msg->isClassMessage()) << msg->getSelector()
12586 << orig->getSourceRange();
12587 return ExprError();
12588 }
John McCall2d2e8702011-04-11 07:02:50 +000012589 } else {
Richard Trieuba63ce62011-09-09 01:45:06 +000012590 S.Diag(E->getExprLoc(), diag::err_unsupported_unknown_any_expr)
12591 << E->getSourceRange();
John McCall2d2e8702011-04-11 07:02:50 +000012592 return ExprError();
12593 }
12594
12595 S.Diag(loc, diagID) << d << orig->getSourceRange();
John McCall31996342011-04-07 08:22:57 +000012596
12597 // Never recoverable.
12598 return ExprError();
12599}
12600
John McCall36e7fe32010-10-12 00:20:44 +000012601/// Check for operands with placeholder types and complain if found.
12602/// Returns true if there was an error and no recovery was possible.
John McCall3aef3d82011-04-10 19:13:55 +000012603ExprResult Sema::CheckPlaceholderExpr(Expr *E) {
John McCall4124c492011-10-17 18:40:02 +000012604 const BuiltinType *placeholderType = E->getType()->getAsPlaceholderType();
12605 if (!placeholderType) return Owned(E);
12606
12607 switch (placeholderType->getKind()) {
John McCall36e7fe32010-10-12 00:20:44 +000012608
John McCall31996342011-04-07 08:22:57 +000012609 // Overloaded expressions.
John McCall4124c492011-10-17 18:40:02 +000012610 case BuiltinType::Overload: {
John McCall50a2c2c2011-10-11 23:14:30 +000012611 // Try to resolve a single function template specialization.
12612 // This is obligatory.
12613 ExprResult result = Owned(E);
12614 if (ResolveAndFixSingleFunctionTemplateSpecialization(result, false)) {
12615 return result;
12616
12617 // If that failed, try to recover with a call.
12618 } else {
12619 tryToRecoverWithCall(result, PDiag(diag::err_ovl_unresolvable),
12620 /*complain*/ true);
12621 return result;
12622 }
12623 }
John McCall31996342011-04-07 08:22:57 +000012624
John McCall0009fcc2011-04-26 20:42:42 +000012625 // Bound member functions.
John McCall4124c492011-10-17 18:40:02 +000012626 case BuiltinType::BoundMember: {
John McCall50a2c2c2011-10-11 23:14:30 +000012627 ExprResult result = Owned(E);
12628 tryToRecoverWithCall(result, PDiag(diag::err_bound_member_function),
12629 /*complain*/ true);
12630 return result;
John McCall4124c492011-10-17 18:40:02 +000012631 }
12632
12633 // ARC unbridged casts.
12634 case BuiltinType::ARCUnbridgedCast: {
12635 Expr *realCast = stripARCUnbridgedCast(E);
12636 diagnoseARCUnbridgedCast(realCast);
12637 return Owned(realCast);
12638 }
John McCall0009fcc2011-04-26 20:42:42 +000012639
John McCall31996342011-04-07 08:22:57 +000012640 // Expressions of unknown type.
John McCall4124c492011-10-17 18:40:02 +000012641 case BuiltinType::UnknownAny:
John McCall31996342011-04-07 08:22:57 +000012642 return diagnoseUnknownAnyExpr(*this, E);
12643
John McCall526ab472011-10-25 17:37:35 +000012644 // Pseudo-objects.
12645 case BuiltinType::PseudoObject:
12646 return checkPseudoObjectRValue(E);
12647
Eli Friedman34866c72012-08-31 00:14:07 +000012648 case BuiltinType::BuiltinFn:
12649 Diag(E->getLocStart(), diag::err_builtin_fn_use);
12650 return ExprError();
12651
John McCalle314e272011-10-18 21:02:43 +000012652 // Everything else should be impossible.
12653#define BUILTIN_TYPE(Id, SingletonId) \
12654 case BuiltinType::Id:
12655#define PLACEHOLDER_TYPE(Id, SingletonId)
12656#include "clang/AST/BuiltinTypes.def"
John McCall4124c492011-10-17 18:40:02 +000012657 break;
12658 }
12659
12660 llvm_unreachable("invalid placeholder type!");
John McCall36e7fe32010-10-12 00:20:44 +000012661}
Richard Trieu2c850c02011-04-21 21:44:26 +000012662
Richard Trieuba63ce62011-09-09 01:45:06 +000012663bool Sema::CheckCaseExpression(Expr *E) {
12664 if (E->isTypeDependent())
Richard Trieu2c850c02011-04-21 21:44:26 +000012665 return true;
Richard Trieuba63ce62011-09-09 01:45:06 +000012666 if (E->isValueDependent() || E->isIntegerConstantExpr(Context))
12667 return E->getType()->isIntegralOrEnumerationType();
Richard Trieu2c850c02011-04-21 21:44:26 +000012668 return false;
12669}
Ted Kremeneke65b0862012-03-06 20:05:56 +000012670
12671/// ActOnObjCBoolLiteral - Parse {__objc_yes,__objc_no} literals.
12672ExprResult
12673Sema::ActOnObjCBoolLiteral(SourceLocation OpLoc, tok::TokenKind Kind) {
12674 assert((Kind == tok::kw___objc_yes || Kind == tok::kw___objc_no) &&
12675 "Unknown Objective-C Boolean value!");
Fariborz Jahanianf2578572012-08-30 18:49:41 +000012676 QualType BoolT = Context.ObjCBuiltinBoolTy;
12677 if (!Context.getBOOLDecl()) {
Fariborz Jahanianeab17302012-10-16 17:08:11 +000012678 LookupResult Result(*this, &Context.Idents.get("BOOL"), OpLoc,
Fariborz Jahanianf2578572012-08-30 18:49:41 +000012679 Sema::LookupOrdinaryName);
Fariborz Jahanian379e5362012-10-16 16:21:20 +000012680 if (LookupName(Result, getCurScope()) && Result.isSingleResult()) {
Fariborz Jahanianf2578572012-08-30 18:49:41 +000012681 NamedDecl *ND = Result.getFoundDecl();
12682 if (TypedefDecl *TD = dyn_cast<TypedefDecl>(ND))
12683 Context.setBOOLDecl(TD);
12684 }
12685 }
12686 if (Context.getBOOLDecl())
12687 BoolT = Context.getBOOLType();
Ted Kremeneke65b0862012-03-06 20:05:56 +000012688 return Owned(new (Context) ObjCBoolLiteralExpr(Kind == tok::kw___objc_yes,
Fariborz Jahanianf2578572012-08-30 18:49:41 +000012689 BoolT, OpLoc));
Ted Kremeneke65b0862012-03-06 20:05:56 +000012690}