blob: b864a2e8a06e07195e891d428e0eb1dbea15b4b8 [file] [log] [blame]
Chris Lattner5b183d82006-11-10 05:03:26 +00001//===--- SemaExpr.cpp - Semantic Analysis for Expressions -----------------===//
2//
3// The LLVM Compiler Infrastructure
4//
Chris Lattner5b12ab82007-12-29 19:59:25 +00005// This file is distributed under the University of Illinois Open Source
6// License. See LICENSE.TXT for details.
Chris Lattner5b183d82006-11-10 05:03:26 +00007//
8//===----------------------------------------------------------------------===//
9//
10// This file implements semantic analysis for expressions.
11//
12//===----------------------------------------------------------------------===//
13
John McCall83024632010-08-25 22:03:47 +000014#include "clang/Sema/SemaInternal.h"
Eli Friedmanfbc0dff2012-01-18 01:05:54 +000015#include "clang/Sema/DelayedDiagnostic.h"
Douglas Gregorc3a6ade2010-08-12 20:07:10 +000016#include "clang/Sema/Initialization.h"
17#include "clang/Sema/Lookup.h"
Eli Friedmanfbc0dff2012-01-18 01:05:54 +000018#include "clang/Sema/ScopeInfo.h"
Douglas Gregorc3a6ade2010-08-12 20:07:10 +000019#include "clang/Sema/AnalysisBasedWarnings.h"
Chris Lattnercb6a3822006-11-10 06:20:45 +000020#include "clang/AST/ASTContext.h"
Argyrios Kyrtzidise5dc5b32012-02-10 20:10:44 +000021#include "clang/AST/ASTConsumer.h"
Sebastian Redl2ac2c722011-04-29 08:19:30 +000022#include "clang/AST/ASTMutationListener.h"
Douglas Gregord1702062010-04-29 00:18:15 +000023#include "clang/AST/CXXInheritance.h"
Daniel Dunbar6e8aa532008-08-11 05:35:13 +000024#include "clang/AST/DeclObjC.h"
Anders Carlsson029fc692009-08-26 22:59:12 +000025#include "clang/AST/DeclTemplate.h"
Douglas Gregor8a01b2a2010-09-11 20:24:53 +000026#include "clang/AST/EvaluatedExprVisitor.h"
Douglas Gregor882211c2010-04-28 22:16:22 +000027#include "clang/AST/Expr.h"
Chris Lattneraa9c7ae2008-04-08 04:40:51 +000028#include "clang/AST/ExprCXX.h"
Steve Naroff021ca182008-05-29 21:12:08 +000029#include "clang/AST/ExprObjC.h"
Douglas Gregor5597ab42010-05-07 23:12:07 +000030#include "clang/AST/RecursiveASTVisitor.h"
Douglas Gregor882211c2010-04-28 22:16:22 +000031#include "clang/AST/TypeLoc.h"
Anders Carlsson029fc692009-08-26 22:59:12 +000032#include "clang/Basic/PartialDiagnostic.h"
Steve Narofff2fb89e2007-03-13 20:29:44 +000033#include "clang/Basic/SourceManager.h"
Chris Lattner5b183d82006-11-10 05:03:26 +000034#include "clang/Basic/TargetInfo.h"
Anders Carlsson029fc692009-08-26 22:59:12 +000035#include "clang/Lex/LiteralSupport.h"
36#include "clang/Lex/Preprocessor.h"
John McCall8b0666c2010-08-20 18:27:03 +000037#include "clang/Sema/DeclSpec.h"
38#include "clang/Sema/Designator.h"
39#include "clang/Sema/Scope.h"
John McCallaab3e412010-08-25 08:40:02 +000040#include "clang/Sema/ScopeInfo.h"
John McCall8b0666c2010-08-20 18:27:03 +000041#include "clang/Sema/ParsedTemplate.h"
Anna Zaks3b402712011-07-28 19:51:27 +000042#include "clang/Sema/SemaFixItUtils.h"
John McCallde6836a2010-08-24 07:21:54 +000043#include "clang/Sema/Template.h"
Eli Friedman456f0182012-01-20 01:26:23 +000044#include "TreeTransform.h"
Chris Lattner5b183d82006-11-10 05:03:26 +000045using namespace clang;
John McCallaab3e412010-08-25 08:40:02 +000046using namespace sema;
Chris Lattner5b183d82006-11-10 05:03:26 +000047
Sebastian Redlb49c46c2011-09-24 17:48:00 +000048/// \brief Determine whether the use of this declaration is valid, without
49/// emitting diagnostics.
50bool Sema::CanUseDecl(NamedDecl *D) {
51 // See if this is an auto-typed variable whose initializer we are parsing.
52 if (ParsingInitForAutoVars.count(D))
53 return false;
54
55 // See if this is a deleted function.
56 if (FunctionDecl *FD = dyn_cast<FunctionDecl>(D)) {
57 if (FD->isDeleted())
58 return false;
59 }
Sebastian Redl5999aec2011-10-16 18:19:16 +000060
61 // See if this function is unavailable.
62 if (D->getAvailability() == AR_Unavailable &&
63 cast<Decl>(CurContext)->getAvailability() != AR_Unavailable)
64 return false;
65
Sebastian Redlb49c46c2011-09-24 17:48:00 +000066 return true;
67}
David Chisnall9f57c292009-08-17 16:35:33 +000068
Fariborz Jahanian66c93f42012-09-06 16:43:18 +000069static void DiagnoseUnusedOfDecl(Sema &S, NamedDecl *D, SourceLocation Loc) {
70 // Warn if this is used but marked unused.
71 if (D->hasAttr<UnusedAttr>()) {
Fariborz Jahanian979780f2012-09-06 18:38:58 +000072 const Decl *DC = cast<Decl>(S.getCurObjCLexicalContext());
Fariborz Jahanian66c93f42012-09-06 16:43:18 +000073 if (!DC->hasAttr<UnusedAttr>())
74 S.Diag(Loc, diag::warn_used_but_marked_unused) << D->getDeclName();
75 }
76}
77
Ted Kremenek6eb25622012-02-10 02:45:47 +000078static AvailabilityResult DiagnoseAvailabilityOfDecl(Sema &S,
Fariborz Jahanian6b854c52011-09-29 22:45:21 +000079 NamedDecl *D, SourceLocation Loc,
80 const ObjCInterfaceDecl *UnknownObjCClass) {
81 // See if this declaration is unavailable or deprecated.
82 std::string Message;
83 AvailabilityResult Result = D->getAvailability(&Message);
Fariborz Jahanian25d09c22011-11-28 19:45:58 +000084 if (const EnumConstantDecl *ECD = dyn_cast<EnumConstantDecl>(D))
85 if (Result == AR_Available) {
86 const DeclContext *DC = ECD->getDeclContext();
87 if (const EnumDecl *TheEnumDecl = dyn_cast<EnumDecl>(DC))
88 Result = TheEnumDecl->getAvailability(&Message);
89 }
Fariborz Jahanian974c9482012-09-21 20:46:37 +000090 const ObjCPropertyDecl *ObjCPDecl = 0;
91 if (Result == AR_Deprecated || Result == AR_Unavailable)
92 if (ObjCPropertyDecl *ND = S.PropertyIfSetterOrGetter(D)) {
93 AvailabilityResult PDeclResult = ND->getAvailability(0);
94 if (PDeclResult == Result)
95 ObjCPDecl = ND;
96 }
Fariborz Jahanian25d09c22011-11-28 19:45:58 +000097
Fariborz Jahanian6b854c52011-09-29 22:45:21 +000098 switch (Result) {
99 case AR_Available:
100 case AR_NotYetIntroduced:
101 break;
102
103 case AR_Deprecated:
Fariborz Jahanian974c9482012-09-21 20:46:37 +0000104 S.EmitDeprecationWarning(D, Message, Loc, UnknownObjCClass, ObjCPDecl);
Fariborz Jahanian6b854c52011-09-29 22:45:21 +0000105 break;
106
107 case AR_Unavailable:
Ted Kremenek6eb25622012-02-10 02:45:47 +0000108 if (S.getCurContextAvailability() != AR_Unavailable) {
Fariborz Jahanian6b854c52011-09-29 22:45:21 +0000109 if (Message.empty()) {
Fariborz Jahanian974c9482012-09-21 20:46:37 +0000110 if (!UnknownObjCClass) {
Ted Kremenek6eb25622012-02-10 02:45:47 +0000111 S.Diag(Loc, diag::err_unavailable) << D->getDeclName();
Fariborz Jahanian974c9482012-09-21 20:46:37 +0000112 if (ObjCPDecl)
113 S.Diag(ObjCPDecl->getLocation(), diag::note_property_attribute)
114 << ObjCPDecl->getDeclName() << 1;
115 }
Fariborz Jahanian6b854c52011-09-29 22:45:21 +0000116 else
Ted Kremenek6eb25622012-02-10 02:45:47 +0000117 S.Diag(Loc, diag::warn_unavailable_fwdclass_message)
Fariborz Jahanian6b854c52011-09-29 22:45:21 +0000118 << D->getDeclName();
119 }
Fariborz Jahanian974c9482012-09-21 20:46:37 +0000120 else
Ted Kremenek6eb25622012-02-10 02:45:47 +0000121 S.Diag(Loc, diag::err_unavailable_message)
Fariborz Jahanian6b854c52011-09-29 22:45:21 +0000122 << D->getDeclName() << Message;
Fariborz Jahanian974c9482012-09-21 20:46:37 +0000123 S.Diag(D->getLocation(), diag::note_unavailable_here)
124 << isa<FunctionDecl>(D) << false;
125 if (ObjCPDecl)
126 S.Diag(ObjCPDecl->getLocation(), diag::note_property_attribute)
127 << ObjCPDecl->getDeclName() << 1;
Fariborz Jahanian6b854c52011-09-29 22:45:21 +0000128 }
129 break;
130 }
131 return Result;
132}
133
Richard Smith852265f2012-03-30 20:53:28 +0000134/// \brief Emit a note explaining that this function is deleted or unavailable.
135void Sema::NoteDeletedFunction(FunctionDecl *Decl) {
136 CXXMethodDecl *Method = dyn_cast<CXXMethodDecl>(Decl);
137
Richard Smith6f1e2c62012-04-02 20:59:25 +0000138 if (Method && Method->isDeleted() && !Method->isDeletedAsWritten()) {
139 // If the method was explicitly defaulted, point at that declaration.
140 if (!Method->isImplicit())
141 Diag(Decl->getLocation(), diag::note_implicitly_deleted);
142
143 // Try to diagnose why this special member function was implicitly
144 // deleted. This might fail, if that reason no longer applies.
Richard Smith852265f2012-03-30 20:53:28 +0000145 CXXSpecialMember CSM = getSpecialMember(Method);
Richard Smith6f1e2c62012-04-02 20:59:25 +0000146 if (CSM != CXXInvalid)
147 ShouldDeleteSpecialMember(Method, CSM, /*Diagnose=*/true);
148
149 return;
Richard Smith852265f2012-03-30 20:53:28 +0000150 }
151
152 Diag(Decl->getLocation(), diag::note_unavailable_here)
153 << 1 << Decl->isDeleted();
154}
155
Jordan Rose28cd12f2012-06-18 22:09:19 +0000156/// \brief Determine whether a FunctionDecl was ever declared with an
157/// explicit storage class.
158static bool hasAnyExplicitStorageClass(const FunctionDecl *D) {
159 for (FunctionDecl::redecl_iterator I = D->redecls_begin(),
160 E = D->redecls_end();
161 I != E; ++I) {
162 if (I->getStorageClassAsWritten() != SC_None)
163 return true;
164 }
165 return false;
166}
167
168/// \brief Check whether we're in an extern inline function and referring to a
Jordan Rosede9e9762012-06-20 18:50:06 +0000169/// variable or function with internal linkage (C11 6.7.4p3).
Jordan Rose28cd12f2012-06-18 22:09:19 +0000170///
Jordan Rose28cd12f2012-06-18 22:09:19 +0000171/// This is only a warning because we used to silently accept this code, but
Jordan Rosede9e9762012-06-20 18:50:06 +0000172/// in many cases it will not behave correctly. This is not enabled in C++ mode
173/// because the restriction language is a bit weaker (C++11 [basic.def.odr]p6)
174/// and so while there may still be user mistakes, most of the time we can't
175/// prove that there are errors.
Jordan Rose28cd12f2012-06-18 22:09:19 +0000176static void diagnoseUseOfInternalDeclInInlineFunction(Sema &S,
177 const NamedDecl *D,
178 SourceLocation Loc) {
Jordan Rosede9e9762012-06-20 18:50:06 +0000179 // This is disabled under C++; there are too many ways for this to fire in
180 // contexts where the warning is a false positive, or where it is technically
181 // correct but benign.
182 if (S.getLangOpts().CPlusPlus)
183 return;
Jordan Rose28cd12f2012-06-18 22:09:19 +0000184
185 // Check if this is an inlined function or method.
186 FunctionDecl *Current = S.getCurFunctionDecl();
187 if (!Current)
188 return;
189 if (!Current->isInlined())
190 return;
191 if (Current->getLinkage() != ExternalLinkage)
192 return;
193
194 // Check if the decl has internal linkage.
Jordan Rosede9e9762012-06-20 18:50:06 +0000195 if (D->getLinkage() != InternalLinkage)
Jordan Rose28cd12f2012-06-18 22:09:19 +0000196 return;
Jordan Rose28cd12f2012-06-18 22:09:19 +0000197
Jordan Rose815fe262012-06-21 05:54:50 +0000198 // Downgrade from ExtWarn to Extension if
199 // (1) the supposedly external inline function is in the main file,
200 // and probably won't be included anywhere else.
201 // (2) the thing we're referencing is a pure function.
202 // (3) the thing we're referencing is another inline function.
203 // This last can give us false negatives, but it's better than warning on
204 // wrappers for simple C library functions.
205 const FunctionDecl *UsedFn = dyn_cast<FunctionDecl>(D);
206 bool DowngradeWarning = S.getSourceManager().isFromMainFile(Loc);
207 if (!DowngradeWarning && UsedFn)
208 DowngradeWarning = UsedFn->isInlined() || UsedFn->hasAttr<ConstAttr>();
209
210 S.Diag(Loc, DowngradeWarning ? diag::ext_internal_in_extern_inline
211 : diag::warn_internal_in_extern_inline)
212 << /*IsVar=*/!UsedFn << D;
Jordan Rose28cd12f2012-06-18 22:09:19 +0000213
214 // Suggest "static" on the inline function, if possible.
Jordan Rosede9e9762012-06-20 18:50:06 +0000215 if (!hasAnyExplicitStorageClass(Current)) {
Jordan Rose28cd12f2012-06-18 22:09:19 +0000216 const FunctionDecl *FirstDecl = Current->getCanonicalDecl();
217 SourceLocation DeclBegin = FirstDecl->getSourceRange().getBegin();
218 S.Diag(DeclBegin, diag::note_convert_inline_to_static)
219 << Current << FixItHint::CreateInsertion(DeclBegin, "static ");
220 }
221
222 S.Diag(D->getCanonicalDecl()->getLocation(),
223 diag::note_internal_decl_declared_here)
224 << D;
225}
226
Douglas Gregor171c45a2009-02-18 21:56:37 +0000227/// \brief Determine whether the use of this declaration is valid, and
228/// emit any corresponding diagnostics.
229///
230/// This routine diagnoses various problems with referencing
231/// declarations that can occur when using a declaration. For example,
232/// it might warn if a deprecated or unavailable declaration is being
233/// used, or produce an error (and return true) if a C++0x deleted
234/// function is being used.
235///
236/// \returns true if there was an error (this declaration cannot be
237/// referenced), false otherwise.
Chris Lattnerb7df3c62009-10-25 22:31:57 +0000238///
Fariborz Jahanian7d6e11a2010-12-21 00:44:01 +0000239bool Sema::DiagnoseUseOfDecl(NamedDecl *D, SourceLocation Loc,
Fariborz Jahanian6b854c52011-09-29 22:45:21 +0000240 const ObjCInterfaceDecl *UnknownObjCClass) {
David Blaikiebbafb8a2012-03-11 07:00:24 +0000241 if (getLangOpts().CPlusPlus && isa<FunctionDecl>(D)) {
Douglas Gregor5bb5e4a2010-10-12 23:32:35 +0000242 // If there were any diagnostics suppressed by template argument deduction,
243 // emit them now.
Chris Lattner0e62c1c2011-07-23 10:55:15 +0000244 llvm::DenseMap<Decl *, SmallVector<PartialDiagnosticAt, 1> >::iterator
Douglas Gregor5bb5e4a2010-10-12 23:32:35 +0000245 Pos = SuppressedDiagnostics.find(D->getCanonicalDecl());
246 if (Pos != SuppressedDiagnostics.end()) {
Chris Lattner0e62c1c2011-07-23 10:55:15 +0000247 SmallVectorImpl<PartialDiagnosticAt> &Suppressed = Pos->second;
Douglas Gregor5bb5e4a2010-10-12 23:32:35 +0000248 for (unsigned I = 0, N = Suppressed.size(); I != N; ++I)
249 Diag(Suppressed[I].first, Suppressed[I].second);
250
251 // Clear out the list of suppressed diagnostics, so that we don't emit
Douglas Gregor20b2ebd2011-03-23 00:50:03 +0000252 // them again for this specialization. However, we don't obsolete this
Douglas Gregor5bb5e4a2010-10-12 23:32:35 +0000253 // entry from the table, because we want to avoid ever emitting these
254 // diagnostics again.
255 Suppressed.clear();
256 }
257 }
258
Richard Smith30482bc2011-02-20 03:19:35 +0000259 // See if this is an auto-typed variable whose initializer we are parsing.
Richard Smithb2bc2e62011-02-21 20:05:19 +0000260 if (ParsingInitForAutoVars.count(D)) {
261 Diag(Loc, diag::err_auto_variable_cannot_appear_in_own_initializer)
262 << D->getDeclName();
263 return true;
Richard Smith30482bc2011-02-20 03:19:35 +0000264 }
265
Douglas Gregor171c45a2009-02-18 21:56:37 +0000266 // See if this is a deleted function.
Douglas Gregorde681d42009-02-24 04:26:15 +0000267 if (FunctionDecl *FD = dyn_cast<FunctionDecl>(D)) {
Douglas Gregor171c45a2009-02-18 21:56:37 +0000268 if (FD->isDeleted()) {
269 Diag(Loc, diag::err_deleted_function_use);
Richard Smith852265f2012-03-30 20:53:28 +0000270 NoteDeletedFunction(FD);
Douglas Gregor171c45a2009-02-18 21:56:37 +0000271 return true;
272 }
Douglas Gregorde681d42009-02-24 04:26:15 +0000273 }
Ted Kremenek6eb25622012-02-10 02:45:47 +0000274 DiagnoseAvailabilityOfDecl(*this, D, Loc, UnknownObjCClass);
Douglas Gregor20b2ebd2011-03-23 00:50:03 +0000275
Fariborz Jahanian66c93f42012-09-06 16:43:18 +0000276 DiagnoseUnusedOfDecl(*this, D, Loc);
Jordan Rose2684c682012-06-15 18:19:48 +0000277
Jordan Rose28cd12f2012-06-18 22:09:19 +0000278 diagnoseUseOfInternalDeclInInlineFunction(*this, D, Loc);
Jordan Rose2684c682012-06-15 18:19:48 +0000279
Douglas Gregor171c45a2009-02-18 21:56:37 +0000280 return false;
Chris Lattner4bf74fd2009-02-15 22:43:40 +0000281}
282
Douglas Gregor20b2ebd2011-03-23 00:50:03 +0000283/// \brief Retrieve the message suffix that should be added to a
284/// diagnostic complaining about the given function being deleted or
285/// unavailable.
286std::string Sema::getDeletedOrUnavailableSuffix(const FunctionDecl *FD) {
287 // FIXME: C++0x implicitly-deleted special member functions could be
288 // detected here so that we could improve diagnostics to say, e.g.,
289 // "base class 'A' had a deleted copy constructor".
290 if (FD->isDeleted())
291 return std::string();
292
293 std::string Message;
294 if (FD->getAvailability(&Message))
295 return ": " + Message;
296
297 return std::string();
298}
299
John McCallb46f2872011-09-09 07:56:05 +0000300/// DiagnoseSentinelCalls - This routine checks whether a call or
301/// message-send is to a declaration with the sentinel attribute, and
302/// if so, it checks that the requirements of the sentinel are
303/// satisfied.
Fariborz Jahanian027b8862009-05-13 18:09:35 +0000304void Sema::DiagnoseSentinelCalls(NamedDecl *D, SourceLocation Loc,
John McCallb46f2872011-09-09 07:56:05 +0000305 Expr **args, unsigned numArgs) {
Argyrios Kyrtzidisb4b64ca2009-06-30 02:34:44 +0000306 const SentinelAttr *attr = D->getAttr<SentinelAttr>();
Mike Stump11289f42009-09-09 15:08:12 +0000307 if (!attr)
Fariborz Jahanian9e877212009-05-13 23:20:50 +0000308 return;
Douglas Gregorc298ffc2010-04-22 16:44:27 +0000309
John McCallb46f2872011-09-09 07:56:05 +0000310 // The number of formal parameters of the declaration.
311 unsigned numFormalParams;
Mike Stump11289f42009-09-09 15:08:12 +0000312
John McCallb46f2872011-09-09 07:56:05 +0000313 // The kind of declaration. This is also an index into a %select in
314 // the diagnostic.
315 enum CalleeType { CT_Function, CT_Method, CT_Block } calleeType;
316
Fariborz Jahanian4a528032009-05-14 18:00:00 +0000317 if (ObjCMethodDecl *MD = dyn_cast<ObjCMethodDecl>(D)) {
John McCallb46f2872011-09-09 07:56:05 +0000318 numFormalParams = MD->param_size();
319 calleeType = CT_Method;
Mike Stump12b8ce12009-08-04 21:02:39 +0000320 } else if (FunctionDecl *FD = dyn_cast<FunctionDecl>(D)) {
John McCallb46f2872011-09-09 07:56:05 +0000321 numFormalParams = FD->param_size();
322 calleeType = CT_Function;
323 } else if (isa<VarDecl>(D)) {
324 QualType type = cast<ValueDecl>(D)->getType();
325 const FunctionType *fn = 0;
326 if (const PointerType *ptr = type->getAs<PointerType>()) {
327 fn = ptr->getPointeeType()->getAs<FunctionType>();
328 if (!fn) return;
329 calleeType = CT_Function;
330 } else if (const BlockPointerType *ptr = type->getAs<BlockPointerType>()) {
331 fn = ptr->getPointeeType()->castAs<FunctionType>();
332 calleeType = CT_Block;
333 } else {
Fariborz Jahanian0aa5c452009-05-15 20:33:25 +0000334 return;
John McCallb46f2872011-09-09 07:56:05 +0000335 }
Fariborz Jahanian4a528032009-05-14 18:00:00 +0000336
John McCallb46f2872011-09-09 07:56:05 +0000337 if (const FunctionProtoType *proto = dyn_cast<FunctionProtoType>(fn)) {
338 numFormalParams = proto->getNumArgs();
339 } else {
340 numFormalParams = 0;
341 }
342 } else {
Fariborz Jahanian9e877212009-05-13 23:20:50 +0000343 return;
344 }
John McCallb46f2872011-09-09 07:56:05 +0000345
346 // "nullPos" is the number of formal parameters at the end which
347 // effectively count as part of the variadic arguments. This is
348 // useful if you would prefer to not have *any* formal parameters,
349 // but the language forces you to have at least one.
350 unsigned nullPos = attr->getNullPos();
351 assert((nullPos == 0 || nullPos == 1) && "invalid null position on sentinel");
352 numFormalParams = (nullPos > numFormalParams ? 0 : numFormalParams - nullPos);
353
354 // The number of arguments which should follow the sentinel.
355 unsigned numArgsAfterSentinel = attr->getSentinel();
356
357 // If there aren't enough arguments for all the formal parameters,
358 // the sentinel, and the args after the sentinel, complain.
359 if (numArgs < numFormalParams + numArgsAfterSentinel + 1) {
Fariborz Jahanian9e877212009-05-13 23:20:50 +0000360 Diag(Loc, diag::warn_not_enough_argument) << D->getDeclName();
John McCallb46f2872011-09-09 07:56:05 +0000361 Diag(D->getLocation(), diag::note_sentinel_here) << calleeType;
Fariborz Jahanian9e877212009-05-13 23:20:50 +0000362 return;
363 }
John McCallb46f2872011-09-09 07:56:05 +0000364
365 // Otherwise, find the sentinel expression.
366 Expr *sentinelExpr = args[numArgs - numArgsAfterSentinel - 1];
John McCall7ddbcf42010-05-06 23:53:00 +0000367 if (!sentinelExpr) return;
John McCall7ddbcf42010-05-06 23:53:00 +0000368 if (sentinelExpr->isValueDependent()) return;
Argyrios Kyrtzidis2e809ce2012-02-03 05:58:16 +0000369 if (Context.isSentinelNullExpr(sentinelExpr)) return;
John McCall7ddbcf42010-05-06 23:53:00 +0000370
John McCallb46f2872011-09-09 07:56:05 +0000371 // Pick a reasonable string to insert. Optimistically use 'nil' or
372 // 'NULL' if those are actually defined in the context. Only use
373 // 'nil' for ObjC methods, where it's much more likely that the
374 // variadic arguments form a list of object pointers.
375 SourceLocation MissingNilLoc
Douglas Gregor5ff4e982011-07-30 08:57:03 +0000376 = PP.getLocForEndOfToken(sentinelExpr->getLocEnd());
377 std::string NullValue;
John McCallb46f2872011-09-09 07:56:05 +0000378 if (calleeType == CT_Method &&
379 PP.getIdentifierInfo("nil")->hasMacroDefinition())
Douglas Gregor5ff4e982011-07-30 08:57:03 +0000380 NullValue = "nil";
381 else if (PP.getIdentifierInfo("NULL")->hasMacroDefinition())
382 NullValue = "NULL";
Douglas Gregor5ff4e982011-07-30 08:57:03 +0000383 else
John McCallb46f2872011-09-09 07:56:05 +0000384 NullValue = "(void*) 0";
Eli Friedman9ab36372011-09-27 23:46:37 +0000385
386 if (MissingNilLoc.isInvalid())
387 Diag(Loc, diag::warn_missing_sentinel) << calleeType;
388 else
389 Diag(MissingNilLoc, diag::warn_missing_sentinel)
390 << calleeType
391 << FixItHint::CreateInsertion(MissingNilLoc, ", " + NullValue);
John McCallb46f2872011-09-09 07:56:05 +0000392 Diag(D->getLocation(), diag::note_sentinel_here) << calleeType;
Fariborz Jahanian027b8862009-05-13 18:09:35 +0000393}
394
Richard Trieuba63ce62011-09-09 01:45:06 +0000395SourceRange Sema::getExprRange(Expr *E) const {
396 return E ? E->getSourceRange() : SourceRange();
Douglas Gregor87f95b02009-02-26 21:00:50 +0000397}
398
Chris Lattner513165e2008-07-25 21:10:04 +0000399//===----------------------------------------------------------------------===//
400// Standard Promotions and Conversions
401//===----------------------------------------------------------------------===//
402
Chris Lattner513165e2008-07-25 21:10:04 +0000403/// DefaultFunctionArrayConversion (C99 6.3.2.1p3, C99 6.3.2.1p4).
John Wiegley01296292011-04-08 18:41:53 +0000404ExprResult Sema::DefaultFunctionArrayConversion(Expr *E) {
John McCall50a2c2c2011-10-11 23:14:30 +0000405 // Handle any placeholder expressions which made it here.
406 if (E->getType()->isPlaceholderType()) {
407 ExprResult result = CheckPlaceholderExpr(E);
408 if (result.isInvalid()) return ExprError();
409 E = result.take();
410 }
411
Chris Lattner513165e2008-07-25 21:10:04 +0000412 QualType Ty = E->getType();
413 assert(!Ty.isNull() && "DefaultFunctionArrayConversion - missing type");
414
Chris Lattner513165e2008-07-25 21:10:04 +0000415 if (Ty->isFunctionType())
John Wiegley01296292011-04-08 18:41:53 +0000416 E = ImpCastExprToType(E, Context.getPointerType(Ty),
417 CK_FunctionToPointerDecay).take();
Chris Lattner61f60a02008-07-25 21:33:13 +0000418 else if (Ty->isArrayType()) {
419 // In C90 mode, arrays only promote to pointers if the array expression is
420 // an lvalue. The relevant legalese is C90 6.2.2.1p3: "an lvalue that has
421 // type 'array of type' is converted to an expression that has type 'pointer
422 // to type'...". In C99 this was changed to: C99 6.3.2.1p3: "an expression
423 // that has type 'array of type' ...". The relevant change is "an lvalue"
424 // (C90) to "an expression" (C99).
Argyrios Kyrtzidis9321c742008-09-11 04:25:59 +0000425 //
426 // C++ 4.2p1:
427 // An lvalue or rvalue of type "array of N T" or "array of unknown bound of
428 // T" can be converted to an rvalue of type "pointer to T".
429 //
David Blaikiebbafb8a2012-03-11 07:00:24 +0000430 if (getLangOpts().C99 || getLangOpts().CPlusPlus || E->isLValue())
John Wiegley01296292011-04-08 18:41:53 +0000431 E = ImpCastExprToType(E, Context.getArrayDecayedType(Ty),
432 CK_ArrayToPointerDecay).take();
Chris Lattner61f60a02008-07-25 21:33:13 +0000433 }
John Wiegley01296292011-04-08 18:41:53 +0000434 return Owned(E);
Chris Lattner513165e2008-07-25 21:10:04 +0000435}
436
Argyrios Kyrtzidisa9b630e2011-04-26 17:41:22 +0000437static void CheckForNullPointerDereference(Sema &S, Expr *E) {
438 // Check to see if we are dereferencing a null pointer. If so,
439 // and if not volatile-qualified, this is undefined behavior that the
440 // optimizer will delete, so warn about it. People sometimes try to use this
441 // to get a deterministic trap and are surprised by clang's behavior. This
442 // only handles the pattern "*null", which is a very syntactic check.
443 if (UnaryOperator *UO = dyn_cast<UnaryOperator>(E->IgnoreParenCasts()))
444 if (UO->getOpcode() == UO_Deref &&
445 UO->getSubExpr()->IgnoreParenCasts()->
446 isNullPointerConstant(S.Context, Expr::NPC_ValueDependentIsNotNull) &&
447 !UO->getType().isVolatileQualified()) {
448 S.DiagRuntimeBehavior(UO->getOperatorLoc(), UO,
449 S.PDiag(diag::warn_indirection_through_null)
450 << UO->getSubExpr()->getSourceRange());
451 S.DiagRuntimeBehavior(UO->getOperatorLoc(), UO,
452 S.PDiag(diag::note_indirection_through_null));
453 }
454}
455
John Wiegley01296292011-04-08 18:41:53 +0000456ExprResult Sema::DefaultLvalueConversion(Expr *E) {
John McCall50a2c2c2011-10-11 23:14:30 +0000457 // Handle any placeholder expressions which made it here.
458 if (E->getType()->isPlaceholderType()) {
459 ExprResult result = CheckPlaceholderExpr(E);
460 if (result.isInvalid()) return ExprError();
461 E = result.take();
462 }
463
John McCallf3735e02010-12-01 04:43:34 +0000464 // C++ [conv.lval]p1:
465 // A glvalue of a non-function, non-array type T can be
466 // converted to a prvalue.
John Wiegley01296292011-04-08 18:41:53 +0000467 if (!E->isGLValue()) return Owned(E);
Kaelyn Uhrain2e7aa5a2011-08-05 23:18:04 +0000468
John McCall27584242010-12-06 20:48:59 +0000469 QualType T = E->getType();
470 assert(!T.isNull() && "r-value conversion on typeless expression?");
John McCall34376a62010-12-04 03:47:34 +0000471
John McCall27584242010-12-06 20:48:59 +0000472 // We don't want to throw lvalue-to-rvalue casts on top of
473 // expressions of certain types in C++.
David Blaikiebbafb8a2012-03-11 07:00:24 +0000474 if (getLangOpts().CPlusPlus &&
John McCall27584242010-12-06 20:48:59 +0000475 (E->getType() == Context.OverloadTy ||
476 T->isDependentType() ||
477 T->isRecordType()))
John Wiegley01296292011-04-08 18:41:53 +0000478 return Owned(E);
John McCall27584242010-12-06 20:48:59 +0000479
480 // The C standard is actually really unclear on this point, and
481 // DR106 tells us what the result should be but not why. It's
482 // generally best to say that void types just doesn't undergo
483 // lvalue-to-rvalue at all. Note that expressions of unqualified
484 // 'void' type are never l-values, but qualified void can be.
485 if (T->isVoidType())
John Wiegley01296292011-04-08 18:41:53 +0000486 return Owned(E);
John McCall27584242010-12-06 20:48:59 +0000487
Argyrios Kyrtzidisa9b630e2011-04-26 17:41:22 +0000488 CheckForNullPointerDereference(*this, E);
489
John McCall27584242010-12-06 20:48:59 +0000490 // C++ [conv.lval]p1:
491 // [...] If T is a non-class type, the type of the prvalue is the
492 // cv-unqualified version of T. Otherwise, the type of the
493 // rvalue is T.
494 //
495 // C99 6.3.2.1p2:
496 // If the lvalue has qualified type, the value has the unqualified
497 // version of the type of the lvalue; otherwise, the value has the
Anton Korobeynikovf0c267e2011-10-14 23:23:15 +0000498 // type of the lvalue.
John McCall27584242010-12-06 20:48:59 +0000499 if (T.hasQualifiers())
500 T = T.getUnqualifiedType();
Anton Korobeynikovf0c267e2011-10-14 23:23:15 +0000501
Eli Friedman3bda6b12012-02-02 23:15:15 +0000502 UpdateMarkingForLValueToRValue(E);
503
Anton Korobeynikovf0c267e2011-10-14 23:23:15 +0000504 ExprResult Res = Owned(ImplicitCastExpr::Create(Context, T, CK_LValueToRValue,
505 E, 0, VK_RValue));
506
Douglas Gregorc79862f2012-04-12 17:51:55 +0000507 // C11 6.3.2.1p2:
508 // ... if the lvalue has atomic type, the value has the non-atomic version
509 // of the type of the lvalue ...
510 if (const AtomicType *Atomic = T->getAs<AtomicType>()) {
511 T = Atomic->getValueType().getUnqualifiedType();
512 Res = Owned(ImplicitCastExpr::Create(Context, T, CK_AtomicToNonAtomic,
513 Res.get(), 0, VK_RValue));
514 }
515
Anton Korobeynikovf0c267e2011-10-14 23:23:15 +0000516 return Res;
John McCall27584242010-12-06 20:48:59 +0000517}
518
John Wiegley01296292011-04-08 18:41:53 +0000519ExprResult Sema::DefaultFunctionArrayLvalueConversion(Expr *E) {
520 ExprResult Res = DefaultFunctionArrayConversion(E);
521 if (Res.isInvalid())
522 return ExprError();
523 Res = DefaultLvalueConversion(Res.take());
524 if (Res.isInvalid())
525 return ExprError();
Benjamin Kramer62b95d82012-08-23 21:35:17 +0000526 return Res;
Douglas Gregorb92a1562010-02-03 00:27:59 +0000527}
528
529
Chris Lattner513165e2008-07-25 21:10:04 +0000530/// UsualUnaryConversions - Performs various conversions that are common to most
Mike Stump11289f42009-09-09 15:08:12 +0000531/// operators (C99 6.3). The conversions of array and function types are
Chris Lattner57540c52011-04-15 05:22:18 +0000532/// sometimes suppressed. For example, the array->pointer conversion doesn't
Chris Lattner513165e2008-07-25 21:10:04 +0000533/// apply if the array is an argument to the sizeof or address (&) operators.
534/// In these instances, this routine should *not* be called.
John Wiegley01296292011-04-08 18:41:53 +0000535ExprResult Sema::UsualUnaryConversions(Expr *E) {
John McCallf3735e02010-12-01 04:43:34 +0000536 // First, convert to an r-value.
John Wiegley01296292011-04-08 18:41:53 +0000537 ExprResult Res = DefaultFunctionArrayLvalueConversion(E);
538 if (Res.isInvalid())
539 return Owned(E);
540 E = Res.take();
Anton Korobeynikovf0c267e2011-10-14 23:23:15 +0000541
John McCallf3735e02010-12-01 04:43:34 +0000542 QualType Ty = E->getType();
Chris Lattner513165e2008-07-25 21:10:04 +0000543 assert(!Ty.isNull() && "UsualUnaryConversions - missing type");
Anton Korobeynikovf0c267e2011-10-14 23:23:15 +0000544
545 // Half FP is a bit different: it's a storage-only type, meaning that any
546 // "use" of it should be promoted to float.
547 if (Ty->isHalfType())
548 return ImpCastExprToType(Res.take(), Context.FloatTy, CK_FloatingCast);
549
John McCallf3735e02010-12-01 04:43:34 +0000550 // Try to perform integral promotions if the object has a theoretically
551 // promotable type.
552 if (Ty->isIntegralOrUnscopedEnumerationType()) {
553 // C99 6.3.1.1p2:
554 //
555 // The following may be used in an expression wherever an int or
556 // unsigned int may be used:
557 // - an object or expression with an integer type whose integer
558 // conversion rank is less than or equal to the rank of int
559 // and unsigned int.
560 // - A bit-field of type _Bool, int, signed int, or unsigned int.
561 //
562 // If an int can represent all values of the original type, the
563 // value is converted to an int; otherwise, it is converted to an
564 // unsigned int. These are called the integer promotions. All
565 // other types are unchanged by the integer promotions.
Anton Korobeynikovf0c267e2011-10-14 23:23:15 +0000566
John McCallf3735e02010-12-01 04:43:34 +0000567 QualType PTy = Context.isPromotableBitField(E);
568 if (!PTy.isNull()) {
John Wiegley01296292011-04-08 18:41:53 +0000569 E = ImpCastExprToType(E, PTy, CK_IntegralCast).take();
570 return Owned(E);
John McCallf3735e02010-12-01 04:43:34 +0000571 }
572 if (Ty->isPromotableIntegerType()) {
573 QualType PT = Context.getPromotedIntegerType(Ty);
John Wiegley01296292011-04-08 18:41:53 +0000574 E = ImpCastExprToType(E, PT, CK_IntegralCast).take();
575 return Owned(E);
John McCallf3735e02010-12-01 04:43:34 +0000576 }
Eli Friedman629ffb92009-08-20 04:21:42 +0000577 }
John Wiegley01296292011-04-08 18:41:53 +0000578 return Owned(E);
Chris Lattner513165e2008-07-25 21:10:04 +0000579}
580
Chris Lattner2ce500f2008-07-25 22:25:12 +0000581/// DefaultArgumentPromotion (C99 6.5.2.2p6). Used for function calls that
Mike Stump11289f42009-09-09 15:08:12 +0000582/// do not have a prototype. Arguments that have type float are promoted to
Chris Lattner2ce500f2008-07-25 22:25:12 +0000583/// double. All other argument types are converted by UsualUnaryConversions().
John Wiegley01296292011-04-08 18:41:53 +0000584ExprResult Sema::DefaultArgumentPromotion(Expr *E) {
585 QualType Ty = E->getType();
Chris Lattner2ce500f2008-07-25 22:25:12 +0000586 assert(!Ty.isNull() && "DefaultArgumentPromotion - missing type");
Mike Stump11289f42009-09-09 15:08:12 +0000587
John Wiegley01296292011-04-08 18:41:53 +0000588 ExprResult Res = UsualUnaryConversions(E);
589 if (Res.isInvalid())
590 return Owned(E);
591 E = Res.take();
John McCall9bc26772010-12-06 18:36:11 +0000592
Chris Lattner2ce500f2008-07-25 22:25:12 +0000593 // If this is a 'float' (CVR qualified or typedef) promote to double.
Chris Lattnerbb53efb2010-05-16 04:01:30 +0000594 if (Ty->isSpecificBuiltinType(BuiltinType::Float))
John Wiegley01296292011-04-08 18:41:53 +0000595 E = ImpCastExprToType(E, Context.DoubleTy, CK_FloatingCast).take();
596
John McCall4bb057d2011-08-27 22:06:17 +0000597 // C++ performs lvalue-to-rvalue conversion as a default argument
John McCall0562caa2011-08-29 23:55:37 +0000598 // promotion, even on class types, but note:
599 // C++11 [conv.lval]p2:
600 // When an lvalue-to-rvalue conversion occurs in an unevaluated
601 // operand or a subexpression thereof the value contained in the
602 // referenced object is not accessed. Otherwise, if the glvalue
603 // has a class type, the conversion copy-initializes a temporary
604 // of type T from the glvalue and the result of the conversion
605 // is a prvalue for the temporary.
Eli Friedman05e28012012-01-17 02:13:45 +0000606 // FIXME: add some way to gate this entire thing for correctness in
607 // potentially potentially evaluated contexts.
David Blaikie131fcb42012-08-06 22:47:24 +0000608 if (getLangOpts().CPlusPlus && E->isGLValue() && !isUnevaluatedContext()) {
Eli Friedman05e28012012-01-17 02:13:45 +0000609 ExprResult Temp = PerformCopyInitialization(
610 InitializedEntity::InitializeTemporary(E->getType()),
611 E->getExprLoc(),
612 Owned(E));
613 if (Temp.isInvalid())
614 return ExprError();
615 E = Temp.get();
John McCall29ad95b2011-08-27 01:09:30 +0000616 }
617
John Wiegley01296292011-04-08 18:41:53 +0000618 return Owned(E);
Chris Lattner2ce500f2008-07-25 22:25:12 +0000619}
620
Richard Smith55ce3522012-06-25 20:30:08 +0000621/// Determine the degree of POD-ness for an expression.
622/// Incomplete types are considered POD, since this check can be performed
623/// when we're in an unevaluated context.
624Sema::VarArgKind Sema::isValidVarArgType(const QualType &Ty) {
Jordan Rose3e0ec582012-07-19 18:10:23 +0000625 if (Ty->isIncompleteType()) {
626 if (Ty->isObjCObjectType())
627 return VAK_Invalid;
Richard Smith55ce3522012-06-25 20:30:08 +0000628 return VAK_Valid;
Jordan Rose3e0ec582012-07-19 18:10:23 +0000629 }
630
631 if (Ty.isCXX98PODType(Context))
632 return VAK_Valid;
633
Richard Smith55ce3522012-06-25 20:30:08 +0000634 // C++0x [expr.call]p7:
635 // Passing a potentially-evaluated argument of class type (Clause 9)
636 // having a non-trivial copy constructor, a non-trivial move constructor,
637 // or a non-trivial destructor, with no corresponding parameter,
638 // is conditionally-supported with implementation-defined semantics.
Richard Smith55ce3522012-06-25 20:30:08 +0000639 if (getLangOpts().CPlusPlus0x && !Ty->isDependentType())
640 if (CXXRecordDecl *Record = Ty->getAsCXXRecordDecl())
641 if (Record->hasTrivialCopyConstructor() &&
642 Record->hasTrivialMoveConstructor() &&
643 Record->hasTrivialDestructor())
644 return VAK_ValidInCXX11;
645
646 if (getLangOpts().ObjCAutoRefCount && Ty->isObjCLifetimeType())
647 return VAK_Valid;
648 return VAK_Invalid;
649}
650
651bool Sema::variadicArgumentPODCheck(const Expr *E, VariadicCallType CT) {
652 // Don't allow one to pass an Objective-C interface to a vararg.
653 const QualType & Ty = E->getType();
654
655 // Complain about passing non-POD types through varargs.
656 switch (isValidVarArgType(Ty)) {
657 case VAK_Valid:
658 break;
659 case VAK_ValidInCXX11:
660 DiagRuntimeBehavior(E->getLocStart(), 0,
661 PDiag(diag::warn_cxx98_compat_pass_non_pod_arg_to_vararg)
662 << E->getType() << CT);
663 break;
Jordan Rose3e0ec582012-07-19 18:10:23 +0000664 case VAK_Invalid: {
665 if (Ty->isObjCObjectType())
666 return DiagRuntimeBehavior(E->getLocStart(), 0,
667 PDiag(diag::err_cannot_pass_objc_interface_to_vararg)
668 << Ty << CT);
669
Richard Smith55ce3522012-06-25 20:30:08 +0000670 return DiagRuntimeBehavior(E->getLocStart(), 0,
671 PDiag(diag::warn_cannot_pass_non_pod_arg_to_vararg)
672 << getLangOpts().CPlusPlus0x << Ty << CT);
673 }
Jordan Rose3e0ec582012-07-19 18:10:23 +0000674 }
Richard Smith55ce3522012-06-25 20:30:08 +0000675 // c++ rules are enforced elsewhere.
676 return false;
677}
678
Chris Lattnera8a7d0f2009-04-12 08:11:20 +0000679/// DefaultVariadicArgumentPromotion - Like DefaultArgumentPromotion, but
Jordan Rose3e0ec582012-07-19 18:10:23 +0000680/// will create a trap if the resulting type is not a POD type.
John Wiegley01296292011-04-08 18:41:53 +0000681ExprResult Sema::DefaultVariadicArgumentPromotion(Expr *E, VariadicCallType CT,
John McCall31168b02011-06-15 23:02:42 +0000682 FunctionDecl *FDecl) {
Richard Smith7659b122012-06-27 20:29:39 +0000683 if (const BuiltinType *PlaceholderTy = E->getType()->getAsPlaceholderType()) {
John McCall4124c492011-10-17 18:40:02 +0000684 // Strip the unbridged-cast placeholder expression off, if applicable.
685 if (PlaceholderTy->getKind() == BuiltinType::ARCUnbridgedCast &&
686 (CT == VariadicMethod ||
687 (FDecl && FDecl->hasAttr<CFAuditedTransferAttr>()))) {
688 E = stripARCUnbridgedCast(E);
689
690 // Otherwise, do normal placeholder checking.
691 } else {
692 ExprResult ExprRes = CheckPlaceholderExpr(E);
693 if (ExprRes.isInvalid())
694 return ExprError();
695 E = ExprRes.take();
696 }
697 }
Douglas Gregorcbd446d2011-06-17 00:15:10 +0000698
John McCall4124c492011-10-17 18:40:02 +0000699 ExprResult ExprRes = DefaultArgumentPromotion(E);
John Wiegley01296292011-04-08 18:41:53 +0000700 if (ExprRes.isInvalid())
701 return ExprError();
702 E = ExprRes.take();
Mike Stump11289f42009-09-09 15:08:12 +0000703
Richard Smith55ce3522012-06-25 20:30:08 +0000704 // Diagnostics regarding non-POD argument types are
705 // emitted along with format string checking in Sema::CheckFunctionCall().
Richard Smith56471fd2012-06-27 20:23:58 +0000706 if (isValidVarArgType(E->getType()) == VAK_Invalid) {
Richard Smith55ce3522012-06-25 20:30:08 +0000707 // Turn this into a trap.
708 CXXScopeSpec SS;
709 SourceLocation TemplateKWLoc;
710 UnqualifiedId Name;
711 Name.setIdentifier(PP.getIdentifierInfo("__builtin_trap"),
712 E->getLocStart());
713 ExprResult TrapFn = ActOnIdExpression(TUScope, SS, TemplateKWLoc,
714 Name, true, false);
715 if (TrapFn.isInvalid())
716 return ExprError();
John McCall31168b02011-06-15 23:02:42 +0000717
Richard Smith55ce3522012-06-25 20:30:08 +0000718 ExprResult Call = ActOnCallExpr(TUScope, TrapFn.get(),
719 E->getLocStart(), MultiExprArg(),
720 E->getLocEnd());
721 if (Call.isInvalid())
722 return ExprError();
Douglas Gregor347e0f22011-05-21 19:26:31 +0000723
Richard Smith55ce3522012-06-25 20:30:08 +0000724 ExprResult Comma = ActOnBinOp(TUScope, E->getLocStart(), tok::comma,
725 Call.get(), E);
726 if (Comma.isInvalid())
727 return ExprError();
728 return Comma.get();
Douglas Gregor253cadf2011-05-21 16:27:21 +0000729 }
Richard Smith55ce3522012-06-25 20:30:08 +0000730
David Blaikiebbafb8a2012-03-11 07:00:24 +0000731 if (!getLangOpts().CPlusPlus &&
Fariborz Jahanian3854a552012-03-01 23:42:00 +0000732 RequireCompleteType(E->getExprLoc(), E->getType(),
Fariborz Jahanianbf482812012-03-02 17:05:03 +0000733 diag::err_call_incomplete_argument))
Fariborz Jahanian3854a552012-03-01 23:42:00 +0000734 return ExprError();
Richard Smith55ce3522012-06-25 20:30:08 +0000735
John Wiegley01296292011-04-08 18:41:53 +0000736 return Owned(E);
Anders Carlssona7d069d2009-01-16 16:48:51 +0000737}
738
Richard Trieu7aa58f12011-09-02 20:58:51 +0000739/// \brief Converts an integer to complex float type. Helper function of
740/// UsualArithmeticConversions()
741///
742/// \return false if the integer expression is an integer type and is
743/// successfully converted to the complex type.
Richard Trieuba63ce62011-09-09 01:45:06 +0000744static bool handleIntegerToComplexFloatConversion(Sema &S, ExprResult &IntExpr,
745 ExprResult &ComplexExpr,
746 QualType IntTy,
747 QualType ComplexTy,
748 bool SkipCast) {
749 if (IntTy->isComplexType() || IntTy->isRealFloatingType()) return true;
750 if (SkipCast) return false;
751 if (IntTy->isIntegerType()) {
752 QualType fpTy = cast<ComplexType>(ComplexTy)->getElementType();
753 IntExpr = S.ImpCastExprToType(IntExpr.take(), fpTy, CK_IntegralToFloating);
754 IntExpr = S.ImpCastExprToType(IntExpr.take(), ComplexTy,
Richard Trieu7aa58f12011-09-02 20:58:51 +0000755 CK_FloatingRealToComplex);
756 } else {
Richard Trieuba63ce62011-09-09 01:45:06 +0000757 assert(IntTy->isComplexIntegerType());
758 IntExpr = S.ImpCastExprToType(IntExpr.take(), ComplexTy,
Richard Trieu7aa58f12011-09-02 20:58:51 +0000759 CK_IntegralComplexToFloatingComplex);
760 }
761 return false;
762}
763
764/// \brief Takes two complex float types and converts them to the same type.
765/// Helper function of UsualArithmeticConversions()
766static QualType
Richard Trieu5065cdd2011-09-06 18:25:09 +0000767handleComplexFloatToComplexFloatConverstion(Sema &S, ExprResult &LHS,
768 ExprResult &RHS, QualType LHSType,
769 QualType RHSType,
Richard Trieuba63ce62011-09-09 01:45:06 +0000770 bool IsCompAssign) {
Richard Trieu5065cdd2011-09-06 18:25:09 +0000771 int order = S.Context.getFloatingTypeOrder(LHSType, RHSType);
Richard Trieu7aa58f12011-09-02 20:58:51 +0000772
773 if (order < 0) {
774 // _Complex float -> _Complex double
Richard Trieuba63ce62011-09-09 01:45:06 +0000775 if (!IsCompAssign)
Richard Trieu5065cdd2011-09-06 18:25:09 +0000776 LHS = S.ImpCastExprToType(LHS.take(), RHSType, CK_FloatingComplexCast);
777 return RHSType;
Richard Trieu7aa58f12011-09-02 20:58:51 +0000778 }
779 if (order > 0)
780 // _Complex float -> _Complex double
Richard Trieu5065cdd2011-09-06 18:25:09 +0000781 RHS = S.ImpCastExprToType(RHS.take(), LHSType, CK_FloatingComplexCast);
782 return LHSType;
Richard Trieu7aa58f12011-09-02 20:58:51 +0000783}
784
785/// \brief Converts otherExpr to complex float and promotes complexExpr if
786/// necessary. Helper function of UsualArithmeticConversions()
787static QualType handleOtherComplexFloatConversion(Sema &S,
Richard Trieuba63ce62011-09-09 01:45:06 +0000788 ExprResult &ComplexExpr,
789 ExprResult &OtherExpr,
790 QualType ComplexTy,
791 QualType OtherTy,
792 bool ConvertComplexExpr,
793 bool ConvertOtherExpr) {
794 int order = S.Context.getFloatingTypeOrder(ComplexTy, OtherTy);
Richard Trieu7aa58f12011-09-02 20:58:51 +0000795
796 // If just the complexExpr is complex, the otherExpr needs to be converted,
797 // and the complexExpr might need to be promoted.
798 if (order > 0) { // complexExpr is wider
799 // float -> _Complex double
Richard Trieuba63ce62011-09-09 01:45:06 +0000800 if (ConvertOtherExpr) {
801 QualType fp = cast<ComplexType>(ComplexTy)->getElementType();
802 OtherExpr = S.ImpCastExprToType(OtherExpr.take(), fp, CK_FloatingCast);
803 OtherExpr = S.ImpCastExprToType(OtherExpr.take(), ComplexTy,
Richard Trieu7aa58f12011-09-02 20:58:51 +0000804 CK_FloatingRealToComplex);
805 }
Richard Trieuba63ce62011-09-09 01:45:06 +0000806 return ComplexTy;
Richard Trieu7aa58f12011-09-02 20:58:51 +0000807 }
808
809 // otherTy is at least as wide. Find its corresponding complex type.
Richard Trieuba63ce62011-09-09 01:45:06 +0000810 QualType result = (order == 0 ? ComplexTy :
811 S.Context.getComplexType(OtherTy));
Richard Trieu7aa58f12011-09-02 20:58:51 +0000812
813 // double -> _Complex double
Richard Trieuba63ce62011-09-09 01:45:06 +0000814 if (ConvertOtherExpr)
815 OtherExpr = S.ImpCastExprToType(OtherExpr.take(), result,
Richard Trieu7aa58f12011-09-02 20:58:51 +0000816 CK_FloatingRealToComplex);
817
818 // _Complex float -> _Complex double
Richard Trieuba63ce62011-09-09 01:45:06 +0000819 if (ConvertComplexExpr && order < 0)
820 ComplexExpr = S.ImpCastExprToType(ComplexExpr.take(), result,
Richard Trieu7aa58f12011-09-02 20:58:51 +0000821 CK_FloatingComplexCast);
822
823 return result;
824}
825
826/// \brief Handle arithmetic conversion with complex types. Helper function of
827/// UsualArithmeticConversions()
Richard Trieu5065cdd2011-09-06 18:25:09 +0000828static QualType handleComplexFloatConversion(Sema &S, ExprResult &LHS,
829 ExprResult &RHS, QualType LHSType,
830 QualType RHSType,
Richard Trieuba63ce62011-09-09 01:45:06 +0000831 bool IsCompAssign) {
Richard Trieu7aa58f12011-09-02 20:58:51 +0000832 // if we have an integer operand, the result is the complex type.
Richard Trieu5065cdd2011-09-06 18:25:09 +0000833 if (!handleIntegerToComplexFloatConversion(S, RHS, LHS, RHSType, LHSType,
Richard Trieu7aa58f12011-09-02 20:58:51 +0000834 /*skipCast*/false))
Richard Trieu5065cdd2011-09-06 18:25:09 +0000835 return LHSType;
836 if (!handleIntegerToComplexFloatConversion(S, LHS, RHS, LHSType, RHSType,
Richard Trieuba63ce62011-09-09 01:45:06 +0000837 /*skipCast*/IsCompAssign))
Richard Trieu5065cdd2011-09-06 18:25:09 +0000838 return RHSType;
Richard Trieu7aa58f12011-09-02 20:58:51 +0000839
840 // This handles complex/complex, complex/float, or float/complex.
841 // When both operands are complex, the shorter operand is converted to the
842 // type of the longer, and that is the type of the result. This corresponds
843 // to what is done when combining two real floating-point operands.
844 // The fun begins when size promotion occur across type domains.
845 // From H&S 6.3.4: When one operand is complex and the other is a real
846 // floating-point type, the less precise type is converted, within it's
847 // real or complex domain, to the precision of the other type. For example,
848 // when combining a "long double" with a "double _Complex", the
849 // "double _Complex" is promoted to "long double _Complex".
850
Richard Trieu5065cdd2011-09-06 18:25:09 +0000851 bool LHSComplexFloat = LHSType->isComplexType();
852 bool RHSComplexFloat = RHSType->isComplexType();
Richard Trieu7aa58f12011-09-02 20:58:51 +0000853
854 // If both are complex, just cast to the more precise type.
855 if (LHSComplexFloat && RHSComplexFloat)
Richard Trieu5065cdd2011-09-06 18:25:09 +0000856 return handleComplexFloatToComplexFloatConverstion(S, LHS, RHS,
857 LHSType, RHSType,
Richard Trieuba63ce62011-09-09 01:45:06 +0000858 IsCompAssign);
Richard Trieu7aa58f12011-09-02 20:58:51 +0000859
860 // If only one operand is complex, promote it if necessary and convert the
861 // other operand to complex.
862 if (LHSComplexFloat)
863 return handleOtherComplexFloatConversion(
Richard Trieuba63ce62011-09-09 01:45:06 +0000864 S, LHS, RHS, LHSType, RHSType, /*convertComplexExpr*/!IsCompAssign,
Richard Trieu7aa58f12011-09-02 20:58:51 +0000865 /*convertOtherExpr*/ true);
866
867 assert(RHSComplexFloat);
868 return handleOtherComplexFloatConversion(
Richard Trieu5065cdd2011-09-06 18:25:09 +0000869 S, RHS, LHS, RHSType, LHSType, /*convertComplexExpr*/true,
Richard Trieuba63ce62011-09-09 01:45:06 +0000870 /*convertOtherExpr*/ !IsCompAssign);
Richard Trieu7aa58f12011-09-02 20:58:51 +0000871}
872
873/// \brief Hande arithmetic conversion from integer to float. Helper function
874/// of UsualArithmeticConversions()
Richard Trieuba63ce62011-09-09 01:45:06 +0000875static QualType handleIntToFloatConversion(Sema &S, ExprResult &FloatExpr,
876 ExprResult &IntExpr,
877 QualType FloatTy, QualType IntTy,
878 bool ConvertFloat, bool ConvertInt) {
879 if (IntTy->isIntegerType()) {
880 if (ConvertInt)
Richard Trieu7aa58f12011-09-02 20:58:51 +0000881 // Convert intExpr to the lhs floating point type.
Richard Trieuba63ce62011-09-09 01:45:06 +0000882 IntExpr = S.ImpCastExprToType(IntExpr.take(), FloatTy,
Richard Trieu7aa58f12011-09-02 20:58:51 +0000883 CK_IntegralToFloating);
Richard Trieuba63ce62011-09-09 01:45:06 +0000884 return FloatTy;
Richard Trieu7aa58f12011-09-02 20:58:51 +0000885 }
886
887 // Convert both sides to the appropriate complex float.
Richard Trieuba63ce62011-09-09 01:45:06 +0000888 assert(IntTy->isComplexIntegerType());
889 QualType result = S.Context.getComplexType(FloatTy);
Richard Trieu7aa58f12011-09-02 20:58:51 +0000890
891 // _Complex int -> _Complex float
Richard Trieuba63ce62011-09-09 01:45:06 +0000892 if (ConvertInt)
893 IntExpr = S.ImpCastExprToType(IntExpr.take(), result,
Richard Trieu7aa58f12011-09-02 20:58:51 +0000894 CK_IntegralComplexToFloatingComplex);
895
896 // float -> _Complex float
Richard Trieuba63ce62011-09-09 01:45:06 +0000897 if (ConvertFloat)
898 FloatExpr = S.ImpCastExprToType(FloatExpr.take(), result,
Richard Trieu7aa58f12011-09-02 20:58:51 +0000899 CK_FloatingRealToComplex);
900
901 return result;
902}
903
904/// \brief Handle arithmethic conversion with floating point types. Helper
905/// function of UsualArithmeticConversions()
Richard Trieucfe3f212011-09-06 18:38:41 +0000906static QualType handleFloatConversion(Sema &S, ExprResult &LHS,
907 ExprResult &RHS, QualType LHSType,
Richard Trieuba63ce62011-09-09 01:45:06 +0000908 QualType RHSType, bool IsCompAssign) {
Richard Trieucfe3f212011-09-06 18:38:41 +0000909 bool LHSFloat = LHSType->isRealFloatingType();
910 bool RHSFloat = RHSType->isRealFloatingType();
Richard Trieu7aa58f12011-09-02 20:58:51 +0000911
912 // If we have two real floating types, convert the smaller operand
913 // to the bigger result.
914 if (LHSFloat && RHSFloat) {
Richard Trieucfe3f212011-09-06 18:38:41 +0000915 int order = S.Context.getFloatingTypeOrder(LHSType, RHSType);
Richard Trieu7aa58f12011-09-02 20:58:51 +0000916 if (order > 0) {
Richard Trieucfe3f212011-09-06 18:38:41 +0000917 RHS = S.ImpCastExprToType(RHS.take(), LHSType, CK_FloatingCast);
918 return LHSType;
Richard Trieu7aa58f12011-09-02 20:58:51 +0000919 }
920
921 assert(order < 0 && "illegal float comparison");
Richard Trieuba63ce62011-09-09 01:45:06 +0000922 if (!IsCompAssign)
Richard Trieucfe3f212011-09-06 18:38:41 +0000923 LHS = S.ImpCastExprToType(LHS.take(), RHSType, CK_FloatingCast);
924 return RHSType;
Richard Trieu7aa58f12011-09-02 20:58:51 +0000925 }
926
927 if (LHSFloat)
Richard Trieucfe3f212011-09-06 18:38:41 +0000928 return handleIntToFloatConversion(S, LHS, RHS, LHSType, RHSType,
Richard Trieuba63ce62011-09-09 01:45:06 +0000929 /*convertFloat=*/!IsCompAssign,
Richard Trieu7aa58f12011-09-02 20:58:51 +0000930 /*convertInt=*/ true);
931 assert(RHSFloat);
Richard Trieucfe3f212011-09-06 18:38:41 +0000932 return handleIntToFloatConversion(S, RHS, LHS, RHSType, LHSType,
Richard Trieu7aa58f12011-09-02 20:58:51 +0000933 /*convertInt=*/ true,
Richard Trieuba63ce62011-09-09 01:45:06 +0000934 /*convertFloat=*/!IsCompAssign);
Richard Trieu7aa58f12011-09-02 20:58:51 +0000935}
936
937/// \brief Handle conversions with GCC complex int extension. Helper function
Benjamin Kramer499c68b2011-09-06 19:57:14 +0000938/// of UsualArithmeticConversions()
Richard Trieu7aa58f12011-09-02 20:58:51 +0000939// FIXME: if the operands are (int, _Complex long), we currently
940// don't promote the complex. Also, signedness?
Benjamin Kramer499c68b2011-09-06 19:57:14 +0000941static QualType handleComplexIntConversion(Sema &S, ExprResult &LHS,
942 ExprResult &RHS, QualType LHSType,
943 QualType RHSType,
Richard Trieuba63ce62011-09-09 01:45:06 +0000944 bool IsCompAssign) {
Richard Trieucfe3f212011-09-06 18:38:41 +0000945 const ComplexType *LHSComplexInt = LHSType->getAsComplexIntegerType();
946 const ComplexType *RHSComplexInt = RHSType->getAsComplexIntegerType();
Richard Trieu7aa58f12011-09-02 20:58:51 +0000947
Richard Trieucfe3f212011-09-06 18:38:41 +0000948 if (LHSComplexInt && RHSComplexInt) {
949 int order = S.Context.getIntegerTypeOrder(LHSComplexInt->getElementType(),
950 RHSComplexInt->getElementType());
Richard Trieu7aa58f12011-09-02 20:58:51 +0000951 assert(order && "inequal types with equal element ordering");
952 if (order > 0) {
953 // _Complex int -> _Complex long
Richard Trieucfe3f212011-09-06 18:38:41 +0000954 RHS = S.ImpCastExprToType(RHS.take(), LHSType, CK_IntegralComplexCast);
955 return LHSType;
Richard Trieu7aa58f12011-09-02 20:58:51 +0000956 }
957
Richard Trieuba63ce62011-09-09 01:45:06 +0000958 if (!IsCompAssign)
Richard Trieucfe3f212011-09-06 18:38:41 +0000959 LHS = S.ImpCastExprToType(LHS.take(), RHSType, CK_IntegralComplexCast);
960 return RHSType;
Richard Trieu7aa58f12011-09-02 20:58:51 +0000961 }
962
Richard Trieucfe3f212011-09-06 18:38:41 +0000963 if (LHSComplexInt) {
Richard Trieu7aa58f12011-09-02 20:58:51 +0000964 // int -> _Complex int
Eli Friedman47133be2011-11-12 03:56:23 +0000965 // FIXME: This needs to take integer ranks into account
966 RHS = S.ImpCastExprToType(RHS.take(), LHSComplexInt->getElementType(),
967 CK_IntegralCast);
Richard Trieucfe3f212011-09-06 18:38:41 +0000968 RHS = S.ImpCastExprToType(RHS.take(), LHSType, CK_IntegralRealToComplex);
969 return LHSType;
Richard Trieu7aa58f12011-09-02 20:58:51 +0000970 }
971
Richard Trieucfe3f212011-09-06 18:38:41 +0000972 assert(RHSComplexInt);
Richard Trieu7aa58f12011-09-02 20:58:51 +0000973 // int -> _Complex int
Eli Friedman47133be2011-11-12 03:56:23 +0000974 // FIXME: This needs to take integer ranks into account
975 if (!IsCompAssign) {
976 LHS = S.ImpCastExprToType(LHS.take(), RHSComplexInt->getElementType(),
977 CK_IntegralCast);
Richard Trieucfe3f212011-09-06 18:38:41 +0000978 LHS = S.ImpCastExprToType(LHS.take(), RHSType, CK_IntegralRealToComplex);
Eli Friedman47133be2011-11-12 03:56:23 +0000979 }
Richard Trieucfe3f212011-09-06 18:38:41 +0000980 return RHSType;
Richard Trieu7aa58f12011-09-02 20:58:51 +0000981}
982
983/// \brief Handle integer arithmetic conversions. Helper function of
984/// UsualArithmeticConversions()
Richard Trieu9a52fbb2011-09-06 19:52:52 +0000985static QualType handleIntegerConversion(Sema &S, ExprResult &LHS,
986 ExprResult &RHS, QualType LHSType,
Richard Trieuba63ce62011-09-09 01:45:06 +0000987 QualType RHSType, bool IsCompAssign) {
Richard Trieu7aa58f12011-09-02 20:58:51 +0000988 // The rules for this case are in C99 6.3.1.8
Richard Trieu9a52fbb2011-09-06 19:52:52 +0000989 int order = S.Context.getIntegerTypeOrder(LHSType, RHSType);
990 bool LHSSigned = LHSType->hasSignedIntegerRepresentation();
991 bool RHSSigned = RHSType->hasSignedIntegerRepresentation();
992 if (LHSSigned == RHSSigned) {
Richard Trieu7aa58f12011-09-02 20:58:51 +0000993 // Same signedness; use the higher-ranked type
994 if (order >= 0) {
Richard Trieu9a52fbb2011-09-06 19:52:52 +0000995 RHS = S.ImpCastExprToType(RHS.take(), LHSType, CK_IntegralCast);
996 return LHSType;
Richard Trieuba63ce62011-09-09 01:45:06 +0000997 } else if (!IsCompAssign)
Richard Trieu9a52fbb2011-09-06 19:52:52 +0000998 LHS = S.ImpCastExprToType(LHS.take(), RHSType, CK_IntegralCast);
999 return RHSType;
1000 } else if (order != (LHSSigned ? 1 : -1)) {
Richard Trieu7aa58f12011-09-02 20:58:51 +00001001 // The unsigned type has greater than or equal rank to the
1002 // signed type, so use the unsigned type
Richard Trieu9a52fbb2011-09-06 19:52:52 +00001003 if (RHSSigned) {
1004 RHS = S.ImpCastExprToType(RHS.take(), LHSType, CK_IntegralCast);
1005 return LHSType;
Richard Trieuba63ce62011-09-09 01:45:06 +00001006 } else if (!IsCompAssign)
Richard Trieu9a52fbb2011-09-06 19:52:52 +00001007 LHS = S.ImpCastExprToType(LHS.take(), RHSType, CK_IntegralCast);
1008 return RHSType;
1009 } else if (S.Context.getIntWidth(LHSType) != S.Context.getIntWidth(RHSType)) {
Richard Trieu7aa58f12011-09-02 20:58:51 +00001010 // The two types are different widths; if we are here, that
1011 // means the signed type is larger than the unsigned type, so
1012 // use the signed type.
Richard Trieu9a52fbb2011-09-06 19:52:52 +00001013 if (LHSSigned) {
1014 RHS = S.ImpCastExprToType(RHS.take(), LHSType, CK_IntegralCast);
1015 return LHSType;
Richard Trieuba63ce62011-09-09 01:45:06 +00001016 } else if (!IsCompAssign)
Richard Trieu9a52fbb2011-09-06 19:52:52 +00001017 LHS = S.ImpCastExprToType(LHS.take(), RHSType, CK_IntegralCast);
1018 return RHSType;
Richard Trieu7aa58f12011-09-02 20:58:51 +00001019 } else {
1020 // The signed type is higher-ranked than the unsigned type,
1021 // but isn't actually any bigger (like unsigned int and long
1022 // on most 32-bit systems). Use the unsigned type corresponding
1023 // to the signed type.
1024 QualType result =
Richard Trieu9a52fbb2011-09-06 19:52:52 +00001025 S.Context.getCorrespondingUnsignedType(LHSSigned ? LHSType : RHSType);
1026 RHS = S.ImpCastExprToType(RHS.take(), result, CK_IntegralCast);
Richard Trieuba63ce62011-09-09 01:45:06 +00001027 if (!IsCompAssign)
Richard Trieu9a52fbb2011-09-06 19:52:52 +00001028 LHS = S.ImpCastExprToType(LHS.take(), result, CK_IntegralCast);
Richard Trieu7aa58f12011-09-02 20:58:51 +00001029 return result;
1030 }
1031}
1032
Chris Lattner513165e2008-07-25 21:10:04 +00001033/// UsualArithmeticConversions - Performs various conversions that are common to
1034/// binary operators (C99 6.3.1.8). If both operands aren't arithmetic, this
Mike Stump11289f42009-09-09 15:08:12 +00001035/// routine returns the first non-arithmetic type found. The client is
Chris Lattner513165e2008-07-25 21:10:04 +00001036/// responsible for emitting appropriate error diagnostics.
1037/// FIXME: verify the conversion rules for "complex int" are consistent with
1038/// GCC.
Richard Trieu9a52fbb2011-09-06 19:52:52 +00001039QualType Sema::UsualArithmeticConversions(ExprResult &LHS, ExprResult &RHS,
Richard Trieuba63ce62011-09-09 01:45:06 +00001040 bool IsCompAssign) {
1041 if (!IsCompAssign) {
Richard Trieu9a52fbb2011-09-06 19:52:52 +00001042 LHS = UsualUnaryConversions(LHS.take());
1043 if (LHS.isInvalid())
John Wiegley01296292011-04-08 18:41:53 +00001044 return QualType();
1045 }
Eli Friedman8b7b1b12009-03-28 01:22:36 +00001046
Richard Trieu9a52fbb2011-09-06 19:52:52 +00001047 RHS = UsualUnaryConversions(RHS.take());
1048 if (RHS.isInvalid())
John Wiegley01296292011-04-08 18:41:53 +00001049 return QualType();
Douglas Gregora11693b2008-11-12 17:17:38 +00001050
Mike Stump11289f42009-09-09 15:08:12 +00001051 // For conversion purposes, we ignore any qualifiers.
Chris Lattner513165e2008-07-25 21:10:04 +00001052 // For example, "const float" and "float" are equivalent.
Richard Trieu9a52fbb2011-09-06 19:52:52 +00001053 QualType LHSType =
1054 Context.getCanonicalType(LHS.get()->getType()).getUnqualifiedType();
1055 QualType RHSType =
1056 Context.getCanonicalType(RHS.get()->getType()).getUnqualifiedType();
Douglas Gregora11693b2008-11-12 17:17:38 +00001057
Eli Friedman93ee5ca2012-06-16 02:19:17 +00001058 // For conversion purposes, we ignore any atomic qualifier on the LHS.
1059 if (const AtomicType *AtomicLHS = LHSType->getAs<AtomicType>())
1060 LHSType = AtomicLHS->getValueType();
1061
Douglas Gregora11693b2008-11-12 17:17:38 +00001062 // If both types are identical, no conversion is needed.
Richard Trieu9a52fbb2011-09-06 19:52:52 +00001063 if (LHSType == RHSType)
1064 return LHSType;
Douglas Gregora11693b2008-11-12 17:17:38 +00001065
1066 // If either side is a non-arithmetic type (e.g. a pointer), we are done.
1067 // The caller can deal with this (e.g. pointer + int).
Richard Trieu9a52fbb2011-09-06 19:52:52 +00001068 if (!LHSType->isArithmeticType() || !RHSType->isArithmeticType())
Eli Friedman93ee5ca2012-06-16 02:19:17 +00001069 return QualType();
Douglas Gregora11693b2008-11-12 17:17:38 +00001070
John McCalld005ac92010-11-13 08:17:45 +00001071 // Apply unary and bitfield promotions to the LHS's type.
Richard Trieu9a52fbb2011-09-06 19:52:52 +00001072 QualType LHSUnpromotedType = LHSType;
1073 if (LHSType->isPromotableIntegerType())
1074 LHSType = Context.getPromotedIntegerType(LHSType);
1075 QualType LHSBitfieldPromoteTy = Context.isPromotableBitField(LHS.get());
Douglas Gregord2c2d172009-05-02 00:36:19 +00001076 if (!LHSBitfieldPromoteTy.isNull())
Richard Trieu9a52fbb2011-09-06 19:52:52 +00001077 LHSType = LHSBitfieldPromoteTy;
Richard Trieuba63ce62011-09-09 01:45:06 +00001078 if (LHSType != LHSUnpromotedType && !IsCompAssign)
Richard Trieu9a52fbb2011-09-06 19:52:52 +00001079 LHS = ImpCastExprToType(LHS.take(), LHSType, CK_IntegralCast);
Douglas Gregord2c2d172009-05-02 00:36:19 +00001080
John McCalld005ac92010-11-13 08:17:45 +00001081 // If both types are identical, no conversion is needed.
Richard Trieu9a52fbb2011-09-06 19:52:52 +00001082 if (LHSType == RHSType)
1083 return LHSType;
John McCalld005ac92010-11-13 08:17:45 +00001084
1085 // At this point, we have two different arithmetic types.
1086
1087 // Handle complex types first (C99 6.3.1.8p1).
Richard Trieu9a52fbb2011-09-06 19:52:52 +00001088 if (LHSType->isComplexType() || RHSType->isComplexType())
1089 return handleComplexFloatConversion(*this, LHS, RHS, LHSType, RHSType,
Richard Trieuba63ce62011-09-09 01:45:06 +00001090 IsCompAssign);
John McCalld005ac92010-11-13 08:17:45 +00001091
1092 // Now handle "real" floating types (i.e. float, double, long double).
Richard Trieu9a52fbb2011-09-06 19:52:52 +00001093 if (LHSType->isRealFloatingType() || RHSType->isRealFloatingType())
1094 return handleFloatConversion(*this, LHS, RHS, LHSType, RHSType,
Richard Trieuba63ce62011-09-09 01:45:06 +00001095 IsCompAssign);
John McCalld005ac92010-11-13 08:17:45 +00001096
1097 // Handle GCC complex int extension.
Richard Trieu9a52fbb2011-09-06 19:52:52 +00001098 if (LHSType->isComplexIntegerType() || RHSType->isComplexIntegerType())
Benjamin Kramer499c68b2011-09-06 19:57:14 +00001099 return handleComplexIntConversion(*this, LHS, RHS, LHSType, RHSType,
Richard Trieuba63ce62011-09-09 01:45:06 +00001100 IsCompAssign);
John McCalld005ac92010-11-13 08:17:45 +00001101
1102 // Finally, we have two differing integer types.
Richard Trieu9a52fbb2011-09-06 19:52:52 +00001103 return handleIntegerConversion(*this, LHS, RHS, LHSType, RHSType,
Richard Trieuba63ce62011-09-09 01:45:06 +00001104 IsCompAssign);
Douglas Gregora11693b2008-11-12 17:17:38 +00001105}
1106
Chris Lattner513165e2008-07-25 21:10:04 +00001107//===----------------------------------------------------------------------===//
1108// Semantic Analysis for various Expression Types
1109//===----------------------------------------------------------------------===//
1110
1111
Peter Collingbourne91147592011-04-15 00:35:48 +00001112ExprResult
1113Sema::ActOnGenericSelectionExpr(SourceLocation KeyLoc,
1114 SourceLocation DefaultLoc,
1115 SourceLocation RParenLoc,
1116 Expr *ControllingExpr,
Richard Trieuba63ce62011-09-09 01:45:06 +00001117 MultiTypeArg ArgTypes,
1118 MultiExprArg ArgExprs) {
1119 unsigned NumAssocs = ArgTypes.size();
1120 assert(NumAssocs == ArgExprs.size());
Peter Collingbourne91147592011-04-15 00:35:48 +00001121
Benjamin Kramercc4c49d2012-08-23 23:38:35 +00001122 ParsedType *ParsedTypes = ArgTypes.data();
1123 Expr **Exprs = ArgExprs.data();
Peter Collingbourne91147592011-04-15 00:35:48 +00001124
1125 TypeSourceInfo **Types = new TypeSourceInfo*[NumAssocs];
1126 for (unsigned i = 0; i < NumAssocs; ++i) {
1127 if (ParsedTypes[i])
1128 (void) GetTypeFromParser(ParsedTypes[i], &Types[i]);
1129 else
1130 Types[i] = 0;
1131 }
1132
1133 ExprResult ER = CreateGenericSelectionExpr(KeyLoc, DefaultLoc, RParenLoc,
1134 ControllingExpr, Types, Exprs,
1135 NumAssocs);
Benjamin Kramer34623762011-04-15 11:21:57 +00001136 delete [] Types;
Peter Collingbourne91147592011-04-15 00:35:48 +00001137 return ER;
1138}
1139
1140ExprResult
1141Sema::CreateGenericSelectionExpr(SourceLocation KeyLoc,
1142 SourceLocation DefaultLoc,
1143 SourceLocation RParenLoc,
1144 Expr *ControllingExpr,
1145 TypeSourceInfo **Types,
1146 Expr **Exprs,
1147 unsigned NumAssocs) {
1148 bool TypeErrorFound = false,
1149 IsResultDependent = ControllingExpr->isTypeDependent(),
1150 ContainsUnexpandedParameterPack
1151 = ControllingExpr->containsUnexpandedParameterPack();
1152
1153 for (unsigned i = 0; i < NumAssocs; ++i) {
1154 if (Exprs[i]->containsUnexpandedParameterPack())
1155 ContainsUnexpandedParameterPack = true;
1156
1157 if (Types[i]) {
1158 if (Types[i]->getType()->containsUnexpandedParameterPack())
1159 ContainsUnexpandedParameterPack = true;
1160
1161 if (Types[i]->getType()->isDependentType()) {
1162 IsResultDependent = true;
1163 } else {
Benjamin Kramere56f3932011-12-23 17:00:35 +00001164 // C11 6.5.1.1p2 "The type name in a generic association shall specify a
Peter Collingbourne91147592011-04-15 00:35:48 +00001165 // complete object type other than a variably modified type."
1166 unsigned D = 0;
1167 if (Types[i]->getType()->isIncompleteType())
1168 D = diag::err_assoc_type_incomplete;
1169 else if (!Types[i]->getType()->isObjectType())
1170 D = diag::err_assoc_type_nonobject;
1171 else if (Types[i]->getType()->isVariablyModifiedType())
1172 D = diag::err_assoc_type_variably_modified;
1173
1174 if (D != 0) {
1175 Diag(Types[i]->getTypeLoc().getBeginLoc(), D)
1176 << Types[i]->getTypeLoc().getSourceRange()
1177 << Types[i]->getType();
1178 TypeErrorFound = true;
1179 }
1180
Benjamin Kramere56f3932011-12-23 17:00:35 +00001181 // C11 6.5.1.1p2 "No two generic associations in the same generic
Peter Collingbourne91147592011-04-15 00:35:48 +00001182 // selection shall specify compatible types."
1183 for (unsigned j = i+1; j < NumAssocs; ++j)
1184 if (Types[j] && !Types[j]->getType()->isDependentType() &&
1185 Context.typesAreCompatible(Types[i]->getType(),
1186 Types[j]->getType())) {
1187 Diag(Types[j]->getTypeLoc().getBeginLoc(),
1188 diag::err_assoc_compatible_types)
1189 << Types[j]->getTypeLoc().getSourceRange()
1190 << Types[j]->getType()
1191 << Types[i]->getType();
1192 Diag(Types[i]->getTypeLoc().getBeginLoc(),
1193 diag::note_compat_assoc)
1194 << Types[i]->getTypeLoc().getSourceRange()
1195 << Types[i]->getType();
1196 TypeErrorFound = true;
1197 }
1198 }
1199 }
1200 }
1201 if (TypeErrorFound)
1202 return ExprError();
1203
1204 // If we determined that the generic selection is result-dependent, don't
1205 // try to compute the result expression.
1206 if (IsResultDependent)
1207 return Owned(new (Context) GenericSelectionExpr(
1208 Context, KeyLoc, ControllingExpr,
Benjamin Kramerc215e762012-08-24 11:54:20 +00001209 llvm::makeArrayRef(Types, NumAssocs),
1210 llvm::makeArrayRef(Exprs, NumAssocs),
1211 DefaultLoc, RParenLoc, ContainsUnexpandedParameterPack));
Peter Collingbourne91147592011-04-15 00:35:48 +00001212
Chris Lattner0e62c1c2011-07-23 10:55:15 +00001213 SmallVector<unsigned, 1> CompatIndices;
Peter Collingbourne91147592011-04-15 00:35:48 +00001214 unsigned DefaultIndex = -1U;
1215 for (unsigned i = 0; i < NumAssocs; ++i) {
1216 if (!Types[i])
1217 DefaultIndex = i;
1218 else if (Context.typesAreCompatible(ControllingExpr->getType(),
1219 Types[i]->getType()))
1220 CompatIndices.push_back(i);
1221 }
1222
Benjamin Kramere56f3932011-12-23 17:00:35 +00001223 // C11 6.5.1.1p2 "The controlling expression of a generic selection shall have
Peter Collingbourne91147592011-04-15 00:35:48 +00001224 // type compatible with at most one of the types named in its generic
1225 // association list."
1226 if (CompatIndices.size() > 1) {
1227 // We strip parens here because the controlling expression is typically
1228 // parenthesized in macro definitions.
1229 ControllingExpr = ControllingExpr->IgnoreParens();
1230 Diag(ControllingExpr->getLocStart(), diag::err_generic_sel_multi_match)
1231 << ControllingExpr->getSourceRange() << ControllingExpr->getType()
1232 << (unsigned) CompatIndices.size();
Chris Lattner0e62c1c2011-07-23 10:55:15 +00001233 for (SmallVector<unsigned, 1>::iterator I = CompatIndices.begin(),
Peter Collingbourne91147592011-04-15 00:35:48 +00001234 E = CompatIndices.end(); I != E; ++I) {
1235 Diag(Types[*I]->getTypeLoc().getBeginLoc(),
1236 diag::note_compat_assoc)
1237 << Types[*I]->getTypeLoc().getSourceRange()
1238 << Types[*I]->getType();
1239 }
1240 return ExprError();
1241 }
1242
Benjamin Kramere56f3932011-12-23 17:00:35 +00001243 // C11 6.5.1.1p2 "If a generic selection has no default generic association,
Peter Collingbourne91147592011-04-15 00:35:48 +00001244 // its controlling expression shall have type compatible with exactly one of
1245 // the types named in its generic association list."
1246 if (DefaultIndex == -1U && CompatIndices.size() == 0) {
1247 // We strip parens here because the controlling expression is typically
1248 // parenthesized in macro definitions.
1249 ControllingExpr = ControllingExpr->IgnoreParens();
1250 Diag(ControllingExpr->getLocStart(), diag::err_generic_sel_no_match)
1251 << ControllingExpr->getSourceRange() << ControllingExpr->getType();
1252 return ExprError();
1253 }
1254
Benjamin Kramere56f3932011-12-23 17:00:35 +00001255 // C11 6.5.1.1p3 "If a generic selection has a generic association with a
Peter Collingbourne91147592011-04-15 00:35:48 +00001256 // type name that is compatible with the type of the controlling expression,
1257 // then the result expression of the generic selection is the expression
1258 // in that generic association. Otherwise, the result expression of the
1259 // generic selection is the expression in the default generic association."
1260 unsigned ResultIndex =
1261 CompatIndices.size() ? CompatIndices[0] : DefaultIndex;
1262
1263 return Owned(new (Context) GenericSelectionExpr(
1264 Context, KeyLoc, ControllingExpr,
Benjamin Kramerc215e762012-08-24 11:54:20 +00001265 llvm::makeArrayRef(Types, NumAssocs),
1266 llvm::makeArrayRef(Exprs, NumAssocs),
1267 DefaultLoc, RParenLoc, ContainsUnexpandedParameterPack,
Peter Collingbourne91147592011-04-15 00:35:48 +00001268 ResultIndex));
1269}
1270
Richard Smith75b67d62012-03-08 01:34:56 +00001271/// getUDSuffixLoc - Create a SourceLocation for a ud-suffix, given the
1272/// location of the token and the offset of the ud-suffix within it.
1273static SourceLocation getUDSuffixLoc(Sema &S, SourceLocation TokLoc,
1274 unsigned Offset) {
1275 return Lexer::AdvanceToTokenCharacter(TokLoc, Offset, S.getSourceManager(),
David Blaikiebbafb8a2012-03-11 07:00:24 +00001276 S.getLangOpts());
Richard Smith75b67d62012-03-08 01:34:56 +00001277}
1278
Richard Smithbcc22fc2012-03-09 08:00:36 +00001279/// BuildCookedLiteralOperatorCall - A user-defined literal was found. Look up
1280/// the corresponding cooked (non-raw) literal operator, and build a call to it.
1281static ExprResult BuildCookedLiteralOperatorCall(Sema &S, Scope *Scope,
1282 IdentifierInfo *UDSuffix,
1283 SourceLocation UDSuffixLoc,
1284 ArrayRef<Expr*> Args,
1285 SourceLocation LitEndLoc) {
1286 assert(Args.size() <= 2 && "too many arguments for literal operator");
1287
1288 QualType ArgTy[2];
1289 for (unsigned ArgIdx = 0; ArgIdx != Args.size(); ++ArgIdx) {
1290 ArgTy[ArgIdx] = Args[ArgIdx]->getType();
1291 if (ArgTy[ArgIdx]->isArrayType())
1292 ArgTy[ArgIdx] = S.Context.getArrayDecayedType(ArgTy[ArgIdx]);
1293 }
1294
1295 DeclarationName OpName =
1296 S.Context.DeclarationNames.getCXXLiteralOperatorName(UDSuffix);
1297 DeclarationNameInfo OpNameInfo(OpName, UDSuffixLoc);
1298 OpNameInfo.setCXXLiteralOperatorNameLoc(UDSuffixLoc);
1299
1300 LookupResult R(S, OpName, UDSuffixLoc, Sema::LookupOrdinaryName);
1301 if (S.LookupLiteralOperator(Scope, R, llvm::makeArrayRef(ArgTy, Args.size()),
1302 /*AllowRawAndTemplate*/false) == Sema::LOLR_Error)
1303 return ExprError();
1304
1305 return S.BuildLiteralOperatorCall(R, OpNameInfo, Args, LitEndLoc);
1306}
1307
Steve Naroff83895f72007-09-16 03:34:24 +00001308/// ActOnStringLiteral - The specified tokens were lexed as pasted string
Chris Lattner5b183d82006-11-10 05:03:26 +00001309/// fragments (e.g. "foo" "bar" L"baz"). The result string has to handle string
1310/// concatenation ([C99 5.1.1.2, translation phase #6]), so it may come from
1311/// multiple tokens. However, the common case is that StringToks points to one
1312/// string.
Sebastian Redlffbcf962009-01-18 18:53:16 +00001313///
John McCalldadc5752010-08-24 06:29:42 +00001314ExprResult
Richard Smithbcc22fc2012-03-09 08:00:36 +00001315Sema::ActOnStringLiteral(const Token *StringToks, unsigned NumStringToks,
1316 Scope *UDLScope) {
Chris Lattner5b183d82006-11-10 05:03:26 +00001317 assert(NumStringToks && "Must have at least one string!");
1318
Chris Lattner8a24e582009-01-16 18:51:42 +00001319 StringLiteralParser Literal(StringToks, NumStringToks, PP);
Steve Naroff4f88b312007-03-13 22:37:02 +00001320 if (Literal.hadError)
Sebastian Redlffbcf962009-01-18 18:53:16 +00001321 return ExprError();
Chris Lattner5b183d82006-11-10 05:03:26 +00001322
Chris Lattner0e62c1c2011-07-23 10:55:15 +00001323 SmallVector<SourceLocation, 4> StringTokLocs;
Chris Lattner5b183d82006-11-10 05:03:26 +00001324 for (unsigned i = 0; i != NumStringToks; ++i)
1325 StringTokLocs.push_back(StringToks[i].getLocation());
Chris Lattner36fc8792008-02-11 00:02:17 +00001326
Chris Lattner36fc8792008-02-11 00:02:17 +00001327 QualType StrTy = Context.CharTy;
Douglas Gregorfb65e592011-07-27 05:40:30 +00001328 if (Literal.isWide())
Anders Carlsson6b06e182011-04-06 18:42:48 +00001329 StrTy = Context.getWCharType();
Douglas Gregorfb65e592011-07-27 05:40:30 +00001330 else if (Literal.isUTF16())
1331 StrTy = Context.Char16Ty;
1332 else if (Literal.isUTF32())
1333 StrTy = Context.Char32Ty;
Eli Friedmanfcec6302011-11-01 02:23:42 +00001334 else if (Literal.isPascal())
Anders Carlsson6b06e182011-04-06 18:42:48 +00001335 StrTy = Context.UnsignedCharTy;
Douglas Gregoraa1e21d2008-09-12 00:47:35 +00001336
Douglas Gregorfb65e592011-07-27 05:40:30 +00001337 StringLiteral::StringKind Kind = StringLiteral::Ascii;
1338 if (Literal.isWide())
1339 Kind = StringLiteral::Wide;
1340 else if (Literal.isUTF8())
1341 Kind = StringLiteral::UTF8;
1342 else if (Literal.isUTF16())
1343 Kind = StringLiteral::UTF16;
1344 else if (Literal.isUTF32())
1345 Kind = StringLiteral::UTF32;
1346
Douglas Gregoraa1e21d2008-09-12 00:47:35 +00001347 // A C++ string literal has a const-qualified element type (C++ 2.13.4p1).
David Blaikiebbafb8a2012-03-11 07:00:24 +00001348 if (getLangOpts().CPlusPlus || getLangOpts().ConstStrings)
Douglas Gregoraa1e21d2008-09-12 00:47:35 +00001349 StrTy.addConst();
Sebastian Redlffbcf962009-01-18 18:53:16 +00001350
Chris Lattner36fc8792008-02-11 00:02:17 +00001351 // Get an array type for the string, according to C99 6.4.5. This includes
1352 // the nul terminator character as well as the string length for pascal
1353 // strings.
1354 StrTy = Context.getConstantArrayType(StrTy,
Chris Lattnerd42c29f2009-02-26 23:01:51 +00001355 llvm::APInt(32, Literal.GetNumStringChars()+1),
Chris Lattner36fc8792008-02-11 00:02:17 +00001356 ArrayType::Normal, 0);
Mike Stump11289f42009-09-09 15:08:12 +00001357
Chris Lattner5b183d82006-11-10 05:03:26 +00001358 // Pass &StringTokLocs[0], StringTokLocs.size() to factory!
Richard Smithc67fdd42012-03-07 08:35:16 +00001359 StringLiteral *Lit = StringLiteral::Create(Context, Literal.GetString(),
1360 Kind, Literal.Pascal, StrTy,
1361 &StringTokLocs[0],
1362 StringTokLocs.size());
1363 if (Literal.getUDSuffix().empty())
1364 return Owned(Lit);
1365
1366 // We're building a user-defined literal.
1367 IdentifierInfo *UDSuffix = &Context.Idents.get(Literal.getUDSuffix());
Richard Smith75b67d62012-03-08 01:34:56 +00001368 SourceLocation UDSuffixLoc =
1369 getUDSuffixLoc(*this, StringTokLocs[Literal.getUDSuffixToken()],
1370 Literal.getUDSuffixOffset());
Richard Smithc67fdd42012-03-07 08:35:16 +00001371
Richard Smithbcc22fc2012-03-09 08:00:36 +00001372 // Make sure we're allowed user-defined literals here.
1373 if (!UDLScope)
1374 return ExprError(Diag(UDSuffixLoc, diag::err_invalid_string_udl));
1375
Richard Smithc67fdd42012-03-07 08:35:16 +00001376 // C++11 [lex.ext]p5: The literal L is treated as a call of the form
1377 // operator "" X (str, len)
1378 QualType SizeType = Context.getSizeType();
1379 llvm::APInt Len(Context.getIntWidth(SizeType), Literal.GetNumStringChars());
1380 IntegerLiteral *LenArg = IntegerLiteral::Create(Context, Len, SizeType,
1381 StringTokLocs[0]);
1382 Expr *Args[] = { Lit, LenArg };
Richard Smithbcc22fc2012-03-09 08:00:36 +00001383 return BuildCookedLiteralOperatorCall(*this, UDLScope, UDSuffix, UDSuffixLoc,
1384 Args, StringTokLocs.back());
Chris Lattner5b183d82006-11-10 05:03:26 +00001385}
1386
John McCalldadc5752010-08-24 06:29:42 +00001387ExprResult
John McCall7decc9e2010-11-18 06:31:45 +00001388Sema::BuildDeclRefExpr(ValueDecl *D, QualType Ty, ExprValueKind VK,
John McCallf4cd4f92011-02-09 01:13:10 +00001389 SourceLocation Loc,
1390 const CXXScopeSpec *SS) {
Abramo Bagnarad6d2f182010-08-11 22:01:17 +00001391 DeclarationNameInfo NameInfo(D->getDeclName(), Loc);
John McCall7decc9e2010-11-18 06:31:45 +00001392 return BuildDeclRefExpr(D, Ty, VK, NameInfo, SS);
Abramo Bagnarad6d2f182010-08-11 22:01:17 +00001393}
1394
John McCallf4cd4f92011-02-09 01:13:10 +00001395/// BuildDeclRefExpr - Build an expression that references a
1396/// declaration that does not require a closure capture.
John McCalldadc5752010-08-24 06:29:42 +00001397ExprResult
John McCallf4cd4f92011-02-09 01:13:10 +00001398Sema::BuildDeclRefExpr(ValueDecl *D, QualType Ty, ExprValueKind VK,
Abramo Bagnarad6d2f182010-08-11 22:01:17 +00001399 const DeclarationNameInfo &NameInfo,
1400 const CXXScopeSpec *SS) {
David Blaikiebbafb8a2012-03-11 07:00:24 +00001401 if (getLangOpts().CUDA)
Peter Collingbourne7277fe82011-10-02 23:49:40 +00001402 if (const FunctionDecl *Caller = dyn_cast<FunctionDecl>(CurContext))
1403 if (const FunctionDecl *Callee = dyn_cast<FunctionDecl>(D)) {
1404 CUDAFunctionTarget CallerTarget = IdentifyCUDATarget(Caller),
1405 CalleeTarget = IdentifyCUDATarget(Callee);
1406 if (CheckCUDATarget(CallerTarget, CalleeTarget)) {
1407 Diag(NameInfo.getLoc(), diag::err_ref_bad_target)
1408 << CalleeTarget << D->getIdentifier() << CallerTarget;
1409 Diag(D->getLocation(), diag::note_previous_decl)
1410 << D->getIdentifier();
1411 return ExprError();
1412 }
1413 }
1414
John McCall113bee02012-03-10 09:33:50 +00001415 bool refersToEnclosingScope =
1416 (CurContext != D->getDeclContext() &&
1417 D->getDeclContext()->isFunctionOrMethod());
1418
Eli Friedmanfa0df832012-02-02 03:46:19 +00001419 DeclRefExpr *E = DeclRefExpr::Create(Context,
1420 SS ? SS->getWithLocInContext(Context)
1421 : NestedNameSpecifierLoc(),
John McCall113bee02012-03-10 09:33:50 +00001422 SourceLocation(),
1423 D, refersToEnclosingScope,
1424 NameInfo, Ty, VK);
Mike Stump11289f42009-09-09 15:08:12 +00001425
Eli Friedmanfa0df832012-02-02 03:46:19 +00001426 MarkDeclRefReferenced(E);
John McCall086a4642010-11-24 05:12:34 +00001427
1428 // Just in case we're building an illegal pointer-to-member.
Richard Smithcaf33902011-10-10 18:28:20 +00001429 FieldDecl *FD = dyn_cast<FieldDecl>(D);
1430 if (FD && FD->isBitField())
John McCall086a4642010-11-24 05:12:34 +00001431 E->setObjectKind(OK_BitField);
1432
1433 return Owned(E);
Douglas Gregorc7acfdf2009-01-06 05:10:23 +00001434}
1435
Abramo Bagnarad6d2f182010-08-11 22:01:17 +00001436/// Decomposes the given name into a DeclarationNameInfo, its location, and
John McCall10eae182009-11-30 22:42:35 +00001437/// possibly a list of template arguments.
1438///
1439/// If this produces template arguments, it is permitted to call
1440/// DecomposeTemplateName.
1441///
1442/// This actually loses a lot of source location information for
1443/// non-standard name kinds; we should consider preserving that in
1444/// some way.
Richard Trieucfc491d2011-08-02 04:35:43 +00001445void
1446Sema::DecomposeUnqualifiedId(const UnqualifiedId &Id,
1447 TemplateArgumentListInfo &Buffer,
1448 DeclarationNameInfo &NameInfo,
1449 const TemplateArgumentListInfo *&TemplateArgs) {
John McCall10eae182009-11-30 22:42:35 +00001450 if (Id.getKind() == UnqualifiedId::IK_TemplateId) {
1451 Buffer.setLAngleLoc(Id.TemplateId->LAngleLoc);
1452 Buffer.setRAngleLoc(Id.TemplateId->RAngleLoc);
1453
Benjamin Kramercc4c49d2012-08-23 23:38:35 +00001454 ASTTemplateArgsPtr TemplateArgsPtr(Id.TemplateId->getTemplateArgs(),
John McCall10eae182009-11-30 22:42:35 +00001455 Id.TemplateId->NumArgs);
Douglas Gregor5476205b2011-06-23 00:49:38 +00001456 translateTemplateArguments(TemplateArgsPtr, Buffer);
John McCall10eae182009-11-30 22:42:35 +00001457
John McCall3e56fd42010-08-23 07:28:44 +00001458 TemplateName TName = Id.TemplateId->Template.get();
Abramo Bagnarad6d2f182010-08-11 22:01:17 +00001459 SourceLocation TNameLoc = Id.TemplateId->TemplateNameLoc;
Douglas Gregor5476205b2011-06-23 00:49:38 +00001460 NameInfo = Context.getNameForTemplate(TName, TNameLoc);
John McCall10eae182009-11-30 22:42:35 +00001461 TemplateArgs = &Buffer;
1462 } else {
Douglas Gregor5476205b2011-06-23 00:49:38 +00001463 NameInfo = GetNameFromUnqualifiedId(Id);
John McCall10eae182009-11-30 22:42:35 +00001464 TemplateArgs = 0;
1465 }
1466}
1467
John McCalld681c392009-12-16 08:11:27 +00001468/// Diagnose an empty lookup.
1469///
1470/// \return false if new lookup candidates were found
Nick Lewyckyc96c37f2010-07-06 19:51:49 +00001471bool Sema::DiagnoseEmptyLookup(Scope *S, CXXScopeSpec &SS, LookupResult &R,
Kaelyn Uhrain79d01c12012-01-18 05:58:54 +00001472 CorrectionCandidateCallback &CCC,
Kaelyn Uhrain42830922011-08-05 00:09:52 +00001473 TemplateArgumentListInfo *ExplicitTemplateArgs,
Ahmed Charlesb24b9aa2012-02-25 11:00:22 +00001474 llvm::ArrayRef<Expr *> Args) {
John McCalld681c392009-12-16 08:11:27 +00001475 DeclarationName Name = R.getLookupName();
1476
John McCalld681c392009-12-16 08:11:27 +00001477 unsigned diagnostic = diag::err_undeclared_var_use;
Douglas Gregor598b08f2009-12-31 05:20:13 +00001478 unsigned diagnostic_suggest = diag::err_undeclared_var_use_suggest;
John McCalld681c392009-12-16 08:11:27 +00001479 if (Name.getNameKind() == DeclarationName::CXXOperatorName ||
1480 Name.getNameKind() == DeclarationName::CXXLiteralOperatorName ||
Douglas Gregor598b08f2009-12-31 05:20:13 +00001481 Name.getNameKind() == DeclarationName::CXXConversionFunctionName) {
John McCalld681c392009-12-16 08:11:27 +00001482 diagnostic = diag::err_undeclared_use;
Douglas Gregor598b08f2009-12-31 05:20:13 +00001483 diagnostic_suggest = diag::err_undeclared_use_suggest;
1484 }
John McCalld681c392009-12-16 08:11:27 +00001485
Douglas Gregor598b08f2009-12-31 05:20:13 +00001486 // If the original lookup was an unqualified lookup, fake an
1487 // unqualified lookup. This is useful when (for example) the
1488 // original lookup would not have found something because it was a
1489 // dependent name.
David Blaikiec4c0e8a2012-05-28 01:26:45 +00001490 DeclContext *DC = (SS.isEmpty() && !CallsUndergoingInstantiation.empty())
1491 ? CurContext : 0;
Francois Pichetde232cb2011-11-25 01:10:54 +00001492 while (DC) {
John McCalld681c392009-12-16 08:11:27 +00001493 if (isa<CXXRecordDecl>(DC)) {
1494 LookupQualifiedName(R, DC);
1495
1496 if (!R.empty()) {
1497 // Don't give errors about ambiguities in this lookup.
1498 R.suppressDiagnostics();
1499
Francois Pichet857f9d62011-11-17 03:44:24 +00001500 // During a default argument instantiation the CurContext points
1501 // to a CXXMethodDecl; but we can't apply a this-> fixit inside a
1502 // function parameter list, hence add an explicit check.
1503 bool isDefaultArgument = !ActiveTemplateInstantiations.empty() &&
1504 ActiveTemplateInstantiations.back().Kind ==
1505 ActiveTemplateInstantiation::DefaultFunctionArgumentInstantiation;
John McCalld681c392009-12-16 08:11:27 +00001506 CXXMethodDecl *CurMethod = dyn_cast<CXXMethodDecl>(CurContext);
1507 bool isInstance = CurMethod &&
1508 CurMethod->isInstance() &&
Francois Pichet857f9d62011-11-17 03:44:24 +00001509 DC == CurMethod->getParent() && !isDefaultArgument;
1510
John McCalld681c392009-12-16 08:11:27 +00001511
1512 // Give a code modification hint to insert 'this->'.
1513 // TODO: fixit for inserting 'Base<T>::' in the other cases.
1514 // Actually quite difficult!
Nico Weberdf7dffb2012-06-20 20:21:42 +00001515 if (getLangOpts().MicrosoftMode)
1516 diagnostic = diag::warn_found_via_dependent_bases_lookup;
Nick Lewyckyc96c37f2010-07-06 19:51:49 +00001517 if (isInstance) {
Nico Weber3c10fb12012-06-22 16:39:39 +00001518 Diag(R.getNameLoc(), diagnostic) << Name
1519 << FixItHint::CreateInsertion(R.getNameLoc(), "this->");
Nick Lewyckyc96c37f2010-07-06 19:51:49 +00001520 UnresolvedLookupExpr *ULE = cast<UnresolvedLookupExpr>(
1521 CallsUndergoingInstantiation.back()->getCallee());
Nico Weber3c10fb12012-06-22 16:39:39 +00001522
1523
1524 CXXMethodDecl *DepMethod;
1525 if (CurMethod->getTemplatedKind() ==
1526 FunctionDecl::TK_FunctionTemplateSpecialization)
1527 DepMethod = cast<CXXMethodDecl>(CurMethod->getPrimaryTemplate()->
1528 getInstantiatedFromMemberTemplate()->getTemplatedDecl());
1529 else
1530 DepMethod = cast<CXXMethodDecl>(
1531 CurMethod->getInstantiatedFromMemberFunction());
1532 assert(DepMethod && "No template pattern found");
1533
1534 QualType DepThisType = DepMethod->getThisType(Context);
1535 CheckCXXThisCapture(R.getNameLoc());
1536 CXXThisExpr *DepThis = new (Context) CXXThisExpr(
1537 R.getNameLoc(), DepThisType, false);
1538 TemplateArgumentListInfo TList;
1539 if (ULE->hasExplicitTemplateArgs())
1540 ULE->copyTemplateArgumentsInto(TList);
1541
1542 CXXScopeSpec SS;
1543 SS.Adopt(ULE->getQualifierLoc());
1544 CXXDependentScopeMemberExpr *DepExpr =
1545 CXXDependentScopeMemberExpr::Create(
1546 Context, DepThis, DepThisType, true, SourceLocation(),
1547 SS.getWithLocInContext(Context),
1548 ULE->getTemplateKeywordLoc(), 0,
1549 R.getLookupNameInfo(),
1550 ULE->hasExplicitTemplateArgs() ? &TList : 0);
1551 CallsUndergoingInstantiation.back()->setCallee(DepExpr);
Nick Lewyckyc96c37f2010-07-06 19:51:49 +00001552 } else {
John McCalld681c392009-12-16 08:11:27 +00001553 Diag(R.getNameLoc(), diagnostic) << Name;
Nick Lewyckyc96c37f2010-07-06 19:51:49 +00001554 }
John McCalld681c392009-12-16 08:11:27 +00001555
1556 // Do we really want to note all of these?
1557 for (LookupResult::iterator I = R.begin(), E = R.end(); I != E; ++I)
1558 Diag((*I)->getLocation(), diag::note_dependent_var_use);
1559
Francois Pichet857f9d62011-11-17 03:44:24 +00001560 // Return true if we are inside a default argument instantiation
1561 // and the found name refers to an instance member function, otherwise
1562 // the function calling DiagnoseEmptyLookup will try to create an
1563 // implicit member call and this is wrong for default argument.
1564 if (isDefaultArgument && ((*R.begin())->isCXXInstanceMember())) {
1565 Diag(R.getNameLoc(), diag::err_member_call_without_object);
1566 return true;
1567 }
1568
John McCalld681c392009-12-16 08:11:27 +00001569 // Tell the callee to try to recover.
1570 return false;
1571 }
Douglas Gregor86b8d9f2010-08-09 22:38:14 +00001572
1573 R.clear();
John McCalld681c392009-12-16 08:11:27 +00001574 }
Francois Pichetde232cb2011-11-25 01:10:54 +00001575
1576 // In Microsoft mode, if we are performing lookup from within a friend
1577 // function definition declared at class scope then we must set
1578 // DC to the lexical parent to be able to search into the parent
1579 // class.
David Blaikiebbafb8a2012-03-11 07:00:24 +00001580 if (getLangOpts().MicrosoftMode && isa<FunctionDecl>(DC) &&
Francois Pichetde232cb2011-11-25 01:10:54 +00001581 cast<FunctionDecl>(DC)->getFriendObjectKind() &&
1582 DC->getLexicalParent()->isRecord())
1583 DC = DC->getLexicalParent();
1584 else
1585 DC = DC->getParent();
John McCalld681c392009-12-16 08:11:27 +00001586 }
1587
Douglas Gregor598b08f2009-12-31 05:20:13 +00001588 // We didn't find anything, so try to correct for a typo.
Douglas Gregorc2fa1692011-06-28 16:20:02 +00001589 TypoCorrection Corrected;
1590 if (S && (Corrected = CorrectTypo(R.getLookupNameInfo(), R.getLookupKind(),
Kaelyn Uhrain4e8942c2012-01-31 23:49:25 +00001591 S, &SS, CCC))) {
David Blaikiebbafb8a2012-03-11 07:00:24 +00001592 std::string CorrectedStr(Corrected.getAsString(getLangOpts()));
1593 std::string CorrectedQuotedStr(Corrected.getQuoted(getLangOpts()));
Douglas Gregorc2fa1692011-06-28 16:20:02 +00001594 R.setLookupName(Corrected.getCorrection());
1595
Hans Wennborg38198de2011-07-12 08:45:31 +00001596 if (NamedDecl *ND = Corrected.getCorrectionDecl()) {
Kaelyn Uhrainacbdc572011-08-03 20:36:05 +00001597 if (Corrected.isOverloaded()) {
1598 OverloadCandidateSet OCS(R.getNameLoc());
1599 OverloadCandidateSet::iterator Best;
1600 for (TypoCorrection::decl_iterator CD = Corrected.begin(),
1601 CDEnd = Corrected.end();
1602 CD != CDEnd; ++CD) {
Kaelyn Uhrain62422202011-08-08 17:35:31 +00001603 if (FunctionTemplateDecl *FTD =
Kaelyn Uhrain42830922011-08-05 00:09:52 +00001604 dyn_cast<FunctionTemplateDecl>(*CD))
1605 AddTemplateOverloadCandidate(
1606 FTD, DeclAccessPair::make(FTD, AS_none), ExplicitTemplateArgs,
Ahmed Charlesb24b9aa2012-02-25 11:00:22 +00001607 Args, OCS);
Kaelyn Uhrain62422202011-08-08 17:35:31 +00001608 else if (FunctionDecl *FD = dyn_cast<FunctionDecl>(*CD))
1609 if (!ExplicitTemplateArgs || ExplicitTemplateArgs->size() == 0)
1610 AddOverloadCandidate(FD, DeclAccessPair::make(FD, AS_none),
Ahmed Charlesb24b9aa2012-02-25 11:00:22 +00001611 Args, OCS);
Kaelyn Uhrainacbdc572011-08-03 20:36:05 +00001612 }
1613 switch (OCS.BestViableFunction(*this, R.getNameLoc(), Best)) {
1614 case OR_Success:
1615 ND = Best->Function;
1616 break;
1617 default:
Kaelyn Uhrainea350182011-08-04 23:30:54 +00001618 break;
Kaelyn Uhrainacbdc572011-08-03 20:36:05 +00001619 }
1620 }
Douglas Gregorc2fa1692011-06-28 16:20:02 +00001621 R.addDecl(ND);
1622 if (isa<ValueDecl>(ND) || isa<FunctionTemplateDecl>(ND)) {
Douglas Gregor280e1ee2010-04-14 20:04:41 +00001623 if (SS.isEmpty())
Douglas Gregorc2fa1692011-06-28 16:20:02 +00001624 Diag(R.getNameLoc(), diagnostic_suggest) << Name << CorrectedQuotedStr
1625 << FixItHint::CreateReplacement(R.getNameLoc(), CorrectedStr);
Douglas Gregor280e1ee2010-04-14 20:04:41 +00001626 else
1627 Diag(R.getNameLoc(), diag::err_no_member_suggest)
Douglas Gregorc2fa1692011-06-28 16:20:02 +00001628 << Name << computeDeclContext(SS, false) << CorrectedQuotedStr
Douglas Gregor280e1ee2010-04-14 20:04:41 +00001629 << SS.getRange()
Douglas Gregorc2fa1692011-06-28 16:20:02 +00001630 << FixItHint::CreateReplacement(R.getNameLoc(), CorrectedStr);
1631 if (ND)
Douglas Gregor280e1ee2010-04-14 20:04:41 +00001632 Diag(ND->getLocation(), diag::note_previous_decl)
Douglas Gregorc2fa1692011-06-28 16:20:02 +00001633 << CorrectedQuotedStr;
Douglas Gregor280e1ee2010-04-14 20:04:41 +00001634
1635 // Tell the callee to try to recover.
1636 return false;
1637 }
Alexis Huntc46382e2010-04-28 23:02:27 +00001638
Douglas Gregorc2fa1692011-06-28 16:20:02 +00001639 if (isa<TypeDecl>(ND) || isa<ObjCInterfaceDecl>(ND)) {
Douglas Gregor280e1ee2010-04-14 20:04:41 +00001640 // FIXME: If we ended up with a typo for a type name or
1641 // Objective-C class name, we're in trouble because the parser
1642 // is in the wrong place to recover. Suggest the typo
1643 // correction, but don't make it a fix-it since we're not going
1644 // to recover well anyway.
1645 if (SS.isEmpty())
Richard Trieucfc491d2011-08-02 04:35:43 +00001646 Diag(R.getNameLoc(), diagnostic_suggest)
1647 << Name << CorrectedQuotedStr;
Douglas Gregor280e1ee2010-04-14 20:04:41 +00001648 else
1649 Diag(R.getNameLoc(), diag::err_no_member_suggest)
Douglas Gregorc2fa1692011-06-28 16:20:02 +00001650 << Name << computeDeclContext(SS, false) << CorrectedQuotedStr
Douglas Gregor280e1ee2010-04-14 20:04:41 +00001651 << SS.getRange();
1652
1653 // Don't try to recover; it won't work.
1654 return true;
1655 }
1656 } else {
Alexis Huntc46382e2010-04-28 23:02:27 +00001657 // FIXME: We found a keyword. Suggest it, but don't provide a fix-it
Douglas Gregor280e1ee2010-04-14 20:04:41 +00001658 // because we aren't able to recover.
Douglas Gregor25363982010-01-01 00:15:04 +00001659 if (SS.isEmpty())
Douglas Gregorc2fa1692011-06-28 16:20:02 +00001660 Diag(R.getNameLoc(), diagnostic_suggest) << Name << CorrectedQuotedStr;
Kovarththanan Rajaratnamba2c6522010-03-13 10:17:05 +00001661 else
Douglas Gregor25363982010-01-01 00:15:04 +00001662 Diag(R.getNameLoc(), diag::err_no_member_suggest)
Douglas Gregorc2fa1692011-06-28 16:20:02 +00001663 << Name << computeDeclContext(SS, false) << CorrectedQuotedStr
Douglas Gregor280e1ee2010-04-14 20:04:41 +00001664 << SS.getRange();
Douglas Gregor25363982010-01-01 00:15:04 +00001665 return true;
1666 }
Douglas Gregor598b08f2009-12-31 05:20:13 +00001667 }
Douglas Gregorc2fa1692011-06-28 16:20:02 +00001668 R.clear();
Douglas Gregor598b08f2009-12-31 05:20:13 +00001669
1670 // Emit a special diagnostic for failed member lookups.
1671 // FIXME: computing the declaration context might fail here (?)
1672 if (!SS.isEmpty()) {
1673 Diag(R.getNameLoc(), diag::err_no_member)
1674 << Name << computeDeclContext(SS, false)
1675 << SS.getRange();
1676 return true;
1677 }
1678
John McCalld681c392009-12-16 08:11:27 +00001679 // Give up, we can't recover.
1680 Diag(R.getNameLoc(), diagnostic) << Name;
1681 return true;
1682}
1683
John McCalldadc5752010-08-24 06:29:42 +00001684ExprResult Sema::ActOnIdExpression(Scope *S,
John McCall24d18942010-08-24 22:52:39 +00001685 CXXScopeSpec &SS,
Abramo Bagnara7945c982012-01-27 09:46:47 +00001686 SourceLocation TemplateKWLoc,
John McCall24d18942010-08-24 22:52:39 +00001687 UnqualifiedId &Id,
1688 bool HasTrailingLParen,
Kaelyn Uhrain77e21fc2012-01-25 20:49:08 +00001689 bool IsAddressOfOperand,
1690 CorrectionCandidateCallback *CCC) {
Richard Trieuba63ce62011-09-09 01:45:06 +00001691 assert(!(IsAddressOfOperand && HasTrailingLParen) &&
John McCalle66edc12009-11-24 19:00:30 +00001692 "cannot be direct & operand and have a trailing lparen");
1693
1694 if (SS.isInvalid())
Douglas Gregored8f2882009-01-30 01:04:22 +00001695 return ExprError();
Douglas Gregor90a1a652009-03-19 17:26:29 +00001696
John McCall10eae182009-11-30 22:42:35 +00001697 TemplateArgumentListInfo TemplateArgsBuffer;
John McCalle66edc12009-11-24 19:00:30 +00001698
1699 // Decompose the UnqualifiedId into the following data.
Abramo Bagnarad6d2f182010-08-11 22:01:17 +00001700 DeclarationNameInfo NameInfo;
John McCalle66edc12009-11-24 19:00:30 +00001701 const TemplateArgumentListInfo *TemplateArgs;
Douglas Gregor5476205b2011-06-23 00:49:38 +00001702 DecomposeUnqualifiedId(Id, TemplateArgsBuffer, NameInfo, TemplateArgs);
Douglas Gregor90a1a652009-03-19 17:26:29 +00001703
Abramo Bagnarad6d2f182010-08-11 22:01:17 +00001704 DeclarationName Name = NameInfo.getName();
Douglas Gregor4ea80432008-11-18 15:03:34 +00001705 IdentifierInfo *II = Name.getAsIdentifierInfo();
Abramo Bagnarad6d2f182010-08-11 22:01:17 +00001706 SourceLocation NameLoc = NameInfo.getLoc();
John McCalld14a8642009-11-21 08:51:07 +00001707
John McCalle66edc12009-11-24 19:00:30 +00001708 // C++ [temp.dep.expr]p3:
1709 // An id-expression is type-dependent if it contains:
Douglas Gregorea0a0a92010-01-11 18:40:55 +00001710 // -- an identifier that was declared with a dependent type,
1711 // (note: handled after lookup)
1712 // -- a template-id that is dependent,
1713 // (note: handled in BuildTemplateIdExpr)
1714 // -- a conversion-function-id that specifies a dependent type,
John McCalle66edc12009-11-24 19:00:30 +00001715 // -- a nested-name-specifier that contains a class-name that
1716 // names a dependent type.
1717 // Determine whether this is a member of an unknown specialization;
1718 // we need to handle these differently.
Eli Friedman964dbda2010-08-06 23:41:47 +00001719 bool DependentID = false;
1720 if (Name.getNameKind() == DeclarationName::CXXConversionFunctionName &&
1721 Name.getCXXNameType()->isDependentType()) {
1722 DependentID = true;
1723 } else if (SS.isSet()) {
Chris Lattnerebb5c6c2011-02-18 01:27:55 +00001724 if (DeclContext *DC = computeDeclContext(SS, false)) {
Eli Friedman964dbda2010-08-06 23:41:47 +00001725 if (RequireCompleteDeclContext(SS, DC))
1726 return ExprError();
Eli Friedman964dbda2010-08-06 23:41:47 +00001727 } else {
1728 DependentID = true;
1729 }
1730 }
1731
Chris Lattnerebb5c6c2011-02-18 01:27:55 +00001732 if (DependentID)
Abramo Bagnara7945c982012-01-27 09:46:47 +00001733 return ActOnDependentIdExpression(SS, TemplateKWLoc, NameInfo,
1734 IsAddressOfOperand, TemplateArgs);
Chris Lattnerebb5c6c2011-02-18 01:27:55 +00001735
John McCalle66edc12009-11-24 19:00:30 +00001736 // Perform the required lookup.
Fariborz Jahanian7f4427f2011-07-12 17:16:56 +00001737 LookupResult R(*this, NameInfo,
1738 (Id.getKind() == UnqualifiedId::IK_ImplicitSelfParam)
1739 ? LookupObjCImplicitSelfParam : LookupOrdinaryName);
John McCalle66edc12009-11-24 19:00:30 +00001740 if (TemplateArgs) {
Douglas Gregor3e51e172010-05-20 20:58:56 +00001741 // Lookup the template name again to correctly establish the context in
1742 // which it was found. This is really unfortunate as we already did the
1743 // lookup to determine that it was a template name in the first place. If
1744 // this becomes a performance hit, we can work harder to preserve those
1745 // results until we get here but it's likely not worth it.
Douglas Gregor786123d2010-05-21 23:18:07 +00001746 bool MemberOfUnknownSpecialization;
1747 LookupTemplateName(R, S, SS, QualType(), /*EnteringContext=*/false,
1748 MemberOfUnknownSpecialization);
Douglas Gregora5226932011-02-04 13:35:07 +00001749
1750 if (MemberOfUnknownSpecialization ||
1751 (R.getResultKind() == LookupResult::NotFoundInCurrentInstantiation))
Abramo Bagnara7945c982012-01-27 09:46:47 +00001752 return ActOnDependentIdExpression(SS, TemplateKWLoc, NameInfo,
1753 IsAddressOfOperand, TemplateArgs);
John McCalle66edc12009-11-24 19:00:30 +00001754 } else {
Benjamin Kramer46921442012-01-20 14:57:34 +00001755 bool IvarLookupFollowUp = II && !SS.isSet() && getCurMethodDecl();
Fariborz Jahanian6fada5b2010-01-12 23:58:59 +00001756 LookupParsedName(R, S, &SS, !IvarLookupFollowUp);
Mike Stump11289f42009-09-09 15:08:12 +00001757
Douglas Gregora5226932011-02-04 13:35:07 +00001758 // If the result might be in a dependent base class, this is a dependent
1759 // id-expression.
1760 if (R.getResultKind() == LookupResult::NotFoundInCurrentInstantiation)
Abramo Bagnara7945c982012-01-27 09:46:47 +00001761 return ActOnDependentIdExpression(SS, TemplateKWLoc, NameInfo,
1762 IsAddressOfOperand, TemplateArgs);
1763
John McCalle66edc12009-11-24 19:00:30 +00001764 // If this reference is in an Objective-C method, then we need to do
1765 // some special Objective-C lookup, too.
Fariborz Jahanian6fada5b2010-01-12 23:58:59 +00001766 if (IvarLookupFollowUp) {
John McCalldadc5752010-08-24 06:29:42 +00001767 ExprResult E(LookupInObjCMethod(R, S, II, true));
John McCalle66edc12009-11-24 19:00:30 +00001768 if (E.isInvalid())
1769 return ExprError();
Mike Stump11289f42009-09-09 15:08:12 +00001770
Chris Lattnerebb5c6c2011-02-18 01:27:55 +00001771 if (Expr *Ex = E.takeAs<Expr>())
1772 return Owned(Ex);
Steve Naroffebf4cb42008-06-02 23:03:37 +00001773 }
Chris Lattner59a25942008-03-31 00:36:02 +00001774 }
Douglas Gregorf15f5d32009-02-16 19:28:42 +00001775
John McCalle66edc12009-11-24 19:00:30 +00001776 if (R.isAmbiguous())
1777 return ExprError();
1778
Douglas Gregor171c45a2009-02-18 21:56:37 +00001779 // Determine whether this name might be a candidate for
1780 // argument-dependent lookup.
John McCalle66edc12009-11-24 19:00:30 +00001781 bool ADL = UseArgumentDependentLookup(SS, R, HasTrailingLParen);
Douglas Gregor171c45a2009-02-18 21:56:37 +00001782
John McCalle66edc12009-11-24 19:00:30 +00001783 if (R.empty() && !ADL) {
Bill Wendling4073ed52007-02-13 01:51:42 +00001784 // Otherwise, this could be an implicitly declared function reference (legal
John McCalle66edc12009-11-24 19:00:30 +00001785 // in C90, extension in C99, forbidden in C++).
David Blaikiebbafb8a2012-03-11 07:00:24 +00001786 if (HasTrailingLParen && II && !getLangOpts().CPlusPlus) {
John McCalle66edc12009-11-24 19:00:30 +00001787 NamedDecl *D = ImplicitlyDefineFunction(NameLoc, *II, S);
1788 if (D) R.addDecl(D);
1789 }
1790
1791 // If this name wasn't predeclared and if this is not a function
1792 // call, diagnose the problem.
1793 if (R.empty()) {
Francois Pichetd8e4e412011-09-24 10:38:05 +00001794
1795 // In Microsoft mode, if we are inside a template class member function
1796 // and we can't resolve an identifier then assume the identifier is type
1797 // dependent. The goal is to postpone name lookup to instantiation time
1798 // to be able to search into type dependent base classes.
David Blaikiebbafb8a2012-03-11 07:00:24 +00001799 if (getLangOpts().MicrosoftMode && CurContext->isDependentContext() &&
Francois Pichetd8e4e412011-09-24 10:38:05 +00001800 isa<CXXMethodDecl>(CurContext))
Abramo Bagnara7945c982012-01-27 09:46:47 +00001801 return ActOnDependentIdExpression(SS, TemplateKWLoc, NameInfo,
1802 IsAddressOfOperand, TemplateArgs);
Francois Pichetd8e4e412011-09-24 10:38:05 +00001803
Kaelyn Uhrain79d01c12012-01-18 05:58:54 +00001804 CorrectionCandidateCallback DefaultValidator;
Kaelyn Uhrain77e21fc2012-01-25 20:49:08 +00001805 if (DiagnoseEmptyLookup(S, SS, R, CCC ? *CCC : DefaultValidator))
John McCalld681c392009-12-16 08:11:27 +00001806 return ExprError();
1807
1808 assert(!R.empty() &&
1809 "DiagnoseEmptyLookup returned false but added no results");
Douglas Gregor35b0bac2010-01-03 18:01:57 +00001810
1811 // If we found an Objective-C instance variable, let
1812 // LookupInObjCMethod build the appropriate expression to
Kovarththanan Rajaratnamba2c6522010-03-13 10:17:05 +00001813 // reference the ivar.
Douglas Gregor35b0bac2010-01-03 18:01:57 +00001814 if (ObjCIvarDecl *Ivar = R.getAsSingle<ObjCIvarDecl>()) {
1815 R.clear();
John McCalldadc5752010-08-24 06:29:42 +00001816 ExprResult E(LookupInObjCMethod(R, S, Ivar->getIdentifier()));
Fariborz Jahanian44653702011-09-23 23:11:38 +00001817 // In a hopelessly buggy code, Objective-C instance variable
1818 // lookup fails and no expression will be built to reference it.
1819 if (!E.isInvalid() && !E.get())
1820 return ExprError();
Benjamin Kramer62b95d82012-08-23 21:35:17 +00001821 return E;
Douglas Gregor35b0bac2010-01-03 18:01:57 +00001822 }
Steve Naroff92e30f82007-04-02 22:35:25 +00001823 }
Chris Lattner17ed4872006-11-20 04:58:19 +00001824 }
Mike Stump11289f42009-09-09 15:08:12 +00001825
John McCalle66edc12009-11-24 19:00:30 +00001826 // This is guaranteed from this point on.
1827 assert(!R.empty() || ADL);
1828
John McCall2d74de92009-12-01 22:10:20 +00001829 // Check whether this might be a C++ implicit instance member access.
John McCall24d18942010-08-24 22:52:39 +00001830 // C++ [class.mfct.non-static]p3:
1831 // When an id-expression that is not part of a class member access
1832 // syntax and not used to form a pointer to member is used in the
1833 // body of a non-static member function of class X, if name lookup
1834 // resolves the name in the id-expression to a non-static non-type
1835 // member of some class C, the id-expression is transformed into a
1836 // class member access expression using (*this) as the
1837 // postfix-expression to the left of the . operator.
John McCall8d08b9b2010-08-27 09:08:28 +00001838 //
1839 // But we don't actually need to do this for '&' operands if R
1840 // resolved to a function or overloaded function set, because the
1841 // expression is ill-formed if it actually works out to be a
1842 // non-static member function:
1843 //
1844 // C++ [expr.ref]p4:
1845 // Otherwise, if E1.E2 refers to a non-static member function. . .
1846 // [t]he expression can be used only as the left-hand operand of a
1847 // member function call.
1848 //
1849 // There are other safeguards against such uses, but it's important
1850 // to get this right here so that we don't end up making a
1851 // spuriously dependent expression if we're inside a dependent
1852 // instance method.
John McCall57500772009-12-16 12:17:52 +00001853 if (!R.empty() && (*R.begin())->isCXXClassMember()) {
John McCall8d08b9b2010-08-27 09:08:28 +00001854 bool MightBeImplicitMember;
Richard Trieuba63ce62011-09-09 01:45:06 +00001855 if (!IsAddressOfOperand)
John McCall8d08b9b2010-08-27 09:08:28 +00001856 MightBeImplicitMember = true;
1857 else if (!SS.isEmpty())
1858 MightBeImplicitMember = false;
1859 else if (R.isOverloadedResult())
1860 MightBeImplicitMember = false;
Douglas Gregor1262b062010-08-30 16:00:47 +00001861 else if (R.isUnresolvableResult())
1862 MightBeImplicitMember = true;
John McCall8d08b9b2010-08-27 09:08:28 +00001863 else
Francois Pichet783dd6e2010-11-21 06:08:52 +00001864 MightBeImplicitMember = isa<FieldDecl>(R.getFoundDecl()) ||
1865 isa<IndirectFieldDecl>(R.getFoundDecl());
John McCall8d08b9b2010-08-27 09:08:28 +00001866
1867 if (MightBeImplicitMember)
Abramo Bagnara7945c982012-01-27 09:46:47 +00001868 return BuildPossibleImplicitMemberExpr(SS, TemplateKWLoc,
1869 R, TemplateArgs);
John McCallb53bbd42009-11-22 01:44:31 +00001870 }
1871
Abramo Bagnara65f7c3d2012-02-06 14:31:00 +00001872 if (TemplateArgs || TemplateKWLoc.isValid())
1873 return BuildTemplateIdExpr(SS, TemplateKWLoc, R, ADL, TemplateArgs);
John McCallb53bbd42009-11-22 01:44:31 +00001874
John McCalle66edc12009-11-24 19:00:30 +00001875 return BuildDeclarationNameExpr(SS, R, ADL);
1876}
1877
John McCall10eae182009-11-30 22:42:35 +00001878/// BuildQualifiedDeclarationNameExpr - Build a C++ qualified
1879/// declaration name, generally during template instantiation.
1880/// There's a large number of things which don't need to be done along
1881/// this path.
John McCalldadc5752010-08-24 06:29:42 +00001882ExprResult
Jeffrey Yasskinc76498d2010-04-08 16:38:48 +00001883Sema::BuildQualifiedDeclarationNameExpr(CXXScopeSpec &SS,
Abramo Bagnarad6d2f182010-08-11 22:01:17 +00001884 const DeclarationNameInfo &NameInfo) {
John McCalle66edc12009-11-24 19:00:30 +00001885 DeclContext *DC;
Douglas Gregora02bb342010-04-28 07:04:26 +00001886 if (!(DC = computeDeclContext(SS, false)) || DC->isDependentContext())
Abramo Bagnara65f7c3d2012-02-06 14:31:00 +00001887 return BuildDependentDeclRefExpr(SS, /*TemplateKWLoc=*/SourceLocation(),
1888 NameInfo, /*TemplateArgs=*/0);
John McCalle66edc12009-11-24 19:00:30 +00001889
John McCall0b66eb32010-05-01 00:40:08 +00001890 if (RequireCompleteDeclContext(SS, DC))
Douglas Gregora02bb342010-04-28 07:04:26 +00001891 return ExprError();
1892
Abramo Bagnarad6d2f182010-08-11 22:01:17 +00001893 LookupResult R(*this, NameInfo, LookupOrdinaryName);
John McCalle66edc12009-11-24 19:00:30 +00001894 LookupQualifiedName(R, DC);
1895
1896 if (R.isAmbiguous())
1897 return ExprError();
1898
1899 if (R.empty()) {
Abramo Bagnarad6d2f182010-08-11 22:01:17 +00001900 Diag(NameInfo.getLoc(), diag::err_no_member)
1901 << NameInfo.getName() << DC << SS.getRange();
John McCalle66edc12009-11-24 19:00:30 +00001902 return ExprError();
1903 }
1904
1905 return BuildDeclarationNameExpr(SS, R, /*ADL*/ false);
1906}
1907
1908/// LookupInObjCMethod - The parser has read a name in, and Sema has
1909/// detected that we're currently inside an ObjC method. Perform some
1910/// additional lookup.
1911///
1912/// Ideally, most of this would be done by lookup, but there's
1913/// actually quite a lot of extra work involved.
1914///
1915/// Returns a null sentinel to indicate trivial success.
John McCalldadc5752010-08-24 06:29:42 +00001916ExprResult
John McCalle66edc12009-11-24 19:00:30 +00001917Sema::LookupInObjCMethod(LookupResult &Lookup, Scope *S,
Chris Lattnera36ec422010-04-11 08:28:14 +00001918 IdentifierInfo *II, bool AllowBuiltinCreation) {
John McCalle66edc12009-11-24 19:00:30 +00001919 SourceLocation Loc = Lookup.getNameLoc();
Chris Lattner87313662010-04-12 05:10:17 +00001920 ObjCMethodDecl *CurMethod = getCurMethodDecl();
Alexis Huntc46382e2010-04-28 23:02:27 +00001921
John McCalle66edc12009-11-24 19:00:30 +00001922 // There are two cases to handle here. 1) scoped lookup could have failed,
1923 // in which case we should look for an ivar. 2) scoped lookup could have
1924 // found a decl, but that decl is outside the current instance method (i.e.
1925 // a global variable). In these two cases, we do a lookup for an ivar with
1926 // this name, if the lookup sucedes, we replace it our current decl.
1927
1928 // If we're in a class method, we don't normally want to look for
1929 // ivars. But if we don't find anything else, and there's an
1930 // ivar, that's an error.
Chris Lattner87313662010-04-12 05:10:17 +00001931 bool IsClassMethod = CurMethod->isClassMethod();
John McCalle66edc12009-11-24 19:00:30 +00001932
1933 bool LookForIvars;
1934 if (Lookup.empty())
1935 LookForIvars = true;
1936 else if (IsClassMethod)
1937 LookForIvars = false;
1938 else
1939 LookForIvars = (Lookup.isSingleResult() &&
1940 Lookup.getFoundDecl()->isDefinedOutsideFunctionOrMethod());
Fariborz Jahanian45878032010-02-09 19:31:38 +00001941 ObjCInterfaceDecl *IFace = 0;
John McCalle66edc12009-11-24 19:00:30 +00001942 if (LookForIvars) {
Chris Lattner87313662010-04-12 05:10:17 +00001943 IFace = CurMethod->getClassInterface();
John McCalle66edc12009-11-24 19:00:30 +00001944 ObjCInterfaceDecl *ClassDeclared;
Argyrios Kyrtzidis4e8b1362011-10-19 02:25:16 +00001945 ObjCIvarDecl *IV = 0;
1946 if (IFace && (IV = IFace->lookupInstanceVariable(II, ClassDeclared))) {
John McCalle66edc12009-11-24 19:00:30 +00001947 // Diagnose using an ivar in a class method.
1948 if (IsClassMethod)
1949 return ExprError(Diag(Loc, diag::error_ivar_use_in_class_method)
1950 << IV->getDeclName());
1951
1952 // If we're referencing an invalid decl, just return this as a silent
1953 // error node. The error diagnostic was already emitted on the decl.
1954 if (IV->isInvalidDecl())
1955 return ExprError();
1956
1957 // Check if referencing a field with __attribute__((deprecated)).
1958 if (DiagnoseUseOfDecl(IV, Loc))
1959 return ExprError();
1960
1961 // Diagnose the use of an ivar outside of the declaring class.
1962 if (IV->getAccessControl() == ObjCIvarDecl::Private &&
Fariborz Jahaniand6cb4a82012-03-07 00:58:41 +00001963 !declaresSameEntity(ClassDeclared, IFace) &&
David Blaikiebbafb8a2012-03-11 07:00:24 +00001964 !getLangOpts().DebuggerSupport)
John McCalle66edc12009-11-24 19:00:30 +00001965 Diag(Loc, diag::error_private_ivar_access) << IV->getDeclName();
1966
1967 // FIXME: This should use a new expr for a direct reference, don't
1968 // turn this into Self->ivar, just return a BareIVarExpr or something.
1969 IdentifierInfo &II = Context.Idents.get("self");
1970 UnqualifiedId SelfName;
Kovarththanan Rajaratnamba2c6522010-03-13 10:17:05 +00001971 SelfName.setIdentifier(&II, SourceLocation());
Fariborz Jahanian7f4427f2011-07-12 17:16:56 +00001972 SelfName.setKind(UnqualifiedId::IK_ImplicitSelfParam);
John McCalle66edc12009-11-24 19:00:30 +00001973 CXXScopeSpec SelfScopeSpec;
Abramo Bagnara7945c982012-01-27 09:46:47 +00001974 SourceLocation TemplateKWLoc;
1975 ExprResult SelfExpr = ActOnIdExpression(S, SelfScopeSpec, TemplateKWLoc,
Douglas Gregora1ed39b2010-09-22 16:33:13 +00001976 SelfName, false, false);
1977 if (SelfExpr.isInvalid())
1978 return ExprError();
1979
John Wiegley01296292011-04-08 18:41:53 +00001980 SelfExpr = DefaultLvalueConversion(SelfExpr.take());
1981 if (SelfExpr.isInvalid())
1982 return ExprError();
John McCall27584242010-12-06 20:48:59 +00001983
Eli Friedmanfa0df832012-02-02 03:46:19 +00001984 MarkAnyDeclReferenced(Loc, IV);
Fariborz Jahaniana5063a62012-08-08 16:41:04 +00001985
1986 ObjCMethodFamily MF = CurMethod->getMethodFamily();
1987 if (MF != OMF_init && MF != OMF_dealloc && MF != OMF_finalize)
1988 Diag(Loc, diag::warn_direct_ivar_access) << IV->getDeclName();
John McCalle66edc12009-11-24 19:00:30 +00001989 return Owned(new (Context)
1990 ObjCIvarRefExpr(IV, IV->getType(), Loc,
John Wiegley01296292011-04-08 18:41:53 +00001991 SelfExpr.take(), true, true));
John McCalle66edc12009-11-24 19:00:30 +00001992 }
Chris Lattner87313662010-04-12 05:10:17 +00001993 } else if (CurMethod->isInstanceMethod()) {
John McCalle66edc12009-11-24 19:00:30 +00001994 // We should warn if a local variable hides an ivar.
Fariborz Jahanian557fc9a2011-11-08 22:51:27 +00001995 if (ObjCInterfaceDecl *IFace = CurMethod->getClassInterface()) {
1996 ObjCInterfaceDecl *ClassDeclared;
1997 if (ObjCIvarDecl *IV = IFace->lookupInstanceVariable(II, ClassDeclared)) {
1998 if (IV->getAccessControl() != ObjCIvarDecl::Private ||
Douglas Gregor0b144e12011-12-15 00:29:59 +00001999 declaresSameEntity(IFace, ClassDeclared))
Fariborz Jahanian557fc9a2011-11-08 22:51:27 +00002000 Diag(Loc, diag::warn_ivar_use_hidden) << IV->getDeclName();
2001 }
John McCalle66edc12009-11-24 19:00:30 +00002002 }
Fariborz Jahanian028b9e12011-12-20 22:21:08 +00002003 } else if (Lookup.isSingleResult() &&
2004 Lookup.getFoundDecl()->isDefinedOutsideFunctionOrMethod()) {
2005 // If accessing a stand-alone ivar in a class method, this is an error.
2006 if (const ObjCIvarDecl *IV = dyn_cast<ObjCIvarDecl>(Lookup.getFoundDecl()))
2007 return ExprError(Diag(Loc, diag::error_ivar_use_in_class_method)
2008 << IV->getDeclName());
John McCalle66edc12009-11-24 19:00:30 +00002009 }
2010
Fariborz Jahanian6fada5b2010-01-12 23:58:59 +00002011 if (Lookup.empty() && II && AllowBuiltinCreation) {
2012 // FIXME. Consolidate this with similar code in LookupName.
2013 if (unsigned BuiltinID = II->getBuiltinID()) {
David Blaikiebbafb8a2012-03-11 07:00:24 +00002014 if (!(getLangOpts().CPlusPlus &&
Fariborz Jahanian6fada5b2010-01-12 23:58:59 +00002015 Context.BuiltinInfo.isPredefinedLibFunction(BuiltinID))) {
2016 NamedDecl *D = LazilyCreateBuiltin((IdentifierInfo *)II, BuiltinID,
2017 S, Lookup.isForRedeclaration(),
2018 Lookup.getNameLoc());
2019 if (D) Lookup.addDecl(D);
2020 }
2021 }
2022 }
John McCalle66edc12009-11-24 19:00:30 +00002023 // Sentinel value saying that we didn't do anything special.
2024 return Owned((Expr*) 0);
Douglas Gregor3256d042009-06-30 15:47:41 +00002025}
John McCalld14a8642009-11-21 08:51:07 +00002026
John McCall16df1e52010-03-30 21:47:33 +00002027/// \brief Cast a base object to a member's actual type.
2028///
2029/// Logically this happens in three phases:
2030///
2031/// * First we cast from the base type to the naming class.
2032/// The naming class is the class into which we were looking
2033/// when we found the member; it's the qualifier type if a
2034/// qualifier was provided, and otherwise it's the base type.
2035///
2036/// * Next we cast from the naming class to the declaring class.
2037/// If the member we found was brought into a class's scope by
2038/// a using declaration, this is that class; otherwise it's
2039/// the class declaring the member.
2040///
2041/// * Finally we cast from the declaring class to the "true"
2042/// declaring class of the member. This conversion does not
2043/// obey access control.
John Wiegley01296292011-04-08 18:41:53 +00002044ExprResult
2045Sema::PerformObjectMemberConversion(Expr *From,
Douglas Gregorcc3f3252010-03-03 23:55:11 +00002046 NestedNameSpecifier *Qualifier,
John McCall16df1e52010-03-30 21:47:33 +00002047 NamedDecl *FoundDecl,
Douglas Gregorcc3f3252010-03-03 23:55:11 +00002048 NamedDecl *Member) {
2049 CXXRecordDecl *RD = dyn_cast<CXXRecordDecl>(Member->getDeclContext());
2050 if (!RD)
John Wiegley01296292011-04-08 18:41:53 +00002051 return Owned(From);
Kovarththanan Rajaratnamba2c6522010-03-13 10:17:05 +00002052
Douglas Gregorcc3f3252010-03-03 23:55:11 +00002053 QualType DestRecordType;
2054 QualType DestType;
2055 QualType FromRecordType;
2056 QualType FromType = From->getType();
2057 bool PointerConversions = false;
2058 if (isa<FieldDecl>(Member)) {
2059 DestRecordType = Context.getCanonicalType(Context.getTypeDeclType(RD));
Kovarththanan Rajaratnamba2c6522010-03-13 10:17:05 +00002060
Douglas Gregorcc3f3252010-03-03 23:55:11 +00002061 if (FromType->getAs<PointerType>()) {
2062 DestType = Context.getPointerType(DestRecordType);
2063 FromRecordType = FromType->getPointeeType();
2064 PointerConversions = true;
2065 } else {
2066 DestType = DestRecordType;
2067 FromRecordType = FromType;
Fariborz Jahanianbb67b822009-07-29 18:40:24 +00002068 }
Douglas Gregorcc3f3252010-03-03 23:55:11 +00002069 } else if (CXXMethodDecl *Method = dyn_cast<CXXMethodDecl>(Member)) {
2070 if (Method->isStatic())
John Wiegley01296292011-04-08 18:41:53 +00002071 return Owned(From);
Kovarththanan Rajaratnamba2c6522010-03-13 10:17:05 +00002072
Douglas Gregorcc3f3252010-03-03 23:55:11 +00002073 DestType = Method->getThisType(Context);
2074 DestRecordType = DestType->getPointeeType();
Kovarththanan Rajaratnamba2c6522010-03-13 10:17:05 +00002075
Douglas Gregorcc3f3252010-03-03 23:55:11 +00002076 if (FromType->getAs<PointerType>()) {
2077 FromRecordType = FromType->getPointeeType();
2078 PointerConversions = true;
2079 } else {
2080 FromRecordType = FromType;
2081 DestType = DestRecordType;
2082 }
2083 } else {
2084 // No conversion necessary.
John Wiegley01296292011-04-08 18:41:53 +00002085 return Owned(From);
Douglas Gregorcc3f3252010-03-03 23:55:11 +00002086 }
Kovarththanan Rajaratnamba2c6522010-03-13 10:17:05 +00002087
Douglas Gregorcc3f3252010-03-03 23:55:11 +00002088 if (DestType->isDependentType() || FromType->isDependentType())
John Wiegley01296292011-04-08 18:41:53 +00002089 return Owned(From);
Kovarththanan Rajaratnamba2c6522010-03-13 10:17:05 +00002090
Douglas Gregorcc3f3252010-03-03 23:55:11 +00002091 // If the unqualified types are the same, no conversion is necessary.
2092 if (Context.hasSameUnqualifiedType(FromRecordType, DestRecordType))
John Wiegley01296292011-04-08 18:41:53 +00002093 return Owned(From);
Kovarththanan Rajaratnamba2c6522010-03-13 10:17:05 +00002094
John McCall16df1e52010-03-30 21:47:33 +00002095 SourceRange FromRange = From->getSourceRange();
2096 SourceLocation FromLoc = FromRange.getBegin();
2097
Eli Friedmanbe4b3632011-09-27 21:58:52 +00002098 ExprValueKind VK = From->getValueKind();
Sebastian Redlc57d34b2010-07-20 04:20:21 +00002099
Douglas Gregorcc3f3252010-03-03 23:55:11 +00002100 // C++ [class.member.lookup]p8:
Kovarththanan Rajaratnamba2c6522010-03-13 10:17:05 +00002101 // [...] Ambiguities can often be resolved by qualifying a name with its
Douglas Gregorcc3f3252010-03-03 23:55:11 +00002102 // class name.
2103 //
2104 // If the member was a qualified name and the qualified referred to a
2105 // specific base subobject type, we'll cast to that intermediate type
2106 // first and then to the object in which the member is declared. That allows
2107 // one to resolve ambiguities in, e.g., a diamond-shaped hierarchy such as:
2108 //
2109 // class Base { public: int x; };
2110 // class Derived1 : public Base { };
2111 // class Derived2 : public Base { };
2112 // class VeryDerived : public Derived1, public Derived2 { void f(); };
2113 //
2114 // void VeryDerived::f() {
2115 // x = 17; // error: ambiguous base subobjects
2116 // Derived1::x = 17; // okay, pick the Base subobject of Derived1
2117 // }
Douglas Gregorcc3f3252010-03-03 23:55:11 +00002118 if (Qualifier) {
John McCall16df1e52010-03-30 21:47:33 +00002119 QualType QType = QualType(Qualifier->getAsType(), 0);
2120 assert(!QType.isNull() && "lookup done with dependent qualifier?");
2121 assert(QType->isRecordType() && "lookup done with non-record type");
2122
2123 QualType QRecordType = QualType(QType->getAs<RecordType>(), 0);
2124
2125 // In C++98, the qualifier type doesn't actually have to be a base
2126 // type of the object type, in which case we just ignore it.
2127 // Otherwise build the appropriate casts.
2128 if (IsDerivedFrom(FromRecordType, QRecordType)) {
John McCallcf142162010-08-07 06:22:56 +00002129 CXXCastPath BasePath;
John McCall16df1e52010-03-30 21:47:33 +00002130 if (CheckDerivedToBaseConversion(FromRecordType, QRecordType,
Anders Carlssonb78feca2010-04-24 19:22:20 +00002131 FromLoc, FromRange, &BasePath))
John Wiegley01296292011-04-08 18:41:53 +00002132 return ExprError();
John McCall16df1e52010-03-30 21:47:33 +00002133
Douglas Gregorcc3f3252010-03-03 23:55:11 +00002134 if (PointerConversions)
John McCall16df1e52010-03-30 21:47:33 +00002135 QType = Context.getPointerType(QType);
John Wiegley01296292011-04-08 18:41:53 +00002136 From = ImpCastExprToType(From, QType, CK_UncheckedDerivedToBase,
2137 VK, &BasePath).take();
John McCall16df1e52010-03-30 21:47:33 +00002138
2139 FromType = QType;
2140 FromRecordType = QRecordType;
2141
2142 // If the qualifier type was the same as the destination type,
2143 // we're done.
2144 if (Context.hasSameUnqualifiedType(FromRecordType, DestRecordType))
John Wiegley01296292011-04-08 18:41:53 +00002145 return Owned(From);
Douglas Gregorcc3f3252010-03-03 23:55:11 +00002146 }
2147 }
Kovarththanan Rajaratnamba2c6522010-03-13 10:17:05 +00002148
John McCall16df1e52010-03-30 21:47:33 +00002149 bool IgnoreAccess = false;
Douglas Gregorcc3f3252010-03-03 23:55:11 +00002150
John McCall16df1e52010-03-30 21:47:33 +00002151 // If we actually found the member through a using declaration, cast
2152 // down to the using declaration's type.
2153 //
2154 // Pointer equality is fine here because only one declaration of a
2155 // class ever has member declarations.
2156 if (FoundDecl->getDeclContext() != Member->getDeclContext()) {
2157 assert(isa<UsingShadowDecl>(FoundDecl));
2158 QualType URecordType = Context.getTypeDeclType(
2159 cast<CXXRecordDecl>(FoundDecl->getDeclContext()));
2160
2161 // We only need to do this if the naming-class to declaring-class
2162 // conversion is non-trivial.
2163 if (!Context.hasSameUnqualifiedType(FromRecordType, URecordType)) {
2164 assert(IsDerivedFrom(FromRecordType, URecordType));
John McCallcf142162010-08-07 06:22:56 +00002165 CXXCastPath BasePath;
John McCall16df1e52010-03-30 21:47:33 +00002166 if (CheckDerivedToBaseConversion(FromRecordType, URecordType,
Anders Carlssonb78feca2010-04-24 19:22:20 +00002167 FromLoc, FromRange, &BasePath))
John Wiegley01296292011-04-08 18:41:53 +00002168 return ExprError();
Alexis Huntc46382e2010-04-28 23:02:27 +00002169
John McCall16df1e52010-03-30 21:47:33 +00002170 QualType UType = URecordType;
2171 if (PointerConversions)
2172 UType = Context.getPointerType(UType);
John Wiegley01296292011-04-08 18:41:53 +00002173 From = ImpCastExprToType(From, UType, CK_UncheckedDerivedToBase,
2174 VK, &BasePath).take();
John McCall16df1e52010-03-30 21:47:33 +00002175 FromType = UType;
2176 FromRecordType = URecordType;
2177 }
2178
2179 // We don't do access control for the conversion from the
2180 // declaring class to the true declaring class.
2181 IgnoreAccess = true;
Douglas Gregorcc3f3252010-03-03 23:55:11 +00002182 }
Kovarththanan Rajaratnamba2c6522010-03-13 10:17:05 +00002183
John McCallcf142162010-08-07 06:22:56 +00002184 CXXCastPath BasePath;
Anders Carlssonb78feca2010-04-24 19:22:20 +00002185 if (CheckDerivedToBaseConversion(FromRecordType, DestRecordType,
2186 FromLoc, FromRange, &BasePath,
John McCall16df1e52010-03-30 21:47:33 +00002187 IgnoreAccess))
John Wiegley01296292011-04-08 18:41:53 +00002188 return ExprError();
Kovarththanan Rajaratnamba2c6522010-03-13 10:17:05 +00002189
John Wiegley01296292011-04-08 18:41:53 +00002190 return ImpCastExprToType(From, DestType, CK_UncheckedDerivedToBase,
2191 VK, &BasePath);
Fariborz Jahanianbb67b822009-07-29 18:40:24 +00002192}
Douglas Gregor3256d042009-06-30 15:47:41 +00002193
John McCalle66edc12009-11-24 19:00:30 +00002194bool Sema::UseArgumentDependentLookup(const CXXScopeSpec &SS,
John McCallb53bbd42009-11-22 01:44:31 +00002195 const LookupResult &R,
2196 bool HasTrailingLParen) {
John McCalld14a8642009-11-21 08:51:07 +00002197 // Only when used directly as the postfix-expression of a call.
2198 if (!HasTrailingLParen)
2199 return false;
2200
2201 // Never if a scope specifier was provided.
John McCalle66edc12009-11-24 19:00:30 +00002202 if (SS.isSet())
John McCalld14a8642009-11-21 08:51:07 +00002203 return false;
2204
2205 // Only in C++ or ObjC++.
David Blaikiebbafb8a2012-03-11 07:00:24 +00002206 if (!getLangOpts().CPlusPlus)
John McCalld14a8642009-11-21 08:51:07 +00002207 return false;
2208
2209 // Turn off ADL when we find certain kinds of declarations during
2210 // normal lookup:
2211 for (LookupResult::iterator I = R.begin(), E = R.end(); I != E; ++I) {
2212 NamedDecl *D = *I;
2213
2214 // C++0x [basic.lookup.argdep]p3:
2215 // -- a declaration of a class member
2216 // Since using decls preserve this property, we check this on the
2217 // original decl.
John McCall57500772009-12-16 12:17:52 +00002218 if (D->isCXXClassMember())
John McCalld14a8642009-11-21 08:51:07 +00002219 return false;
2220
2221 // C++0x [basic.lookup.argdep]p3:
2222 // -- a block-scope function declaration that is not a
2223 // using-declaration
2224 // NOTE: we also trigger this for function templates (in fact, we
2225 // don't check the decl type at all, since all other decl types
2226 // turn off ADL anyway).
2227 if (isa<UsingShadowDecl>(D))
2228 D = cast<UsingShadowDecl>(D)->getTargetDecl();
2229 else if (D->getDeclContext()->isFunctionOrMethod())
2230 return false;
2231
2232 // C++0x [basic.lookup.argdep]p3:
2233 // -- a declaration that is neither a function or a function
2234 // template
2235 // And also for builtin functions.
2236 if (isa<FunctionDecl>(D)) {
2237 FunctionDecl *FDecl = cast<FunctionDecl>(D);
2238
2239 // But also builtin functions.
2240 if (FDecl->getBuiltinID() && FDecl->isImplicit())
2241 return false;
2242 } else if (!isa<FunctionTemplateDecl>(D))
2243 return false;
2244 }
2245
2246 return true;
2247}
2248
2249
John McCalld14a8642009-11-21 08:51:07 +00002250/// Diagnoses obvious problems with the use of the given declaration
2251/// as an expression. This is only actually called for lookups that
2252/// were not overloaded, and it doesn't promise that the declaration
2253/// will in fact be used.
2254static bool CheckDeclInExpr(Sema &S, SourceLocation Loc, NamedDecl *D) {
Richard Smithdda56e42011-04-15 14:24:37 +00002255 if (isa<TypedefNameDecl>(D)) {
John McCalld14a8642009-11-21 08:51:07 +00002256 S.Diag(Loc, diag::err_unexpected_typedef) << D->getDeclName();
2257 return true;
2258 }
2259
2260 if (isa<ObjCInterfaceDecl>(D)) {
2261 S.Diag(Loc, diag::err_unexpected_interface) << D->getDeclName();
2262 return true;
2263 }
2264
2265 if (isa<NamespaceDecl>(D)) {
2266 S.Diag(Loc, diag::err_unexpected_namespace) << D->getDeclName();
2267 return true;
2268 }
2269
2270 return false;
2271}
2272
John McCalldadc5752010-08-24 06:29:42 +00002273ExprResult
John McCalle66edc12009-11-24 19:00:30 +00002274Sema::BuildDeclarationNameExpr(const CXXScopeSpec &SS,
John McCallb53bbd42009-11-22 01:44:31 +00002275 LookupResult &R,
2276 bool NeedsADL) {
John McCall3a60c872009-12-08 22:45:53 +00002277 // If this is a single, fully-resolved result and we don't need ADL,
2278 // just build an ordinary singleton decl ref.
Douglas Gregor4b4844f2010-01-29 17:15:43 +00002279 if (!NeedsADL && R.isSingleResult() && !R.getAsSingle<FunctionTemplateDecl>())
Abramo Bagnarad6d2f182010-08-11 22:01:17 +00002280 return BuildDeclarationNameExpr(SS, R.getLookupNameInfo(),
2281 R.getFoundDecl());
John McCalld14a8642009-11-21 08:51:07 +00002282
2283 // We only need to check the declaration if there's exactly one
2284 // result, because in the overloaded case the results can only be
2285 // functions and function templates.
John McCallb53bbd42009-11-22 01:44:31 +00002286 if (R.isSingleResult() &&
2287 CheckDeclInExpr(*this, R.getNameLoc(), R.getFoundDecl()))
John McCalld14a8642009-11-21 08:51:07 +00002288 return ExprError();
2289
John McCall58cc69d2010-01-27 01:50:18 +00002290 // Otherwise, just build an unresolved lookup expression. Suppress
2291 // any lookup-related diagnostics; we'll hash these out later, when
2292 // we've picked a target.
2293 R.suppressDiagnostics();
2294
John McCalld14a8642009-11-21 08:51:07 +00002295 UnresolvedLookupExpr *ULE
Douglas Gregora6e053e2010-12-15 01:34:56 +00002296 = UnresolvedLookupExpr::Create(Context, R.getNamingClass(),
Douglas Gregor0da1d432011-02-28 20:01:57 +00002297 SS.getWithLocInContext(Context),
2298 R.getLookupNameInfo(),
Douglas Gregor30a4f4c2010-05-23 18:57:34 +00002299 NeedsADL, R.isOverloadedResult(),
2300 R.begin(), R.end());
John McCalld14a8642009-11-21 08:51:07 +00002301
2302 return Owned(ULE);
2303}
Kovarththanan Rajaratnamba2c6522010-03-13 10:17:05 +00002304
John McCalld14a8642009-11-21 08:51:07 +00002305/// \brief Complete semantic analysis for a reference to the given declaration.
John McCalldadc5752010-08-24 06:29:42 +00002306ExprResult
John McCalle66edc12009-11-24 19:00:30 +00002307Sema::BuildDeclarationNameExpr(const CXXScopeSpec &SS,
Abramo Bagnarad6d2f182010-08-11 22:01:17 +00002308 const DeclarationNameInfo &NameInfo,
2309 NamedDecl *D) {
John McCalld14a8642009-11-21 08:51:07 +00002310 assert(D && "Cannot refer to a NULL declaration");
John McCall283b9012009-11-22 00:44:51 +00002311 assert(!isa<FunctionTemplateDecl>(D) &&
2312 "Cannot refer unambiguously to a function template");
John McCalld14a8642009-11-21 08:51:07 +00002313
Abramo Bagnarad6d2f182010-08-11 22:01:17 +00002314 SourceLocation Loc = NameInfo.getLoc();
John McCalld14a8642009-11-21 08:51:07 +00002315 if (CheckDeclInExpr(*this, Loc, D))
2316 return ExprError();
Steve Narofff1e53692007-03-23 22:27:02 +00002317
Douglas Gregore7488b92009-12-01 16:58:18 +00002318 if (TemplateDecl *Template = dyn_cast<TemplateDecl>(D)) {
2319 // Specifically diagnose references to class templates that are missing
2320 // a template argument list.
2321 Diag(Loc, diag::err_template_decl_ref)
2322 << Template << SS.getRange();
2323 Diag(Template->getLocation(), diag::note_template_decl_here);
2324 return ExprError();
2325 }
2326
2327 // Make sure that we're referring to a value.
2328 ValueDecl *VD = dyn_cast<ValueDecl>(D);
2329 if (!VD) {
Kovarththanan Rajaratnamba2c6522010-03-13 10:17:05 +00002330 Diag(Loc, diag::err_ref_non_value)
Douglas Gregore7488b92009-12-01 16:58:18 +00002331 << D << SS.getRange();
John McCallb48971d2009-12-18 18:35:10 +00002332 Diag(D->getLocation(), diag::note_declared_at);
Douglas Gregore7488b92009-12-01 16:58:18 +00002333 return ExprError();
2334 }
Sebastian Redlffbcf962009-01-18 18:53:16 +00002335
Douglas Gregor171c45a2009-02-18 21:56:37 +00002336 // Check whether this declaration can be used. Note that we suppress
2337 // this check when we're going to perform argument-dependent lookup
2338 // on this function name, because this might not be the function
2339 // that overload resolution actually selects.
John McCalld14a8642009-11-21 08:51:07 +00002340 if (DiagnoseUseOfDecl(VD, Loc))
Douglas Gregor171c45a2009-02-18 21:56:37 +00002341 return ExprError();
2342
Steve Naroff8de9c3a2008-09-05 22:11:13 +00002343 // Only create DeclRefExpr's for valid Decl's.
2344 if (VD->isInvalidDecl())
Sebastian Redlffbcf962009-01-18 18:53:16 +00002345 return ExprError();
2346
John McCallf3a88602011-02-03 08:15:49 +00002347 // Handle members of anonymous structs and unions. If we got here,
2348 // and the reference is to a class member indirect field, then this
2349 // must be the subject of a pointer-to-member expression.
2350 if (IndirectFieldDecl *indirectField = dyn_cast<IndirectFieldDecl>(VD))
2351 if (!indirectField->isCXXClassMember())
2352 return BuildAnonymousStructUnionMemberReference(SS, NameInfo.getLoc(),
2353 indirectField);
Francois Pichet783dd6e2010-11-21 06:08:52 +00002354
Eli Friedman9bb33f52012-02-03 02:04:35 +00002355 {
John McCallf4cd4f92011-02-09 01:13:10 +00002356 QualType type = VD->getType();
Daniel Dunbar7c2dc362011-02-10 18:29:28 +00002357 ExprValueKind valueKind = VK_RValue;
John McCallf4cd4f92011-02-09 01:13:10 +00002358
2359 switch (D->getKind()) {
2360 // Ignore all the non-ValueDecl kinds.
2361#define ABSTRACT_DECL(kind)
2362#define VALUE(type, base)
2363#define DECL(type, base) \
2364 case Decl::type:
2365#include "clang/AST/DeclNodes.inc"
2366 llvm_unreachable("invalid value decl kind");
John McCallf4cd4f92011-02-09 01:13:10 +00002367
2368 // These shouldn't make it here.
2369 case Decl::ObjCAtDefsField:
2370 case Decl::ObjCIvar:
2371 llvm_unreachable("forming non-member reference to ivar?");
John McCallf4cd4f92011-02-09 01:13:10 +00002372
2373 // Enum constants are always r-values and never references.
2374 // Unresolved using declarations are dependent.
2375 case Decl::EnumConstant:
2376 case Decl::UnresolvedUsingValue:
2377 valueKind = VK_RValue;
2378 break;
2379
2380 // Fields and indirect fields that got here must be for
2381 // pointer-to-member expressions; we just call them l-values for
2382 // internal consistency, because this subexpression doesn't really
2383 // exist in the high-level semantics.
2384 case Decl::Field:
2385 case Decl::IndirectField:
David Blaikiebbafb8a2012-03-11 07:00:24 +00002386 assert(getLangOpts().CPlusPlus &&
John McCallf4cd4f92011-02-09 01:13:10 +00002387 "building reference to field in C?");
2388
2389 // These can't have reference type in well-formed programs, but
2390 // for internal consistency we do this anyway.
2391 type = type.getNonReferenceType();
2392 valueKind = VK_LValue;
2393 break;
2394
2395 // Non-type template parameters are either l-values or r-values
2396 // depending on the type.
2397 case Decl::NonTypeTemplateParm: {
2398 if (const ReferenceType *reftype = type->getAs<ReferenceType>()) {
2399 type = reftype->getPointeeType();
2400 valueKind = VK_LValue; // even if the parameter is an r-value reference
2401 break;
2402 }
2403
2404 // For non-references, we need to strip qualifiers just in case
2405 // the template parameter was declared as 'const int' or whatever.
2406 valueKind = VK_RValue;
2407 type = type.getUnqualifiedType();
2408 break;
2409 }
2410
2411 case Decl::Var:
2412 // In C, "extern void blah;" is valid and is an r-value.
David Blaikiebbafb8a2012-03-11 07:00:24 +00002413 if (!getLangOpts().CPlusPlus &&
John McCallf4cd4f92011-02-09 01:13:10 +00002414 !type.hasQualifiers() &&
2415 type->isVoidType()) {
2416 valueKind = VK_RValue;
2417 break;
2418 }
2419 // fallthrough
2420
2421 case Decl::ImplicitParam:
Douglas Gregor812d8f62012-02-18 05:51:20 +00002422 case Decl::ParmVar: {
John McCallf4cd4f92011-02-09 01:13:10 +00002423 // These are always l-values.
2424 valueKind = VK_LValue;
2425 type = type.getNonReferenceType();
Eli Friedman9bb33f52012-02-03 02:04:35 +00002426
Douglas Gregor812d8f62012-02-18 05:51:20 +00002427 // FIXME: Does the addition of const really only apply in
2428 // potentially-evaluated contexts? Since the variable isn't actually
2429 // captured in an unevaluated context, it seems that the answer is no.
David Blaikie131fcb42012-08-06 22:47:24 +00002430 if (!isUnevaluatedContext()) {
Douglas Gregor812d8f62012-02-18 05:51:20 +00002431 QualType CapturedType = getCapturedDeclRefType(cast<VarDecl>(VD), Loc);
2432 if (!CapturedType.isNull())
2433 type = CapturedType;
2434 }
2435
John McCallf4cd4f92011-02-09 01:13:10 +00002436 break;
Douglas Gregor812d8f62012-02-18 05:51:20 +00002437 }
2438
John McCallf4cd4f92011-02-09 01:13:10 +00002439 case Decl::Function: {
Eli Friedman34866c72012-08-31 00:14:07 +00002440 if (unsigned BID = cast<FunctionDecl>(VD)->getBuiltinID()) {
2441 if (!Context.BuiltinInfo.isPredefinedLibFunction(BID)) {
2442 type = Context.BuiltinFnTy;
2443 valueKind = VK_RValue;
2444 break;
2445 }
2446 }
2447
John McCall2979fe02011-04-12 00:42:48 +00002448 const FunctionType *fty = type->castAs<FunctionType>();
2449
2450 // If we're referring to a function with an __unknown_anytype
2451 // result type, make the entire expression __unknown_anytype.
2452 if (fty->getResultType() == Context.UnknownAnyTy) {
2453 type = Context.UnknownAnyTy;
2454 valueKind = VK_RValue;
2455 break;
2456 }
2457
John McCallf4cd4f92011-02-09 01:13:10 +00002458 // Functions are l-values in C++.
David Blaikiebbafb8a2012-03-11 07:00:24 +00002459 if (getLangOpts().CPlusPlus) {
John McCallf4cd4f92011-02-09 01:13:10 +00002460 valueKind = VK_LValue;
2461 break;
2462 }
2463
2464 // C99 DR 316 says that, if a function type comes from a
2465 // function definition (without a prototype), that type is only
2466 // used for checking compatibility. Therefore, when referencing
2467 // the function, we pretend that we don't have the full function
2468 // type.
John McCall2979fe02011-04-12 00:42:48 +00002469 if (!cast<FunctionDecl>(VD)->hasPrototype() &&
2470 isa<FunctionProtoType>(fty))
2471 type = Context.getFunctionNoProtoType(fty->getResultType(),
2472 fty->getExtInfo());
John McCallf4cd4f92011-02-09 01:13:10 +00002473
2474 // Functions are r-values in C.
2475 valueKind = VK_RValue;
2476 break;
2477 }
2478
2479 case Decl::CXXMethod:
John McCall2979fe02011-04-12 00:42:48 +00002480 // If we're referring to a method with an __unknown_anytype
2481 // result type, make the entire expression __unknown_anytype.
2482 // This should only be possible with a type written directly.
Richard Trieucfc491d2011-08-02 04:35:43 +00002483 if (const FunctionProtoType *proto
2484 = dyn_cast<FunctionProtoType>(VD->getType()))
John McCall2979fe02011-04-12 00:42:48 +00002485 if (proto->getResultType() == Context.UnknownAnyTy) {
2486 type = Context.UnknownAnyTy;
2487 valueKind = VK_RValue;
2488 break;
2489 }
2490
John McCallf4cd4f92011-02-09 01:13:10 +00002491 // C++ methods are l-values if static, r-values if non-static.
2492 if (cast<CXXMethodDecl>(VD)->isStatic()) {
2493 valueKind = VK_LValue;
2494 break;
2495 }
2496 // fallthrough
2497
2498 case Decl::CXXConversion:
2499 case Decl::CXXDestructor:
2500 case Decl::CXXConstructor:
2501 valueKind = VK_RValue;
2502 break;
2503 }
2504
2505 return BuildDeclRefExpr(VD, type, valueKind, NameInfo, &SS);
2506 }
Chris Lattner17ed4872006-11-20 04:58:19 +00002507}
Chris Lattnere168f762006-11-10 05:29:30 +00002508
John McCall2979fe02011-04-12 00:42:48 +00002509ExprResult Sema::ActOnPredefinedExpr(SourceLocation Loc, tok::TokenKind Kind) {
Chris Lattner6307f192008-08-10 01:53:14 +00002510 PredefinedExpr::IdentType IT;
Sebastian Redlffbcf962009-01-18 18:53:16 +00002511
Chris Lattnere168f762006-11-10 05:29:30 +00002512 switch (Kind) {
David Blaikie83d382b2011-09-23 05:06:16 +00002513 default: llvm_unreachable("Unknown simple primary expr!");
Chris Lattner6307f192008-08-10 01:53:14 +00002514 case tok::kw___func__: IT = PredefinedExpr::Func; break; // [C99 6.4.2.2]
2515 case tok::kw___FUNCTION__: IT = PredefinedExpr::Function; break;
Nico Weber3a691a32012-06-23 02:07:59 +00002516 case tok::kw_L__FUNCTION__: IT = PredefinedExpr::LFunction; break;
Chris Lattner6307f192008-08-10 01:53:14 +00002517 case tok::kw___PRETTY_FUNCTION__: IT = PredefinedExpr::PrettyFunction; break;
Chris Lattnere168f762006-11-10 05:29:30 +00002518 }
Chris Lattner317e6ba2008-01-12 18:39:25 +00002519
Chris Lattnera81a0272008-01-12 08:14:25 +00002520 // Pre-defined identifiers are of type char[x], where x is the length of the
2521 // string.
Mike Stump11289f42009-09-09 15:08:12 +00002522
Anders Carlsson2fb08242009-09-08 18:24:21 +00002523 Decl *currentDecl = getCurFunctionOrMethodDecl();
Fariborz Jahanian94627442010-07-23 21:53:24 +00002524 if (!currentDecl && getCurBlock())
2525 currentDecl = getCurBlock()->TheDecl;
Anders Carlsson2fb08242009-09-08 18:24:21 +00002526 if (!currentDecl) {
Chris Lattnerf45c5ec2008-12-12 05:05:20 +00002527 Diag(Loc, diag::ext_predef_outside_function);
Anders Carlsson2fb08242009-09-08 18:24:21 +00002528 currentDecl = Context.getTranslationUnitDecl();
Chris Lattnerf45c5ec2008-12-12 05:05:20 +00002529 }
Sebastian Redlffbcf962009-01-18 18:53:16 +00002530
Anders Carlsson0b209a82009-09-11 01:22:35 +00002531 QualType ResTy;
2532 if (cast<DeclContext>(currentDecl)->isDependentContext()) {
2533 ResTy = Context.DependentTy;
2534 } else {
Anders Carlsson5bd8d192010-02-11 18:20:28 +00002535 unsigned Length = PredefinedExpr::ComputeName(IT, currentDecl).length();
Sebastian Redlffbcf962009-01-18 18:53:16 +00002536
Anders Carlsson0b209a82009-09-11 01:22:35 +00002537 llvm::APInt LengthI(32, Length + 1);
Nico Weber3052abd2012-06-29 16:39:58 +00002538 if (IT == PredefinedExpr::LFunction)
Nico Weber3a691a32012-06-23 02:07:59 +00002539 ResTy = Context.WCharTy.withConst();
2540 else
2541 ResTy = Context.CharTy.withConst();
Anders Carlsson0b209a82009-09-11 01:22:35 +00002542 ResTy = Context.getConstantArrayType(ResTy, LengthI, ArrayType::Normal, 0);
2543 }
Steve Narofff6009ed2009-01-21 00:14:39 +00002544 return Owned(new (Context) PredefinedExpr(Loc, ResTy, IT));
Chris Lattnere168f762006-11-10 05:29:30 +00002545}
2546
Richard Smithbcc22fc2012-03-09 08:00:36 +00002547ExprResult Sema::ActOnCharacterConstant(const Token &Tok, Scope *UDLScope) {
Dylan Noblesmith2c1dd272012-02-05 02:13:05 +00002548 SmallString<16> CharBuffer;
Douglas Gregordc970f02010-03-16 22:30:13 +00002549 bool Invalid = false;
Chris Lattner0e62c1c2011-07-23 10:55:15 +00002550 StringRef ThisTok = PP.getSpelling(Tok, CharBuffer, &Invalid);
Douglas Gregordc970f02010-03-16 22:30:13 +00002551 if (Invalid)
2552 return ExprError();
Sebastian Redlffbcf962009-01-18 18:53:16 +00002553
Benjamin Kramer0a1abd42010-02-27 13:44:12 +00002554 CharLiteralParser Literal(ThisTok.begin(), ThisTok.end(), Tok.getLocation(),
Douglas Gregorfb65e592011-07-27 05:40:30 +00002555 PP, Tok.getKind());
Steve Naroffae4143e2007-04-26 20:39:23 +00002556 if (Literal.hadError())
Sebastian Redlffbcf962009-01-18 18:53:16 +00002557 return ExprError();
Chris Lattneref24b382008-03-01 08:32:21 +00002558
Chris Lattnerc3847ba2009-12-30 21:19:39 +00002559 QualType Ty;
Seth Cantrell02f86052012-01-18 12:27:06 +00002560 if (Literal.isWide())
2561 Ty = Context.WCharTy; // L'x' -> wchar_t in C and C++.
Douglas Gregorfb65e592011-07-27 05:40:30 +00002562 else if (Literal.isUTF16())
Seth Cantrell02f86052012-01-18 12:27:06 +00002563 Ty = Context.Char16Ty; // u'x' -> char16_t in C11 and C++11.
Douglas Gregorfb65e592011-07-27 05:40:30 +00002564 else if (Literal.isUTF32())
Seth Cantrell02f86052012-01-18 12:27:06 +00002565 Ty = Context.Char32Ty; // U'x' -> char32_t in C11 and C++11.
David Blaikiebbafb8a2012-03-11 07:00:24 +00002566 else if (!getLangOpts().CPlusPlus || Literal.isMultiChar())
Seth Cantrell02f86052012-01-18 12:27:06 +00002567 Ty = Context.IntTy; // 'x' -> int in C, 'wxyz' -> int in C++.
Chris Lattnerc3847ba2009-12-30 21:19:39 +00002568 else
2569 Ty = Context.CharTy; // 'x' -> char in C++
Chris Lattneref24b382008-03-01 08:32:21 +00002570
Douglas Gregorfb65e592011-07-27 05:40:30 +00002571 CharacterLiteral::CharacterKind Kind = CharacterLiteral::Ascii;
2572 if (Literal.isWide())
2573 Kind = CharacterLiteral::Wide;
2574 else if (Literal.isUTF16())
2575 Kind = CharacterLiteral::UTF16;
2576 else if (Literal.isUTF32())
2577 Kind = CharacterLiteral::UTF32;
2578
Richard Smith75b67d62012-03-08 01:34:56 +00002579 Expr *Lit = new (Context) CharacterLiteral(Literal.getValue(), Kind, Ty,
2580 Tok.getLocation());
2581
2582 if (Literal.getUDSuffix().empty())
2583 return Owned(Lit);
2584
2585 // We're building a user-defined literal.
2586 IdentifierInfo *UDSuffix = &Context.Idents.get(Literal.getUDSuffix());
2587 SourceLocation UDSuffixLoc =
2588 getUDSuffixLoc(*this, Tok.getLocation(), Literal.getUDSuffixOffset());
2589
Richard Smithbcc22fc2012-03-09 08:00:36 +00002590 // Make sure we're allowed user-defined literals here.
2591 if (!UDLScope)
2592 return ExprError(Diag(UDSuffixLoc, diag::err_invalid_character_udl));
2593
Richard Smith75b67d62012-03-08 01:34:56 +00002594 // C++11 [lex.ext]p6: The literal L is treated as a call of the form
2595 // operator "" X (ch)
Richard Smithbcc22fc2012-03-09 08:00:36 +00002596 return BuildCookedLiteralOperatorCall(*this, UDLScope, UDSuffix, UDSuffixLoc,
2597 llvm::makeArrayRef(&Lit, 1),
2598 Tok.getLocation());
Steve Naroffae4143e2007-04-26 20:39:23 +00002599}
2600
Ted Kremeneke65b0862012-03-06 20:05:56 +00002601ExprResult Sema::ActOnIntegerConstant(SourceLocation Loc, uint64_t Val) {
2602 unsigned IntSize = Context.getTargetInfo().getIntWidth();
2603 return Owned(IntegerLiteral::Create(Context, llvm::APInt(IntSize, Val),
2604 Context.IntTy, Loc));
2605}
2606
Richard Smith39570d002012-03-08 08:45:32 +00002607static Expr *BuildFloatingLiteral(Sema &S, NumericLiteralParser &Literal,
2608 QualType Ty, SourceLocation Loc) {
2609 const llvm::fltSemantics &Format = S.Context.getFloatTypeSemantics(Ty);
2610
2611 using llvm::APFloat;
2612 APFloat Val(Format);
2613
2614 APFloat::opStatus result = Literal.GetFloatValue(Val);
2615
2616 // Overflow is always an error, but underflow is only an error if
2617 // we underflowed to zero (APFloat reports denormals as underflow).
2618 if ((result & APFloat::opOverflow) ||
2619 ((result & APFloat::opUnderflow) && Val.isZero())) {
2620 unsigned diagnostic;
2621 SmallString<20> buffer;
2622 if (result & APFloat::opOverflow) {
2623 diagnostic = diag::warn_float_overflow;
2624 APFloat::getLargest(Format).toString(buffer);
2625 } else {
2626 diagnostic = diag::warn_float_underflow;
2627 APFloat::getSmallest(Format).toString(buffer);
2628 }
2629
2630 S.Diag(Loc, diagnostic)
2631 << Ty
2632 << StringRef(buffer.data(), buffer.size());
2633 }
2634
2635 bool isExact = (result == APFloat::opOK);
2636 return FloatingLiteral::Create(S.Context, Val, isExact, Ty, Loc);
2637}
2638
Richard Smithbcc22fc2012-03-09 08:00:36 +00002639ExprResult Sema::ActOnNumericConstant(const Token &Tok, Scope *UDLScope) {
Sebastian Redlffbcf962009-01-18 18:53:16 +00002640 // Fast path for a single digit (which is quite common). A single digit
Richard Smithbcc22fc2012-03-09 08:00:36 +00002641 // cannot have a trigraph, escaped newline, radix prefix, or suffix.
Steve Narofff2fb89e2007-03-13 20:29:44 +00002642 if (Tok.getLength() == 1) {
Chris Lattner9240b3e2009-01-26 22:36:52 +00002643 const char Val = PP.getSpellingOfSingleCharacterNumericConstant(Tok);
Ted Kremeneke65b0862012-03-06 20:05:56 +00002644 return ActOnIntegerConstant(Tok.getLocation(), Val-'0');
Steve Narofff2fb89e2007-03-13 20:29:44 +00002645 }
Ted Kremeneke9814182009-01-13 23:19:12 +00002646
Dmitri Gribenko7ba91722012-09-24 09:53:54 +00002647 SmallString<128> SpellingBuffer;
2648 // NumericLiteralParser wants to overread by one character. Add padding to
2649 // the buffer in case the token is copied to the buffer. If getSpelling()
2650 // returns a StringRef to the memory buffer, it should have a null char at
2651 // the EOF, so it is also safe.
2652 SpellingBuffer.resize(Tok.getLength() + 1);
Sebastian Redlffbcf962009-01-18 18:53:16 +00002653
Chris Lattner67ca9252007-05-21 01:08:44 +00002654 // Get the spelling of the token, which eliminates trigraphs, etc.
Douglas Gregordc970f02010-03-16 22:30:13 +00002655 bool Invalid = false;
Dmitri Gribenko7ba91722012-09-24 09:53:54 +00002656 StringRef TokSpelling = PP.getSpelling(Tok, SpellingBuffer, &Invalid);
Douglas Gregordc970f02010-03-16 22:30:13 +00002657 if (Invalid)
2658 return ExprError();
Sebastian Redlffbcf962009-01-18 18:53:16 +00002659
Dmitri Gribenko7ba91722012-09-24 09:53:54 +00002660 NumericLiteralParser Literal(TokSpelling, Tok.getLocation(), PP);
Steve Narofff2fb89e2007-03-13 20:29:44 +00002661 if (Literal.hadError)
Sebastian Redlffbcf962009-01-18 18:53:16 +00002662 return ExprError();
2663
Richard Smith39570d002012-03-08 08:45:32 +00002664 if (Literal.hasUDSuffix()) {
2665 // We're building a user-defined literal.
2666 IdentifierInfo *UDSuffix = &Context.Idents.get(Literal.getUDSuffix());
2667 SourceLocation UDSuffixLoc =
2668 getUDSuffixLoc(*this, Tok.getLocation(), Literal.getUDSuffixOffset());
2669
Richard Smithbcc22fc2012-03-09 08:00:36 +00002670 // Make sure we're allowed user-defined literals here.
2671 if (!UDLScope)
2672 return ExprError(Diag(UDSuffixLoc, diag::err_invalid_numeric_udl));
Richard Smith39570d002012-03-08 08:45:32 +00002673
Richard Smithbcc22fc2012-03-09 08:00:36 +00002674 QualType CookedTy;
Richard Smith39570d002012-03-08 08:45:32 +00002675 if (Literal.isFloatingLiteral()) {
2676 // C++11 [lex.ext]p4: If S contains a literal operator with parameter type
2677 // long double, the literal is treated as a call of the form
2678 // operator "" X (f L)
Richard Smithbcc22fc2012-03-09 08:00:36 +00002679 CookedTy = Context.LongDoubleTy;
Richard Smith39570d002012-03-08 08:45:32 +00002680 } else {
2681 // C++11 [lex.ext]p3: If S contains a literal operator with parameter type
2682 // unsigned long long, the literal is treated as a call of the form
2683 // operator "" X (n ULL)
Richard Smithbcc22fc2012-03-09 08:00:36 +00002684 CookedTy = Context.UnsignedLongLongTy;
Richard Smith39570d002012-03-08 08:45:32 +00002685 }
2686
Richard Smithbcc22fc2012-03-09 08:00:36 +00002687 DeclarationName OpName =
2688 Context.DeclarationNames.getCXXLiteralOperatorName(UDSuffix);
2689 DeclarationNameInfo OpNameInfo(OpName, UDSuffixLoc);
2690 OpNameInfo.setCXXLiteralOperatorNameLoc(UDSuffixLoc);
2691
2692 // Perform literal operator lookup to determine if we're building a raw
2693 // literal or a cooked one.
2694 LookupResult R(*this, OpName, UDSuffixLoc, LookupOrdinaryName);
2695 switch (LookupLiteralOperator(UDLScope, R, llvm::makeArrayRef(&CookedTy, 1),
2696 /*AllowRawAndTemplate*/true)) {
2697 case LOLR_Error:
2698 return ExprError();
2699
2700 case LOLR_Cooked: {
2701 Expr *Lit;
2702 if (Literal.isFloatingLiteral()) {
2703 Lit = BuildFloatingLiteral(*this, Literal, CookedTy, Tok.getLocation());
2704 } else {
2705 llvm::APInt ResultVal(Context.getTargetInfo().getLongLongWidth(), 0);
2706 if (Literal.GetIntegerValue(ResultVal))
2707 Diag(Tok.getLocation(), diag::warn_integer_too_large);
2708 Lit = IntegerLiteral::Create(Context, ResultVal, CookedTy,
2709 Tok.getLocation());
2710 }
2711 return BuildLiteralOperatorCall(R, OpNameInfo,
2712 llvm::makeArrayRef(&Lit, 1),
2713 Tok.getLocation());
2714 }
2715
2716 case LOLR_Raw: {
2717 // C++11 [lit.ext]p3, p4: If S contains a raw literal operator, the
2718 // literal is treated as a call of the form
2719 // operator "" X ("n")
2720 SourceLocation TokLoc = Tok.getLocation();
2721 unsigned Length = Literal.getUDSuffixOffset();
2722 QualType StrTy = Context.getConstantArrayType(
2723 Context.CharTy, llvm::APInt(32, Length + 1),
2724 ArrayType::Normal, 0);
2725 Expr *Lit = StringLiteral::Create(
Dmitri Gribenko7ba91722012-09-24 09:53:54 +00002726 Context, StringRef(TokSpelling.data(), Length), StringLiteral::Ascii,
Richard Smithbcc22fc2012-03-09 08:00:36 +00002727 /*Pascal*/false, StrTy, &TokLoc, 1);
2728 return BuildLiteralOperatorCall(R, OpNameInfo,
2729 llvm::makeArrayRef(&Lit, 1), TokLoc);
2730 }
2731
2732 case LOLR_Template:
2733 // C++11 [lit.ext]p3, p4: Otherwise (S contains a literal operator
2734 // template), L is treated as a call fo the form
2735 // operator "" X <'c1', 'c2', ... 'ck'>()
2736 // where n is the source character sequence c1 c2 ... ck.
2737 TemplateArgumentListInfo ExplicitArgs;
2738 unsigned CharBits = Context.getIntWidth(Context.CharTy);
2739 bool CharIsUnsigned = Context.CharTy->isUnsignedIntegerType();
2740 llvm::APSInt Value(CharBits, CharIsUnsigned);
2741 for (unsigned I = 0, N = Literal.getUDSuffixOffset(); I != N; ++I) {
Dmitri Gribenko7ba91722012-09-24 09:53:54 +00002742 Value = TokSpelling[I];
Benjamin Kramer6003ad52012-06-07 15:09:51 +00002743 TemplateArgument Arg(Context, Value, Context.CharTy);
Richard Smithbcc22fc2012-03-09 08:00:36 +00002744 TemplateArgumentLocInfo ArgInfo;
2745 ExplicitArgs.addArgument(TemplateArgumentLoc(Arg, ArgInfo));
2746 }
2747 return BuildLiteralOperatorCall(R, OpNameInfo, ArrayRef<Expr*>(),
2748 Tok.getLocation(), &ExplicitArgs);
2749 }
2750
2751 llvm_unreachable("unexpected literal operator lookup result");
Richard Smith39570d002012-03-08 08:45:32 +00002752 }
2753
Chris Lattner1c20a172007-08-26 03:42:43 +00002754 Expr *Res;
Sebastian Redlffbcf962009-01-18 18:53:16 +00002755
Chris Lattner1c20a172007-08-26 03:42:43 +00002756 if (Literal.isFloatingLiteral()) {
Chris Lattnerec0a6d92007-09-22 18:29:59 +00002757 QualType Ty;
Chris Lattner9a8d1d92008-06-30 18:32:54 +00002758 if (Literal.isFloat)
Chris Lattnerec0a6d92007-09-22 18:29:59 +00002759 Ty = Context.FloatTy;
Chris Lattner9a8d1d92008-06-30 18:32:54 +00002760 else if (!Literal.isLong)
Chris Lattnerec0a6d92007-09-22 18:29:59 +00002761 Ty = Context.DoubleTy;
Chris Lattner9a8d1d92008-06-30 18:32:54 +00002762 else
Chris Lattner7570e9c2008-03-08 08:52:55 +00002763 Ty = Context.LongDoubleTy;
Chris Lattner9a8d1d92008-06-30 18:32:54 +00002764
Richard Smith39570d002012-03-08 08:45:32 +00002765 Res = BuildFloatingLiteral(*this, Literal, Ty, Tok.getLocation());
Sebastian Redlffbcf962009-01-18 18:53:16 +00002766
Peter Collingbournec77f85b2011-03-11 19:24:59 +00002767 if (Ty == Context.DoubleTy) {
David Blaikiebbafb8a2012-03-11 07:00:24 +00002768 if (getLangOpts().SinglePrecisionConstants) {
John Wiegley01296292011-04-08 18:41:53 +00002769 Res = ImpCastExprToType(Res, Context.FloatTy, CK_FloatingCast).take();
David Blaikiebbafb8a2012-03-11 07:00:24 +00002770 } else if (getLangOpts().OpenCL && !getOpenCLOptions().cl_khr_fp64) {
Peter Collingbournec77f85b2011-03-11 19:24:59 +00002771 Diag(Tok.getLocation(), diag::warn_double_const_requires_fp64);
John Wiegley01296292011-04-08 18:41:53 +00002772 Res = ImpCastExprToType(Res, Context.FloatTy, CK_FloatingCast).take();
Peter Collingbournec77f85b2011-03-11 19:24:59 +00002773 }
2774 }
Chris Lattner1c20a172007-08-26 03:42:43 +00002775 } else if (!Literal.isIntegerLiteral()) {
Sebastian Redlffbcf962009-01-18 18:53:16 +00002776 return ExprError();
Chris Lattner1c20a172007-08-26 03:42:43 +00002777 } else {
Chris Lattner24d5bfe2008-04-02 04:24:33 +00002778 QualType Ty;
Chris Lattner67ca9252007-05-21 01:08:44 +00002779
Neil Boothac582c52007-08-29 22:00:19 +00002780 // long long is a C99 feature.
David Blaikiebbafb8a2012-03-11 07:00:24 +00002781 if (!getLangOpts().C99 && Literal.isLongLong)
Richard Smith0bf8a4922011-10-18 20:49:44 +00002782 Diag(Tok.getLocation(),
David Blaikiebbafb8a2012-03-11 07:00:24 +00002783 getLangOpts().CPlusPlus0x ?
Richard Smith0bf8a4922011-10-18 20:49:44 +00002784 diag::warn_cxx98_compat_longlong : diag::ext_longlong);
Neil Boothac582c52007-08-29 22:00:19 +00002785
Chris Lattner67ca9252007-05-21 01:08:44 +00002786 // Get the value in the widest-possible width.
Stephen Canonfdc6c1a2012-05-03 22:49:43 +00002787 unsigned MaxWidth = Context.getTargetInfo().getIntMaxTWidth();
2788 // The microsoft literal suffix extensions support 128-bit literals, which
2789 // may be wider than [u]intmax_t.
2790 if (Literal.isMicrosoftInteger && MaxWidth < 128)
2791 MaxWidth = 128;
2792 llvm::APInt ResultVal(MaxWidth, 0);
Sebastian Redlffbcf962009-01-18 18:53:16 +00002793
Chris Lattner67ca9252007-05-21 01:08:44 +00002794 if (Literal.GetIntegerValue(ResultVal)) {
2795 // If this value didn't fit into uintmax_t, warn and force to ull.
2796 Diag(Tok.getLocation(), diag::warn_integer_too_large);
Chris Lattner24d5bfe2008-04-02 04:24:33 +00002797 Ty = Context.UnsignedLongLongTy;
2798 assert(Context.getTypeSize(Ty) == ResultVal.getBitWidth() &&
Chris Lattner37e05872008-03-05 18:54:05 +00002799 "long long is not intmax_t?");
Steve Naroff09ef4742007-03-09 23:16:33 +00002800 } else {
Chris Lattner67ca9252007-05-21 01:08:44 +00002801 // If this value fits into a ULL, try to figure out what else it fits into
2802 // according to the rules of C99 6.4.4.1p5.
Sebastian Redlffbcf962009-01-18 18:53:16 +00002803
Chris Lattner67ca9252007-05-21 01:08:44 +00002804 // Octal, Hexadecimal, and integers with a U suffix are allowed to
2805 // be an unsigned int.
2806 bool AllowUnsigned = Literal.isUnsigned || Literal.getRadix() != 10;
2807
2808 // Check from smallest to largest, picking the smallest type we can.
Chris Lattner55258cf2008-05-09 05:59:00 +00002809 unsigned Width = 0;
Chris Lattner7b939cf2007-08-23 21:58:08 +00002810 if (!Literal.isLong && !Literal.isLongLong) {
2811 // Are int/unsigned possibilities?
Douglas Gregore8bbc122011-09-02 00:18:52 +00002812 unsigned IntSize = Context.getTargetInfo().getIntWidth();
Sebastian Redlffbcf962009-01-18 18:53:16 +00002813
Chris Lattner67ca9252007-05-21 01:08:44 +00002814 // Does it fit in a unsigned int?
2815 if (ResultVal.isIntN(IntSize)) {
2816 // Does it fit in a signed int?
2817 if (!Literal.isUnsigned && ResultVal[IntSize-1] == 0)
Chris Lattner24d5bfe2008-04-02 04:24:33 +00002818 Ty = Context.IntTy;
Chris Lattner67ca9252007-05-21 01:08:44 +00002819 else if (AllowUnsigned)
Chris Lattner24d5bfe2008-04-02 04:24:33 +00002820 Ty = Context.UnsignedIntTy;
Chris Lattner55258cf2008-05-09 05:59:00 +00002821 Width = IntSize;
Chris Lattner67ca9252007-05-21 01:08:44 +00002822 }
Chris Lattner67ca9252007-05-21 01:08:44 +00002823 }
Sebastian Redlffbcf962009-01-18 18:53:16 +00002824
Chris Lattner67ca9252007-05-21 01:08:44 +00002825 // Are long/unsigned long possibilities?
Chris Lattner24d5bfe2008-04-02 04:24:33 +00002826 if (Ty.isNull() && !Literal.isLongLong) {
Douglas Gregore8bbc122011-09-02 00:18:52 +00002827 unsigned LongSize = Context.getTargetInfo().getLongWidth();
Sebastian Redlffbcf962009-01-18 18:53:16 +00002828
Chris Lattner67ca9252007-05-21 01:08:44 +00002829 // Does it fit in a unsigned long?
2830 if (ResultVal.isIntN(LongSize)) {
2831 // Does it fit in a signed long?
2832 if (!Literal.isUnsigned && ResultVal[LongSize-1] == 0)
Chris Lattner24d5bfe2008-04-02 04:24:33 +00002833 Ty = Context.LongTy;
Chris Lattner67ca9252007-05-21 01:08:44 +00002834 else if (AllowUnsigned)
Chris Lattner24d5bfe2008-04-02 04:24:33 +00002835 Ty = Context.UnsignedLongTy;
Chris Lattner55258cf2008-05-09 05:59:00 +00002836 Width = LongSize;
Chris Lattner67ca9252007-05-21 01:08:44 +00002837 }
Sebastian Redlffbcf962009-01-18 18:53:16 +00002838 }
2839
Stephen Canonfdc6c1a2012-05-03 22:49:43 +00002840 // Check long long if needed.
Chris Lattner24d5bfe2008-04-02 04:24:33 +00002841 if (Ty.isNull()) {
Douglas Gregore8bbc122011-09-02 00:18:52 +00002842 unsigned LongLongSize = Context.getTargetInfo().getLongLongWidth();
Sebastian Redlffbcf962009-01-18 18:53:16 +00002843
Chris Lattner67ca9252007-05-21 01:08:44 +00002844 // Does it fit in a unsigned long long?
2845 if (ResultVal.isIntN(LongLongSize)) {
2846 // Does it fit in a signed long long?
Francois Pichetc3e73b32011-01-11 23:38:13 +00002847 // To be compatible with MSVC, hex integer literals ending with the
2848 // LL or i64 suffix are always signed in Microsoft mode.
Francois Pichetbf711d92011-01-11 12:23:00 +00002849 if (!Literal.isUnsigned && (ResultVal[LongLongSize-1] == 0 ||
David Blaikiebbafb8a2012-03-11 07:00:24 +00002850 (getLangOpts().MicrosoftExt && Literal.isLongLong)))
Chris Lattner24d5bfe2008-04-02 04:24:33 +00002851 Ty = Context.LongLongTy;
Chris Lattner67ca9252007-05-21 01:08:44 +00002852 else if (AllowUnsigned)
Chris Lattner24d5bfe2008-04-02 04:24:33 +00002853 Ty = Context.UnsignedLongLongTy;
Chris Lattner55258cf2008-05-09 05:59:00 +00002854 Width = LongLongSize;
Chris Lattner67ca9252007-05-21 01:08:44 +00002855 }
2856 }
Stephen Canonfdc6c1a2012-05-03 22:49:43 +00002857
2858 // If it doesn't fit in unsigned long long, and we're using Microsoft
2859 // extensions, then its a 128-bit integer literal.
2860 if (Ty.isNull() && Literal.isMicrosoftInteger) {
2861 if (Literal.isUnsigned)
2862 Ty = Context.UnsignedInt128Ty;
2863 else
2864 Ty = Context.Int128Ty;
2865 Width = 128;
2866 }
Sebastian Redlffbcf962009-01-18 18:53:16 +00002867
Chris Lattner67ca9252007-05-21 01:08:44 +00002868 // If we still couldn't decide a type, we probably have something that
2869 // does not fit in a signed long long, but has no U suffix.
Chris Lattner24d5bfe2008-04-02 04:24:33 +00002870 if (Ty.isNull()) {
Chris Lattner67ca9252007-05-21 01:08:44 +00002871 Diag(Tok.getLocation(), diag::warn_integer_too_large_for_signed);
Chris Lattner24d5bfe2008-04-02 04:24:33 +00002872 Ty = Context.UnsignedLongLongTy;
Douglas Gregore8bbc122011-09-02 00:18:52 +00002873 Width = Context.getTargetInfo().getLongLongWidth();
Chris Lattner67ca9252007-05-21 01:08:44 +00002874 }
Sebastian Redlffbcf962009-01-18 18:53:16 +00002875
Chris Lattner55258cf2008-05-09 05:59:00 +00002876 if (ResultVal.getBitWidth() != Width)
Jay Foad6d4db0c2010-12-07 08:25:34 +00002877 ResultVal = ResultVal.trunc(Width);
Steve Naroff09ef4742007-03-09 23:16:33 +00002878 }
Argyrios Kyrtzidis43b20572010-08-28 09:06:06 +00002879 Res = IntegerLiteral::Create(Context, ResultVal, Ty, Tok.getLocation());
Steve Naroff09ef4742007-03-09 23:16:33 +00002880 }
Sebastian Redlffbcf962009-01-18 18:53:16 +00002881
Chris Lattner1c20a172007-08-26 03:42:43 +00002882 // If this is an imaginary literal, create the ImaginaryLiteral wrapper.
2883 if (Literal.isImaginary)
Mike Stump11289f42009-09-09 15:08:12 +00002884 Res = new (Context) ImaginaryLiteral(Res,
Steve Narofff6009ed2009-01-21 00:14:39 +00002885 Context.getComplexType(Res->getType()));
Sebastian Redlffbcf962009-01-18 18:53:16 +00002886
2887 return Owned(Res);
Chris Lattnere168f762006-11-10 05:29:30 +00002888}
2889
Richard Trieuba63ce62011-09-09 01:45:06 +00002890ExprResult Sema::ActOnParenExpr(SourceLocation L, SourceLocation R, Expr *E) {
Chris Lattner24d5bfe2008-04-02 04:24:33 +00002891 assert((E != 0) && "ActOnParenExpr() missing expr");
Steve Narofff6009ed2009-01-21 00:14:39 +00002892 return Owned(new (Context) ParenExpr(L, R, E));
Chris Lattnere168f762006-11-10 05:29:30 +00002893}
2894
Chandler Carruth62da79c2011-05-26 08:53:12 +00002895static bool CheckVecStepTraitOperandType(Sema &S, QualType T,
2896 SourceLocation Loc,
2897 SourceRange ArgRange) {
2898 // [OpenCL 1.1 6.11.12] "The vec_step built-in function takes a built-in
2899 // scalar or vector data type argument..."
2900 // Every built-in scalar type (OpenCL 1.1 6.1.1) is either an arithmetic
2901 // type (C99 6.2.5p18) or void.
2902 if (!(T->isArithmeticType() || T->isVoidType() || T->isVectorType())) {
2903 S.Diag(Loc, diag::err_vecstep_non_scalar_vector_type)
2904 << T << ArgRange;
2905 return true;
2906 }
2907
2908 assert((T->isVoidType() || !T->isIncompleteType()) &&
2909 "Scalar types should always be complete");
2910 return false;
2911}
2912
Chandler Carruthcea1aac2011-05-26 08:53:16 +00002913static bool CheckExtensionTraitOperandType(Sema &S, QualType T,
2914 SourceLocation Loc,
2915 SourceRange ArgRange,
2916 UnaryExprOrTypeTrait TraitKind) {
2917 // C99 6.5.3.4p1:
2918 if (T->isFunctionType()) {
2919 // alignof(function) is allowed as an extension.
2920 if (TraitKind == UETT_SizeOf)
2921 S.Diag(Loc, diag::ext_sizeof_function_type) << ArgRange;
2922 return false;
2923 }
2924
2925 // Allow sizeof(void)/alignof(void) as an extension.
2926 if (T->isVoidType()) {
2927 S.Diag(Loc, diag::ext_sizeof_void_type) << TraitKind << ArgRange;
2928 return false;
2929 }
2930
2931 return true;
2932}
2933
2934static bool CheckObjCTraitOperandConstraints(Sema &S, QualType T,
2935 SourceLocation Loc,
2936 SourceRange ArgRange,
2937 UnaryExprOrTypeTrait TraitKind) {
John McCallf2538342012-07-31 05:14:30 +00002938 // Reject sizeof(interface) and sizeof(interface<proto>) if the
2939 // runtime doesn't allow it.
2940 if (!S.LangOpts.ObjCRuntime.allowsSizeofAlignof() && T->isObjCObjectType()) {
Chandler Carruthcea1aac2011-05-26 08:53:16 +00002941 S.Diag(Loc, diag::err_sizeof_nonfragile_interface)
2942 << T << (TraitKind == UETT_SizeOf)
2943 << ArgRange;
2944 return true;
2945 }
2946
2947 return false;
2948}
2949
Chandler Carruth14502c22011-05-26 08:53:10 +00002950/// \brief Check the constrains on expression operands to unary type expression
2951/// and type traits.
2952///
Chandler Carruth7c430c02011-05-27 01:33:31 +00002953/// Completes any types necessary and validates the constraints on the operand
2954/// expression. The logic mostly mirrors the type-based overload, but may modify
2955/// the expression as it completes the type for that expression through template
2956/// instantiation, etc.
Richard Trieuba63ce62011-09-09 01:45:06 +00002957bool Sema::CheckUnaryExprOrTypeTraitOperand(Expr *E,
Chandler Carruth14502c22011-05-26 08:53:10 +00002958 UnaryExprOrTypeTrait ExprKind) {
Richard Trieuba63ce62011-09-09 01:45:06 +00002959 QualType ExprTy = E->getType();
Chandler Carruth7c430c02011-05-27 01:33:31 +00002960
2961 // C++ [expr.sizeof]p2: "When applied to a reference or a reference type,
2962 // the result is the size of the referenced type."
2963 // C++ [expr.alignof]p3: "When alignof is applied to a reference type, the
2964 // result shall be the alignment of the referenced type."
2965 if (const ReferenceType *Ref = ExprTy->getAs<ReferenceType>())
2966 ExprTy = Ref->getPointeeType();
2967
2968 if (ExprKind == UETT_VecStep)
Richard Trieuba63ce62011-09-09 01:45:06 +00002969 return CheckVecStepTraitOperandType(*this, ExprTy, E->getExprLoc(),
2970 E->getSourceRange());
Chandler Carruth7c430c02011-05-27 01:33:31 +00002971
2972 // Whitelist some types as extensions
Richard Trieuba63ce62011-09-09 01:45:06 +00002973 if (!CheckExtensionTraitOperandType(*this, ExprTy, E->getExprLoc(),
2974 E->getSourceRange(), ExprKind))
Chandler Carruth7c430c02011-05-27 01:33:31 +00002975 return false;
2976
Richard Trieuba63ce62011-09-09 01:45:06 +00002977 if (RequireCompleteExprType(E,
Douglas Gregor7bfb2d02012-05-04 16:32:21 +00002978 diag::err_sizeof_alignof_incomplete_type,
2979 ExprKind, E->getSourceRange()))
Chandler Carruth7c430c02011-05-27 01:33:31 +00002980 return true;
2981
2982 // Completeing the expression's type may have changed it.
Richard Trieuba63ce62011-09-09 01:45:06 +00002983 ExprTy = E->getType();
Chandler Carruth7c430c02011-05-27 01:33:31 +00002984 if (const ReferenceType *Ref = ExprTy->getAs<ReferenceType>())
2985 ExprTy = Ref->getPointeeType();
2986
Richard Trieuba63ce62011-09-09 01:45:06 +00002987 if (CheckObjCTraitOperandConstraints(*this, ExprTy, E->getExprLoc(),
2988 E->getSourceRange(), ExprKind))
Chandler Carruth7c430c02011-05-27 01:33:31 +00002989 return true;
2990
Nico Weber0870deb2011-06-15 02:47:03 +00002991 if (ExprKind == UETT_SizeOf) {
Richard Trieuba63ce62011-09-09 01:45:06 +00002992 if (DeclRefExpr *DeclRef = dyn_cast<DeclRefExpr>(E->IgnoreParens())) {
Nico Weber0870deb2011-06-15 02:47:03 +00002993 if (ParmVarDecl *PVD = dyn_cast<ParmVarDecl>(DeclRef->getFoundDecl())) {
2994 QualType OType = PVD->getOriginalType();
2995 QualType Type = PVD->getType();
2996 if (Type->isPointerType() && OType->isArrayType()) {
Richard Trieuba63ce62011-09-09 01:45:06 +00002997 Diag(E->getExprLoc(), diag::warn_sizeof_array_param)
Nico Weber0870deb2011-06-15 02:47:03 +00002998 << Type << OType;
2999 Diag(PVD->getLocation(), diag::note_declared_at);
3000 }
3001 }
3002 }
3003 }
3004
Chandler Carruth7c430c02011-05-27 01:33:31 +00003005 return false;
Chandler Carruth14502c22011-05-26 08:53:10 +00003006}
3007
3008/// \brief Check the constraints on operands to unary expression and type
3009/// traits.
3010///
3011/// This will complete any types necessary, and validate the various constraints
3012/// on those operands.
3013///
Steve Naroff71b59a92007-06-04 22:22:31 +00003014/// The UsualUnaryConversions() function is *not* called by this routine.
Chandler Carruth14502c22011-05-26 08:53:10 +00003015/// C99 6.3.2.1p[2-4] all state:
3016/// Except when it is the operand of the sizeof operator ...
3017///
3018/// C++ [expr.sizeof]p4
3019/// The lvalue-to-rvalue, array-to-pointer, and function-to-pointer
3020/// standard conversions are not applied to the operand of sizeof.
3021///
3022/// This policy is followed for all of the unary trait expressions.
Richard Trieuba63ce62011-09-09 01:45:06 +00003023bool Sema::CheckUnaryExprOrTypeTraitOperand(QualType ExprType,
Peter Collingbournee190dee2011-03-11 19:24:49 +00003024 SourceLocation OpLoc,
3025 SourceRange ExprRange,
3026 UnaryExprOrTypeTrait ExprKind) {
Richard Trieuba63ce62011-09-09 01:45:06 +00003027 if (ExprType->isDependentType())
Sebastian Redl8d2ccae2009-02-26 14:39:58 +00003028 return false;
3029
Sebastian Redl22e2e5c2009-11-23 17:18:46 +00003030 // C++ [expr.sizeof]p2: "When applied to a reference or a reference type,
3031 // the result is the size of the referenced type."
3032 // C++ [expr.alignof]p3: "When alignof is applied to a reference type, the
3033 // result shall be the alignment of the referenced type."
Richard Trieuba63ce62011-09-09 01:45:06 +00003034 if (const ReferenceType *Ref = ExprType->getAs<ReferenceType>())
3035 ExprType = Ref->getPointeeType();
Sebastian Redl22e2e5c2009-11-23 17:18:46 +00003036
Chandler Carruth62da79c2011-05-26 08:53:12 +00003037 if (ExprKind == UETT_VecStep)
Richard Trieuba63ce62011-09-09 01:45:06 +00003038 return CheckVecStepTraitOperandType(*this, ExprType, OpLoc, ExprRange);
Peter Collingbournee190dee2011-03-11 19:24:49 +00003039
Chandler Carruthcea1aac2011-05-26 08:53:16 +00003040 // Whitelist some types as extensions
Richard Trieuba63ce62011-09-09 01:45:06 +00003041 if (!CheckExtensionTraitOperandType(*this, ExprType, OpLoc, ExprRange,
Chandler Carruthcea1aac2011-05-26 08:53:16 +00003042 ExprKind))
Chris Lattnerb1355b12009-01-24 19:46:37 +00003043 return false;
Mike Stump11289f42009-09-09 15:08:12 +00003044
Richard Trieuba63ce62011-09-09 01:45:06 +00003045 if (RequireCompleteType(OpLoc, ExprType,
Douglas Gregor7bfb2d02012-05-04 16:32:21 +00003046 diag::err_sizeof_alignof_incomplete_type,
3047 ExprKind, ExprRange))
Chris Lattner62975a72009-04-24 00:30:45 +00003048 return true;
Mike Stump11289f42009-09-09 15:08:12 +00003049
Richard Trieuba63ce62011-09-09 01:45:06 +00003050 if (CheckObjCTraitOperandConstraints(*this, ExprType, OpLoc, ExprRange,
Chandler Carruthcea1aac2011-05-26 08:53:16 +00003051 ExprKind))
Chris Lattnercd2a8c52009-04-24 22:30:50 +00003052 return true;
Mike Stump11289f42009-09-09 15:08:12 +00003053
Chris Lattner62975a72009-04-24 00:30:45 +00003054 return false;
Steve Naroff043d45d2007-05-15 02:32:35 +00003055}
3056
Chandler Carruth14502c22011-05-26 08:53:10 +00003057static bool CheckAlignOfExpr(Sema &S, Expr *E) {
Chris Lattner8dff0172009-01-24 20:17:12 +00003058 E = E->IgnoreParens();
Sebastian Redl8d2ccae2009-02-26 14:39:58 +00003059
Mike Stump11289f42009-09-09 15:08:12 +00003060 // alignof decl is always ok.
Chris Lattner8dff0172009-01-24 20:17:12 +00003061 if (isa<DeclRefExpr>(E))
3062 return false;
Sebastian Redl8d2ccae2009-02-26 14:39:58 +00003063
3064 // Cannot know anything else if the expression is dependent.
3065 if (E->isTypeDependent())
3066 return false;
3067
Douglas Gregor71235ec2009-05-02 02:18:30 +00003068 if (E->getBitField()) {
Chandler Carruth14502c22011-05-26 08:53:10 +00003069 S.Diag(E->getExprLoc(), diag::err_sizeof_alignof_bitfield)
3070 << 1 << E->getSourceRange();
Douglas Gregor71235ec2009-05-02 02:18:30 +00003071 return true;
Chris Lattner8dff0172009-01-24 20:17:12 +00003072 }
Douglas Gregor71235ec2009-05-02 02:18:30 +00003073
3074 // Alignment of a field access is always okay, so long as it isn't a
3075 // bit-field.
3076 if (MemberExpr *ME = dyn_cast<MemberExpr>(E))
Mike Stump212005c2009-07-22 18:58:19 +00003077 if (isa<FieldDecl>(ME->getMemberDecl()))
Douglas Gregor71235ec2009-05-02 02:18:30 +00003078 return false;
3079
Chandler Carruth14502c22011-05-26 08:53:10 +00003080 return S.CheckUnaryExprOrTypeTraitOperand(E, UETT_AlignOf);
Peter Collingbournee190dee2011-03-11 19:24:49 +00003081}
3082
Chandler Carruth14502c22011-05-26 08:53:10 +00003083bool Sema::CheckVecStepExpr(Expr *E) {
Peter Collingbournee190dee2011-03-11 19:24:49 +00003084 E = E->IgnoreParens();
3085
3086 // Cannot know anything else if the expression is dependent.
3087 if (E->isTypeDependent())
3088 return false;
3089
Chandler Carruth14502c22011-05-26 08:53:10 +00003090 return CheckUnaryExprOrTypeTraitOperand(E, UETT_VecStep);
Chris Lattner8dff0172009-01-24 20:17:12 +00003091}
3092
Douglas Gregor0950e412009-03-13 21:01:28 +00003093/// \brief Build a sizeof or alignof expression given a type operand.
John McCalldadc5752010-08-24 06:29:42 +00003094ExprResult
Peter Collingbournee190dee2011-03-11 19:24:49 +00003095Sema::CreateUnaryExprOrTypeTraitExpr(TypeSourceInfo *TInfo,
3096 SourceLocation OpLoc,
3097 UnaryExprOrTypeTrait ExprKind,
3098 SourceRange R) {
John McCallbcd03502009-12-07 02:54:59 +00003099 if (!TInfo)
Douglas Gregor0950e412009-03-13 21:01:28 +00003100 return ExprError();
3101
John McCallbcd03502009-12-07 02:54:59 +00003102 QualType T = TInfo->getType();
John McCall4c98fd82009-11-04 07:28:41 +00003103
Douglas Gregor0950e412009-03-13 21:01:28 +00003104 if (!T->isDependentType() &&
Peter Collingbournee190dee2011-03-11 19:24:49 +00003105 CheckUnaryExprOrTypeTraitOperand(T, OpLoc, R, ExprKind))
Douglas Gregor0950e412009-03-13 21:01:28 +00003106 return ExprError();
3107
3108 // C99 6.5.3.4p4: the type (an unsigned integer type) is size_t.
Peter Collingbournee190dee2011-03-11 19:24:49 +00003109 return Owned(new (Context) UnaryExprOrTypeTraitExpr(ExprKind, TInfo,
3110 Context.getSizeType(),
3111 OpLoc, R.getEnd()));
Douglas Gregor0950e412009-03-13 21:01:28 +00003112}
3113
3114/// \brief Build a sizeof or alignof expression given an expression
3115/// operand.
John McCalldadc5752010-08-24 06:29:42 +00003116ExprResult
Chandler Carrutha923fb22011-05-29 07:32:14 +00003117Sema::CreateUnaryExprOrTypeTraitExpr(Expr *E, SourceLocation OpLoc,
3118 UnaryExprOrTypeTrait ExprKind) {
Douglas Gregor835af982011-06-22 23:21:00 +00003119 ExprResult PE = CheckPlaceholderExpr(E);
3120 if (PE.isInvalid())
3121 return ExprError();
3122
3123 E = PE.get();
3124
Douglas Gregor0950e412009-03-13 21:01:28 +00003125 // Verify that the operand is valid.
3126 bool isInvalid = false;
3127 if (E->isTypeDependent()) {
3128 // Delay type-checking for type-dependent expressions.
Peter Collingbournee190dee2011-03-11 19:24:49 +00003129 } else if (ExprKind == UETT_AlignOf) {
Chandler Carruth14502c22011-05-26 08:53:10 +00003130 isInvalid = CheckAlignOfExpr(*this, E);
Peter Collingbournee190dee2011-03-11 19:24:49 +00003131 } else if (ExprKind == UETT_VecStep) {
Chandler Carruth14502c22011-05-26 08:53:10 +00003132 isInvalid = CheckVecStepExpr(E);
Douglas Gregor71235ec2009-05-02 02:18:30 +00003133 } else if (E->getBitField()) { // C99 6.5.3.4p1.
Chandler Carruth14502c22011-05-26 08:53:10 +00003134 Diag(E->getExprLoc(), diag::err_sizeof_alignof_bitfield) << 0;
Douglas Gregor0950e412009-03-13 21:01:28 +00003135 isInvalid = true;
3136 } else {
Chandler Carruth14502c22011-05-26 08:53:10 +00003137 isInvalid = CheckUnaryExprOrTypeTraitOperand(E, UETT_SizeOf);
Douglas Gregor0950e412009-03-13 21:01:28 +00003138 }
3139
3140 if (isInvalid)
3141 return ExprError();
3142
Eli Friedmane0afc982012-01-21 01:01:51 +00003143 if (ExprKind == UETT_SizeOf && E->getType()->isVariableArrayType()) {
3144 PE = TranformToPotentiallyEvaluated(E);
3145 if (PE.isInvalid()) return ExprError();
3146 E = PE.take();
3147 }
3148
Douglas Gregor0950e412009-03-13 21:01:28 +00003149 // C99 6.5.3.4p4: the type (an unsigned integer type) is size_t.
Chandler Carruth14502c22011-05-26 08:53:10 +00003150 return Owned(new (Context) UnaryExprOrTypeTraitExpr(
Chandler Carrutha923fb22011-05-29 07:32:14 +00003151 ExprKind, E, Context.getSizeType(), OpLoc,
Chandler Carruth14502c22011-05-26 08:53:10 +00003152 E->getSourceRange().getEnd()));
Douglas Gregor0950e412009-03-13 21:01:28 +00003153}
3154
Peter Collingbournee190dee2011-03-11 19:24:49 +00003155/// ActOnUnaryExprOrTypeTraitExpr - Handle @c sizeof(type) and @c sizeof @c
3156/// expr and the same for @c alignof and @c __alignof
Sebastian Redl6f282892008-11-11 17:56:53 +00003157/// Note that the ArgRange is invalid if isType is false.
John McCalldadc5752010-08-24 06:29:42 +00003158ExprResult
Peter Collingbournee190dee2011-03-11 19:24:49 +00003159Sema::ActOnUnaryExprOrTypeTraitExpr(SourceLocation OpLoc,
Richard Trieuba63ce62011-09-09 01:45:06 +00003160 UnaryExprOrTypeTrait ExprKind, bool IsType,
Peter Collingbournee190dee2011-03-11 19:24:49 +00003161 void *TyOrEx, const SourceRange &ArgRange) {
Chris Lattner0d8b1a12006-11-20 04:34:45 +00003162 // If error parsing type, ignore.
Sebastian Redlc215cfc2009-01-19 00:08:26 +00003163 if (TyOrEx == 0) return ExprError();
Steve Naroff043d45d2007-05-15 02:32:35 +00003164
Richard Trieuba63ce62011-09-09 01:45:06 +00003165 if (IsType) {
John McCallbcd03502009-12-07 02:54:59 +00003166 TypeSourceInfo *TInfo;
John McCallba7bf592010-08-24 05:47:05 +00003167 (void) GetTypeFromParser(ParsedType::getFromOpaquePtr(TyOrEx), &TInfo);
Peter Collingbournee190dee2011-03-11 19:24:49 +00003168 return CreateUnaryExprOrTypeTraitExpr(TInfo, OpLoc, ExprKind, ArgRange);
Mike Stump11289f42009-09-09 15:08:12 +00003169 }
Sebastian Redl6f282892008-11-11 17:56:53 +00003170
Douglas Gregor0950e412009-03-13 21:01:28 +00003171 Expr *ArgEx = (Expr *)TyOrEx;
Chandler Carrutha923fb22011-05-29 07:32:14 +00003172 ExprResult Result = CreateUnaryExprOrTypeTraitExpr(ArgEx, OpLoc, ExprKind);
Benjamin Kramer62b95d82012-08-23 21:35:17 +00003173 return Result;
Chris Lattnere168f762006-11-10 05:29:30 +00003174}
3175
John Wiegley01296292011-04-08 18:41:53 +00003176static QualType CheckRealImagOperand(Sema &S, ExprResult &V, SourceLocation Loc,
Richard Trieuba63ce62011-09-09 01:45:06 +00003177 bool IsReal) {
John Wiegley01296292011-04-08 18:41:53 +00003178 if (V.get()->isTypeDependent())
John McCall4bc41ae2010-11-18 19:01:18 +00003179 return S.Context.DependentTy;
Mike Stump11289f42009-09-09 15:08:12 +00003180
John McCall34376a62010-12-04 03:47:34 +00003181 // _Real and _Imag are only l-values for normal l-values.
John Wiegley01296292011-04-08 18:41:53 +00003182 if (V.get()->getObjectKind() != OK_Ordinary) {
3183 V = S.DefaultLvalueConversion(V.take());
3184 if (V.isInvalid())
3185 return QualType();
3186 }
John McCall34376a62010-12-04 03:47:34 +00003187
Chris Lattnere267f5d2007-08-26 05:39:26 +00003188 // These operators return the element type of a complex type.
John Wiegley01296292011-04-08 18:41:53 +00003189 if (const ComplexType *CT = V.get()->getType()->getAs<ComplexType>())
Chris Lattner30b5dd02007-08-24 21:16:53 +00003190 return CT->getElementType();
Mike Stump11289f42009-09-09 15:08:12 +00003191
Chris Lattnere267f5d2007-08-26 05:39:26 +00003192 // Otherwise they pass through real integer and floating point types here.
John Wiegley01296292011-04-08 18:41:53 +00003193 if (V.get()->getType()->isArithmeticType())
3194 return V.get()->getType();
Mike Stump11289f42009-09-09 15:08:12 +00003195
John McCall36226622010-10-12 02:09:17 +00003196 // Test for placeholders.
John McCall3aef3d82011-04-10 19:13:55 +00003197 ExprResult PR = S.CheckPlaceholderExpr(V.get());
John McCall36226622010-10-12 02:09:17 +00003198 if (PR.isInvalid()) return QualType();
John Wiegley01296292011-04-08 18:41:53 +00003199 if (PR.get() != V.get()) {
Benjamin Kramer62b95d82012-08-23 21:35:17 +00003200 V = PR;
Richard Trieuba63ce62011-09-09 01:45:06 +00003201 return CheckRealImagOperand(S, V, Loc, IsReal);
John McCall36226622010-10-12 02:09:17 +00003202 }
3203
Chris Lattnere267f5d2007-08-26 05:39:26 +00003204 // Reject anything else.
John Wiegley01296292011-04-08 18:41:53 +00003205 S.Diag(Loc, diag::err_realimag_invalid_type) << V.get()->getType()
Richard Trieuba63ce62011-09-09 01:45:06 +00003206 << (IsReal ? "__real" : "__imag");
Chris Lattnere267f5d2007-08-26 05:39:26 +00003207 return QualType();
Chris Lattner30b5dd02007-08-24 21:16:53 +00003208}
3209
3210
Chris Lattnere168f762006-11-10 05:29:30 +00003211
John McCalldadc5752010-08-24 06:29:42 +00003212ExprResult
Sebastian Redlc215cfc2009-01-19 00:08:26 +00003213Sema::ActOnPostfixUnaryOp(Scope *S, SourceLocation OpLoc,
John McCallb268a282010-08-23 23:25:46 +00003214 tok::TokenKind Kind, Expr *Input) {
John McCalle3027922010-08-25 11:45:40 +00003215 UnaryOperatorKind Opc;
Chris Lattnere168f762006-11-10 05:29:30 +00003216 switch (Kind) {
David Blaikie83d382b2011-09-23 05:06:16 +00003217 default: llvm_unreachable("Unknown unary op!");
John McCalle3027922010-08-25 11:45:40 +00003218 case tok::plusplus: Opc = UO_PostInc; break;
3219 case tok::minusminus: Opc = UO_PostDec; break;
Chris Lattnere168f762006-11-10 05:29:30 +00003220 }
Sebastian Redlc215cfc2009-01-19 00:08:26 +00003221
Sebastian Redla9351792012-02-11 23:51:47 +00003222 // Since this might is a postfix expression, get rid of ParenListExprs.
3223 ExprResult Result = MaybeConvertParenListExprToParenExpr(S, Input);
3224 if (Result.isInvalid()) return ExprError();
3225 Input = Result.take();
3226
John McCallb268a282010-08-23 23:25:46 +00003227 return BuildUnaryOp(S, OpLoc, Opc, Input);
Chris Lattnere168f762006-11-10 05:29:30 +00003228}
3229
John McCallf2538342012-07-31 05:14:30 +00003230/// \brief Diagnose if arithmetic on the given ObjC pointer is illegal.
3231///
3232/// \return true on error
3233static bool checkArithmeticOnObjCPointer(Sema &S,
3234 SourceLocation opLoc,
3235 Expr *op) {
3236 assert(op->getType()->isObjCObjectPointerType());
3237 if (S.LangOpts.ObjCRuntime.allowsPointerArithmetic())
3238 return false;
3239
3240 S.Diag(opLoc, diag::err_arithmetic_nonfragile_interface)
3241 << op->getType()->castAs<ObjCObjectPointerType>()->getPointeeType()
3242 << op->getSourceRange();
3243 return true;
3244}
3245
John McCalldadc5752010-08-24 06:29:42 +00003246ExprResult
John McCallb268a282010-08-23 23:25:46 +00003247Sema::ActOnArraySubscriptExpr(Scope *S, Expr *Base, SourceLocation LLoc,
3248 Expr *Idx, SourceLocation RLoc) {
Nate Begeman5ec4b312009-08-10 23:49:36 +00003249 // Since this might be a postfix expression, get rid of ParenListExprs.
John McCalldadc5752010-08-24 06:29:42 +00003250 ExprResult Result = MaybeConvertParenListExprToParenExpr(S, Base);
John McCallb268a282010-08-23 23:25:46 +00003251 if (Result.isInvalid()) return ExprError();
3252 Base = Result.take();
Nate Begeman5ec4b312009-08-10 23:49:36 +00003253
John McCallb268a282010-08-23 23:25:46 +00003254 Expr *LHSExp = Base, *RHSExp = Idx;
Mike Stump11289f42009-09-09 15:08:12 +00003255
David Blaikiebbafb8a2012-03-11 07:00:24 +00003256 if (getLangOpts().CPlusPlus &&
Douglas Gregor7a77a6b2009-05-19 00:01:19 +00003257 (LHSExp->isTypeDependent() || RHSExp->isTypeDependent())) {
Douglas Gregor7a77a6b2009-05-19 00:01:19 +00003258 return Owned(new (Context) ArraySubscriptExpr(LHSExp, RHSExp,
John McCall7decc9e2010-11-18 06:31:45 +00003259 Context.DependentTy,
3260 VK_LValue, OK_Ordinary,
3261 RLoc));
Douglas Gregor7a77a6b2009-05-19 00:01:19 +00003262 }
3263
David Blaikiebbafb8a2012-03-11 07:00:24 +00003264 if (getLangOpts().CPlusPlus &&
Sebastian Redlc215cfc2009-01-19 00:08:26 +00003265 (LHSExp->getType()->isRecordType() ||
Eli Friedman254a1a22008-12-15 22:34:21 +00003266 LHSExp->getType()->isEnumeralType() ||
3267 RHSExp->getType()->isRecordType() ||
Ted Kremeneke65b0862012-03-06 20:05:56 +00003268 RHSExp->getType()->isEnumeralType()) &&
3269 !LHSExp->getType()->isObjCObjectPointerType()) {
John McCallb268a282010-08-23 23:25:46 +00003270 return CreateOverloadedArraySubscriptExpr(LLoc, RLoc, Base, Idx);
Douglas Gregor40412ac2008-11-19 17:17:41 +00003271 }
3272
John McCallb268a282010-08-23 23:25:46 +00003273 return CreateBuiltinArraySubscriptExpr(Base, LLoc, Idx, RLoc);
Sebastian Redladba46e2009-10-29 20:17:01 +00003274}
3275
John McCalldadc5752010-08-24 06:29:42 +00003276ExprResult
John McCallb268a282010-08-23 23:25:46 +00003277Sema::CreateBuiltinArraySubscriptExpr(Expr *Base, SourceLocation LLoc,
Richard Trieuba63ce62011-09-09 01:45:06 +00003278 Expr *Idx, SourceLocation RLoc) {
John McCallb268a282010-08-23 23:25:46 +00003279 Expr *LHSExp = Base;
3280 Expr *RHSExp = Idx;
Sebastian Redladba46e2009-10-29 20:17:01 +00003281
Chris Lattner36d572b2007-07-16 00:14:47 +00003282 // Perform default conversions.
John Wiegley01296292011-04-08 18:41:53 +00003283 if (!LHSExp->getType()->getAs<VectorType>()) {
3284 ExprResult Result = DefaultFunctionArrayLvalueConversion(LHSExp);
3285 if (Result.isInvalid())
3286 return ExprError();
3287 LHSExp = Result.take();
3288 }
3289 ExprResult Result = DefaultFunctionArrayLvalueConversion(RHSExp);
3290 if (Result.isInvalid())
3291 return ExprError();
3292 RHSExp = Result.take();
Sebastian Redlc215cfc2009-01-19 00:08:26 +00003293
Chris Lattner36d572b2007-07-16 00:14:47 +00003294 QualType LHSTy = LHSExp->getType(), RHSTy = RHSExp->getType();
John McCall7decc9e2010-11-18 06:31:45 +00003295 ExprValueKind VK = VK_LValue;
3296 ExprObjectKind OK = OK_Ordinary;
Steve Narofff1e53692007-03-23 22:27:02 +00003297
Steve Naroffc1aadb12007-03-28 21:49:40 +00003298 // C99 6.5.2.1p2: the expression e1[e2] is by definition precisely equivalent
Chris Lattnerf17bd422007-08-30 17:45:32 +00003299 // to the expression *((e1)+(e2)). This means the array "Base" may actually be
Mike Stump4e1f26a2009-02-19 03:04:26 +00003300 // in the subscript position. As a result, we need to derive the array base
Steve Narofff1e53692007-03-23 22:27:02 +00003301 // and index from the expression types.
Chris Lattner36d572b2007-07-16 00:14:47 +00003302 Expr *BaseExpr, *IndexExpr;
3303 QualType ResultType;
Sebastian Redl8d2ccae2009-02-26 14:39:58 +00003304 if (LHSTy->isDependentType() || RHSTy->isDependentType()) {
3305 BaseExpr = LHSExp;
3306 IndexExpr = RHSExp;
3307 ResultType = Context.DependentTy;
Ted Kremenekc23c7e62009-07-29 21:53:49 +00003308 } else if (const PointerType *PTy = LHSTy->getAs<PointerType>()) {
Chris Lattner36d572b2007-07-16 00:14:47 +00003309 BaseExpr = LHSExp;
3310 IndexExpr = RHSExp;
Chris Lattner36d572b2007-07-16 00:14:47 +00003311 ResultType = PTy->getPointeeType();
Mike Stump11289f42009-09-09 15:08:12 +00003312 } else if (const ObjCObjectPointerType *PTy =
John McCallf2538342012-07-31 05:14:30 +00003313 LHSTy->getAs<ObjCObjectPointerType>()) {
Steve Naroff7cae42b2009-07-10 23:34:53 +00003314 BaseExpr = LHSExp;
3315 IndexExpr = RHSExp;
John McCallf2538342012-07-31 05:14:30 +00003316
3317 // Use custom logic if this should be the pseudo-object subscript
3318 // expression.
3319 if (!LangOpts.ObjCRuntime.isSubscriptPointerArithmetic())
3320 return BuildObjCSubscriptExpression(RLoc, BaseExpr, IndexExpr, 0, 0);
3321
Steve Naroff7cae42b2009-07-10 23:34:53 +00003322 ResultType = PTy->getPointeeType();
John McCallf2538342012-07-31 05:14:30 +00003323 if (!LangOpts.ObjCRuntime.allowsPointerArithmetic()) {
3324 Diag(LLoc, diag::err_subscript_nonfragile_interface)
3325 << ResultType << BaseExpr->getSourceRange();
3326 return ExprError();
3327 }
Fariborz Jahanianba0afde2012-03-28 17:56:49 +00003328 } else if (const PointerType *PTy = RHSTy->getAs<PointerType>()) {
3329 // Handle the uncommon case of "123[Ptr]".
3330 BaseExpr = RHSExp;
3331 IndexExpr = LHSExp;
3332 ResultType = PTy->getPointeeType();
Mike Stump11289f42009-09-09 15:08:12 +00003333 } else if (const ObjCObjectPointerType *PTy =
John McCall9dd450b2009-09-21 23:43:11 +00003334 RHSTy->getAs<ObjCObjectPointerType>()) {
Steve Naroff7cae42b2009-07-10 23:34:53 +00003335 // Handle the uncommon case of "123[Ptr]".
3336 BaseExpr = RHSExp;
3337 IndexExpr = LHSExp;
3338 ResultType = PTy->getPointeeType();
John McCallf2538342012-07-31 05:14:30 +00003339 if (!LangOpts.ObjCRuntime.allowsPointerArithmetic()) {
3340 Diag(LLoc, diag::err_subscript_nonfragile_interface)
3341 << ResultType << BaseExpr->getSourceRange();
3342 return ExprError();
3343 }
John McCall9dd450b2009-09-21 23:43:11 +00003344 } else if (const VectorType *VTy = LHSTy->getAs<VectorType>()) {
Chris Lattner41977962007-07-31 19:29:30 +00003345 BaseExpr = LHSExp; // vectors: V[123]
Chris Lattner36d572b2007-07-16 00:14:47 +00003346 IndexExpr = RHSExp;
John McCall7decc9e2010-11-18 06:31:45 +00003347 VK = LHSExp->getValueKind();
3348 if (VK != VK_RValue)
3349 OK = OK_VectorComponent;
Nate Begemanc1bf0612009-01-18 00:45:31 +00003350
Chris Lattner36d572b2007-07-16 00:14:47 +00003351 // FIXME: need to deal with const...
3352 ResultType = VTy->getElementType();
Eli Friedmanab2784f2009-04-25 23:46:54 +00003353 } else if (LHSTy->isArrayType()) {
3354 // If we see an array that wasn't promoted by
Douglas Gregorb92a1562010-02-03 00:27:59 +00003355 // DefaultFunctionArrayLvalueConversion, it must be an array that
Eli Friedmanab2784f2009-04-25 23:46:54 +00003356 // wasn't promoted because of the C90 rule that doesn't
3357 // allow promoting non-lvalue arrays. Warn, then
3358 // force the promotion here.
3359 Diag(LHSExp->getLocStart(), diag::ext_subscript_non_lvalue) <<
3360 LHSExp->getSourceRange();
John Wiegley01296292011-04-08 18:41:53 +00003361 LHSExp = ImpCastExprToType(LHSExp, Context.getArrayDecayedType(LHSTy),
3362 CK_ArrayToPointerDecay).take();
Eli Friedmanab2784f2009-04-25 23:46:54 +00003363 LHSTy = LHSExp->getType();
3364
3365 BaseExpr = LHSExp;
3366 IndexExpr = RHSExp;
Ted Kremenekc23c7e62009-07-29 21:53:49 +00003367 ResultType = LHSTy->getAs<PointerType>()->getPointeeType();
Eli Friedmanab2784f2009-04-25 23:46:54 +00003368 } else if (RHSTy->isArrayType()) {
3369 // Same as previous, except for 123[f().a] case
3370 Diag(RHSExp->getLocStart(), diag::ext_subscript_non_lvalue) <<
3371 RHSExp->getSourceRange();
John Wiegley01296292011-04-08 18:41:53 +00003372 RHSExp = ImpCastExprToType(RHSExp, Context.getArrayDecayedType(RHSTy),
3373 CK_ArrayToPointerDecay).take();
Eli Friedmanab2784f2009-04-25 23:46:54 +00003374 RHSTy = RHSExp->getType();
3375
3376 BaseExpr = RHSExp;
3377 IndexExpr = LHSExp;
Ted Kremenekc23c7e62009-07-29 21:53:49 +00003378 ResultType = RHSTy->getAs<PointerType>()->getPointeeType();
Steve Naroffb3096442007-06-09 03:47:53 +00003379 } else {
Chris Lattner003af242009-04-25 22:50:55 +00003380 return ExprError(Diag(LLoc, diag::err_typecheck_subscript_value)
3381 << LHSExp->getSourceRange() << RHSExp->getSourceRange());
Sebastian Redlc215cfc2009-01-19 00:08:26 +00003382 }
Steve Naroffc1aadb12007-03-28 21:49:40 +00003383 // C99 6.5.2.1p1
Douglas Gregor5cc2c8b2010-07-23 15:58:24 +00003384 if (!IndexExpr->getType()->isIntegerType() && !IndexExpr->isTypeDependent())
Chris Lattner003af242009-04-25 22:50:55 +00003385 return ExprError(Diag(LLoc, diag::err_typecheck_subscript_not_integer)
3386 << IndexExpr->getSourceRange());
Steve Naroffb29cdd52007-07-10 18:23:31 +00003387
Daniel Dunbar4782a6e2009-09-17 06:31:17 +00003388 if ((IndexExpr->getType()->isSpecificBuiltinType(BuiltinType::Char_S) ||
Sam Weinigb7608d72009-09-14 20:14:57 +00003389 IndexExpr->getType()->isSpecificBuiltinType(BuiltinType::Char_U))
3390 && !IndexExpr->isTypeDependent())
Sam Weinig914244e2009-09-14 01:58:58 +00003391 Diag(LLoc, diag::warn_subscript_is_char) << IndexExpr->getSourceRange();
3392
Douglas Gregorac1fb652009-03-24 19:52:54 +00003393 // C99 6.5.2.1p1: "shall have type "pointer to *object* type". Similarly,
Mike Stump11289f42009-09-09 15:08:12 +00003394 // C++ [expr.sub]p1: The type "T" shall be a completely-defined object
3395 // type. Note that Functions are not objects, and that (in C99 parlance)
Douglas Gregorac1fb652009-03-24 19:52:54 +00003396 // incomplete types are not object types.
3397 if (ResultType->isFunctionType()) {
3398 Diag(BaseExpr->getLocStart(), diag::err_subscript_function_type)
3399 << ResultType << BaseExpr->getSourceRange();
3400 return ExprError();
3401 }
Mike Stump11289f42009-09-09 15:08:12 +00003402
David Blaikiebbafb8a2012-03-11 07:00:24 +00003403 if (ResultType->isVoidType() && !getLangOpts().CPlusPlus) {
Abramo Bagnara3aabb4b2010-09-13 06:50:07 +00003404 // GNU extension: subscripting on pointer to void
Chandler Carruth4cc3f292011-06-27 16:32:27 +00003405 Diag(LLoc, diag::ext_gnu_subscript_void_type)
3406 << BaseExpr->getSourceRange();
John McCall4bc41ae2010-11-18 19:01:18 +00003407
3408 // C forbids expressions of unqualified void type from being l-values.
3409 // See IsCForbiddenLValueType.
3410 if (!ResultType.hasQualifiers()) VK = VK_RValue;
Abramo Bagnara3aabb4b2010-09-13 06:50:07 +00003411 } else if (!ResultType->isDependentType() &&
Mike Stump11289f42009-09-09 15:08:12 +00003412 RequireCompleteType(LLoc, ResultType,
Douglas Gregor7bfb2d02012-05-04 16:32:21 +00003413 diag::err_subscript_incomplete_type, BaseExpr))
Douglas Gregorac1fb652009-03-24 19:52:54 +00003414 return ExprError();
Mike Stump11289f42009-09-09 15:08:12 +00003415
John McCall4bc41ae2010-11-18 19:01:18 +00003416 assert(VK == VK_RValue || LangOpts.CPlusPlus ||
Douglas Gregor5476205b2011-06-23 00:49:38 +00003417 !ResultType.isCForbiddenLValueType());
John McCall4bc41ae2010-11-18 19:01:18 +00003418
Mike Stump4e1f26a2009-02-19 03:04:26 +00003419 return Owned(new (Context) ArraySubscriptExpr(LHSExp, RHSExp,
John McCall7decc9e2010-11-18 06:31:45 +00003420 ResultType, VK, OK, RLoc));
Chris Lattnere168f762006-11-10 05:29:30 +00003421}
3422
John McCalldadc5752010-08-24 06:29:42 +00003423ExprResult Sema::BuildCXXDefaultArgExpr(SourceLocation CallLoc,
Nico Weber44887f62010-11-29 18:19:25 +00003424 FunctionDecl *FD,
3425 ParmVarDecl *Param) {
Anders Carlsson355933d2009-08-25 03:49:14 +00003426 if (Param->hasUnparsedDefaultArg()) {
Douglas Gregor8a01b2a2010-09-11 20:24:53 +00003427 Diag(CallLoc,
Nico Weberebd45a02010-11-30 04:44:33 +00003428 diag::err_use_of_default_argument_to_function_declared_later) <<
Anders Carlsson355933d2009-08-25 03:49:14 +00003429 FD << cast<CXXRecordDecl>(FD->getDeclContext())->getDeclName();
Mike Stump11289f42009-09-09 15:08:12 +00003430 Diag(UnparsedDefaultArgLocs[Param],
Nico Weberebd45a02010-11-30 04:44:33 +00003431 diag::note_default_argument_declared_here);
Douglas Gregor8a01b2a2010-09-11 20:24:53 +00003432 return ExprError();
3433 }
3434
3435 if (Param->hasUninstantiatedDefaultArg()) {
3436 Expr *UninstExpr = Param->getUninstantiatedDefaultArg();
Anders Carlsson355933d2009-08-25 03:49:14 +00003437
Richard Smith505df232012-07-22 23:45:10 +00003438 EnterExpressionEvaluationContext EvalContext(*this, PotentiallyEvaluated,
3439 Param);
3440
Douglas Gregor8a01b2a2010-09-11 20:24:53 +00003441 // Instantiate the expression.
3442 MultiLevelTemplateArgumentList ArgList
3443 = getTemplateInstantiationArgs(FD, 0, /*RelativeToPrimary=*/true);
Anders Carlsson657bad42009-09-05 05:14:19 +00003444
Nico Weber44887f62010-11-29 18:19:25 +00003445 std::pair<const TemplateArgument *, unsigned> Innermost
Douglas Gregor8a01b2a2010-09-11 20:24:53 +00003446 = ArgList.getInnermost();
Richard Smith80934652012-07-16 01:09:10 +00003447 InstantiatingTemplate Inst(*this, CallLoc, Param,
3448 ArrayRef<TemplateArgument>(Innermost.first,
3449 Innermost.second));
Richard Smith8a874c92012-07-08 02:38:24 +00003450 if (Inst)
3451 return ExprError();
Anders Carlsson355933d2009-08-25 03:49:14 +00003452
Nico Weber44887f62010-11-29 18:19:25 +00003453 ExprResult Result;
3454 {
3455 // C++ [dcl.fct.default]p5:
3456 // The names in the [default argument] expression are bound, and
3457 // the semantic constraints are checked, at the point where the
3458 // default argument expression appears.
Nico Weberebd45a02010-11-30 04:44:33 +00003459 ContextRAII SavedContext(*this, FD);
Douglas Gregora86bc002012-02-16 21:36:18 +00003460 LocalInstantiationScope Local(*this);
Nico Weber44887f62010-11-29 18:19:25 +00003461 Result = SubstExpr(UninstExpr, ArgList);
3462 }
Douglas Gregor8a01b2a2010-09-11 20:24:53 +00003463 if (Result.isInvalid())
3464 return ExprError();
Mike Stump11289f42009-09-09 15:08:12 +00003465
Douglas Gregor8a01b2a2010-09-11 20:24:53 +00003466 // Check the expression as an initializer for the parameter.
3467 InitializedEntity Entity
Fariborz Jahanian8fb87ae2010-09-24 17:30:16 +00003468 = InitializedEntity::InitializeParameter(Context, Param);
Douglas Gregor8a01b2a2010-09-11 20:24:53 +00003469 InitializationKind Kind
3470 = InitializationKind::CreateCopy(Param->getLocation(),
Daniel Dunbar62ee6412012-03-09 18:35:03 +00003471 /*FIXME:EqualLoc*/UninstExpr->getLocStart());
Douglas Gregor8a01b2a2010-09-11 20:24:53 +00003472 Expr *ResultE = Result.takeAs<Expr>();
Douglas Gregor25ab25f2009-12-23 18:19:08 +00003473
Douglas Gregor8a01b2a2010-09-11 20:24:53 +00003474 InitializationSequence InitSeq(*this, Entity, Kind, &ResultE, 1);
Benjamin Kramercc4c49d2012-08-23 23:38:35 +00003475 Result = InitSeq.Perform(*this, Entity, Kind, ResultE);
Douglas Gregor8a01b2a2010-09-11 20:24:53 +00003476 if (Result.isInvalid())
3477 return ExprError();
Kovarththanan Rajaratnamba2c6522010-03-13 10:17:05 +00003478
David Blaikief68e8092012-04-30 18:21:31 +00003479 Expr *Arg = Result.takeAs<Expr>();
David Blaikie18e9ac72012-05-15 21:57:38 +00003480 CheckImplicitConversions(Arg, Param->getOuterLocStart());
Douglas Gregor8a01b2a2010-09-11 20:24:53 +00003481 // Build the default argument expression.
David Blaikief68e8092012-04-30 18:21:31 +00003482 return Owned(CXXDefaultArgExpr::Create(Context, CallLoc, Param, Arg));
Anders Carlsson355933d2009-08-25 03:49:14 +00003483 }
3484
Douglas Gregor8a01b2a2010-09-11 20:24:53 +00003485 // If the default expression creates temporaries, we need to
3486 // push them to the current stack of expression temporaries so they'll
3487 // be properly destroyed.
3488 // FIXME: We should really be rebuilding the default argument with new
3489 // bound temporaries; see the comment in PR5810.
John McCall28fc7092011-11-10 05:35:25 +00003490 // We don't need to do that with block decls, though, because
3491 // blocks in default argument expression can never capture anything.
3492 if (isa<ExprWithCleanups>(Param->getInit())) {
3493 // Set the "needs cleanups" bit regardless of whether there are
3494 // any explicit objects.
John McCall31168b02011-06-15 23:02:42 +00003495 ExprNeedsCleanups = true;
John McCall28fc7092011-11-10 05:35:25 +00003496
3497 // Append all the objects to the cleanup list. Right now, this
3498 // should always be a no-op, because blocks in default argument
3499 // expressions should never be able to capture anything.
3500 assert(!cast<ExprWithCleanups>(Param->getInit())->getNumObjects() &&
3501 "default argument expression has capturing blocks?");
Douglas Gregor6ed2fee2010-09-14 22:55:20 +00003502 }
Douglas Gregor8a01b2a2010-09-11 20:24:53 +00003503
3504 // We already type-checked the argument, so we know it works.
Douglas Gregor32b3de52010-09-11 23:32:50 +00003505 // Just mark all of the declarations in this potentially-evaluated expression
3506 // as being "referenced".
Douglas Gregor680e9e02012-02-21 19:11:17 +00003507 MarkDeclarationsReferencedInExpr(Param->getDefaultArg(),
3508 /*SkipLocalVariables=*/true);
Douglas Gregor033f6752009-12-23 23:03:06 +00003509 return Owned(CXXDefaultArgExpr::Create(Context, CallLoc, Param));
Anders Carlsson355933d2009-08-25 03:49:14 +00003510}
3511
Richard Smith55ce3522012-06-25 20:30:08 +00003512
3513Sema::VariadicCallType
3514Sema::getVariadicCallType(FunctionDecl *FDecl, const FunctionProtoType *Proto,
3515 Expr *Fn) {
3516 if (Proto && Proto->isVariadic()) {
3517 if (dyn_cast_or_null<CXXConstructorDecl>(FDecl))
3518 return VariadicConstructor;
3519 else if (Fn && Fn->getType()->isBlockPointerType())
3520 return VariadicBlock;
3521 else if (FDecl) {
3522 if (CXXMethodDecl *Method = dyn_cast_or_null<CXXMethodDecl>(FDecl))
3523 if (Method->isInstance())
3524 return VariadicMethod;
3525 }
3526 return VariadicFunction;
3527 }
3528 return VariadicDoesNotApply;
3529}
3530
Douglas Gregor97fd6e22008-12-22 05:46:06 +00003531/// ConvertArgumentsForCall - Converts the arguments specified in
3532/// Args/NumArgs to the parameter types of the function FDecl with
3533/// function prototype Proto. Call is the call expression itself, and
3534/// Fn is the function expression. For a C++ member function, this
3535/// routine does not attempt to convert the object argument. Returns
3536/// true if the call is ill-formed.
Mike Stump4e1f26a2009-02-19 03:04:26 +00003537bool
3538Sema::ConvertArgumentsForCall(CallExpr *Call, Expr *Fn,
Douglas Gregor97fd6e22008-12-22 05:46:06 +00003539 FunctionDecl *FDecl,
Douglas Gregordeaad8c2009-02-26 23:50:07 +00003540 const FunctionProtoType *Proto,
Douglas Gregor97fd6e22008-12-22 05:46:06 +00003541 Expr **Args, unsigned NumArgs,
Peter Collingbourne619a8c72011-10-02 23:49:29 +00003542 SourceLocation RParenLoc,
3543 bool IsExecConfig) {
John McCallbebede42011-02-26 05:39:39 +00003544 // Bail out early if calling a builtin with custom typechecking.
3545 // We don't need to do this in the
3546 if (FDecl)
3547 if (unsigned ID = FDecl->getBuiltinID())
3548 if (Context.BuiltinInfo.hasCustomTypechecking(ID))
3549 return false;
3550
Mike Stump4e1f26a2009-02-19 03:04:26 +00003551 // C99 6.5.2.2p7 - the arguments are implicitly converted, as if by
Douglas Gregor97fd6e22008-12-22 05:46:06 +00003552 // assignment, to the types of the corresponding parameter, ...
3553 unsigned NumArgsInProto = Proto->getNumArgs();
Douglas Gregorb6b99612009-01-23 21:30:56 +00003554 bool Invalid = false;
Peter Collingbourne740afe22011-10-02 23:49:20 +00003555 unsigned MinArgs = FDecl ? FDecl->getMinRequiredArguments() : NumArgsInProto;
Peter Collingbourne619a8c72011-10-02 23:49:29 +00003556 unsigned FnKind = Fn->getType()->isBlockPointerType()
3557 ? 1 /* block */
3558 : (IsExecConfig ? 3 /* kernel function (exec config) */
3559 : 0 /* function */);
Kovarththanan Rajaratnamba2c6522010-03-13 10:17:05 +00003560
Douglas Gregor97fd6e22008-12-22 05:46:06 +00003561 // If too few arguments are available (and we don't have default
3562 // arguments for the remaining parameters), don't make the call.
3563 if (NumArgs < NumArgsInProto) {
Peter Collingbourne740afe22011-10-02 23:49:20 +00003564 if (NumArgs < MinArgs) {
Richard Smith10ff50d2012-05-11 05:16:41 +00003565 if (MinArgs == 1 && FDecl && FDecl->getParamDecl(0)->getDeclName())
3566 Diag(RParenLoc, MinArgs == NumArgsInProto && !Proto->isVariadic()
3567 ? diag::err_typecheck_call_too_few_args_one
3568 : diag::err_typecheck_call_too_few_args_at_least_one)
3569 << FnKind
3570 << FDecl->getParamDecl(0) << Fn->getSourceRange();
3571 else
3572 Diag(RParenLoc, MinArgs == NumArgsInProto && !Proto->isVariadic()
3573 ? diag::err_typecheck_call_too_few_args
3574 : diag::err_typecheck_call_too_few_args_at_least)
3575 << FnKind
3576 << MinArgs << NumArgs << Fn->getSourceRange();
Peter Collingbourne3bc84ca2011-07-29 00:24:42 +00003577
3578 // Emit the location of the prototype.
Peter Collingbourne619a8c72011-10-02 23:49:29 +00003579 if (FDecl && !FDecl->getBuiltinID() && !IsExecConfig)
Peter Collingbourne3bc84ca2011-07-29 00:24:42 +00003580 Diag(FDecl->getLocStart(), diag::note_callee_decl)
3581 << FDecl;
3582
3583 return true;
3584 }
Ted Kremenek5a201952009-02-07 01:47:29 +00003585 Call->setNumArgs(Context, NumArgsInProto);
Douglas Gregor97fd6e22008-12-22 05:46:06 +00003586 }
3587
3588 // If too many are passed and not variadic, error on the extras and drop
3589 // them.
3590 if (NumArgs > NumArgsInProto) {
3591 if (!Proto->isVariadic()) {
Richard Smithd72da152012-05-15 06:21:54 +00003592 if (NumArgsInProto == 1 && FDecl && FDecl->getParamDecl(0)->getDeclName())
3593 Diag(Args[NumArgsInProto]->getLocStart(),
3594 MinArgs == NumArgsInProto
3595 ? diag::err_typecheck_call_too_many_args_one
3596 : diag::err_typecheck_call_too_many_args_at_most_one)
3597 << FnKind
3598 << FDecl->getParamDecl(0) << NumArgs << Fn->getSourceRange()
3599 << SourceRange(Args[NumArgsInProto]->getLocStart(),
3600 Args[NumArgs-1]->getLocEnd());
3601 else
3602 Diag(Args[NumArgsInProto]->getLocStart(),
3603 MinArgs == NumArgsInProto
3604 ? diag::err_typecheck_call_too_many_args
3605 : diag::err_typecheck_call_too_many_args_at_most)
3606 << FnKind
3607 << NumArgsInProto << NumArgs << Fn->getSourceRange()
3608 << SourceRange(Args[NumArgsInProto]->getLocStart(),
3609 Args[NumArgs-1]->getLocEnd());
Ted Kremenek99a337e2011-04-04 17:22:27 +00003610
3611 // Emit the location of the prototype.
Peter Collingbourne619a8c72011-10-02 23:49:29 +00003612 if (FDecl && !FDecl->getBuiltinID() && !IsExecConfig)
Peter Collingbourne3bc84ca2011-07-29 00:24:42 +00003613 Diag(FDecl->getLocStart(), diag::note_callee_decl)
3614 << FDecl;
Ted Kremenek99a337e2011-04-04 17:22:27 +00003615
Douglas Gregor97fd6e22008-12-22 05:46:06 +00003616 // This deletes the extra arguments.
Ted Kremenek5a201952009-02-07 01:47:29 +00003617 Call->setNumArgs(Context, NumArgsInProto);
Fariborz Jahanian835026e2009-11-24 18:29:37 +00003618 return true;
Douglas Gregor97fd6e22008-12-22 05:46:06 +00003619 }
Douglas Gregor97fd6e22008-12-22 05:46:06 +00003620 }
Chris Lattner0e62c1c2011-07-23 10:55:15 +00003621 SmallVector<Expr *, 8> AllArgs;
Richard Smith55ce3522012-06-25 20:30:08 +00003622 VariadicCallType CallType = getVariadicCallType(FDecl, Proto, Fn);
3623
Daniel Dunbar62ee6412012-03-09 18:35:03 +00003624 Invalid = GatherArgumentsForCall(Call->getLocStart(), FDecl,
Fariborz Jahanian4fa66ce2009-11-24 21:37:28 +00003625 Proto, 0, Args, NumArgs, AllArgs, CallType);
Fariborz Jahanian835026e2009-11-24 18:29:37 +00003626 if (Invalid)
3627 return true;
3628 unsigned TotalNumArgs = AllArgs.size();
3629 for (unsigned i = 0; i < TotalNumArgs; ++i)
3630 Call->setArg(i, AllArgs[i]);
Kovarththanan Rajaratnamba2c6522010-03-13 10:17:05 +00003631
Fariborz Jahanian835026e2009-11-24 18:29:37 +00003632 return false;
3633}
Mike Stump4e1f26a2009-02-19 03:04:26 +00003634
Fariborz Jahanian835026e2009-11-24 18:29:37 +00003635bool Sema::GatherArgumentsForCall(SourceLocation CallLoc,
3636 FunctionDecl *FDecl,
3637 const FunctionProtoType *Proto,
3638 unsigned FirstProtoArg,
3639 Expr **Args, unsigned NumArgs,
Chris Lattner0e62c1c2011-07-23 10:55:15 +00003640 SmallVector<Expr *, 8> &AllArgs,
Douglas Gregor6073dca2012-02-24 23:56:31 +00003641 VariadicCallType CallType,
3642 bool AllowExplicit) {
Fariborz Jahanian835026e2009-11-24 18:29:37 +00003643 unsigned NumArgsInProto = Proto->getNumArgs();
3644 unsigned NumArgsToCheck = NumArgs;
3645 bool Invalid = false;
3646 if (NumArgs != NumArgsInProto)
3647 // Use default arguments for missing arguments
3648 NumArgsToCheck = NumArgsInProto;
3649 unsigned ArgIx = 0;
Douglas Gregor97fd6e22008-12-22 05:46:06 +00003650 // Continue to check argument types (even if we have too few/many args).
Fariborz Jahanian835026e2009-11-24 18:29:37 +00003651 for (unsigned i = FirstProtoArg; i != NumArgsToCheck; i++) {
Douglas Gregor97fd6e22008-12-22 05:46:06 +00003652 QualType ProtoArgType = Proto->getArgType(i);
Kovarththanan Rajaratnamba2c6522010-03-13 10:17:05 +00003653
Douglas Gregor97fd6e22008-12-22 05:46:06 +00003654 Expr *Arg;
Peter Collingbournea48f33f2011-10-19 00:16:45 +00003655 ParmVarDecl *Param;
Fariborz Jahanian835026e2009-11-24 18:29:37 +00003656 if (ArgIx < NumArgs) {
3657 Arg = Args[ArgIx++];
Kovarththanan Rajaratnamba2c6522010-03-13 10:17:05 +00003658
Daniel Dunbar62ee6412012-03-09 18:35:03 +00003659 if (RequireCompleteType(Arg->getLocStart(),
Eli Friedman3164fb12009-03-22 22:00:50 +00003660 ProtoArgType,
Douglas Gregor7bfb2d02012-05-04 16:32:21 +00003661 diag::err_call_incomplete_argument, Arg))
Eli Friedman3164fb12009-03-22 22:00:50 +00003662 return true;
Kovarththanan Rajaratnamba2c6522010-03-13 10:17:05 +00003663
Douglas Gregorbbeb5c32009-12-22 16:09:06 +00003664 // Pass the argument
Peter Collingbournea48f33f2011-10-19 00:16:45 +00003665 Param = 0;
Douglas Gregorbbeb5c32009-12-22 16:09:06 +00003666 if (FDecl && i < FDecl->getNumParams())
3667 Param = FDecl->getParamDecl(i);
Douglas Gregor96596c92009-12-22 07:24:36 +00003668
John McCall4124c492011-10-17 18:40:02 +00003669 // Strip the unbridged-cast placeholder expression off, if applicable.
3670 if (Arg->getType() == Context.ARCUnbridgedCastTy &&
3671 FDecl && FDecl->hasAttr<CFAuditedTransferAttr>() &&
3672 (!Param || !Param->hasAttr<CFConsumedAttr>()))
3673 Arg = stripARCUnbridgedCast(Arg);
3674
Douglas Gregorbbeb5c32009-12-22 16:09:06 +00003675 InitializedEntity Entity =
Fariborz Jahanian8fb87ae2010-09-24 17:30:16 +00003676 Param? InitializedEntity::InitializeParameter(Context, Param)
John McCall31168b02011-06-15 23:02:42 +00003677 : InitializedEntity::InitializeParameter(Context, ProtoArgType,
3678 Proto->isArgConsumed(i));
John McCalldadc5752010-08-24 06:29:42 +00003679 ExprResult ArgE = PerformCopyInitialization(Entity,
John McCall34376a62010-12-04 03:47:34 +00003680 SourceLocation(),
Douglas Gregor6073dca2012-02-24 23:56:31 +00003681 Owned(Arg),
3682 /*TopLevelOfInitList=*/false,
3683 AllowExplicit);
Douglas Gregorbbeb5c32009-12-22 16:09:06 +00003684 if (ArgE.isInvalid())
3685 return true;
3686
3687 Arg = ArgE.takeAs<Expr>();
Anders Carlsson84613c42009-06-12 16:51:40 +00003688 } else {
Peter Collingbournea48f33f2011-10-19 00:16:45 +00003689 Param = FDecl->getParamDecl(i);
Kovarththanan Rajaratnamba2c6522010-03-13 10:17:05 +00003690
John McCalldadc5752010-08-24 06:29:42 +00003691 ExprResult ArgExpr =
Fariborz Jahanian835026e2009-11-24 18:29:37 +00003692 BuildCXXDefaultArgExpr(CallLoc, FDecl, Param);
Anders Carlsson355933d2009-08-25 03:49:14 +00003693 if (ArgExpr.isInvalid())
3694 return true;
Kovarththanan Rajaratnamba2c6522010-03-13 10:17:05 +00003695
Anders Carlsson355933d2009-08-25 03:49:14 +00003696 Arg = ArgExpr.takeAs<Expr>();
Anders Carlsson84613c42009-06-12 16:51:40 +00003697 }
Kaelyn Uhrain2e7aa5a2011-08-05 23:18:04 +00003698
3699 // Check for array bounds violations for each argument to the call. This
3700 // check only triggers warnings when the argument isn't a more complex Expr
3701 // with its own checking, such as a BinaryOperator.
3702 CheckArrayAccess(Arg);
3703
Peter Collingbournea48f33f2011-10-19 00:16:45 +00003704 // Check for violations of C99 static array rules (C99 6.7.5.3p7).
3705 CheckStaticArrayArgument(CallLoc, Param, Arg);
3706
Fariborz Jahanian835026e2009-11-24 18:29:37 +00003707 AllArgs.push_back(Arg);
Douglas Gregor97fd6e22008-12-22 05:46:06 +00003708 }
Kovarththanan Rajaratnamba2c6522010-03-13 10:17:05 +00003709
Douglas Gregor97fd6e22008-12-22 05:46:06 +00003710 // If this is a variadic call, handle args passed through "...".
Fariborz Jahanian6f2d25e2009-11-24 19:27:49 +00003711 if (CallType != VariadicDoesNotApply) {
John McCall2979fe02011-04-12 00:42:48 +00003712 // Assume that extern "C" functions with variadic arguments that
3713 // return __unknown_anytype aren't *really* variadic.
3714 if (Proto->getResultType() == Context.UnknownAnyTy &&
3715 FDecl && FDecl->isExternC()) {
3716 for (unsigned i = ArgIx; i != NumArgs; ++i) {
3717 ExprResult arg;
3718 if (isa<ExplicitCastExpr>(Args[i]->IgnoreParens()))
3719 arg = DefaultFunctionArrayLvalueConversion(Args[i]);
3720 else
3721 arg = DefaultVariadicArgumentPromotion(Args[i], CallType, FDecl);
3722 Invalid |= arg.isInvalid();
3723 AllArgs.push_back(arg.take());
3724 }
3725
3726 // Otherwise do argument promotion, (C99 6.5.2.2p7).
3727 } else {
3728 for (unsigned i = ArgIx; i != NumArgs; ++i) {
Richard Trieucfc491d2011-08-02 04:35:43 +00003729 ExprResult Arg = DefaultVariadicArgumentPromotion(Args[i], CallType,
3730 FDecl);
John McCall2979fe02011-04-12 00:42:48 +00003731 Invalid |= Arg.isInvalid();
3732 AllArgs.push_back(Arg.take());
3733 }
Douglas Gregor97fd6e22008-12-22 05:46:06 +00003734 }
Ted Kremenekd41f3462011-09-26 23:36:13 +00003735
3736 // Check for array bounds violations.
3737 for (unsigned i = ArgIx; i != NumArgs; ++i)
3738 CheckArrayAccess(Args[i]);
Douglas Gregor97fd6e22008-12-22 05:46:06 +00003739 }
Douglas Gregorb6b99612009-01-23 21:30:56 +00003740 return Invalid;
Douglas Gregor97fd6e22008-12-22 05:46:06 +00003741}
3742
Peter Collingbournea48f33f2011-10-19 00:16:45 +00003743static void DiagnoseCalleeStaticArrayParam(Sema &S, ParmVarDecl *PVD) {
3744 TypeLoc TL = PVD->getTypeSourceInfo()->getTypeLoc();
3745 if (ArrayTypeLoc *ATL = dyn_cast<ArrayTypeLoc>(&TL))
3746 S.Diag(PVD->getLocation(), diag::note_callee_static_array)
3747 << ATL->getLocalSourceRange();
3748}
3749
3750/// CheckStaticArrayArgument - If the given argument corresponds to a static
3751/// array parameter, check that it is non-null, and that if it is formed by
3752/// array-to-pointer decay, the underlying array is sufficiently large.
3753///
3754/// C99 6.7.5.3p7: If the keyword static also appears within the [ and ] of the
3755/// array type derivation, then for each call to the function, the value of the
3756/// corresponding actual argument shall provide access to the first element of
3757/// an array with at least as many elements as specified by the size expression.
3758void
3759Sema::CheckStaticArrayArgument(SourceLocation CallLoc,
3760 ParmVarDecl *Param,
3761 const Expr *ArgExpr) {
3762 // Static array parameters are not supported in C++.
David Blaikiebbafb8a2012-03-11 07:00:24 +00003763 if (!Param || getLangOpts().CPlusPlus)
Peter Collingbournea48f33f2011-10-19 00:16:45 +00003764 return;
3765
3766 QualType OrigTy = Param->getOriginalType();
3767
3768 const ArrayType *AT = Context.getAsArrayType(OrigTy);
3769 if (!AT || AT->getSizeModifier() != ArrayType::Static)
3770 return;
3771
3772 if (ArgExpr->isNullPointerConstant(Context,
3773 Expr::NPC_NeverValueDependent)) {
3774 Diag(CallLoc, diag::warn_null_arg) << ArgExpr->getSourceRange();
3775 DiagnoseCalleeStaticArrayParam(*this, Param);
3776 return;
3777 }
3778
3779 const ConstantArrayType *CAT = dyn_cast<ConstantArrayType>(AT);
3780 if (!CAT)
3781 return;
3782
3783 const ConstantArrayType *ArgCAT =
3784 Context.getAsConstantArrayType(ArgExpr->IgnoreParenImpCasts()->getType());
3785 if (!ArgCAT)
3786 return;
3787
3788 if (ArgCAT->getSize().ult(CAT->getSize())) {
3789 Diag(CallLoc, diag::warn_static_array_too_small)
3790 << ArgExpr->getSourceRange()
3791 << (unsigned) ArgCAT->getSize().getZExtValue()
3792 << (unsigned) CAT->getSize().getZExtValue();
3793 DiagnoseCalleeStaticArrayParam(*this, Param);
3794 }
3795}
3796
John McCall2979fe02011-04-12 00:42:48 +00003797/// Given a function expression of unknown-any type, try to rebuild it
3798/// to have a function type.
3799static ExprResult rebuildUnknownAnyFunction(Sema &S, Expr *fn);
3800
Steve Naroff83895f72007-09-16 03:34:24 +00003801/// ActOnCallExpr - Handle a call to Fn with the specified array of arguments.
Chris Lattnere168f762006-11-10 05:29:30 +00003802/// This provides the location of the left/right parens and a list of comma
3803/// locations.
John McCalldadc5752010-08-24 06:29:42 +00003804ExprResult
John McCallb268a282010-08-23 23:25:46 +00003805Sema::ActOnCallExpr(Scope *S, Expr *Fn, SourceLocation LParenLoc,
Richard Trieuba63ce62011-09-09 01:45:06 +00003806 MultiExprArg ArgExprs, SourceLocation RParenLoc,
Peter Collingbourne619a8c72011-10-02 23:49:29 +00003807 Expr *ExecConfig, bool IsExecConfig) {
Nate Begeman5ec4b312009-08-10 23:49:36 +00003808 // Since this might be a postfix expression, get rid of ParenListExprs.
John McCalldadc5752010-08-24 06:29:42 +00003809 ExprResult Result = MaybeConvertParenListExprToParenExpr(S, Fn);
John McCallb268a282010-08-23 23:25:46 +00003810 if (Result.isInvalid()) return ExprError();
3811 Fn = Result.take();
Mike Stump11289f42009-09-09 15:08:12 +00003812
David Blaikiebbafb8a2012-03-11 07:00:24 +00003813 if (getLangOpts().CPlusPlus) {
Douglas Gregorad8a3362009-09-04 17:36:40 +00003814 // If this is a pseudo-destructor expression, build the call immediately.
3815 if (isa<CXXPseudoDestructorExpr>(Fn)) {
Benjamin Kramerc215e762012-08-24 11:54:20 +00003816 if (!ArgExprs.empty()) {
Douglas Gregorad8a3362009-09-04 17:36:40 +00003817 // Pseudo-destructor calls should not have any arguments.
3818 Diag(Fn->getLocStart(), diag::err_pseudo_dtor_call_with_args)
Douglas Gregora771f462010-03-31 17:46:05 +00003819 << FixItHint::CreateRemoval(
Benjamin Kramerc215e762012-08-24 11:54:20 +00003820 SourceRange(ArgExprs[0]->getLocStart(),
3821 ArgExprs.back()->getLocEnd()));
Douglas Gregorad8a3362009-09-04 17:36:40 +00003822 }
Mike Stump11289f42009-09-09 15:08:12 +00003823
Benjamin Kramerc215e762012-08-24 11:54:20 +00003824 return Owned(new (Context) CallExpr(Context, Fn, MultiExprArg(),
3825 Context.VoidTy, VK_RValue,
3826 RParenLoc));
Douglas Gregorad8a3362009-09-04 17:36:40 +00003827 }
Mike Stump11289f42009-09-09 15:08:12 +00003828
Douglas Gregorb8a9a412009-02-04 15:01:18 +00003829 // Determine whether this is a dependent call inside a C++ template,
Mike Stump4e1f26a2009-02-19 03:04:26 +00003830 // in which case we won't do any semantic analysis now.
Mike Stump87c57ac2009-05-16 07:39:55 +00003831 // FIXME: Will need to cache the results of name lookup (including ADL) in
3832 // Fn.
Douglas Gregorb8a9a412009-02-04 15:01:18 +00003833 bool Dependent = false;
3834 if (Fn->isTypeDependent())
3835 Dependent = true;
Benjamin Kramerc215e762012-08-24 11:54:20 +00003836 else if (Expr::hasAnyTypeDependentArguments(ArgExprs))
Douglas Gregorb8a9a412009-02-04 15:01:18 +00003837 Dependent = true;
3838
Peter Collingbourne41f85462011-02-09 21:07:24 +00003839 if (Dependent) {
3840 if (ExecConfig) {
3841 return Owned(new (Context) CUDAKernelCallExpr(
Benjamin Kramerc215e762012-08-24 11:54:20 +00003842 Context, Fn, cast<CallExpr>(ExecConfig), ArgExprs,
Peter Collingbourne41f85462011-02-09 21:07:24 +00003843 Context.DependentTy, VK_RValue, RParenLoc));
3844 } else {
Benjamin Kramerc215e762012-08-24 11:54:20 +00003845 return Owned(new (Context) CallExpr(Context, Fn, ArgExprs,
Peter Collingbourne41f85462011-02-09 21:07:24 +00003846 Context.DependentTy, VK_RValue,
3847 RParenLoc));
3848 }
3849 }
Douglas Gregorb8a9a412009-02-04 15:01:18 +00003850
3851 // Determine whether this is a call to an object (C++ [over.call.object]).
3852 if (Fn->getType()->isRecordType())
Benjamin Kramerc215e762012-08-24 11:54:20 +00003853 return Owned(BuildCallToObjectOfClassType(S, Fn, LParenLoc,
3854 ArgExprs.data(),
3855 ArgExprs.size(), RParenLoc));
Douglas Gregorb8a9a412009-02-04 15:01:18 +00003856
John McCall2979fe02011-04-12 00:42:48 +00003857 if (Fn->getType() == Context.UnknownAnyTy) {
3858 ExprResult result = rebuildUnknownAnyFunction(*this, Fn);
3859 if (result.isInvalid()) return ExprError();
3860 Fn = result.take();
3861 }
3862
John McCall0009fcc2011-04-26 20:42:42 +00003863 if (Fn->getType() == Context.BoundMemberTy) {
Benjamin Kramerc215e762012-08-24 11:54:20 +00003864 return BuildCallToMemberFunction(S, Fn, LParenLoc, ArgExprs.data(),
3865 ArgExprs.size(), RParenLoc);
John McCall10eae182009-11-30 22:42:35 +00003866 }
John McCall0009fcc2011-04-26 20:42:42 +00003867 }
John McCall10eae182009-11-30 22:42:35 +00003868
John McCall0009fcc2011-04-26 20:42:42 +00003869 // Check for overloaded calls. This can happen even in C due to extensions.
3870 if (Fn->getType() == Context.OverloadTy) {
3871 OverloadExpr::FindResult find = OverloadExpr::find(Fn);
3872
Douglas Gregorcda22702011-10-13 18:10:35 +00003873 // We aren't supposed to apply this logic for if there's an '&' involved.
Douglas Gregorf4a06c22011-10-13 18:26:27 +00003874 if (!find.HasFormOfMemberPointer) {
John McCall0009fcc2011-04-26 20:42:42 +00003875 OverloadExpr *ovl = find.Expression;
3876 if (isa<UnresolvedLookupExpr>(ovl)) {
3877 UnresolvedLookupExpr *ULE = cast<UnresolvedLookupExpr>(ovl);
Benjamin Kramerc215e762012-08-24 11:54:20 +00003878 return BuildOverloadedCallExpr(S, Fn, ULE, LParenLoc, ArgExprs.data(),
3879 ArgExprs.size(), RParenLoc, ExecConfig);
John McCall0009fcc2011-04-26 20:42:42 +00003880 } else {
Benjamin Kramerc215e762012-08-24 11:54:20 +00003881 return BuildCallToMemberFunction(S, Fn, LParenLoc, ArgExprs.data(),
3882 ArgExprs.size(), RParenLoc);
Anders Carlsson61914b52009-10-03 17:40:22 +00003883 }
3884 }
Douglas Gregor97fd6e22008-12-22 05:46:06 +00003885 }
3886
Douglas Gregore254f902009-02-04 00:32:51 +00003887 // If we're directly calling a function, get the appropriate declaration.
Douglas Gregord8fb1e32011-12-01 01:37:36 +00003888 if (Fn->getType() == Context.UnknownAnyTy) {
3889 ExprResult result = rebuildUnknownAnyFunction(*this, Fn);
3890 if (result.isInvalid()) return ExprError();
3891 Fn = result.take();
3892 }
Mike Stump4e1f26a2009-02-19 03:04:26 +00003893
Eli Friedmane14b1992009-12-26 03:35:45 +00003894 Expr *NakedFn = Fn->IgnoreParens();
Douglas Gregor928479e2010-11-09 20:03:54 +00003895
John McCall57500772009-12-16 12:17:52 +00003896 NamedDecl *NDecl = 0;
Douglas Gregor59f16ed2010-10-25 20:48:33 +00003897 if (UnaryOperator *UnOp = dyn_cast<UnaryOperator>(NakedFn))
3898 if (UnOp->getOpcode() == UO_AddrOf)
3899 NakedFn = UnOp->getSubExpr()->IgnoreParens();
3900
John McCall57500772009-12-16 12:17:52 +00003901 if (isa<DeclRefExpr>(NakedFn))
3902 NDecl = cast<DeclRefExpr>(NakedFn)->getDecl();
John McCall0009fcc2011-04-26 20:42:42 +00003903 else if (isa<MemberExpr>(NakedFn))
3904 NDecl = cast<MemberExpr>(NakedFn)->getMemberDecl();
John McCall57500772009-12-16 12:17:52 +00003905
Benjamin Kramerc215e762012-08-24 11:54:20 +00003906 return BuildResolvedCallExpr(Fn, NDecl, LParenLoc, ArgExprs.data(),
3907 ArgExprs.size(), RParenLoc, ExecConfig,
3908 IsExecConfig);
Peter Collingbourne41f85462011-02-09 21:07:24 +00003909}
3910
3911ExprResult
3912Sema::ActOnCUDAExecConfigExpr(Scope *S, SourceLocation LLLLoc,
Richard Trieuba63ce62011-09-09 01:45:06 +00003913 MultiExprArg ExecConfig, SourceLocation GGGLoc) {
Peter Collingbourne41f85462011-02-09 21:07:24 +00003914 FunctionDecl *ConfigDecl = Context.getcudaConfigureCallDecl();
3915 if (!ConfigDecl)
3916 return ExprError(Diag(LLLLoc, diag::err_undeclared_var_use)
3917 << "cudaConfigureCall");
3918 QualType ConfigQTy = ConfigDecl->getType();
3919
3920 DeclRefExpr *ConfigDR = new (Context) DeclRefExpr(
John McCall113bee02012-03-10 09:33:50 +00003921 ConfigDecl, false, ConfigQTy, VK_LValue, LLLLoc);
Eli Friedmanfa0df832012-02-02 03:46:19 +00003922 MarkFunctionReferenced(LLLLoc, ConfigDecl);
Peter Collingbourne41f85462011-02-09 21:07:24 +00003923
Peter Collingbourne619a8c72011-10-02 23:49:29 +00003924 return ActOnCallExpr(S, ConfigDR, LLLLoc, ExecConfig, GGGLoc, 0,
3925 /*IsExecConfig=*/true);
John McCall2d74de92009-12-01 22:10:20 +00003926}
3927
Tanya Lattner55808c12011-06-04 00:47:47 +00003928/// ActOnAsTypeExpr - create a new asType (bitcast) from the arguments.
3929///
3930/// __builtin_astype( value, dst type )
3931///
Richard Trieuba63ce62011-09-09 01:45:06 +00003932ExprResult Sema::ActOnAsTypeExpr(Expr *E, ParsedType ParsedDestTy,
Tanya Lattner55808c12011-06-04 00:47:47 +00003933 SourceLocation BuiltinLoc,
3934 SourceLocation RParenLoc) {
3935 ExprValueKind VK = VK_RValue;
3936 ExprObjectKind OK = OK_Ordinary;
Richard Trieuba63ce62011-09-09 01:45:06 +00003937 QualType DstTy = GetTypeFromParser(ParsedDestTy);
3938 QualType SrcTy = E->getType();
Tanya Lattner55808c12011-06-04 00:47:47 +00003939 if (Context.getTypeSize(DstTy) != Context.getTypeSize(SrcTy))
3940 return ExprError(Diag(BuiltinLoc,
3941 diag::err_invalid_astype_of_different_size)
Peter Collingbourne23f1bee2011-06-08 15:15:17 +00003942 << DstTy
3943 << SrcTy
Richard Trieuba63ce62011-09-09 01:45:06 +00003944 << E->getSourceRange());
3945 return Owned(new (Context) AsTypeExpr(E, DstTy, VK, OK, BuiltinLoc,
Richard Trieucfc491d2011-08-02 04:35:43 +00003946 RParenLoc));
Tanya Lattner55808c12011-06-04 00:47:47 +00003947}
3948
John McCall57500772009-12-16 12:17:52 +00003949/// BuildResolvedCallExpr - Build a call to a resolved expression,
3950/// i.e. an expression not of \p OverloadTy. The expression should
John McCall2d74de92009-12-01 22:10:20 +00003951/// unary-convert to an expression of function-pointer or
3952/// block-pointer type.
3953///
3954/// \param NDecl the declaration being called, if available
John McCalldadc5752010-08-24 06:29:42 +00003955ExprResult
John McCall2d74de92009-12-01 22:10:20 +00003956Sema::BuildResolvedCallExpr(Expr *Fn, NamedDecl *NDecl,
3957 SourceLocation LParenLoc,
3958 Expr **Args, unsigned NumArgs,
Peter Collingbourne41f85462011-02-09 21:07:24 +00003959 SourceLocation RParenLoc,
Peter Collingbourne619a8c72011-10-02 23:49:29 +00003960 Expr *Config, bool IsExecConfig) {
John McCall2d74de92009-12-01 22:10:20 +00003961 FunctionDecl *FDecl = dyn_cast_or_null<FunctionDecl>(NDecl);
Eli Friedman34866c72012-08-31 00:14:07 +00003962 unsigned BuiltinID = (FDecl ? FDecl->getBuiltinID() : 0);
John McCall2d74de92009-12-01 22:10:20 +00003963
Chris Lattneraa9c7ae2008-04-08 04:40:51 +00003964 // Promote the function operand.
Eli Friedman34866c72012-08-31 00:14:07 +00003965 // We special-case function promotion here because we only allow promoting
3966 // builtin functions to function pointers in the callee of a call.
3967 ExprResult Result;
3968 if (BuiltinID &&
3969 Fn->getType()->isSpecificBuiltinType(BuiltinType::BuiltinFn)) {
3970 Result = ImpCastExprToType(Fn, Context.getPointerType(FDecl->getType()),
3971 CK_BuiltinFnToFnPtr).take();
3972 } else {
3973 Result = UsualUnaryConversions(Fn);
3974 }
John Wiegley01296292011-04-08 18:41:53 +00003975 if (Result.isInvalid())
3976 return ExprError();
3977 Fn = Result.take();
Chris Lattneraa9c7ae2008-04-08 04:40:51 +00003978
Chris Lattner08464942007-12-28 05:29:59 +00003979 // Make the call expr early, before semantic checks. This guarantees cleanup
3980 // of arguments and function on error.
Peter Collingbourne41f85462011-02-09 21:07:24 +00003981 CallExpr *TheCall;
Eric Christopher13586ab2012-05-30 01:14:28 +00003982 if (Config)
Peter Collingbourne41f85462011-02-09 21:07:24 +00003983 TheCall = new (Context) CUDAKernelCallExpr(Context, Fn,
3984 cast<CallExpr>(Config),
Benjamin Kramerc215e762012-08-24 11:54:20 +00003985 llvm::makeArrayRef(Args,NumArgs),
Peter Collingbourne41f85462011-02-09 21:07:24 +00003986 Context.BoolTy,
3987 VK_RValue,
3988 RParenLoc);
Eric Christopher13586ab2012-05-30 01:14:28 +00003989 else
Peter Collingbourne41f85462011-02-09 21:07:24 +00003990 TheCall = new (Context) CallExpr(Context, Fn,
Benjamin Kramerc215e762012-08-24 11:54:20 +00003991 llvm::makeArrayRef(Args, NumArgs),
Peter Collingbourne41f85462011-02-09 21:07:24 +00003992 Context.BoolTy,
3993 VK_RValue,
3994 RParenLoc);
Sebastian Redlc215cfc2009-01-19 00:08:26 +00003995
John McCallbebede42011-02-26 05:39:39 +00003996 // Bail out early if calling a builtin with custom typechecking.
3997 if (BuiltinID && Context.BuiltinInfo.hasCustomTypechecking(BuiltinID))
3998 return CheckBuiltinFunctionCall(BuiltinID, TheCall);
3999
John McCall31996342011-04-07 08:22:57 +00004000 retry:
Steve Naroff8de9c3a2008-09-05 22:11:13 +00004001 const FunctionType *FuncT;
John McCallbebede42011-02-26 05:39:39 +00004002 if (const PointerType *PT = Fn->getType()->getAs<PointerType>()) {
Steve Naroff8de9c3a2008-09-05 22:11:13 +00004003 // C99 6.5.2.2p1 - "The expression that denotes the called function shall
4004 // have type pointer to function".
John McCall9dd450b2009-09-21 23:43:11 +00004005 FuncT = PT->getPointeeType()->getAs<FunctionType>();
John McCallbebede42011-02-26 05:39:39 +00004006 if (FuncT == 0)
4007 return ExprError(Diag(LParenLoc, diag::err_typecheck_call_not_function)
4008 << Fn->getType() << Fn->getSourceRange());
4009 } else if (const BlockPointerType *BPT =
4010 Fn->getType()->getAs<BlockPointerType>()) {
4011 FuncT = BPT->getPointeeType()->castAs<FunctionType>();
4012 } else {
John McCall31996342011-04-07 08:22:57 +00004013 // Handle calls to expressions of unknown-any type.
4014 if (Fn->getType() == Context.UnknownAnyTy) {
John McCall2979fe02011-04-12 00:42:48 +00004015 ExprResult rewrite = rebuildUnknownAnyFunction(*this, Fn);
John McCall31996342011-04-07 08:22:57 +00004016 if (rewrite.isInvalid()) return ExprError();
4017 Fn = rewrite.take();
John McCall39439732011-04-09 22:50:59 +00004018 TheCall->setCallee(Fn);
John McCall31996342011-04-07 08:22:57 +00004019 goto retry;
4020 }
4021
Sebastian Redlc215cfc2009-01-19 00:08:26 +00004022 return ExprError(Diag(LParenLoc, diag::err_typecheck_call_not_function)
4023 << Fn->getType() << Fn->getSourceRange());
John McCallbebede42011-02-26 05:39:39 +00004024 }
Sebastian Redlc215cfc2009-01-19 00:08:26 +00004025
David Blaikiebbafb8a2012-03-11 07:00:24 +00004026 if (getLangOpts().CUDA) {
Peter Collingbourne4b66c472011-02-23 01:53:29 +00004027 if (Config) {
4028 // CUDA: Kernel calls must be to global functions
4029 if (FDecl && !FDecl->hasAttr<CUDAGlobalAttr>())
4030 return ExprError(Diag(LParenLoc,diag::err_kern_call_not_global_function)
4031 << FDecl->getName() << Fn->getSourceRange());
4032
4033 // CUDA: Kernel function must have 'void' return type
4034 if (!FuncT->getResultType()->isVoidType())
4035 return ExprError(Diag(LParenLoc, diag::err_kern_type_not_void_return)
4036 << Fn->getType() << Fn->getSourceRange());
Peter Collingbourne34a20b02011-10-02 23:49:15 +00004037 } else {
4038 // CUDA: Calls to global functions must be configured
4039 if (FDecl && FDecl->hasAttr<CUDAGlobalAttr>())
4040 return ExprError(Diag(LParenLoc, diag::err_global_call_not_config)
4041 << FDecl->getName() << Fn->getSourceRange());
Peter Collingbourne4b66c472011-02-23 01:53:29 +00004042 }
4043 }
4044
Eli Friedman3164fb12009-03-22 22:00:50 +00004045 // Check for a valid return type
Kovarththanan Rajaratnamba2c6522010-03-13 10:17:05 +00004046 if (CheckCallReturnType(FuncT->getResultType(),
Daniel Dunbar62ee6412012-03-09 18:35:03 +00004047 Fn->getLocStart(), TheCall,
Anders Carlsson7f84ed92009-10-09 23:51:55 +00004048 FDecl))
Eli Friedman3164fb12009-03-22 22:00:50 +00004049 return ExprError();
4050
Chris Lattner08464942007-12-28 05:29:59 +00004051 // We know the result type of the call, set it.
Douglas Gregor603d81b2010-07-13 08:18:22 +00004052 TheCall->setType(FuncT->getCallResultType(Context));
John McCall7decc9e2010-11-18 06:31:45 +00004053 TheCall->setValueKind(Expr::getValueKindForType(FuncT->getResultType()));
Sebastian Redlc215cfc2009-01-19 00:08:26 +00004054
Richard Smith55ce3522012-06-25 20:30:08 +00004055 const FunctionProtoType *Proto = dyn_cast<FunctionProtoType>(FuncT);
4056 if (Proto) {
John McCallb268a282010-08-23 23:25:46 +00004057 if (ConvertArgumentsForCall(TheCall, Fn, FDecl, Proto, Args, NumArgs,
Peter Collingbourne619a8c72011-10-02 23:49:29 +00004058 RParenLoc, IsExecConfig))
Sebastian Redlc215cfc2009-01-19 00:08:26 +00004059 return ExprError();
Chris Lattner08464942007-12-28 05:29:59 +00004060 } else {
Douglas Gregordeaad8c2009-02-26 23:50:07 +00004061 assert(isa<FunctionNoProtoType>(FuncT) && "Unknown FunctionType!");
Sebastian Redlc215cfc2009-01-19 00:08:26 +00004062
Douglas Gregord8e97de2009-04-02 15:37:10 +00004063 if (FDecl) {
4064 // Check if we have too few/too many template arguments, based
4065 // on our knowledge of the function definition.
4066 const FunctionDecl *Def = 0;
Argyrios Kyrtzidis36ea3222010-07-07 11:31:19 +00004067 if (FDecl->hasBody(Def) && NumArgs != Def->param_size()) {
Richard Smith55ce3522012-06-25 20:30:08 +00004068 Proto = Def->getType()->getAs<FunctionProtoType>();
Douglas Gregor8e09a722010-10-25 20:39:23 +00004069 if (!Proto || !(Proto->isVariadic() && NumArgs >= Def->param_size()))
Eli Friedmanfcbf7d22009-06-01 09:24:59 +00004070 Diag(RParenLoc, diag::warn_call_wrong_number_of_arguments)
4071 << (NumArgs > Def->param_size()) << FDecl << Fn->getSourceRange();
Eli Friedmanfcbf7d22009-06-01 09:24:59 +00004072 }
Douglas Gregor8e09a722010-10-25 20:39:23 +00004073
4074 // If the function we're calling isn't a function prototype, but we have
4075 // a function prototype from a prior declaratiom, use that prototype.
4076 if (!FDecl->hasPrototype())
4077 Proto = FDecl->getType()->getAs<FunctionProtoType>();
Douglas Gregord8e97de2009-04-02 15:37:10 +00004078 }
4079
Steve Naroff0b661582007-08-28 23:30:39 +00004080 // Promote the arguments (C99 6.5.2.2p6).
Chris Lattner08464942007-12-28 05:29:59 +00004081 for (unsigned i = 0; i != NumArgs; i++) {
4082 Expr *Arg = Args[i];
Douglas Gregor8e09a722010-10-25 20:39:23 +00004083
4084 if (Proto && i < Proto->getNumArgs()) {
Douglas Gregor8e09a722010-10-25 20:39:23 +00004085 InitializedEntity Entity
4086 = InitializedEntity::InitializeParameter(Context,
John McCall31168b02011-06-15 23:02:42 +00004087 Proto->getArgType(i),
4088 Proto->isArgConsumed(i));
Douglas Gregor8e09a722010-10-25 20:39:23 +00004089 ExprResult ArgE = PerformCopyInitialization(Entity,
4090 SourceLocation(),
4091 Owned(Arg));
4092 if (ArgE.isInvalid())
4093 return true;
4094
4095 Arg = ArgE.takeAs<Expr>();
4096
4097 } else {
John Wiegley01296292011-04-08 18:41:53 +00004098 ExprResult ArgE = DefaultArgumentPromotion(Arg);
4099
4100 if (ArgE.isInvalid())
4101 return true;
4102
4103 Arg = ArgE.takeAs<Expr>();
Douglas Gregor8e09a722010-10-25 20:39:23 +00004104 }
4105
Daniel Dunbar62ee6412012-03-09 18:35:03 +00004106 if (RequireCompleteType(Arg->getLocStart(),
Douglas Gregor83025412010-10-26 05:45:40 +00004107 Arg->getType(),
Douglas Gregor7bfb2d02012-05-04 16:32:21 +00004108 diag::err_call_incomplete_argument, Arg))
Douglas Gregor83025412010-10-26 05:45:40 +00004109 return ExprError();
4110
Chris Lattner08464942007-12-28 05:29:59 +00004111 TheCall->setArg(i, Arg);
Steve Naroff0b661582007-08-28 23:30:39 +00004112 }
Steve Naroffae4143e2007-04-26 20:39:23 +00004113 }
Chris Lattner08464942007-12-28 05:29:59 +00004114
Douglas Gregor97fd6e22008-12-22 05:46:06 +00004115 if (CXXMethodDecl *Method = dyn_cast_or_null<CXXMethodDecl>(FDecl))
4116 if (!Method->isStatic())
Sebastian Redlc215cfc2009-01-19 00:08:26 +00004117 return ExprError(Diag(LParenLoc, diag::err_member_call_without_object)
4118 << Fn->getSourceRange());
Douglas Gregor97fd6e22008-12-22 05:46:06 +00004119
Fariborz Jahanian0aa5c452009-05-15 20:33:25 +00004120 // Check for sentinels
4121 if (NDecl)
4122 DiagnoseSentinelCalls(NDecl, LParenLoc, Args, NumArgs);
Mike Stump11289f42009-09-09 15:08:12 +00004123
Chris Lattnerb87b1b32007-08-10 20:18:51 +00004124 // Do special checking on direct calls to functions.
Anders Carlssonbc4c1072009-08-16 01:56:34 +00004125 if (FDecl) {
Richard Smith55ce3522012-06-25 20:30:08 +00004126 if (CheckFunctionCall(FDecl, TheCall, Proto))
Anders Carlssonbc4c1072009-08-16 01:56:34 +00004127 return ExprError();
Mike Stump11289f42009-09-09 15:08:12 +00004128
John McCallbebede42011-02-26 05:39:39 +00004129 if (BuiltinID)
Fariborz Jahaniane8473c22010-11-30 17:35:24 +00004130 return CheckBuiltinFunctionCall(BuiltinID, TheCall);
Anders Carlssonbc4c1072009-08-16 01:56:34 +00004131 } else if (NDecl) {
Richard Smith55ce3522012-06-25 20:30:08 +00004132 if (CheckBlockCall(NDecl, TheCall, Proto))
Anders Carlssonbc4c1072009-08-16 01:56:34 +00004133 return ExprError();
4134 }
Chris Lattnerb87b1b32007-08-10 20:18:51 +00004135
John McCallb268a282010-08-23 23:25:46 +00004136 return MaybeBindToTemporary(TheCall);
Chris Lattnere168f762006-11-10 05:29:30 +00004137}
4138
John McCalldadc5752010-08-24 06:29:42 +00004139ExprResult
John McCallba7bf592010-08-24 05:47:05 +00004140Sema::ActOnCompoundLiteral(SourceLocation LParenLoc, ParsedType Ty,
John McCallb268a282010-08-23 23:25:46 +00004141 SourceLocation RParenLoc, Expr *InitExpr) {
Steve Naroff83895f72007-09-16 03:34:24 +00004142 assert((Ty != 0) && "ActOnCompoundLiteral(): missing type");
Steve Naroff57eb2c52007-07-19 21:32:11 +00004143 // FIXME: put back this assert when initializers are worked out.
Steve Naroff83895f72007-09-16 03:34:24 +00004144 //assert((InitExpr != 0) && "ActOnCompoundLiteral(): missing expression");
John McCalle15bbff2010-01-18 19:35:47 +00004145
4146 TypeSourceInfo *TInfo;
4147 QualType literalType = GetTypeFromParser(Ty, &TInfo);
4148 if (!TInfo)
4149 TInfo = Context.getTrivialTypeSourceInfo(literalType);
4150
John McCallb268a282010-08-23 23:25:46 +00004151 return BuildCompoundLiteralExpr(LParenLoc, TInfo, RParenLoc, InitExpr);
John McCalle15bbff2010-01-18 19:35:47 +00004152}
4153
John McCalldadc5752010-08-24 06:29:42 +00004154ExprResult
John McCalle15bbff2010-01-18 19:35:47 +00004155Sema::BuildCompoundLiteralExpr(SourceLocation LParenLoc, TypeSourceInfo *TInfo,
Richard Trieuba63ce62011-09-09 01:45:06 +00004156 SourceLocation RParenLoc, Expr *LiteralExpr) {
John McCalle15bbff2010-01-18 19:35:47 +00004157 QualType literalType = TInfo->getType();
Anders Carlsson2c1ec6d2007-12-05 07:24:19 +00004158
Eli Friedman37a186d2008-05-20 05:22:08 +00004159 if (literalType->isArrayType()) {
Argyrios Kyrtzidis85663562010-11-08 19:14:19 +00004160 if (RequireCompleteType(LParenLoc, Context.getBaseElementType(literalType),
Douglas Gregor7bfb2d02012-05-04 16:32:21 +00004161 diag::err_illegal_decl_array_incomplete_type,
4162 SourceRange(LParenLoc,
4163 LiteralExpr->getSourceRange().getEnd())))
Argyrios Kyrtzidis85663562010-11-08 19:14:19 +00004164 return ExprError();
Chris Lattner7adf0762008-08-04 07:31:14 +00004165 if (literalType->isVariableArrayType())
Sebastian Redlb5d49352009-01-19 22:31:54 +00004166 return ExprError(Diag(LParenLoc, diag::err_variable_object_no_init)
Richard Trieuba63ce62011-09-09 01:45:06 +00004167 << SourceRange(LParenLoc, LiteralExpr->getSourceRange().getEnd()));
Douglas Gregor1c37d9e2009-05-21 23:48:18 +00004168 } else if (!literalType->isDependentType() &&
4169 RequireCompleteType(LParenLoc, literalType,
Douglas Gregor7bfb2d02012-05-04 16:32:21 +00004170 diag::err_typecheck_decl_incomplete_type,
4171 SourceRange(LParenLoc, LiteralExpr->getSourceRange().getEnd())))
Sebastian Redlb5d49352009-01-19 22:31:54 +00004172 return ExprError();
Eli Friedman37a186d2008-05-20 05:22:08 +00004173
Douglas Gregor85dabae2009-12-16 01:38:02 +00004174 InitializedEntity Entity
Douglas Gregor1b303932009-12-22 15:35:07 +00004175 = InitializedEntity::InitializeTemporary(literalType);
Douglas Gregor85dabae2009-12-16 01:38:02 +00004176 InitializationKind Kind
John McCall31168b02011-06-15 23:02:42 +00004177 = InitializationKind::CreateCStyleCast(LParenLoc,
Sebastian Redl0501c632012-02-12 16:37:36 +00004178 SourceRange(LParenLoc, RParenLoc),
4179 /*InitList=*/true);
Richard Trieuba63ce62011-09-09 01:45:06 +00004180 InitializationSequence InitSeq(*this, Entity, Kind, &LiteralExpr, 1);
Benjamin Kramercc4c49d2012-08-23 23:38:35 +00004181 ExprResult Result = InitSeq.Perform(*this, Entity, Kind, LiteralExpr,
4182 &literalType);
Eli Friedmana553d4a2009-12-22 02:35:53 +00004183 if (Result.isInvalid())
Sebastian Redlb5d49352009-01-19 22:31:54 +00004184 return ExprError();
Richard Trieuba63ce62011-09-09 01:45:06 +00004185 LiteralExpr = Result.get();
Steve Naroffd32419d2008-01-14 18:19:28 +00004186
Chris Lattner79413952008-12-04 23:50:19 +00004187 bool isFileScope = getCurFunctionOrMethodDecl() == 0;
Steve Naroffd32419d2008-01-14 18:19:28 +00004188 if (isFileScope) { // 6.5.2.5p3
Richard Trieuba63ce62011-09-09 01:45:06 +00004189 if (CheckForConstantInitializer(LiteralExpr, literalType))
Sebastian Redlb5d49352009-01-19 22:31:54 +00004190 return ExprError();
Steve Naroff98f72032008-01-10 22:15:12 +00004191 }
Eli Friedmana553d4a2009-12-22 02:35:53 +00004192
John McCall7decc9e2010-11-18 06:31:45 +00004193 // In C, compound literals are l-values for some reason.
David Blaikiebbafb8a2012-03-11 07:00:24 +00004194 ExprValueKind VK = getLangOpts().CPlusPlus ? VK_RValue : VK_LValue;
John McCall7decc9e2010-11-18 06:31:45 +00004195
Douglas Gregor9b71f0c2011-06-17 04:59:12 +00004196 return MaybeBindToTemporary(
4197 new (Context) CompoundLiteralExpr(LParenLoc, TInfo, literalType,
Richard Trieuba63ce62011-09-09 01:45:06 +00004198 VK, LiteralExpr, isFileScope));
Steve Narofffbd09832007-07-19 01:06:55 +00004199}
4200
John McCalldadc5752010-08-24 06:29:42 +00004201ExprResult
Richard Trieuba63ce62011-09-09 01:45:06 +00004202Sema::ActOnInitList(SourceLocation LBraceLoc, MultiExprArg InitArgList,
Sebastian Redlb5d49352009-01-19 22:31:54 +00004203 SourceLocation RBraceLoc) {
John McCall526ab472011-10-25 17:37:35 +00004204 // Immediately handle non-overload placeholders. Overloads can be
4205 // resolved contextually, but everything else here can't.
Benjamin Kramerc215e762012-08-24 11:54:20 +00004206 for (unsigned I = 0, E = InitArgList.size(); I != E; ++I) {
4207 if (InitArgList[I]->getType()->isNonOverloadPlaceholderType()) {
4208 ExprResult result = CheckPlaceholderExpr(InitArgList[I]);
John McCall526ab472011-10-25 17:37:35 +00004209
4210 // Ignore failures; dropping the entire initializer list because
4211 // of one failure would be terrible for indexing/etc.
4212 if (result.isInvalid()) continue;
4213
Benjamin Kramerc215e762012-08-24 11:54:20 +00004214 InitArgList[I] = result.take();
John McCall526ab472011-10-25 17:37:35 +00004215 }
4216 }
4217
Steve Naroff30d242c2007-09-15 18:49:24 +00004218 // Semantic analysis for initializers is done by ActOnDeclarator() and
Mike Stump4e1f26a2009-02-19 03:04:26 +00004219 // CheckInitializer() - it requires knowledge of the object being intialized.
Sebastian Redlb5d49352009-01-19 22:31:54 +00004220
Benjamin Kramerc215e762012-08-24 11:54:20 +00004221 InitListExpr *E = new (Context) InitListExpr(Context, LBraceLoc, InitArgList,
4222 RBraceLoc);
Chris Lattner24d5bfe2008-04-02 04:24:33 +00004223 E->setType(Context.VoidTy); // FIXME: just a place holder for now.
Sebastian Redlb5d49352009-01-19 22:31:54 +00004224 return Owned(E);
Steve Narofffbd09832007-07-19 01:06:55 +00004225}
4226
John McCallcd78e802011-09-10 01:16:55 +00004227/// Do an explicit extend of the given block pointer if we're in ARC.
4228static void maybeExtendBlockObject(Sema &S, ExprResult &E) {
4229 assert(E.get()->getType()->isBlockPointerType());
4230 assert(E.get()->isRValue());
4231
4232 // Only do this in an r-value context.
David Blaikiebbafb8a2012-03-11 07:00:24 +00004233 if (!S.getLangOpts().ObjCAutoRefCount) return;
John McCallcd78e802011-09-10 01:16:55 +00004234
4235 E = ImplicitCastExpr::Create(S.Context, E.get()->getType(),
John McCall2d637d22011-09-10 06:18:15 +00004236 CK_ARCExtendBlockObject, E.get(),
John McCallcd78e802011-09-10 01:16:55 +00004237 /*base path*/ 0, VK_RValue);
4238 S.ExprNeedsCleanups = true;
4239}
4240
4241/// Prepare a conversion of the given expression to an ObjC object
4242/// pointer type.
4243CastKind Sema::PrepareCastToObjCObjectPointer(ExprResult &E) {
4244 QualType type = E.get()->getType();
4245 if (type->isObjCObjectPointerType()) {
4246 return CK_BitCast;
4247 } else if (type->isBlockPointerType()) {
4248 maybeExtendBlockObject(*this, E);
4249 return CK_BlockPointerToObjCPointerCast;
4250 } else {
4251 assert(type->isPointerType());
4252 return CK_CPointerToObjCPointerCast;
4253 }
4254}
4255
John McCalld7646252010-11-14 08:17:51 +00004256/// Prepares for a scalar cast, performing all the necessary stages
4257/// except the final cast and returning the kind required.
John McCall9776e432011-10-06 23:25:11 +00004258CastKind Sema::PrepareScalarCast(ExprResult &Src, QualType DestTy) {
John McCalld7646252010-11-14 08:17:51 +00004259 // Both Src and Dest are scalar types, i.e. arithmetic or pointer.
4260 // Also, callers should have filtered out the invalid cases with
4261 // pointers. Everything else should be possible.
4262
John Wiegley01296292011-04-08 18:41:53 +00004263 QualType SrcTy = Src.get()->getType();
John McCall9776e432011-10-06 23:25:11 +00004264 if (Context.hasSameUnqualifiedType(SrcTy, DestTy))
John McCalle3027922010-08-25 11:45:40 +00004265 return CK_NoOp;
Anders Carlsson094c4592009-10-18 18:12:03 +00004266
John McCall9320b872011-09-09 05:25:32 +00004267 switch (Type::ScalarTypeKind SrcKind = SrcTy->getScalarTypeKind()) {
John McCall8cb679e2010-11-15 09:13:47 +00004268 case Type::STK_MemberPointer:
4269 llvm_unreachable("member pointer type in C");
Abramo Bagnaraba854972011-01-04 09:50:03 +00004270
John McCall9320b872011-09-09 05:25:32 +00004271 case Type::STK_CPointer:
4272 case Type::STK_BlockPointer:
4273 case Type::STK_ObjCObjectPointer:
John McCall8cb679e2010-11-15 09:13:47 +00004274 switch (DestTy->getScalarTypeKind()) {
John McCall9320b872011-09-09 05:25:32 +00004275 case Type::STK_CPointer:
4276 return CK_BitCast;
4277 case Type::STK_BlockPointer:
4278 return (SrcKind == Type::STK_BlockPointer
4279 ? CK_BitCast : CK_AnyPointerToBlockPointerCast);
4280 case Type::STK_ObjCObjectPointer:
4281 if (SrcKind == Type::STK_ObjCObjectPointer)
4282 return CK_BitCast;
David Blaikie8a40f702012-01-17 06:56:22 +00004283 if (SrcKind == Type::STK_CPointer)
John McCall9320b872011-09-09 05:25:32 +00004284 return CK_CPointerToObjCPointerCast;
David Blaikie8a40f702012-01-17 06:56:22 +00004285 maybeExtendBlockObject(*this, Src);
4286 return CK_BlockPointerToObjCPointerCast;
John McCall8cb679e2010-11-15 09:13:47 +00004287 case Type::STK_Bool:
4288 return CK_PointerToBoolean;
4289 case Type::STK_Integral:
4290 return CK_PointerToIntegral;
4291 case Type::STK_Floating:
4292 case Type::STK_FloatingComplex:
4293 case Type::STK_IntegralComplex:
4294 case Type::STK_MemberPointer:
4295 llvm_unreachable("illegal cast from pointer");
4296 }
David Blaikie8a40f702012-01-17 06:56:22 +00004297 llvm_unreachable("Should have returned before this");
Kovarththanan Rajaratnamba2c6522010-03-13 10:17:05 +00004298
John McCall8cb679e2010-11-15 09:13:47 +00004299 case Type::STK_Bool: // casting from bool is like casting from an integer
4300 case Type::STK_Integral:
4301 switch (DestTy->getScalarTypeKind()) {
John McCall9320b872011-09-09 05:25:32 +00004302 case Type::STK_CPointer:
4303 case Type::STK_ObjCObjectPointer:
4304 case Type::STK_BlockPointer:
John McCall9776e432011-10-06 23:25:11 +00004305 if (Src.get()->isNullPointerConstant(Context,
Richard Trieucfc491d2011-08-02 04:35:43 +00004306 Expr::NPC_ValueDependentIsNull))
John McCalle84af4e2010-11-13 01:35:44 +00004307 return CK_NullToPointer;
John McCalle3027922010-08-25 11:45:40 +00004308 return CK_IntegralToPointer;
John McCall8cb679e2010-11-15 09:13:47 +00004309 case Type::STK_Bool:
4310 return CK_IntegralToBoolean;
4311 case Type::STK_Integral:
John McCalld7646252010-11-14 08:17:51 +00004312 return CK_IntegralCast;
John McCall8cb679e2010-11-15 09:13:47 +00004313 case Type::STK_Floating:
John McCalle3027922010-08-25 11:45:40 +00004314 return CK_IntegralToFloating;
John McCall8cb679e2010-11-15 09:13:47 +00004315 case Type::STK_IntegralComplex:
John McCall9776e432011-10-06 23:25:11 +00004316 Src = ImpCastExprToType(Src.take(),
4317 DestTy->castAs<ComplexType>()->getElementType(),
4318 CK_IntegralCast);
John McCalld7646252010-11-14 08:17:51 +00004319 return CK_IntegralRealToComplex;
John McCall8cb679e2010-11-15 09:13:47 +00004320 case Type::STK_FloatingComplex:
John McCall9776e432011-10-06 23:25:11 +00004321 Src = ImpCastExprToType(Src.take(),
4322 DestTy->castAs<ComplexType>()->getElementType(),
4323 CK_IntegralToFloating);
John McCalld7646252010-11-14 08:17:51 +00004324 return CK_FloatingRealToComplex;
John McCall8cb679e2010-11-15 09:13:47 +00004325 case Type::STK_MemberPointer:
4326 llvm_unreachable("member pointer type in C");
John McCalld7646252010-11-14 08:17:51 +00004327 }
David Blaikie8a40f702012-01-17 06:56:22 +00004328 llvm_unreachable("Should have returned before this");
Kovarththanan Rajaratnamba2c6522010-03-13 10:17:05 +00004329
John McCall8cb679e2010-11-15 09:13:47 +00004330 case Type::STK_Floating:
4331 switch (DestTy->getScalarTypeKind()) {
4332 case Type::STK_Floating:
John McCalle3027922010-08-25 11:45:40 +00004333 return CK_FloatingCast;
John McCall8cb679e2010-11-15 09:13:47 +00004334 case Type::STK_Bool:
4335 return CK_FloatingToBoolean;
4336 case Type::STK_Integral:
John McCalle3027922010-08-25 11:45:40 +00004337 return CK_FloatingToIntegral;
John McCall8cb679e2010-11-15 09:13:47 +00004338 case Type::STK_FloatingComplex:
John McCall9776e432011-10-06 23:25:11 +00004339 Src = ImpCastExprToType(Src.take(),
4340 DestTy->castAs<ComplexType>()->getElementType(),
4341 CK_FloatingCast);
John McCalld7646252010-11-14 08:17:51 +00004342 return CK_FloatingRealToComplex;
John McCall8cb679e2010-11-15 09:13:47 +00004343 case Type::STK_IntegralComplex:
John McCall9776e432011-10-06 23:25:11 +00004344 Src = ImpCastExprToType(Src.take(),
4345 DestTy->castAs<ComplexType>()->getElementType(),
4346 CK_FloatingToIntegral);
John McCalld7646252010-11-14 08:17:51 +00004347 return CK_IntegralRealToComplex;
John McCall9320b872011-09-09 05:25:32 +00004348 case Type::STK_CPointer:
4349 case Type::STK_ObjCObjectPointer:
4350 case Type::STK_BlockPointer:
John McCall8cb679e2010-11-15 09:13:47 +00004351 llvm_unreachable("valid float->pointer cast?");
4352 case Type::STK_MemberPointer:
4353 llvm_unreachable("member pointer type in C");
John McCalld7646252010-11-14 08:17:51 +00004354 }
David Blaikie8a40f702012-01-17 06:56:22 +00004355 llvm_unreachable("Should have returned before this");
John McCalld7646252010-11-14 08:17:51 +00004356
John McCall8cb679e2010-11-15 09:13:47 +00004357 case Type::STK_FloatingComplex:
4358 switch (DestTy->getScalarTypeKind()) {
4359 case Type::STK_FloatingComplex:
John McCalld7646252010-11-14 08:17:51 +00004360 return CK_FloatingComplexCast;
John McCall8cb679e2010-11-15 09:13:47 +00004361 case Type::STK_IntegralComplex:
John McCalld7646252010-11-14 08:17:51 +00004362 return CK_FloatingComplexToIntegralComplex;
John McCallfcef3cf2010-12-14 17:51:41 +00004363 case Type::STK_Floating: {
John McCall9776e432011-10-06 23:25:11 +00004364 QualType ET = SrcTy->castAs<ComplexType>()->getElementType();
4365 if (Context.hasSameType(ET, DestTy))
John McCallfcef3cf2010-12-14 17:51:41 +00004366 return CK_FloatingComplexToReal;
John McCall9776e432011-10-06 23:25:11 +00004367 Src = ImpCastExprToType(Src.take(), ET, CK_FloatingComplexToReal);
John McCallfcef3cf2010-12-14 17:51:41 +00004368 return CK_FloatingCast;
4369 }
John McCall8cb679e2010-11-15 09:13:47 +00004370 case Type::STK_Bool:
John McCalld7646252010-11-14 08:17:51 +00004371 return CK_FloatingComplexToBoolean;
John McCall8cb679e2010-11-15 09:13:47 +00004372 case Type::STK_Integral:
John McCall9776e432011-10-06 23:25:11 +00004373 Src = ImpCastExprToType(Src.take(),
4374 SrcTy->castAs<ComplexType>()->getElementType(),
4375 CK_FloatingComplexToReal);
John McCalld7646252010-11-14 08:17:51 +00004376 return CK_FloatingToIntegral;
John McCall9320b872011-09-09 05:25:32 +00004377 case Type::STK_CPointer:
4378 case Type::STK_ObjCObjectPointer:
4379 case Type::STK_BlockPointer:
John McCall8cb679e2010-11-15 09:13:47 +00004380 llvm_unreachable("valid complex float->pointer cast?");
4381 case Type::STK_MemberPointer:
4382 llvm_unreachable("member pointer type in C");
John McCalld7646252010-11-14 08:17:51 +00004383 }
David Blaikie8a40f702012-01-17 06:56:22 +00004384 llvm_unreachable("Should have returned before this");
John McCalld7646252010-11-14 08:17:51 +00004385
John McCall8cb679e2010-11-15 09:13:47 +00004386 case Type::STK_IntegralComplex:
4387 switch (DestTy->getScalarTypeKind()) {
4388 case Type::STK_FloatingComplex:
John McCalld7646252010-11-14 08:17:51 +00004389 return CK_IntegralComplexToFloatingComplex;
John McCall8cb679e2010-11-15 09:13:47 +00004390 case Type::STK_IntegralComplex:
John McCalld7646252010-11-14 08:17:51 +00004391 return CK_IntegralComplexCast;
John McCallfcef3cf2010-12-14 17:51:41 +00004392 case Type::STK_Integral: {
John McCall9776e432011-10-06 23:25:11 +00004393 QualType ET = SrcTy->castAs<ComplexType>()->getElementType();
4394 if (Context.hasSameType(ET, DestTy))
John McCallfcef3cf2010-12-14 17:51:41 +00004395 return CK_IntegralComplexToReal;
John McCall9776e432011-10-06 23:25:11 +00004396 Src = ImpCastExprToType(Src.take(), ET, CK_IntegralComplexToReal);
John McCallfcef3cf2010-12-14 17:51:41 +00004397 return CK_IntegralCast;
4398 }
John McCall8cb679e2010-11-15 09:13:47 +00004399 case Type::STK_Bool:
John McCalld7646252010-11-14 08:17:51 +00004400 return CK_IntegralComplexToBoolean;
John McCall8cb679e2010-11-15 09:13:47 +00004401 case Type::STK_Floating:
John McCall9776e432011-10-06 23:25:11 +00004402 Src = ImpCastExprToType(Src.take(),
4403 SrcTy->castAs<ComplexType>()->getElementType(),
4404 CK_IntegralComplexToReal);
John McCalld7646252010-11-14 08:17:51 +00004405 return CK_IntegralToFloating;
John McCall9320b872011-09-09 05:25:32 +00004406 case Type::STK_CPointer:
4407 case Type::STK_ObjCObjectPointer:
4408 case Type::STK_BlockPointer:
John McCall8cb679e2010-11-15 09:13:47 +00004409 llvm_unreachable("valid complex int->pointer cast?");
4410 case Type::STK_MemberPointer:
4411 llvm_unreachable("member pointer type in C");
John McCalld7646252010-11-14 08:17:51 +00004412 }
David Blaikie8a40f702012-01-17 06:56:22 +00004413 llvm_unreachable("Should have returned before this");
Anders Carlsson094c4592009-10-18 18:12:03 +00004414 }
Kovarththanan Rajaratnamba2c6522010-03-13 10:17:05 +00004415
John McCalld7646252010-11-14 08:17:51 +00004416 llvm_unreachable("Unhandled scalar cast");
Anders Carlsson094c4592009-10-18 18:12:03 +00004417}
4418
Anders Carlsson525b76b2009-10-16 02:48:28 +00004419bool Sema::CheckVectorCast(SourceRange R, QualType VectorTy, QualType Ty,
John McCalle3027922010-08-25 11:45:40 +00004420 CastKind &Kind) {
Anders Carlssonde71adf2007-11-27 05:51:55 +00004421 assert(VectorTy->isVectorType() && "Not a vector type!");
Mike Stump4e1f26a2009-02-19 03:04:26 +00004422
Anders Carlssonde71adf2007-11-27 05:51:55 +00004423 if (Ty->isVectorType() || Ty->isIntegerType()) {
Chris Lattner37e05872008-03-05 18:54:05 +00004424 if (Context.getTypeSize(VectorTy) != Context.getTypeSize(Ty))
Anders Carlssonde71adf2007-11-27 05:51:55 +00004425 return Diag(R.getBegin(),
Mike Stump4e1f26a2009-02-19 03:04:26 +00004426 Ty->isVectorType() ?
Anders Carlssonde71adf2007-11-27 05:51:55 +00004427 diag::err_invalid_conversion_between_vectors :
Chris Lattner3b054132008-11-19 05:08:23 +00004428 diag::err_invalid_conversion_between_vector_and_integer)
Chris Lattner1e5665e2008-11-24 06:25:27 +00004429 << VectorTy << Ty << R;
Anders Carlssonde71adf2007-11-27 05:51:55 +00004430 } else
4431 return Diag(R.getBegin(),
Chris Lattner3b054132008-11-19 05:08:23 +00004432 diag::err_invalid_conversion_between_vector_and_scalar)
Chris Lattner1e5665e2008-11-24 06:25:27 +00004433 << VectorTy << Ty << R;
Mike Stump4e1f26a2009-02-19 03:04:26 +00004434
John McCalle3027922010-08-25 11:45:40 +00004435 Kind = CK_BitCast;
Anders Carlssonde71adf2007-11-27 05:51:55 +00004436 return false;
4437}
4438
John Wiegley01296292011-04-08 18:41:53 +00004439ExprResult Sema::CheckExtVectorCast(SourceRange R, QualType DestTy,
4440 Expr *CastExpr, CastKind &Kind) {
Nate Begemanc69b7402009-06-26 00:50:28 +00004441 assert(DestTy->isExtVectorType() && "Not an extended vector type!");
Kovarththanan Rajaratnamba2c6522010-03-13 10:17:05 +00004442
Anders Carlsson43d70f82009-10-16 05:23:41 +00004443 QualType SrcTy = CastExpr->getType();
Kovarththanan Rajaratnamba2c6522010-03-13 10:17:05 +00004444
Nate Begemanc8961a42009-06-27 22:05:55 +00004445 // If SrcTy is a VectorType, the total size must match to explicitly cast to
4446 // an ExtVectorType.
Tobias Grosser766bcc22011-09-22 13:03:14 +00004447 // In OpenCL, casts between vectors of different types are not allowed.
4448 // (See OpenCL 6.2).
Nate Begemanc69b7402009-06-26 00:50:28 +00004449 if (SrcTy->isVectorType()) {
Tobias Grosser766bcc22011-09-22 13:03:14 +00004450 if (Context.getTypeSize(DestTy) != Context.getTypeSize(SrcTy)
David Blaikiebbafb8a2012-03-11 07:00:24 +00004451 || (getLangOpts().OpenCL &&
Tobias Grosser766bcc22011-09-22 13:03:14 +00004452 (DestTy.getCanonicalType() != SrcTy.getCanonicalType()))) {
John Wiegley01296292011-04-08 18:41:53 +00004453 Diag(R.getBegin(),diag::err_invalid_conversion_between_ext_vectors)
Nate Begemanc69b7402009-06-26 00:50:28 +00004454 << DestTy << SrcTy << R;
John Wiegley01296292011-04-08 18:41:53 +00004455 return ExprError();
4456 }
John McCalle3027922010-08-25 11:45:40 +00004457 Kind = CK_BitCast;
John Wiegley01296292011-04-08 18:41:53 +00004458 return Owned(CastExpr);
Nate Begemanc69b7402009-06-26 00:50:28 +00004459 }
4460
Nate Begemanbd956c42009-06-28 02:36:38 +00004461 // All non-pointer scalars can be cast to ExtVector type. The appropriate
Nate Begemanc69b7402009-06-26 00:50:28 +00004462 // conversion will take place first from scalar to elt type, and then
4463 // splat from elt type to vector.
Nate Begemanbd956c42009-06-28 02:36:38 +00004464 if (SrcTy->isPointerType())
4465 return Diag(R.getBegin(),
4466 diag::err_invalid_conversion_between_vector_and_scalar)
4467 << DestTy << SrcTy << R;
Eli Friedman06ed2a52009-10-20 08:27:19 +00004468
4469 QualType DestElemTy = DestTy->getAs<ExtVectorType>()->getElementType();
John Wiegley01296292011-04-08 18:41:53 +00004470 ExprResult CastExprRes = Owned(CastExpr);
John McCall9776e432011-10-06 23:25:11 +00004471 CastKind CK = PrepareScalarCast(CastExprRes, DestElemTy);
John Wiegley01296292011-04-08 18:41:53 +00004472 if (CastExprRes.isInvalid())
4473 return ExprError();
4474 CastExpr = ImpCastExprToType(CastExprRes.take(), DestElemTy, CK).take();
Kovarththanan Rajaratnamba2c6522010-03-13 10:17:05 +00004475
John McCalle3027922010-08-25 11:45:40 +00004476 Kind = CK_VectorSplat;
John Wiegley01296292011-04-08 18:41:53 +00004477 return Owned(CastExpr);
Nate Begemanc69b7402009-06-26 00:50:28 +00004478}
4479
John McCalldadc5752010-08-24 06:29:42 +00004480ExprResult
Argyrios Kyrtzidis7192a3b2011-07-01 22:22:59 +00004481Sema::ActOnCastExpr(Scope *S, SourceLocation LParenLoc,
4482 Declarator &D, ParsedType &Ty,
Richard Trieuba63ce62011-09-09 01:45:06 +00004483 SourceLocation RParenLoc, Expr *CastExpr) {
4484 assert(!D.isInvalidType() && (CastExpr != 0) &&
Sebastian Redlb5d49352009-01-19 22:31:54 +00004485 "ActOnCastExpr(): missing type or expr");
Steve Naroff1a2cf6b2007-07-16 23:25:18 +00004486
Richard Trieuba63ce62011-09-09 01:45:06 +00004487 TypeSourceInfo *castTInfo = GetTypeForDeclaratorCast(D, CastExpr->getType());
Argyrios Kyrtzidis7192a3b2011-07-01 22:22:59 +00004488 if (D.isInvalidType())
4489 return ExprError();
4490
David Blaikiebbafb8a2012-03-11 07:00:24 +00004491 if (getLangOpts().CPlusPlus) {
Argyrios Kyrtzidis7192a3b2011-07-01 22:22:59 +00004492 // Check that there are no default arguments (C++ only).
4493 CheckExtraCXXDefaultArguments(D);
4494 }
4495
John McCall42856de2011-10-01 05:17:03 +00004496 checkUnusedDeclAttributes(D);
4497
Argyrios Kyrtzidis7192a3b2011-07-01 22:22:59 +00004498 QualType castType = castTInfo->getType();
4499 Ty = CreateParsedType(castType, castTInfo);
Mike Stump11289f42009-09-09 15:08:12 +00004500
Argyrios Kyrtzidisd8701b62011-07-01 22:22:54 +00004501 bool isVectorLiteral = false;
4502
4503 // Check for an altivec or OpenCL literal,
4504 // i.e. all the elements are integer constants.
Richard Trieuba63ce62011-09-09 01:45:06 +00004505 ParenExpr *PE = dyn_cast<ParenExpr>(CastExpr);
4506 ParenListExpr *PLE = dyn_cast<ParenListExpr>(CastExpr);
David Blaikiebbafb8a2012-03-11 07:00:24 +00004507 if ((getLangOpts().AltiVec || getLangOpts().OpenCL)
Tobias Grosser0a3a22f2011-09-21 18:28:29 +00004508 && castType->isVectorType() && (PE || PLE)) {
Argyrios Kyrtzidisd8701b62011-07-01 22:22:54 +00004509 if (PLE && PLE->getNumExprs() == 0) {
4510 Diag(PLE->getExprLoc(), diag::err_altivec_empty_initializer);
4511 return ExprError();
4512 }
4513 if (PE || PLE->getNumExprs() == 1) {
4514 Expr *E = (PE ? PE->getSubExpr() : PLE->getExpr(0));
4515 if (!E->getType()->isVectorType())
4516 isVectorLiteral = true;
4517 }
4518 else
4519 isVectorLiteral = true;
4520 }
4521
4522 // If this is a vector initializer, '(' type ')' '(' init, ..., init ')'
4523 // then handle it as such.
4524 if (isVectorLiteral)
Richard Trieuba63ce62011-09-09 01:45:06 +00004525 return BuildVectorLiteral(LParenLoc, RParenLoc, CastExpr, castTInfo);
Argyrios Kyrtzidisd8701b62011-07-01 22:22:54 +00004526
Nate Begeman5ec4b312009-08-10 23:49:36 +00004527 // If the Expr being casted is a ParenListExpr, handle it specially.
Argyrios Kyrtzidisd8701b62011-07-01 22:22:54 +00004528 // This is not an AltiVec-style cast, so turn the ParenListExpr into a
4529 // sequence of BinOp comma operators.
Richard Trieuba63ce62011-09-09 01:45:06 +00004530 if (isa<ParenListExpr>(CastExpr)) {
4531 ExprResult Result = MaybeConvertParenListExprToParenExpr(S, CastExpr);
Argyrios Kyrtzidisd8701b62011-07-01 22:22:54 +00004532 if (Result.isInvalid()) return ExprError();
Richard Trieuba63ce62011-09-09 01:45:06 +00004533 CastExpr = Result.take();
Argyrios Kyrtzidisd8701b62011-07-01 22:22:54 +00004534 }
John McCallebe54742010-01-15 18:56:44 +00004535
Richard Trieuba63ce62011-09-09 01:45:06 +00004536 return BuildCStyleCastExpr(LParenLoc, castTInfo, RParenLoc, CastExpr);
John McCallebe54742010-01-15 18:56:44 +00004537}
4538
Argyrios Kyrtzidisd8701b62011-07-01 22:22:54 +00004539ExprResult Sema::BuildVectorLiteral(SourceLocation LParenLoc,
4540 SourceLocation RParenLoc, Expr *E,
4541 TypeSourceInfo *TInfo) {
4542 assert((isa<ParenListExpr>(E) || isa<ParenExpr>(E)) &&
4543 "Expected paren or paren list expression");
4544
4545 Expr **exprs;
4546 unsigned numExprs;
4547 Expr *subExpr;
4548 if (ParenListExpr *PE = dyn_cast<ParenListExpr>(E)) {
4549 exprs = PE->getExprs();
4550 numExprs = PE->getNumExprs();
4551 } else {
4552 subExpr = cast<ParenExpr>(E)->getSubExpr();
4553 exprs = &subExpr;
4554 numExprs = 1;
4555 }
4556
4557 QualType Ty = TInfo->getType();
4558 assert(Ty->isVectorType() && "Expected vector type");
4559
Chris Lattner0e62c1c2011-07-23 10:55:15 +00004560 SmallVector<Expr *, 8> initExprs;
Tanya Lattner83559382011-07-15 23:07:01 +00004561 const VectorType *VTy = Ty->getAs<VectorType>();
4562 unsigned numElems = Ty->getAs<VectorType>()->getNumElements();
4563
Argyrios Kyrtzidisd8701b62011-07-01 22:22:54 +00004564 // '(...)' form of vector initialization in AltiVec: the number of
4565 // initializers must be one or must match the size of the vector.
4566 // If a single value is specified in the initializer then it will be
4567 // replicated to all the components of the vector
Tanya Lattner83559382011-07-15 23:07:01 +00004568 if (VTy->getVectorKind() == VectorType::AltiVecVector) {
Argyrios Kyrtzidisd8701b62011-07-01 22:22:54 +00004569 // The number of initializers must be one or must match the size of the
4570 // vector. If a single value is specified in the initializer then it will
4571 // be replicated to all the components of the vector
4572 if (numExprs == 1) {
4573 QualType ElemTy = Ty->getAs<VectorType>()->getElementType();
Richard Smith01ebacd2011-10-27 23:31:58 +00004574 ExprResult Literal = DefaultLvalueConversion(exprs[0]);
4575 if (Literal.isInvalid())
4576 return ExprError();
Argyrios Kyrtzidisd8701b62011-07-01 22:22:54 +00004577 Literal = ImpCastExprToType(Literal.take(), ElemTy,
John McCall9776e432011-10-06 23:25:11 +00004578 PrepareScalarCast(Literal, ElemTy));
Argyrios Kyrtzidisd8701b62011-07-01 22:22:54 +00004579 return BuildCStyleCastExpr(LParenLoc, TInfo, RParenLoc, Literal.take());
4580 }
4581 else if (numExprs < numElems) {
4582 Diag(E->getExprLoc(),
4583 diag::err_incorrect_number_of_vector_initializers);
4584 return ExprError();
4585 }
4586 else
Benjamin Kramer8001f742012-02-14 12:06:21 +00004587 initExprs.append(exprs, exprs + numExprs);
Argyrios Kyrtzidisd8701b62011-07-01 22:22:54 +00004588 }
Tanya Lattner83559382011-07-15 23:07:01 +00004589 else {
4590 // For OpenCL, when the number of initializers is a single value,
4591 // it will be replicated to all components of the vector.
David Blaikiebbafb8a2012-03-11 07:00:24 +00004592 if (getLangOpts().OpenCL &&
Tanya Lattner83559382011-07-15 23:07:01 +00004593 VTy->getVectorKind() == VectorType::GenericVector &&
4594 numExprs == 1) {
4595 QualType ElemTy = Ty->getAs<VectorType>()->getElementType();
Richard Smith01ebacd2011-10-27 23:31:58 +00004596 ExprResult Literal = DefaultLvalueConversion(exprs[0]);
4597 if (Literal.isInvalid())
4598 return ExprError();
Tanya Lattner83559382011-07-15 23:07:01 +00004599 Literal = ImpCastExprToType(Literal.take(), ElemTy,
John McCall9776e432011-10-06 23:25:11 +00004600 PrepareScalarCast(Literal, ElemTy));
Tanya Lattner83559382011-07-15 23:07:01 +00004601 return BuildCStyleCastExpr(LParenLoc, TInfo, RParenLoc, Literal.take());
4602 }
4603
Benjamin Kramer8001f742012-02-14 12:06:21 +00004604 initExprs.append(exprs, exprs + numExprs);
Tanya Lattner83559382011-07-15 23:07:01 +00004605 }
Argyrios Kyrtzidisd8701b62011-07-01 22:22:54 +00004606 // FIXME: This means that pretty-printing the final AST will produce curly
4607 // braces instead of the original commas.
4608 InitListExpr *initE = new (Context) InitListExpr(Context, LParenLoc,
Benjamin Kramerc215e762012-08-24 11:54:20 +00004609 initExprs, RParenLoc);
Argyrios Kyrtzidisd8701b62011-07-01 22:22:54 +00004610 initE->setType(Ty);
4611 return BuildCompoundLiteralExpr(LParenLoc, TInfo, RParenLoc, initE);
4612}
4613
Sebastian Redla9351792012-02-11 23:51:47 +00004614/// This is not an AltiVec-style cast or or C++ direct-initialization, so turn
4615/// the ParenListExpr into a sequence of comma binary operators.
John McCalldadc5752010-08-24 06:29:42 +00004616ExprResult
Richard Trieuba63ce62011-09-09 01:45:06 +00004617Sema::MaybeConvertParenListExprToParenExpr(Scope *S, Expr *OrigExpr) {
4618 ParenListExpr *E = dyn_cast<ParenListExpr>(OrigExpr);
Nate Begeman5ec4b312009-08-10 23:49:36 +00004619 if (!E)
Richard Trieuba63ce62011-09-09 01:45:06 +00004620 return Owned(OrigExpr);
Mike Stump11289f42009-09-09 15:08:12 +00004621
John McCalldadc5752010-08-24 06:29:42 +00004622 ExprResult Result(E->getExpr(0));
Mike Stump11289f42009-09-09 15:08:12 +00004623
Nate Begeman5ec4b312009-08-10 23:49:36 +00004624 for (unsigned i = 1, e = E->getNumExprs(); i != e && !Result.isInvalid(); ++i)
John McCallb268a282010-08-23 23:25:46 +00004625 Result = ActOnBinOp(S, E->getExprLoc(), tok::comma, Result.get(),
4626 E->getExpr(i));
Mike Stump11289f42009-09-09 15:08:12 +00004627
John McCallb268a282010-08-23 23:25:46 +00004628 if (Result.isInvalid()) return ExprError();
4629
4630 return ActOnParenExpr(E->getLParenLoc(), E->getRParenLoc(), Result.get());
Nate Begeman5ec4b312009-08-10 23:49:36 +00004631}
4632
Sebastian Redla9351792012-02-11 23:51:47 +00004633ExprResult Sema::ActOnParenListExpr(SourceLocation L,
4634 SourceLocation R,
4635 MultiExprArg Val) {
Benjamin Kramerc215e762012-08-24 11:54:20 +00004636 assert(Val.data() != 0 && "ActOnParenOrParenListExpr() missing expr list");
4637 Expr *expr = new (Context) ParenListExpr(Context, L, Val, R);
Nate Begeman5ec4b312009-08-10 23:49:36 +00004638 return Owned(expr);
4639}
4640
Chandler Carrutha8bea4b2011-02-18 23:54:50 +00004641/// \brief Emit a specialized diagnostic when one expression is a null pointer
Richard Trieu27ae4cb2011-09-02 01:51:02 +00004642/// constant and the other is not a pointer. Returns true if a diagnostic is
4643/// emitted.
Richard Trieud33e46e2011-09-06 20:06:39 +00004644bool Sema::DiagnoseConditionalForNull(Expr *LHSExpr, Expr *RHSExpr,
Chandler Carrutha8bea4b2011-02-18 23:54:50 +00004645 SourceLocation QuestionLoc) {
Richard Trieud33e46e2011-09-06 20:06:39 +00004646 Expr *NullExpr = LHSExpr;
4647 Expr *NonPointerExpr = RHSExpr;
Chandler Carrutha8bea4b2011-02-18 23:54:50 +00004648 Expr::NullPointerConstantKind NullKind =
4649 NullExpr->isNullPointerConstant(Context,
4650 Expr::NPC_ValueDependentIsNotNull);
4651
4652 if (NullKind == Expr::NPCK_NotNull) {
Richard Trieud33e46e2011-09-06 20:06:39 +00004653 NullExpr = RHSExpr;
4654 NonPointerExpr = LHSExpr;
Chandler Carrutha8bea4b2011-02-18 23:54:50 +00004655 NullKind =
4656 NullExpr->isNullPointerConstant(Context,
4657 Expr::NPC_ValueDependentIsNotNull);
4658 }
4659
4660 if (NullKind == Expr::NPCK_NotNull)
4661 return false;
4662
David Blaikie1c7c8f72012-08-08 17:33:31 +00004663 if (NullKind == Expr::NPCK_ZeroExpression)
4664 return false;
4665
4666 if (NullKind == Expr::NPCK_ZeroLiteral) {
Chandler Carrutha8bea4b2011-02-18 23:54:50 +00004667 // In this case, check to make sure that we got here from a "NULL"
4668 // string in the source code.
4669 NullExpr = NullExpr->IgnoreParenImpCasts();
John McCall462c0552011-03-08 07:59:04 +00004670 SourceLocation loc = NullExpr->getExprLoc();
4671 if (!findMacroSpelling(loc, "NULL"))
Chandler Carrutha8bea4b2011-02-18 23:54:50 +00004672 return false;
4673 }
4674
4675 int DiagType = (NullKind == Expr::NPCK_CXX0X_nullptr);
4676 Diag(QuestionLoc, diag::err_typecheck_cond_incompatible_operands_null)
4677 << NonPointerExpr->getType() << DiagType
4678 << NonPointerExpr->getSourceRange();
4679 return true;
4680}
4681
Richard Trieu27ae4cb2011-09-02 01:51:02 +00004682/// \brief Return false if the condition expression is valid, true otherwise.
4683static bool checkCondition(Sema &S, Expr *Cond) {
4684 QualType CondTy = Cond->getType();
4685
4686 // C99 6.5.15p2
4687 if (CondTy->isScalarType()) return false;
4688
4689 // OpenCL: Sec 6.3.i says the condition is allowed to be a vector or scalar.
David Blaikiebbafb8a2012-03-11 07:00:24 +00004690 if (S.getLangOpts().OpenCL && CondTy->isVectorType())
Richard Trieu27ae4cb2011-09-02 01:51:02 +00004691 return false;
4692
4693 // Emit the proper error message.
David Blaikiebbafb8a2012-03-11 07:00:24 +00004694 S.Diag(Cond->getLocStart(), S.getLangOpts().OpenCL ?
Richard Trieu27ae4cb2011-09-02 01:51:02 +00004695 diag::err_typecheck_cond_expect_scalar :
4696 diag::err_typecheck_cond_expect_scalar_or_vector)
4697 << CondTy;
4698 return true;
4699}
4700
4701/// \brief Return false if the two expressions can be converted to a vector,
4702/// true otherwise
4703static bool checkConditionalConvertScalarsToVectors(Sema &S, ExprResult &LHS,
4704 ExprResult &RHS,
4705 QualType CondTy) {
4706 // Both operands should be of scalar type.
4707 if (!LHS.get()->getType()->isScalarType()) {
4708 S.Diag(LHS.get()->getLocStart(), diag::err_typecheck_cond_expect_scalar)
4709 << CondTy;
4710 return true;
4711 }
4712 if (!RHS.get()->getType()->isScalarType()) {
4713 S.Diag(RHS.get()->getLocStart(), diag::err_typecheck_cond_expect_scalar)
4714 << CondTy;
4715 return true;
4716 }
4717
4718 // Implicity convert these scalars to the type of the condition.
4719 LHS = S.ImpCastExprToType(LHS.take(), CondTy, CK_IntegralCast);
4720 RHS = S.ImpCastExprToType(RHS.take(), CondTy, CK_IntegralCast);
4721 return false;
4722}
4723
4724/// \brief Handle when one or both operands are void type.
4725static QualType checkConditionalVoidType(Sema &S, ExprResult &LHS,
4726 ExprResult &RHS) {
4727 Expr *LHSExpr = LHS.get();
4728 Expr *RHSExpr = RHS.get();
4729
4730 if (!LHSExpr->getType()->isVoidType())
4731 S.Diag(RHSExpr->getLocStart(), diag::ext_typecheck_cond_one_void)
4732 << RHSExpr->getSourceRange();
4733 if (!RHSExpr->getType()->isVoidType())
4734 S.Diag(LHSExpr->getLocStart(), diag::ext_typecheck_cond_one_void)
4735 << LHSExpr->getSourceRange();
4736 LHS = S.ImpCastExprToType(LHS.take(), S.Context.VoidTy, CK_ToVoid);
4737 RHS = S.ImpCastExprToType(RHS.take(), S.Context.VoidTy, CK_ToVoid);
4738 return S.Context.VoidTy;
4739}
4740
4741/// \brief Return false if the NullExpr can be promoted to PointerTy,
4742/// true otherwise.
4743static bool checkConditionalNullPointer(Sema &S, ExprResult &NullExpr,
4744 QualType PointerTy) {
4745 if ((!PointerTy->isAnyPointerType() && !PointerTy->isBlockPointerType()) ||
4746 !NullExpr.get()->isNullPointerConstant(S.Context,
4747 Expr::NPC_ValueDependentIsNull))
4748 return true;
4749
4750 NullExpr = S.ImpCastExprToType(NullExpr.take(), PointerTy, CK_NullToPointer);
4751 return false;
4752}
4753
4754/// \brief Checks compatibility between two pointers and return the resulting
4755/// type.
4756static QualType checkConditionalPointerCompatibility(Sema &S, ExprResult &LHS,
4757 ExprResult &RHS,
4758 SourceLocation Loc) {
4759 QualType LHSTy = LHS.get()->getType();
4760 QualType RHSTy = RHS.get()->getType();
4761
4762 if (S.Context.hasSameType(LHSTy, RHSTy)) {
4763 // Two identical pointers types are always compatible.
4764 return LHSTy;
4765 }
4766
4767 QualType lhptee, rhptee;
4768
4769 // Get the pointee types.
John McCall9320b872011-09-09 05:25:32 +00004770 if (const BlockPointerType *LHSBTy = LHSTy->getAs<BlockPointerType>()) {
4771 lhptee = LHSBTy->getPointeeType();
4772 rhptee = RHSTy->castAs<BlockPointerType>()->getPointeeType();
Richard Trieu27ae4cb2011-09-02 01:51:02 +00004773 } else {
John McCall9320b872011-09-09 05:25:32 +00004774 lhptee = LHSTy->castAs<PointerType>()->getPointeeType();
4775 rhptee = RHSTy->castAs<PointerType>()->getPointeeType();
Richard Trieu27ae4cb2011-09-02 01:51:02 +00004776 }
4777
Eli Friedman57a75392012-04-05 22:30:04 +00004778 // C99 6.5.15p6: If both operands are pointers to compatible types or to
4779 // differently qualified versions of compatible types, the result type is
4780 // a pointer to an appropriately qualified version of the composite
4781 // type.
4782
4783 // Only CVR-qualifiers exist in the standard, and the differently-qualified
4784 // clause doesn't make sense for our extensions. E.g. address space 2 should
4785 // be incompatible with address space 3: they may live on different devices or
4786 // anything.
4787 Qualifiers lhQual = lhptee.getQualifiers();
4788 Qualifiers rhQual = rhptee.getQualifiers();
4789
4790 unsigned MergedCVRQual = lhQual.getCVRQualifiers() | rhQual.getCVRQualifiers();
4791 lhQual.removeCVRQualifiers();
4792 rhQual.removeCVRQualifiers();
4793
4794 lhptee = S.Context.getQualifiedType(lhptee.getUnqualifiedType(), lhQual);
4795 rhptee = S.Context.getQualifiedType(rhptee.getUnqualifiedType(), rhQual);
4796
4797 QualType CompositeTy = S.Context.mergeTypes(lhptee, rhptee);
4798
4799 if (CompositeTy.isNull()) {
Richard Trieu27ae4cb2011-09-02 01:51:02 +00004800 S.Diag(Loc, diag::warn_typecheck_cond_incompatible_pointers)
4801 << LHSTy << RHSTy << LHS.get()->getSourceRange()
4802 << RHS.get()->getSourceRange();
4803 // In this situation, we assume void* type. No especially good
4804 // reason, but this is what gcc does, and we do have to pick
4805 // to get a consistent AST.
4806 QualType incompatTy = S.Context.getPointerType(S.Context.VoidTy);
4807 LHS = S.ImpCastExprToType(LHS.take(), incompatTy, CK_BitCast);
4808 RHS = S.ImpCastExprToType(RHS.take(), incompatTy, CK_BitCast);
4809 return incompatTy;
4810 }
4811
4812 // The pointer types are compatible.
Eli Friedman57a75392012-04-05 22:30:04 +00004813 QualType ResultTy = CompositeTy.withCVRQualifiers(MergedCVRQual);
4814 ResultTy = S.Context.getPointerType(ResultTy);
Richard Trieu27ae4cb2011-09-02 01:51:02 +00004815
Eli Friedman57a75392012-04-05 22:30:04 +00004816 LHS = S.ImpCastExprToType(LHS.take(), ResultTy, CK_BitCast);
4817 RHS = S.ImpCastExprToType(RHS.take(), ResultTy, CK_BitCast);
4818 return ResultTy;
Richard Trieu27ae4cb2011-09-02 01:51:02 +00004819}
4820
4821/// \brief Return the resulting type when the operands are both block pointers.
4822static QualType checkConditionalBlockPointerCompatibility(Sema &S,
4823 ExprResult &LHS,
4824 ExprResult &RHS,
4825 SourceLocation Loc) {
4826 QualType LHSTy = LHS.get()->getType();
4827 QualType RHSTy = RHS.get()->getType();
4828
4829 if (!LHSTy->isBlockPointerType() || !RHSTy->isBlockPointerType()) {
4830 if (LHSTy->isVoidPointerType() || RHSTy->isVoidPointerType()) {
4831 QualType destType = S.Context.getPointerType(S.Context.VoidTy);
4832 LHS = S.ImpCastExprToType(LHS.take(), destType, CK_BitCast);
4833 RHS = S.ImpCastExprToType(RHS.take(), destType, CK_BitCast);
4834 return destType;
4835 }
4836 S.Diag(Loc, diag::err_typecheck_cond_incompatible_operands)
4837 << LHSTy << RHSTy << LHS.get()->getSourceRange()
4838 << RHS.get()->getSourceRange();
4839 return QualType();
4840 }
4841
4842 // We have 2 block pointer types.
4843 return checkConditionalPointerCompatibility(S, LHS, RHS, Loc);
4844}
4845
4846/// \brief Return the resulting type when the operands are both pointers.
4847static QualType
4848checkConditionalObjectPointersCompatibility(Sema &S, ExprResult &LHS,
4849 ExprResult &RHS,
4850 SourceLocation Loc) {
4851 // get the pointer types
4852 QualType LHSTy = LHS.get()->getType();
4853 QualType RHSTy = RHS.get()->getType();
4854
4855 // get the "pointed to" types
4856 QualType lhptee = LHSTy->getAs<PointerType>()->getPointeeType();
4857 QualType rhptee = RHSTy->getAs<PointerType>()->getPointeeType();
4858
4859 // ignore qualifiers on void (C99 6.5.15p3, clause 6)
4860 if (lhptee->isVoidType() && rhptee->isIncompleteOrObjectType()) {
4861 // Figure out necessary qualifiers (C99 6.5.15p6)
4862 QualType destPointee
4863 = S.Context.getQualifiedType(lhptee, rhptee.getQualifiers());
4864 QualType destType = S.Context.getPointerType(destPointee);
4865 // Add qualifiers if necessary.
4866 LHS = S.ImpCastExprToType(LHS.take(), destType, CK_NoOp);
4867 // Promote to void*.
4868 RHS = S.ImpCastExprToType(RHS.take(), destType, CK_BitCast);
4869 return destType;
4870 }
4871 if (rhptee->isVoidType() && lhptee->isIncompleteOrObjectType()) {
4872 QualType destPointee
4873 = S.Context.getQualifiedType(rhptee, lhptee.getQualifiers());
4874 QualType destType = S.Context.getPointerType(destPointee);
4875 // Add qualifiers if necessary.
4876 RHS = S.ImpCastExprToType(RHS.take(), destType, CK_NoOp);
4877 // Promote to void*.
4878 LHS = S.ImpCastExprToType(LHS.take(), destType, CK_BitCast);
4879 return destType;
4880 }
4881
4882 return checkConditionalPointerCompatibility(S, LHS, RHS, Loc);
4883}
4884
4885/// \brief Return false if the first expression is not an integer and the second
4886/// expression is not a pointer, true otherwise.
4887static bool checkPointerIntegerMismatch(Sema &S, ExprResult &Int,
4888 Expr* PointerExpr, SourceLocation Loc,
Richard Trieuba63ce62011-09-09 01:45:06 +00004889 bool IsIntFirstExpr) {
Richard Trieu27ae4cb2011-09-02 01:51:02 +00004890 if (!PointerExpr->getType()->isPointerType() ||
4891 !Int.get()->getType()->isIntegerType())
4892 return false;
4893
Richard Trieuba63ce62011-09-09 01:45:06 +00004894 Expr *Expr1 = IsIntFirstExpr ? Int.get() : PointerExpr;
4895 Expr *Expr2 = IsIntFirstExpr ? PointerExpr : Int.get();
Richard Trieu27ae4cb2011-09-02 01:51:02 +00004896
4897 S.Diag(Loc, diag::warn_typecheck_cond_pointer_integer_mismatch)
4898 << Expr1->getType() << Expr2->getType()
4899 << Expr1->getSourceRange() << Expr2->getSourceRange();
4900 Int = S.ImpCastExprToType(Int.take(), PointerExpr->getType(),
4901 CK_IntegralToPointer);
4902 return true;
4903}
4904
Richard Trieud33e46e2011-09-06 20:06:39 +00004905/// Note that LHS is not null here, even if this is the gnu "x ?: y" extension.
4906/// In that case, LHS = cond.
Chris Lattner2c486602009-02-18 04:38:20 +00004907/// C99 6.5.15
Richard Trieucfc491d2011-08-02 04:35:43 +00004908QualType Sema::CheckConditionalOperands(ExprResult &Cond, ExprResult &LHS,
4909 ExprResult &RHS, ExprValueKind &VK,
4910 ExprObjectKind &OK,
Chris Lattner2c486602009-02-18 04:38:20 +00004911 SourceLocation QuestionLoc) {
Douglas Gregor1beec452011-03-12 01:48:56 +00004912
Richard Trieud33e46e2011-09-06 20:06:39 +00004913 ExprResult LHSResult = CheckPlaceholderExpr(LHS.get());
4914 if (!LHSResult.isUsable()) return QualType();
Benjamin Kramer62b95d82012-08-23 21:35:17 +00004915 LHS = LHSResult;
Douglas Gregor0124e9b2010-11-09 21:07:58 +00004916
Richard Trieud33e46e2011-09-06 20:06:39 +00004917 ExprResult RHSResult = CheckPlaceholderExpr(RHS.get());
4918 if (!RHSResult.isUsable()) return QualType();
Benjamin Kramer62b95d82012-08-23 21:35:17 +00004919 RHS = RHSResult;
Douglas Gregor0124e9b2010-11-09 21:07:58 +00004920
Sebastian Redl1a99f442009-04-16 17:51:27 +00004921 // C++ is sufficiently different to merit its own checker.
David Blaikiebbafb8a2012-03-11 07:00:24 +00004922 if (getLangOpts().CPlusPlus)
John McCallc07a0c72011-02-17 10:25:35 +00004923 return CXXCheckConditionalOperands(Cond, LHS, RHS, VK, OK, QuestionLoc);
John McCall7decc9e2010-11-18 06:31:45 +00004924
4925 VK = VK_RValue;
John McCall4bc41ae2010-11-18 19:01:18 +00004926 OK = OK_Ordinary;
Sebastian Redl1a99f442009-04-16 17:51:27 +00004927
John Wiegley01296292011-04-08 18:41:53 +00004928 Cond = UsualUnaryConversions(Cond.take());
4929 if (Cond.isInvalid())
4930 return QualType();
4931 LHS = UsualUnaryConversions(LHS.take());
4932 if (LHS.isInvalid())
4933 return QualType();
4934 RHS = UsualUnaryConversions(RHS.take());
4935 if (RHS.isInvalid())
4936 return QualType();
4937
4938 QualType CondTy = Cond.get()->getType();
4939 QualType LHSTy = LHS.get()->getType();
4940 QualType RHSTy = RHS.get()->getType();
Steve Naroff31090012007-07-16 21:54:35 +00004941
Steve Naroffa78fe7e2007-05-16 19:47:19 +00004942 // first, check the condition.
Richard Trieu27ae4cb2011-09-02 01:51:02 +00004943 if (checkCondition(*this, Cond.get()))
4944 return QualType();
Mike Stump4e1f26a2009-02-19 03:04:26 +00004945
Chris Lattnere2949f42008-01-06 22:42:25 +00004946 // Now check the two expressions.
Nate Begeman5ec4b312009-08-10 23:49:36 +00004947 if (LHSTy->isVectorType() || RHSTy->isVectorType())
Eli Friedman1408bc92011-06-23 18:10:35 +00004948 return CheckVectorOperands(LHS, RHS, QuestionLoc, /*isCompAssign*/false);
Douglas Gregor4619e432008-12-05 23:32:09 +00004949
Nate Begemanabb5a732010-09-20 22:41:17 +00004950 // OpenCL: If the condition is a vector, and both operands are scalar,
4951 // attempt to implicity convert them to the vector type to act like the
4952 // built in select.
David Blaikiebbafb8a2012-03-11 07:00:24 +00004953 if (getLangOpts().OpenCL && CondTy->isVectorType())
Richard Trieu27ae4cb2011-09-02 01:51:02 +00004954 if (checkConditionalConvertScalarsToVectors(*this, LHS, RHS, CondTy))
Nate Begemanabb5a732010-09-20 22:41:17 +00004955 return QualType();
Nate Begemanabb5a732010-09-20 22:41:17 +00004956
Chris Lattnere2949f42008-01-06 22:42:25 +00004957 // If both operands have arithmetic type, do the usual arithmetic conversions
4958 // to find a common type: C99 6.5.15p3,5.
Chris Lattner432cff52009-02-18 04:28:32 +00004959 if (LHSTy->isArithmeticType() && RHSTy->isArithmeticType()) {
4960 UsualArithmeticConversions(LHS, RHS);
John Wiegley01296292011-04-08 18:41:53 +00004961 if (LHS.isInvalid() || RHS.isInvalid())
4962 return QualType();
4963 return LHS.get()->getType();
Steve Naroffdbd9e892007-07-17 00:58:39 +00004964 }
Mike Stump4e1f26a2009-02-19 03:04:26 +00004965
Chris Lattnere2949f42008-01-06 22:42:25 +00004966 // If both operands are the same structure or union type, the result is that
4967 // type.
Ted Kremenekc23c7e62009-07-29 21:53:49 +00004968 if (const RecordType *LHSRT = LHSTy->getAs<RecordType>()) { // C99 6.5.15p3
4969 if (const RecordType *RHSRT = RHSTy->getAs<RecordType>())
Chris Lattner2ab40a62007-11-26 01:40:58 +00004970 if (LHSRT->getDecl() == RHSRT->getDecl())
Mike Stump4e1f26a2009-02-19 03:04:26 +00004971 // "If both the operands have structure or union type, the result has
Chris Lattnere2949f42008-01-06 22:42:25 +00004972 // that type." This implies that CV qualifiers are dropped.
Chris Lattner432cff52009-02-18 04:28:32 +00004973 return LHSTy.getUnqualifiedType();
Eli Friedmanba961a92009-03-23 00:24:07 +00004974 // FIXME: Type of conditional expression must be complete in C mode.
Steve Naroffa78fe7e2007-05-16 19:47:19 +00004975 }
Mike Stump4e1f26a2009-02-19 03:04:26 +00004976
Chris Lattnere2949f42008-01-06 22:42:25 +00004977 // C99 6.5.15p5: "If both operands have void type, the result has void type."
Steve Naroffbf1516c2008-05-12 21:44:38 +00004978 // The following || allows only one side to be void (a GCC-ism).
Chris Lattner432cff52009-02-18 04:28:32 +00004979 if (LHSTy->isVoidType() || RHSTy->isVoidType()) {
Richard Trieu27ae4cb2011-09-02 01:51:02 +00004980 return checkConditionalVoidType(*this, LHS, RHS);
Steve Naroffbf1516c2008-05-12 21:44:38 +00004981 }
Richard Trieu27ae4cb2011-09-02 01:51:02 +00004982
Steve Naroff039ad3c2008-01-08 01:11:38 +00004983 // C99 6.5.15p6 - "if one operand is a null pointer constant, the result has
4984 // the type of the other operand."
Richard Trieu27ae4cb2011-09-02 01:51:02 +00004985 if (!checkConditionalNullPointer(*this, RHS, LHSTy)) return LHSTy;
4986 if (!checkConditionalNullPointer(*this, LHS, RHSTy)) return RHSTy;
Kovarththanan Rajaratnamba2c6522010-03-13 10:17:05 +00004987
Fariborz Jahaniana430f712009-12-10 19:47:41 +00004988 // All objective-c pointer type analysis is done here.
4989 QualType compositeType = FindCompositeObjCPointerType(LHS, RHS,
4990 QuestionLoc);
John Wiegley01296292011-04-08 18:41:53 +00004991 if (LHS.isInvalid() || RHS.isInvalid())
4992 return QualType();
Fariborz Jahaniana430f712009-12-10 19:47:41 +00004993 if (!compositeType.isNull())
4994 return compositeType;
Kovarththanan Rajaratnamba2c6522010-03-13 10:17:05 +00004995
4996
Steve Naroff05efa972009-07-01 14:36:47 +00004997 // Handle block pointer types.
Richard Trieu27ae4cb2011-09-02 01:51:02 +00004998 if (LHSTy->isBlockPointerType() || RHSTy->isBlockPointerType())
4999 return checkConditionalBlockPointerCompatibility(*this, LHS, RHS,
5000 QuestionLoc);
Kovarththanan Rajaratnamba2c6522010-03-13 10:17:05 +00005001
Steve Naroff05efa972009-07-01 14:36:47 +00005002 // Check constraints for C object pointers types (C99 6.5.15p3,6).
Richard Trieu27ae4cb2011-09-02 01:51:02 +00005003 if (LHSTy->isPointerType() && RHSTy->isPointerType())
5004 return checkConditionalObjectPointersCompatibility(*this, LHS, RHS,
5005 QuestionLoc);
Mike Stump11289f42009-09-09 15:08:12 +00005006
John McCalle84af4e2010-11-13 01:35:44 +00005007 // GCC compatibility: soften pointer/integer mismatch. Note that
5008 // null pointers have been filtered out by this point.
Richard Trieu27ae4cb2011-09-02 01:51:02 +00005009 if (checkPointerIntegerMismatch(*this, LHS, RHS.get(), QuestionLoc,
5010 /*isIntFirstExpr=*/true))
Steve Naroff05efa972009-07-01 14:36:47 +00005011 return RHSTy;
Richard Trieu27ae4cb2011-09-02 01:51:02 +00005012 if (checkPointerIntegerMismatch(*this, RHS, LHS.get(), QuestionLoc,
5013 /*isIntFirstExpr=*/false))
Steve Naroff05efa972009-07-01 14:36:47 +00005014 return LHSTy;
Daniel Dunbar484603b2008-09-11 23:12:46 +00005015
Chandler Carrutha8bea4b2011-02-18 23:54:50 +00005016 // Emit a better diagnostic if one of the expressions is a null pointer
5017 // constant and the other is not a pointer type. In this case, the user most
5018 // likely forgot to take the address of the other expression.
John Wiegley01296292011-04-08 18:41:53 +00005019 if (DiagnoseConditionalForNull(LHS.get(), RHS.get(), QuestionLoc))
Chandler Carrutha8bea4b2011-02-18 23:54:50 +00005020 return QualType();
5021
Chris Lattnere2949f42008-01-06 22:42:25 +00005022 // Otherwise, the operands are not compatible.
Chris Lattner432cff52009-02-18 04:28:32 +00005023 Diag(QuestionLoc, diag::err_typecheck_cond_incompatible_operands)
Richard Trieucfc491d2011-08-02 04:35:43 +00005024 << LHSTy << RHSTy << LHS.get()->getSourceRange()
5025 << RHS.get()->getSourceRange();
Steve Naroffa78fe7e2007-05-16 19:47:19 +00005026 return QualType();
Steve Narofff8a28c52007-05-15 20:29:32 +00005027}
5028
Fariborz Jahaniana430f712009-12-10 19:47:41 +00005029/// FindCompositeObjCPointerType - Helper method to find composite type of
5030/// two objective-c pointer types of the two input expressions.
John Wiegley01296292011-04-08 18:41:53 +00005031QualType Sema::FindCompositeObjCPointerType(ExprResult &LHS, ExprResult &RHS,
Richard Trieucfc491d2011-08-02 04:35:43 +00005032 SourceLocation QuestionLoc) {
John Wiegley01296292011-04-08 18:41:53 +00005033 QualType LHSTy = LHS.get()->getType();
5034 QualType RHSTy = RHS.get()->getType();
Kovarththanan Rajaratnamba2c6522010-03-13 10:17:05 +00005035
Fariborz Jahaniana430f712009-12-10 19:47:41 +00005036 // Handle things like Class and struct objc_class*. Here we case the result
5037 // to the pseudo-builtin, because that will be implicitly cast back to the
5038 // redefinition type if an attempt is made to access its fields.
5039 if (LHSTy->isObjCClassType() &&
Douglas Gregor97673472011-08-11 20:58:55 +00005040 (Context.hasSameType(RHSTy, Context.getObjCClassRedefinitionType()))) {
John McCall9320b872011-09-09 05:25:32 +00005041 RHS = ImpCastExprToType(RHS.take(), LHSTy, CK_CPointerToObjCPointerCast);
Fariborz Jahaniana430f712009-12-10 19:47:41 +00005042 return LHSTy;
5043 }
5044 if (RHSTy->isObjCClassType() &&
Douglas Gregor97673472011-08-11 20:58:55 +00005045 (Context.hasSameType(LHSTy, Context.getObjCClassRedefinitionType()))) {
John McCall9320b872011-09-09 05:25:32 +00005046 LHS = ImpCastExprToType(LHS.take(), RHSTy, CK_CPointerToObjCPointerCast);
Fariborz Jahaniana430f712009-12-10 19:47:41 +00005047 return RHSTy;
5048 }
5049 // And the same for struct objc_object* / id
5050 if (LHSTy->isObjCIdType() &&
Douglas Gregor97673472011-08-11 20:58:55 +00005051 (Context.hasSameType(RHSTy, Context.getObjCIdRedefinitionType()))) {
John McCall9320b872011-09-09 05:25:32 +00005052 RHS = ImpCastExprToType(RHS.take(), LHSTy, CK_CPointerToObjCPointerCast);
Fariborz Jahaniana430f712009-12-10 19:47:41 +00005053 return LHSTy;
5054 }
5055 if (RHSTy->isObjCIdType() &&
Douglas Gregor97673472011-08-11 20:58:55 +00005056 (Context.hasSameType(LHSTy, Context.getObjCIdRedefinitionType()))) {
John McCall9320b872011-09-09 05:25:32 +00005057 LHS = ImpCastExprToType(LHS.take(), RHSTy, CK_CPointerToObjCPointerCast);
Fariborz Jahaniana430f712009-12-10 19:47:41 +00005058 return RHSTy;
5059 }
5060 // And the same for struct objc_selector* / SEL
5061 if (Context.isObjCSelType(LHSTy) &&
Douglas Gregor97673472011-08-11 20:58:55 +00005062 (Context.hasSameType(RHSTy, Context.getObjCSelRedefinitionType()))) {
John Wiegley01296292011-04-08 18:41:53 +00005063 RHS = ImpCastExprToType(RHS.take(), LHSTy, CK_BitCast);
Fariborz Jahaniana430f712009-12-10 19:47:41 +00005064 return LHSTy;
5065 }
5066 if (Context.isObjCSelType(RHSTy) &&
Douglas Gregor97673472011-08-11 20:58:55 +00005067 (Context.hasSameType(LHSTy, Context.getObjCSelRedefinitionType()))) {
John Wiegley01296292011-04-08 18:41:53 +00005068 LHS = ImpCastExprToType(LHS.take(), RHSTy, CK_BitCast);
Fariborz Jahaniana430f712009-12-10 19:47:41 +00005069 return RHSTy;
5070 }
5071 // Check constraints for Objective-C object pointers types.
5072 if (LHSTy->isObjCObjectPointerType() && RHSTy->isObjCObjectPointerType()) {
Kovarththanan Rajaratnamba2c6522010-03-13 10:17:05 +00005073
Fariborz Jahaniana430f712009-12-10 19:47:41 +00005074 if (Context.getCanonicalType(LHSTy) == Context.getCanonicalType(RHSTy)) {
5075 // Two identical object pointer types are always compatible.
5076 return LHSTy;
5077 }
John McCall9320b872011-09-09 05:25:32 +00005078 const ObjCObjectPointerType *LHSOPT = LHSTy->castAs<ObjCObjectPointerType>();
5079 const ObjCObjectPointerType *RHSOPT = RHSTy->castAs<ObjCObjectPointerType>();
Fariborz Jahaniana430f712009-12-10 19:47:41 +00005080 QualType compositeType = LHSTy;
Kovarththanan Rajaratnamba2c6522010-03-13 10:17:05 +00005081
Fariborz Jahaniana430f712009-12-10 19:47:41 +00005082 // If both operands are interfaces and either operand can be
5083 // assigned to the other, use that type as the composite
5084 // type. This allows
5085 // xxx ? (A*) a : (B*) b
5086 // where B is a subclass of A.
5087 //
5088 // Additionally, as for assignment, if either type is 'id'
5089 // allow silent coercion. Finally, if the types are
5090 // incompatible then make sure to use 'id' as the composite
5091 // type so the result is acceptable for sending messages to.
Kovarththanan Rajaratnamba2c6522010-03-13 10:17:05 +00005092
Fariborz Jahaniana430f712009-12-10 19:47:41 +00005093 // FIXME: Consider unifying with 'areComparableObjCPointerTypes'.
5094 // It could return the composite type.
5095 if (Context.canAssignObjCInterfaces(LHSOPT, RHSOPT)) {
5096 compositeType = RHSOPT->isObjCBuiltinType() ? RHSTy : LHSTy;
5097 } else if (Context.canAssignObjCInterfaces(RHSOPT, LHSOPT)) {
5098 compositeType = LHSOPT->isObjCBuiltinType() ? LHSTy : RHSTy;
5099 } else if ((LHSTy->isObjCQualifiedIdType() ||
5100 RHSTy->isObjCQualifiedIdType()) &&
5101 Context.ObjCQualifiedIdTypesAreCompatible(LHSTy, RHSTy, true)) {
5102 // Need to handle "id<xx>" explicitly.
5103 // GCC allows qualified id and any Objective-C type to devolve to
5104 // id. Currently localizing to here until clear this should be
5105 // part of ObjCQualifiedIdTypesAreCompatible.
5106 compositeType = Context.getObjCIdType();
5107 } else if (LHSTy->isObjCIdType() || RHSTy->isObjCIdType()) {
5108 compositeType = Context.getObjCIdType();
Kovarththanan Rajaratnamba2c6522010-03-13 10:17:05 +00005109 } else if (!(compositeType =
Fariborz Jahaniana430f712009-12-10 19:47:41 +00005110 Context.areCommonBaseCompatible(LHSOPT, RHSOPT)).isNull())
5111 ;
5112 else {
5113 Diag(QuestionLoc, diag::ext_typecheck_cond_incompatible_operands)
5114 << LHSTy << RHSTy
John Wiegley01296292011-04-08 18:41:53 +00005115 << LHS.get()->getSourceRange() << RHS.get()->getSourceRange();
Fariborz Jahaniana430f712009-12-10 19:47:41 +00005116 QualType incompatTy = Context.getObjCIdType();
John Wiegley01296292011-04-08 18:41:53 +00005117 LHS = ImpCastExprToType(LHS.take(), incompatTy, CK_BitCast);
5118 RHS = ImpCastExprToType(RHS.take(), incompatTy, CK_BitCast);
Fariborz Jahaniana430f712009-12-10 19:47:41 +00005119 return incompatTy;
5120 }
5121 // The object pointer types are compatible.
John Wiegley01296292011-04-08 18:41:53 +00005122 LHS = ImpCastExprToType(LHS.take(), compositeType, CK_BitCast);
5123 RHS = ImpCastExprToType(RHS.take(), compositeType, CK_BitCast);
Fariborz Jahaniana430f712009-12-10 19:47:41 +00005124 return compositeType;
5125 }
5126 // Check Objective-C object pointer types and 'void *'
5127 if (LHSTy->isVoidPointerType() && RHSTy->isObjCObjectPointerType()) {
David Blaikiebbafb8a2012-03-11 07:00:24 +00005128 if (getLangOpts().ObjCAutoRefCount) {
Eli Friedman8a78a582012-02-25 00:23:44 +00005129 // ARC forbids the implicit conversion of object pointers to 'void *',
5130 // so these types are not compatible.
5131 Diag(QuestionLoc, diag::err_cond_voidptr_arc) << LHSTy << RHSTy
5132 << LHS.get()->getSourceRange() << RHS.get()->getSourceRange();
5133 LHS = RHS = true;
5134 return QualType();
5135 }
Fariborz Jahaniana430f712009-12-10 19:47:41 +00005136 QualType lhptee = LHSTy->getAs<PointerType>()->getPointeeType();
5137 QualType rhptee = RHSTy->getAs<ObjCObjectPointerType>()->getPointeeType();
5138 QualType destPointee
5139 = Context.getQualifiedType(lhptee, rhptee.getQualifiers());
5140 QualType destType = Context.getPointerType(destPointee);
5141 // Add qualifiers if necessary.
John Wiegley01296292011-04-08 18:41:53 +00005142 LHS = ImpCastExprToType(LHS.take(), destType, CK_NoOp);
Fariborz Jahaniana430f712009-12-10 19:47:41 +00005143 // Promote to void*.
John Wiegley01296292011-04-08 18:41:53 +00005144 RHS = ImpCastExprToType(RHS.take(), destType, CK_BitCast);
Fariborz Jahaniana430f712009-12-10 19:47:41 +00005145 return destType;
5146 }
5147 if (LHSTy->isObjCObjectPointerType() && RHSTy->isVoidPointerType()) {
David Blaikiebbafb8a2012-03-11 07:00:24 +00005148 if (getLangOpts().ObjCAutoRefCount) {
Eli Friedman8a78a582012-02-25 00:23:44 +00005149 // ARC forbids the implicit conversion of object pointers to 'void *',
5150 // so these types are not compatible.
5151 Diag(QuestionLoc, diag::err_cond_voidptr_arc) << LHSTy << RHSTy
5152 << LHS.get()->getSourceRange() << RHS.get()->getSourceRange();
5153 LHS = RHS = true;
5154 return QualType();
5155 }
Fariborz Jahaniana430f712009-12-10 19:47:41 +00005156 QualType lhptee = LHSTy->getAs<ObjCObjectPointerType>()->getPointeeType();
5157 QualType rhptee = RHSTy->getAs<PointerType>()->getPointeeType();
5158 QualType destPointee
5159 = Context.getQualifiedType(rhptee, lhptee.getQualifiers());
5160 QualType destType = Context.getPointerType(destPointee);
5161 // Add qualifiers if necessary.
John Wiegley01296292011-04-08 18:41:53 +00005162 RHS = ImpCastExprToType(RHS.take(), destType, CK_NoOp);
Fariborz Jahaniana430f712009-12-10 19:47:41 +00005163 // Promote to void*.
John Wiegley01296292011-04-08 18:41:53 +00005164 LHS = ImpCastExprToType(LHS.take(), destType, CK_BitCast);
Fariborz Jahaniana430f712009-12-10 19:47:41 +00005165 return destType;
5166 }
5167 return QualType();
5168}
5169
Chandler Carruthb00e8c02011-06-16 01:05:14 +00005170/// SuggestParentheses - Emit a note with a fixit hint that wraps
Hans Wennborgcf9bac42011-06-03 18:00:36 +00005171/// ParenRange in parentheses.
5172static void SuggestParentheses(Sema &Self, SourceLocation Loc,
Chandler Carruthb00e8c02011-06-16 01:05:14 +00005173 const PartialDiagnostic &Note,
5174 SourceRange ParenRange) {
5175 SourceLocation EndLoc = Self.PP.getLocForEndOfToken(ParenRange.getEnd());
5176 if (ParenRange.getBegin().isFileID() && ParenRange.getEnd().isFileID() &&
5177 EndLoc.isValid()) {
5178 Self.Diag(Loc, Note)
5179 << FixItHint::CreateInsertion(ParenRange.getBegin(), "(")
5180 << FixItHint::CreateInsertion(EndLoc, ")");
5181 } else {
5182 // We can't display the parentheses, so just show the bare note.
5183 Self.Diag(Loc, Note) << ParenRange;
Hans Wennborgcf9bac42011-06-03 18:00:36 +00005184 }
Hans Wennborgcf9bac42011-06-03 18:00:36 +00005185}
5186
5187static bool IsArithmeticOp(BinaryOperatorKind Opc) {
5188 return Opc >= BO_Mul && Opc <= BO_Shr;
5189}
5190
Hans Wennborgde2e67e2011-06-09 17:06:51 +00005191/// IsArithmeticBinaryExpr - Returns true if E is an arithmetic binary
5192/// expression, either using a built-in or overloaded operator,
Richard Trieud33e46e2011-09-06 20:06:39 +00005193/// and sets *OpCode to the opcode and *RHSExprs to the right-hand side
5194/// expression.
Hans Wennborgde2e67e2011-06-09 17:06:51 +00005195static bool IsArithmeticBinaryExpr(Expr *E, BinaryOperatorKind *Opcode,
Richard Trieud33e46e2011-09-06 20:06:39 +00005196 Expr **RHSExprs) {
Hans Wennborgbe207b32011-09-12 12:07:30 +00005197 // Don't strip parenthesis: we should not warn if E is in parenthesis.
5198 E = E->IgnoreImpCasts();
Hans Wennborgde2e67e2011-06-09 17:06:51 +00005199 E = E->IgnoreConversionOperator();
Hans Wennborgbe207b32011-09-12 12:07:30 +00005200 E = E->IgnoreImpCasts();
Hans Wennborgde2e67e2011-06-09 17:06:51 +00005201
5202 // Built-in binary operator.
5203 if (BinaryOperator *OP = dyn_cast<BinaryOperator>(E)) {
5204 if (IsArithmeticOp(OP->getOpcode())) {
5205 *Opcode = OP->getOpcode();
Richard Trieud33e46e2011-09-06 20:06:39 +00005206 *RHSExprs = OP->getRHS();
Hans Wennborgde2e67e2011-06-09 17:06:51 +00005207 return true;
5208 }
5209 }
5210
5211 // Overloaded operator.
5212 if (CXXOperatorCallExpr *Call = dyn_cast<CXXOperatorCallExpr>(E)) {
5213 if (Call->getNumArgs() != 2)
5214 return false;
5215
5216 // Make sure this is really a binary operator that is safe to pass into
5217 // BinaryOperator::getOverloadedOpcode(), e.g. it's not a subscript op.
5218 OverloadedOperatorKind OO = Call->getOperator();
5219 if (OO < OO_Plus || OO > OO_Arrow)
5220 return false;
5221
5222 BinaryOperatorKind OpKind = BinaryOperator::getOverloadedOpcode(OO);
5223 if (IsArithmeticOp(OpKind)) {
5224 *Opcode = OpKind;
Richard Trieud33e46e2011-09-06 20:06:39 +00005225 *RHSExprs = Call->getArg(1);
Hans Wennborgde2e67e2011-06-09 17:06:51 +00005226 return true;
5227 }
5228 }
5229
5230 return false;
5231}
5232
Hans Wennborgcf9bac42011-06-03 18:00:36 +00005233static bool IsLogicOp(BinaryOperatorKind Opc) {
5234 return (Opc >= BO_LT && Opc <= BO_NE) || (Opc >= BO_LAnd && Opc <= BO_LOr);
5235}
5236
Hans Wennborgde2e67e2011-06-09 17:06:51 +00005237/// ExprLooksBoolean - Returns true if E looks boolean, i.e. it has boolean type
5238/// or is a logical expression such as (x==y) which has int type, but is
5239/// commonly interpreted as boolean.
5240static bool ExprLooksBoolean(Expr *E) {
5241 E = E->IgnoreParenImpCasts();
5242
5243 if (E->getType()->isBooleanType())
5244 return true;
5245 if (BinaryOperator *OP = dyn_cast<BinaryOperator>(E))
5246 return IsLogicOp(OP->getOpcode());
5247 if (UnaryOperator *OP = dyn_cast<UnaryOperator>(E))
5248 return OP->getOpcode() == UO_LNot;
5249
5250 return false;
5251}
5252
Hans Wennborgcf9bac42011-06-03 18:00:36 +00005253/// DiagnoseConditionalPrecedence - Emit a warning when a conditional operator
5254/// and binary operator are mixed in a way that suggests the programmer assumed
5255/// the conditional operator has higher precedence, for example:
5256/// "int x = a + someBinaryCondition ? 1 : 2".
5257static void DiagnoseConditionalPrecedence(Sema &Self,
5258 SourceLocation OpLoc,
Chandler Carruth08dc2ba2011-06-16 01:05:08 +00005259 Expr *Condition,
Richard Trieud33e46e2011-09-06 20:06:39 +00005260 Expr *LHSExpr,
5261 Expr *RHSExpr) {
Hans Wennborgde2e67e2011-06-09 17:06:51 +00005262 BinaryOperatorKind CondOpcode;
5263 Expr *CondRHS;
Hans Wennborgcf9bac42011-06-03 18:00:36 +00005264
Chandler Carruth08dc2ba2011-06-16 01:05:08 +00005265 if (!IsArithmeticBinaryExpr(Condition, &CondOpcode, &CondRHS))
Hans Wennborgde2e67e2011-06-09 17:06:51 +00005266 return;
5267 if (!ExprLooksBoolean(CondRHS))
5268 return;
Hans Wennborgcf9bac42011-06-03 18:00:36 +00005269
Hans Wennborgde2e67e2011-06-09 17:06:51 +00005270 // The condition is an arithmetic binary expression, with a right-
5271 // hand side that looks boolean, so warn.
Hans Wennborgcf9bac42011-06-03 18:00:36 +00005272
Chandler Carruthb00e8c02011-06-16 01:05:14 +00005273 Self.Diag(OpLoc, diag::warn_precedence_conditional)
Chandler Carruth08dc2ba2011-06-16 01:05:08 +00005274 << Condition->getSourceRange()
Hans Wennborgde2e67e2011-06-09 17:06:51 +00005275 << BinaryOperator::getOpcodeStr(CondOpcode);
Hans Wennborgcf9bac42011-06-03 18:00:36 +00005276
Chandler Carruthb00e8c02011-06-16 01:05:14 +00005277 SuggestParentheses(Self, OpLoc,
5278 Self.PDiag(diag::note_precedence_conditional_silence)
5279 << BinaryOperator::getOpcodeStr(CondOpcode),
5280 SourceRange(Condition->getLocStart(), Condition->getLocEnd()));
Chandler Carruthf51c5a52011-06-21 23:04:18 +00005281
5282 SuggestParentheses(Self, OpLoc,
5283 Self.PDiag(diag::note_precedence_conditional_first),
Richard Trieud33e46e2011-09-06 20:06:39 +00005284 SourceRange(CondRHS->getLocStart(), RHSExpr->getLocEnd()));
Hans Wennborgcf9bac42011-06-03 18:00:36 +00005285}
5286
Steve Naroff83895f72007-09-16 03:34:24 +00005287/// ActOnConditionalOp - Parse a ?: operation. Note that 'LHS' may be null
Chris Lattnere168f762006-11-10 05:29:30 +00005288/// in the case of a the GNU conditional expr extension.
John McCalldadc5752010-08-24 06:29:42 +00005289ExprResult Sema::ActOnConditionalOp(SourceLocation QuestionLoc,
John McCallc07a0c72011-02-17 10:25:35 +00005290 SourceLocation ColonLoc,
5291 Expr *CondExpr, Expr *LHSExpr,
5292 Expr *RHSExpr) {
Chris Lattner2ab40a62007-11-26 01:40:58 +00005293 // If this is the gnu "x ?: y" extension, analyze the types as though the LHS
5294 // was the condition.
John McCallc07a0c72011-02-17 10:25:35 +00005295 OpaqueValueExpr *opaqueValue = 0;
5296 Expr *commonExpr = 0;
5297 if (LHSExpr == 0) {
5298 commonExpr = CondExpr;
5299
5300 // We usually want to apply unary conversions *before* saving, except
5301 // in the special case of a C++ l-value conditional.
David Blaikiebbafb8a2012-03-11 07:00:24 +00005302 if (!(getLangOpts().CPlusPlus
John McCallc07a0c72011-02-17 10:25:35 +00005303 && !commonExpr->isTypeDependent()
5304 && commonExpr->getValueKind() == RHSExpr->getValueKind()
5305 && commonExpr->isGLValue()
5306 && commonExpr->isOrdinaryOrBitFieldObject()
5307 && RHSExpr->isOrdinaryOrBitFieldObject()
5308 && Context.hasSameType(commonExpr->getType(), RHSExpr->getType()))) {
John Wiegley01296292011-04-08 18:41:53 +00005309 ExprResult commonRes = UsualUnaryConversions(commonExpr);
5310 if (commonRes.isInvalid())
5311 return ExprError();
5312 commonExpr = commonRes.take();
John McCallc07a0c72011-02-17 10:25:35 +00005313 }
5314
5315 opaqueValue = new (Context) OpaqueValueExpr(commonExpr->getExprLoc(),
5316 commonExpr->getType(),
5317 commonExpr->getValueKind(),
Douglas Gregor2d5aea02012-02-23 22:17:26 +00005318 commonExpr->getObjectKind(),
5319 commonExpr);
John McCallc07a0c72011-02-17 10:25:35 +00005320 LHSExpr = CondExpr = opaqueValue;
Fariborz Jahanianc6bf0bd2010-08-31 18:02:20 +00005321 }
Sebastian Redlb5d49352009-01-19 22:31:54 +00005322
John McCall7decc9e2010-11-18 06:31:45 +00005323 ExprValueKind VK = VK_RValue;
John McCall4bc41ae2010-11-18 19:01:18 +00005324 ExprObjectKind OK = OK_Ordinary;
John Wiegley01296292011-04-08 18:41:53 +00005325 ExprResult Cond = Owned(CondExpr), LHS = Owned(LHSExpr), RHS = Owned(RHSExpr);
5326 QualType result = CheckConditionalOperands(Cond, LHS, RHS,
John McCallc07a0c72011-02-17 10:25:35 +00005327 VK, OK, QuestionLoc);
John Wiegley01296292011-04-08 18:41:53 +00005328 if (result.isNull() || Cond.isInvalid() || LHS.isInvalid() ||
5329 RHS.isInvalid())
Sebastian Redlb5d49352009-01-19 22:31:54 +00005330 return ExprError();
5331
Hans Wennborgcf9bac42011-06-03 18:00:36 +00005332 DiagnoseConditionalPrecedence(*this, QuestionLoc, Cond.get(), LHS.get(),
5333 RHS.get());
5334
John McCallc07a0c72011-02-17 10:25:35 +00005335 if (!commonExpr)
John Wiegley01296292011-04-08 18:41:53 +00005336 return Owned(new (Context) ConditionalOperator(Cond.take(), QuestionLoc,
5337 LHS.take(), ColonLoc,
5338 RHS.take(), result, VK, OK));
John McCallc07a0c72011-02-17 10:25:35 +00005339
5340 return Owned(new (Context)
John Wiegley01296292011-04-08 18:41:53 +00005341 BinaryConditionalOperator(commonExpr, opaqueValue, Cond.take(), LHS.take(),
Richard Trieucfc491d2011-08-02 04:35:43 +00005342 RHS.take(), QuestionLoc, ColonLoc, result, VK,
5343 OK));
Chris Lattnere168f762006-11-10 05:29:30 +00005344}
5345
John McCallaba90822011-01-31 23:13:11 +00005346// checkPointerTypesForAssignment - This is a very tricky routine (despite
Mike Stump4e1f26a2009-02-19 03:04:26 +00005347// being closely modeled after the C99 spec:-). The odd characteristic of this
Steve Naroff3f597292007-05-11 22:18:03 +00005348// routine is it effectively iqnores the qualifiers on the top level pointee.
5349// This circumvents the usual type rules specified in 6.2.7p1 & 6.7.5.[1-3].
5350// FIXME: add a couple examples in this comment.
John McCallaba90822011-01-31 23:13:11 +00005351static Sema::AssignConvertType
Richard Trieua871b972011-09-06 20:21:22 +00005352checkPointerTypesForAssignment(Sema &S, QualType LHSType, QualType RHSType) {
5353 assert(LHSType.isCanonical() && "LHS not canonicalized!");
5354 assert(RHSType.isCanonical() && "RHS not canonicalized!");
Mike Stump4e1f26a2009-02-19 03:04:26 +00005355
Steve Naroff1f4d7272007-05-11 04:00:31 +00005356 // get the "pointed to" type (ignoring qualifiers at the top level)
John McCall4fff8f62011-02-01 00:10:29 +00005357 const Type *lhptee, *rhptee;
5358 Qualifiers lhq, rhq;
Richard Trieua871b972011-09-06 20:21:22 +00005359 llvm::tie(lhptee, lhq) = cast<PointerType>(LHSType)->getPointeeType().split();
5360 llvm::tie(rhptee, rhq) = cast<PointerType>(RHSType)->getPointeeType().split();
Mike Stump4e1f26a2009-02-19 03:04:26 +00005361
John McCallaba90822011-01-31 23:13:11 +00005362 Sema::AssignConvertType ConvTy = Sema::Compatible;
Mike Stump4e1f26a2009-02-19 03:04:26 +00005363
5364 // C99 6.5.16.1p1: This following citation is common to constraints
5365 // 3 & 4 (below). ...and the type *pointed to* by the left has all the
5366 // qualifiers of the type *pointed to* by the right;
John McCall4fff8f62011-02-01 00:10:29 +00005367 Qualifiers lq;
5368
John McCall31168b02011-06-15 23:02:42 +00005369 // As a special case, 'non-__weak A *' -> 'non-__weak const *' is okay.
5370 if (lhq.getObjCLifetime() != rhq.getObjCLifetime() &&
5371 lhq.compatiblyIncludesObjCLifetime(rhq)) {
5372 // Ignore lifetime for further calculation.
5373 lhq.removeObjCLifetime();
5374 rhq.removeObjCLifetime();
5375 }
5376
John McCall4fff8f62011-02-01 00:10:29 +00005377 if (!lhq.compatiblyIncludes(rhq)) {
5378 // Treat address-space mismatches as fatal. TODO: address subspaces
5379 if (lhq.getAddressSpace() != rhq.getAddressSpace())
5380 ConvTy = Sema::IncompatiblePointerDiscardsQualifiers;
5381
John McCall31168b02011-06-15 23:02:42 +00005382 // It's okay to add or remove GC or lifetime qualifiers when converting to
John McCall78535952011-03-26 02:56:45 +00005383 // and from void*.
John McCall18ce25e2012-02-08 00:46:36 +00005384 else if (lhq.withoutObjCGCAttr().withoutObjCLifetime()
John McCall31168b02011-06-15 23:02:42 +00005385 .compatiblyIncludes(
John McCall18ce25e2012-02-08 00:46:36 +00005386 rhq.withoutObjCGCAttr().withoutObjCLifetime())
John McCall78535952011-03-26 02:56:45 +00005387 && (lhptee->isVoidType() || rhptee->isVoidType()))
5388 ; // keep old
5389
John McCall31168b02011-06-15 23:02:42 +00005390 // Treat lifetime mismatches as fatal.
5391 else if (lhq.getObjCLifetime() != rhq.getObjCLifetime())
5392 ConvTy = Sema::IncompatiblePointerDiscardsQualifiers;
5393
John McCall4fff8f62011-02-01 00:10:29 +00005394 // For GCC compatibility, other qualifier mismatches are treated
5395 // as still compatible in C.
5396 else ConvTy = Sema::CompatiblePointerDiscardsQualifiers;
5397 }
Steve Naroff3f597292007-05-11 22:18:03 +00005398
Mike Stump4e1f26a2009-02-19 03:04:26 +00005399 // C99 6.5.16.1p1 (constraint 4): If one operand is a pointer to an object or
5400 // incomplete type and the other is a pointer to a qualified or unqualified
Steve Naroff3f597292007-05-11 22:18:03 +00005401 // version of void...
Chris Lattner0a788432008-01-03 22:56:36 +00005402 if (lhptee->isVoidType()) {
Chris Lattnerb3a176d2008-04-02 06:59:01 +00005403 if (rhptee->isIncompleteOrObjectType())
Chris Lattner9bad62c2008-01-04 18:04:52 +00005404 return ConvTy;
Mike Stump4e1f26a2009-02-19 03:04:26 +00005405
Chris Lattner0a788432008-01-03 22:56:36 +00005406 // As an extension, we allow cast to/from void* to function pointer.
Chris Lattnerb3a176d2008-04-02 06:59:01 +00005407 assert(rhptee->isFunctionType());
John McCallaba90822011-01-31 23:13:11 +00005408 return Sema::FunctionVoidPointer;
Chris Lattner0a788432008-01-03 22:56:36 +00005409 }
Mike Stump4e1f26a2009-02-19 03:04:26 +00005410
Chris Lattner0a788432008-01-03 22:56:36 +00005411 if (rhptee->isVoidType()) {
Chris Lattnerb3a176d2008-04-02 06:59:01 +00005412 if (lhptee->isIncompleteOrObjectType())
Chris Lattner9bad62c2008-01-04 18:04:52 +00005413 return ConvTy;
Chris Lattner0a788432008-01-03 22:56:36 +00005414
5415 // As an extension, we allow cast to/from void* to function pointer.
Chris Lattnerb3a176d2008-04-02 06:59:01 +00005416 assert(lhptee->isFunctionType());
John McCallaba90822011-01-31 23:13:11 +00005417 return Sema::FunctionVoidPointer;
Chris Lattner0a788432008-01-03 22:56:36 +00005418 }
John McCall4fff8f62011-02-01 00:10:29 +00005419
Mike Stump4e1f26a2009-02-19 03:04:26 +00005420 // C99 6.5.16.1p1 (constraint 3): both operands are pointers to qualified or
Steve Naroff3f597292007-05-11 22:18:03 +00005421 // unqualified versions of compatible types, ...
John McCall4fff8f62011-02-01 00:10:29 +00005422 QualType ltrans = QualType(lhptee, 0), rtrans = QualType(rhptee, 0);
5423 if (!S.Context.typesAreCompatible(ltrans, rtrans)) {
Eli Friedman80160bd2009-03-22 23:59:44 +00005424 // Check if the pointee types are compatible ignoring the sign.
5425 // We explicitly check for char so that we catch "char" vs
5426 // "unsigned char" on systems where "char" is unsigned.
Chris Lattnerec3a1562009-10-17 20:33:28 +00005427 if (lhptee->isCharType())
John McCall4fff8f62011-02-01 00:10:29 +00005428 ltrans = S.Context.UnsignedCharTy;
Douglas Gregor5cc2c8b2010-07-23 15:58:24 +00005429 else if (lhptee->hasSignedIntegerRepresentation())
John McCall4fff8f62011-02-01 00:10:29 +00005430 ltrans = S.Context.getCorrespondingUnsignedType(ltrans);
Kovarththanan Rajaratnamba2c6522010-03-13 10:17:05 +00005431
Chris Lattnerec3a1562009-10-17 20:33:28 +00005432 if (rhptee->isCharType())
John McCall4fff8f62011-02-01 00:10:29 +00005433 rtrans = S.Context.UnsignedCharTy;
Douglas Gregor5cc2c8b2010-07-23 15:58:24 +00005434 else if (rhptee->hasSignedIntegerRepresentation())
John McCall4fff8f62011-02-01 00:10:29 +00005435 rtrans = S.Context.getCorrespondingUnsignedType(rtrans);
Chris Lattnerec3a1562009-10-17 20:33:28 +00005436
John McCall4fff8f62011-02-01 00:10:29 +00005437 if (ltrans == rtrans) {
Eli Friedman80160bd2009-03-22 23:59:44 +00005438 // Types are compatible ignoring the sign. Qualifier incompatibility
5439 // takes priority over sign incompatibility because the sign
5440 // warning can be disabled.
John McCallaba90822011-01-31 23:13:11 +00005441 if (ConvTy != Sema::Compatible)
Eli Friedman80160bd2009-03-22 23:59:44 +00005442 return ConvTy;
John McCall4fff8f62011-02-01 00:10:29 +00005443
John McCallaba90822011-01-31 23:13:11 +00005444 return Sema::IncompatiblePointerSign;
Eli Friedman80160bd2009-03-22 23:59:44 +00005445 }
Kovarththanan Rajaratnamba2c6522010-03-13 10:17:05 +00005446
Fariborz Jahaniand7aa9d82009-11-07 20:20:40 +00005447 // If we are a multi-level pointer, it's possible that our issue is simply
5448 // one of qualification - e.g. char ** -> const char ** is not allowed. If
5449 // the eventual target type is the same and the pointers have the same
5450 // level of indirection, this must be the issue.
John McCallaba90822011-01-31 23:13:11 +00005451 if (isa<PointerType>(lhptee) && isa<PointerType>(rhptee)) {
Fariborz Jahaniand7aa9d82009-11-07 20:20:40 +00005452 do {
John McCall4fff8f62011-02-01 00:10:29 +00005453 lhptee = cast<PointerType>(lhptee)->getPointeeType().getTypePtr();
5454 rhptee = cast<PointerType>(rhptee)->getPointeeType().getTypePtr();
John McCallaba90822011-01-31 23:13:11 +00005455 } while (isa<PointerType>(lhptee) && isa<PointerType>(rhptee));
Kovarththanan Rajaratnamba2c6522010-03-13 10:17:05 +00005456
John McCall4fff8f62011-02-01 00:10:29 +00005457 if (lhptee == rhptee)
John McCallaba90822011-01-31 23:13:11 +00005458 return Sema::IncompatibleNestedPointerQualifiers;
Fariborz Jahaniand7aa9d82009-11-07 20:20:40 +00005459 }
Kovarththanan Rajaratnamba2c6522010-03-13 10:17:05 +00005460
Eli Friedman80160bd2009-03-22 23:59:44 +00005461 // General pointer incompatibility takes priority over qualifiers.
John McCallaba90822011-01-31 23:13:11 +00005462 return Sema::IncompatiblePointer;
Eli Friedman80160bd2009-03-22 23:59:44 +00005463 }
David Blaikiebbafb8a2012-03-11 07:00:24 +00005464 if (!S.getLangOpts().CPlusPlus &&
Fariborz Jahanian48c69102011-10-05 00:05:34 +00005465 S.IsNoReturnConversion(ltrans, rtrans, ltrans))
5466 return Sema::IncompatiblePointer;
Chris Lattner9bad62c2008-01-04 18:04:52 +00005467 return ConvTy;
Steve Naroff1f4d7272007-05-11 04:00:31 +00005468}
5469
John McCallaba90822011-01-31 23:13:11 +00005470/// checkBlockPointerTypesForAssignment - This routine determines whether two
Steve Naroff081c7422008-09-04 15:10:53 +00005471/// block pointer types are compatible or whether a block and normal pointer
5472/// are compatible. It is more restrict than comparing two function pointer
5473// types.
John McCallaba90822011-01-31 23:13:11 +00005474static Sema::AssignConvertType
Richard Trieua871b972011-09-06 20:21:22 +00005475checkBlockPointerTypesForAssignment(Sema &S, QualType LHSType,
5476 QualType RHSType) {
5477 assert(LHSType.isCanonical() && "LHS not canonicalized!");
5478 assert(RHSType.isCanonical() && "RHS not canonicalized!");
John McCallaba90822011-01-31 23:13:11 +00005479
Steve Naroff081c7422008-09-04 15:10:53 +00005480 QualType lhptee, rhptee;
Mike Stump4e1f26a2009-02-19 03:04:26 +00005481
Steve Naroff081c7422008-09-04 15:10:53 +00005482 // get the "pointed to" type (ignoring qualifiers at the top level)
Richard Trieua871b972011-09-06 20:21:22 +00005483 lhptee = cast<BlockPointerType>(LHSType)->getPointeeType();
5484 rhptee = cast<BlockPointerType>(RHSType)->getPointeeType();
Mike Stump4e1f26a2009-02-19 03:04:26 +00005485
John McCallaba90822011-01-31 23:13:11 +00005486 // In C++, the types have to match exactly.
David Blaikiebbafb8a2012-03-11 07:00:24 +00005487 if (S.getLangOpts().CPlusPlus)
John McCallaba90822011-01-31 23:13:11 +00005488 return Sema::IncompatibleBlockPointer;
Mike Stump4e1f26a2009-02-19 03:04:26 +00005489
John McCallaba90822011-01-31 23:13:11 +00005490 Sema::AssignConvertType ConvTy = Sema::Compatible;
Mike Stump4e1f26a2009-02-19 03:04:26 +00005491
Steve Naroff081c7422008-09-04 15:10:53 +00005492 // For blocks we enforce that qualifiers are identical.
John McCallaba90822011-01-31 23:13:11 +00005493 if (lhptee.getLocalQualifiers() != rhptee.getLocalQualifiers())
5494 ConvTy = Sema::CompatiblePointerDiscardsQualifiers;
Mike Stump4e1f26a2009-02-19 03:04:26 +00005495
Richard Trieua871b972011-09-06 20:21:22 +00005496 if (!S.Context.typesAreBlockPointerCompatible(LHSType, RHSType))
John McCallaba90822011-01-31 23:13:11 +00005497 return Sema::IncompatibleBlockPointer;
5498
Steve Naroff081c7422008-09-04 15:10:53 +00005499 return ConvTy;
5500}
5501
John McCallaba90822011-01-31 23:13:11 +00005502/// checkObjCPointerTypesForAssignment - Compares two objective-c pointer types
Fariborz Jahanian410f2eb2009-12-08 18:24:49 +00005503/// for assignment compatibility.
John McCallaba90822011-01-31 23:13:11 +00005504static Sema::AssignConvertType
Richard Trieua871b972011-09-06 20:21:22 +00005505checkObjCPointerTypesForAssignment(Sema &S, QualType LHSType,
5506 QualType RHSType) {
5507 assert(LHSType.isCanonical() && "LHS was not canonicalized!");
5508 assert(RHSType.isCanonical() && "RHS was not canonicalized!");
John McCallaba90822011-01-31 23:13:11 +00005509
Richard Trieua871b972011-09-06 20:21:22 +00005510 if (LHSType->isObjCBuiltinType()) {
Fariborz Jahaniand5bb8cb2010-03-19 18:06:10 +00005511 // Class is not compatible with ObjC object pointers.
Richard Trieua871b972011-09-06 20:21:22 +00005512 if (LHSType->isObjCClassType() && !RHSType->isObjCBuiltinType() &&
5513 !RHSType->isObjCQualifiedClassType())
John McCallaba90822011-01-31 23:13:11 +00005514 return Sema::IncompatiblePointer;
5515 return Sema::Compatible;
Fariborz Jahaniand5bb8cb2010-03-19 18:06:10 +00005516 }
Richard Trieua871b972011-09-06 20:21:22 +00005517 if (RHSType->isObjCBuiltinType()) {
Richard Trieua871b972011-09-06 20:21:22 +00005518 if (RHSType->isObjCClassType() && !LHSType->isObjCBuiltinType() &&
5519 !LHSType->isObjCQualifiedClassType())
Fariborz Jahaniand923eb02011-09-15 20:40:18 +00005520 return Sema::IncompatiblePointer;
John McCallaba90822011-01-31 23:13:11 +00005521 return Sema::Compatible;
Fariborz Jahaniand5bb8cb2010-03-19 18:06:10 +00005522 }
Richard Trieua871b972011-09-06 20:21:22 +00005523 QualType lhptee = LHSType->getAs<ObjCObjectPointerType>()->getPointeeType();
5524 QualType rhptee = RHSType->getAs<ObjCObjectPointerType>()->getPointeeType();
Kovarththanan Rajaratnamba2c6522010-03-13 10:17:05 +00005525
Fariborz Jahaniane74d47e2012-01-12 22:12:08 +00005526 if (!lhptee.isAtLeastAsQualifiedAs(rhptee) &&
5527 // make an exception for id<P>
5528 !LHSType->isObjCQualifiedIdType())
John McCallaba90822011-01-31 23:13:11 +00005529 return Sema::CompatiblePointerDiscardsQualifiers;
5530
Richard Trieua871b972011-09-06 20:21:22 +00005531 if (S.Context.typesAreCompatible(LHSType, RHSType))
John McCallaba90822011-01-31 23:13:11 +00005532 return Sema::Compatible;
Richard Trieua871b972011-09-06 20:21:22 +00005533 if (LHSType->isObjCQualifiedIdType() || RHSType->isObjCQualifiedIdType())
John McCallaba90822011-01-31 23:13:11 +00005534 return Sema::IncompatibleObjCQualifiedId;
5535 return Sema::IncompatiblePointer;
Fariborz Jahanian410f2eb2009-12-08 18:24:49 +00005536}
5537
John McCall29600e12010-11-16 02:32:08 +00005538Sema::AssignConvertType
Douglas Gregorc03a1082011-01-28 02:26:04 +00005539Sema::CheckAssignmentConstraints(SourceLocation Loc,
Richard Trieua871b972011-09-06 20:21:22 +00005540 QualType LHSType, QualType RHSType) {
John McCall29600e12010-11-16 02:32:08 +00005541 // Fake up an opaque expression. We don't actually care about what
5542 // cast operations are required, so if CheckAssignmentConstraints
5543 // adds casts to this they'll be wasted, but fortunately that doesn't
5544 // usually happen on valid code.
Richard Trieua871b972011-09-06 20:21:22 +00005545 OpaqueValueExpr RHSExpr(Loc, RHSType, VK_RValue);
5546 ExprResult RHSPtr = &RHSExpr;
John McCall29600e12010-11-16 02:32:08 +00005547 CastKind K = CK_Invalid;
5548
Richard Trieua871b972011-09-06 20:21:22 +00005549 return CheckAssignmentConstraints(LHSType, RHSPtr, K);
John McCall29600e12010-11-16 02:32:08 +00005550}
5551
Mike Stump4e1f26a2009-02-19 03:04:26 +00005552/// CheckAssignmentConstraints (C99 6.5.16) - This routine currently
5553/// has code to accommodate several GCC extensions when type checking
Steve Naroff17f76e02007-05-03 21:03:48 +00005554/// pointers. Here are some objectionable examples that GCC considers warnings:
5555///
5556/// int a, *pint;
5557/// short *pshort;
5558/// struct foo *pfoo;
5559///
5560/// pint = pshort; // warning: assignment from incompatible pointer type
5561/// a = pint; // warning: assignment makes integer from pointer without a cast
5562/// pint = a; // warning: assignment makes pointer from integer without a cast
5563/// pint = pfoo; // warning: assignment from incompatible pointer type
5564///
5565/// As a result, the code for dealing with pointers is more complex than the
Mike Stump4e1f26a2009-02-19 03:04:26 +00005566/// C99 spec dictates.
Steve Naroff17f76e02007-05-03 21:03:48 +00005567///
John McCall8cb679e2010-11-15 09:13:47 +00005568/// Sets 'Kind' for any result kind except Incompatible.
Chris Lattner9bad62c2008-01-04 18:04:52 +00005569Sema::AssignConvertType
Richard Trieude4958f2011-09-06 20:30:53 +00005570Sema::CheckAssignmentConstraints(QualType LHSType, ExprResult &RHS,
John McCall8cb679e2010-11-15 09:13:47 +00005571 CastKind &Kind) {
Richard Trieude4958f2011-09-06 20:30:53 +00005572 QualType RHSType = RHS.get()->getType();
5573 QualType OrigLHSType = LHSType;
John McCall29600e12010-11-16 02:32:08 +00005574
Chris Lattnera52c2f22008-01-04 23:18:45 +00005575 // Get canonical types. We're not formatting these types, just comparing
5576 // them.
Richard Trieude4958f2011-09-06 20:30:53 +00005577 LHSType = Context.getCanonicalType(LHSType).getUnqualifiedType();
5578 RHSType = Context.getCanonicalType(RHSType).getUnqualifiedType();
Eli Friedman3360d892008-05-30 18:07:22 +00005579
Eli Friedman0dfb8892011-10-06 23:00:33 +00005580
John McCalle5255932011-01-31 22:28:28 +00005581 // Common case: no conversion required.
Richard Trieude4958f2011-09-06 20:30:53 +00005582 if (LHSType == RHSType) {
John McCall8cb679e2010-11-15 09:13:47 +00005583 Kind = CK_NoOp;
John McCall8cb679e2010-11-15 09:13:47 +00005584 return Compatible;
David Chisnall9f57c292009-08-17 16:35:33 +00005585 }
5586
Eli Friedman93ee5ca2012-06-16 02:19:17 +00005587 // If we have an atomic type, try a non-atomic assignment, then just add an
5588 // atomic qualification step.
David Chisnallfa35df62012-01-16 17:27:18 +00005589 if (const AtomicType *AtomicTy = dyn_cast<AtomicType>(LHSType)) {
Eli Friedman93ee5ca2012-06-16 02:19:17 +00005590 Sema::AssignConvertType result =
5591 CheckAssignmentConstraints(AtomicTy->getValueType(), RHS, Kind);
5592 if (result != Compatible)
5593 return result;
5594 if (Kind != CK_NoOp)
5595 RHS = ImpCastExprToType(RHS.take(), AtomicTy->getValueType(), Kind);
5596 Kind = CK_NonAtomicToAtomic;
5597 return Compatible;
David Chisnallfa35df62012-01-16 17:27:18 +00005598 }
5599
Douglas Gregor6b754842008-10-28 00:22:11 +00005600 // If the left-hand side is a reference type, then we are in a
5601 // (rare!) case where we've allowed the use of references in C,
5602 // e.g., as a parameter type in a built-in function. In this case,
5603 // just make sure that the type referenced is compatible with the
5604 // right-hand side type. The caller is responsible for adjusting
Richard Trieude4958f2011-09-06 20:30:53 +00005605 // LHSType so that the resulting expression does not have reference
Douglas Gregor6b754842008-10-28 00:22:11 +00005606 // type.
Richard Trieude4958f2011-09-06 20:30:53 +00005607 if (const ReferenceType *LHSTypeRef = LHSType->getAs<ReferenceType>()) {
5608 if (Context.typesAreCompatible(LHSTypeRef->getPointeeType(), RHSType)) {
John McCall8cb679e2010-11-15 09:13:47 +00005609 Kind = CK_LValueBitCast;
Anders Carlsson24ebce62007-10-12 23:56:29 +00005610 return Compatible;
John McCall8cb679e2010-11-15 09:13:47 +00005611 }
Chris Lattnera52c2f22008-01-04 23:18:45 +00005612 return Incompatible;
Fariborz Jahaniana1e34202007-12-19 17:45:58 +00005613 }
John McCalle5255932011-01-31 22:28:28 +00005614
Nate Begemanbd956c42009-06-28 02:36:38 +00005615 // Allow scalar to ExtVector assignments, and assignments of an ExtVector type
5616 // to the same ExtVector type.
Richard Trieude4958f2011-09-06 20:30:53 +00005617 if (LHSType->isExtVectorType()) {
5618 if (RHSType->isExtVectorType())
John McCall8cb679e2010-11-15 09:13:47 +00005619 return Incompatible;
Richard Trieude4958f2011-09-06 20:30:53 +00005620 if (RHSType->isArithmeticType()) {
John McCall29600e12010-11-16 02:32:08 +00005621 // CK_VectorSplat does T -> vector T, so first cast to the
5622 // element type.
Richard Trieude4958f2011-09-06 20:30:53 +00005623 QualType elType = cast<ExtVectorType>(LHSType)->getElementType();
5624 if (elType != RHSType) {
John McCall9776e432011-10-06 23:25:11 +00005625 Kind = PrepareScalarCast(RHS, elType);
Richard Trieude4958f2011-09-06 20:30:53 +00005626 RHS = ImpCastExprToType(RHS.take(), elType, Kind);
John McCall29600e12010-11-16 02:32:08 +00005627 }
5628 Kind = CK_VectorSplat;
Nate Begemanbd956c42009-06-28 02:36:38 +00005629 return Compatible;
John McCall8cb679e2010-11-15 09:13:47 +00005630 }
Nate Begemanbd956c42009-06-28 02:36:38 +00005631 }
Mike Stump11289f42009-09-09 15:08:12 +00005632
John McCalle5255932011-01-31 22:28:28 +00005633 // Conversions to or from vector type.
Richard Trieude4958f2011-09-06 20:30:53 +00005634 if (LHSType->isVectorType() || RHSType->isVectorType()) {
5635 if (LHSType->isVectorType() && RHSType->isVectorType()) {
Bob Wilson01856f32010-12-02 00:25:15 +00005636 // Allow assignments of an AltiVec vector type to an equivalent GCC
5637 // vector type and vice versa
Richard Trieude4958f2011-09-06 20:30:53 +00005638 if (Context.areCompatibleVectorTypes(LHSType, RHSType)) {
Bob Wilson01856f32010-12-02 00:25:15 +00005639 Kind = CK_BitCast;
5640 return Compatible;
5641 }
5642
Douglas Gregor59e8b3b2010-08-06 10:14:59 +00005643 // If we are allowing lax vector conversions, and LHS and RHS are both
5644 // vectors, the total size only needs to be the same. This is a bitcast;
5645 // no bits are changed but the result type is different.
David Blaikiebbafb8a2012-03-11 07:00:24 +00005646 if (getLangOpts().LaxVectorConversions &&
Richard Trieude4958f2011-09-06 20:30:53 +00005647 (Context.getTypeSize(LHSType) == Context.getTypeSize(RHSType))) {
John McCall3065d042010-11-15 10:08:00 +00005648 Kind = CK_BitCast;
Anders Carlssondb5a9b62009-01-30 23:17:46 +00005649 return IncompatibleVectors;
John McCall8cb679e2010-11-15 09:13:47 +00005650 }
Chris Lattner881a2122008-01-04 23:32:24 +00005651 }
5652 return Incompatible;
Mike Stump4e1f26a2009-02-19 03:04:26 +00005653 }
Eli Friedman3360d892008-05-30 18:07:22 +00005654
John McCalle5255932011-01-31 22:28:28 +00005655 // Arithmetic conversions.
Richard Trieude4958f2011-09-06 20:30:53 +00005656 if (LHSType->isArithmeticType() && RHSType->isArithmeticType() &&
David Blaikiebbafb8a2012-03-11 07:00:24 +00005657 !(getLangOpts().CPlusPlus && LHSType->isEnumeralType())) {
John McCall9776e432011-10-06 23:25:11 +00005658 Kind = PrepareScalarCast(RHS, LHSType);
Steve Naroff98cf3e92007-06-06 18:38:38 +00005659 return Compatible;
John McCall8cb679e2010-11-15 09:13:47 +00005660 }
Eli Friedman3360d892008-05-30 18:07:22 +00005661
John McCalle5255932011-01-31 22:28:28 +00005662 // Conversions to normal pointers.
Richard Trieude4958f2011-09-06 20:30:53 +00005663 if (const PointerType *LHSPointer = dyn_cast<PointerType>(LHSType)) {
John McCalle5255932011-01-31 22:28:28 +00005664 // U* -> T*
Richard Trieude4958f2011-09-06 20:30:53 +00005665 if (isa<PointerType>(RHSType)) {
John McCall8cb679e2010-11-15 09:13:47 +00005666 Kind = CK_BitCast;
Richard Trieude4958f2011-09-06 20:30:53 +00005667 return checkPointerTypesForAssignment(*this, LHSType, RHSType);
John McCall8cb679e2010-11-15 09:13:47 +00005668 }
Mike Stump4e1f26a2009-02-19 03:04:26 +00005669
John McCalle5255932011-01-31 22:28:28 +00005670 // int -> T*
Richard Trieude4958f2011-09-06 20:30:53 +00005671 if (RHSType->isIntegerType()) {
John McCalle5255932011-01-31 22:28:28 +00005672 Kind = CK_IntegralToPointer; // FIXME: null?
5673 return IntToPointer;
Steve Naroff7cae42b2009-07-10 23:34:53 +00005674 }
John McCalle5255932011-01-31 22:28:28 +00005675
5676 // C pointers are not compatible with ObjC object pointers,
5677 // with two exceptions:
Richard Trieude4958f2011-09-06 20:30:53 +00005678 if (isa<ObjCObjectPointerType>(RHSType)) {
John McCalle5255932011-01-31 22:28:28 +00005679 // - conversions to void*
Richard Trieude4958f2011-09-06 20:30:53 +00005680 if (LHSPointer->getPointeeType()->isVoidType()) {
John McCall9320b872011-09-09 05:25:32 +00005681 Kind = CK_BitCast;
John McCalle5255932011-01-31 22:28:28 +00005682 return Compatible;
5683 }
5684
5685 // - conversions from 'Class' to the redefinition type
Richard Trieude4958f2011-09-06 20:30:53 +00005686 if (RHSType->isObjCClassType() &&
5687 Context.hasSameType(LHSType,
Douglas Gregor97673472011-08-11 20:58:55 +00005688 Context.getObjCClassRedefinitionType())) {
John McCall8cb679e2010-11-15 09:13:47 +00005689 Kind = CK_BitCast;
Douglas Gregore7dd1452008-11-27 00:44:28 +00005690 return Compatible;
John McCall8cb679e2010-11-15 09:13:47 +00005691 }
Douglas Gregor486b74e2011-09-27 16:10:05 +00005692
John McCalle5255932011-01-31 22:28:28 +00005693 Kind = CK_BitCast;
5694 return IncompatiblePointer;
5695 }
5696
5697 // U^ -> void*
Richard Trieude4958f2011-09-06 20:30:53 +00005698 if (RHSType->getAs<BlockPointerType>()) {
5699 if (LHSPointer->getPointeeType()->isVoidType()) {
John McCalle5255932011-01-31 22:28:28 +00005700 Kind = CK_BitCast;
Steve Naroff32d072c2008-09-29 18:10:17 +00005701 return Compatible;
John McCall8cb679e2010-11-15 09:13:47 +00005702 }
Steve Naroff32d072c2008-09-29 18:10:17 +00005703 }
John McCalle5255932011-01-31 22:28:28 +00005704
Steve Naroff081c7422008-09-04 15:10:53 +00005705 return Incompatible;
5706 }
5707
John McCalle5255932011-01-31 22:28:28 +00005708 // Conversions to block pointers.
Richard Trieude4958f2011-09-06 20:30:53 +00005709 if (isa<BlockPointerType>(LHSType)) {
John McCalle5255932011-01-31 22:28:28 +00005710 // U^ -> T^
Richard Trieude4958f2011-09-06 20:30:53 +00005711 if (RHSType->isBlockPointerType()) {
John McCall9320b872011-09-09 05:25:32 +00005712 Kind = CK_BitCast;
Richard Trieude4958f2011-09-06 20:30:53 +00005713 return checkBlockPointerTypesForAssignment(*this, LHSType, RHSType);
John McCalle5255932011-01-31 22:28:28 +00005714 }
5715
5716 // int or null -> T^
Richard Trieude4958f2011-09-06 20:30:53 +00005717 if (RHSType->isIntegerType()) {
John McCall8cb679e2010-11-15 09:13:47 +00005718 Kind = CK_IntegralToPointer; // FIXME: null
Eli Friedman8163b7a2009-02-25 04:20:42 +00005719 return IntToBlockPointer;
John McCall8cb679e2010-11-15 09:13:47 +00005720 }
5721
John McCalle5255932011-01-31 22:28:28 +00005722 // id -> T^
David Blaikiebbafb8a2012-03-11 07:00:24 +00005723 if (getLangOpts().ObjC1 && RHSType->isObjCIdType()) {
John McCalle5255932011-01-31 22:28:28 +00005724 Kind = CK_AnyPointerToBlockPointerCast;
Steve Naroff32d072c2008-09-29 18:10:17 +00005725 return Compatible;
John McCalle5255932011-01-31 22:28:28 +00005726 }
Steve Naroff32d072c2008-09-29 18:10:17 +00005727
John McCalle5255932011-01-31 22:28:28 +00005728 // void* -> T^
Richard Trieude4958f2011-09-06 20:30:53 +00005729 if (const PointerType *RHSPT = RHSType->getAs<PointerType>())
John McCalle5255932011-01-31 22:28:28 +00005730 if (RHSPT->getPointeeType()->isVoidType()) {
5731 Kind = CK_AnyPointerToBlockPointerCast;
Douglas Gregore7dd1452008-11-27 00:44:28 +00005732 return Compatible;
John McCalle5255932011-01-31 22:28:28 +00005733 }
John McCall8cb679e2010-11-15 09:13:47 +00005734
Chris Lattnera52c2f22008-01-04 23:18:45 +00005735 return Incompatible;
5736 }
5737
John McCalle5255932011-01-31 22:28:28 +00005738 // Conversions to Objective-C pointers.
Richard Trieude4958f2011-09-06 20:30:53 +00005739 if (isa<ObjCObjectPointerType>(LHSType)) {
John McCalle5255932011-01-31 22:28:28 +00005740 // A* -> B*
Richard Trieude4958f2011-09-06 20:30:53 +00005741 if (RHSType->isObjCObjectPointerType()) {
John McCalle5255932011-01-31 22:28:28 +00005742 Kind = CK_BitCast;
Fariborz Jahanian6f472e82011-07-07 18:55:47 +00005743 Sema::AssignConvertType result =
Richard Trieude4958f2011-09-06 20:30:53 +00005744 checkObjCPointerTypesForAssignment(*this, LHSType, RHSType);
David Blaikiebbafb8a2012-03-11 07:00:24 +00005745 if (getLangOpts().ObjCAutoRefCount &&
Fariborz Jahanian6f472e82011-07-07 18:55:47 +00005746 result == Compatible &&
Richard Trieude4958f2011-09-06 20:30:53 +00005747 !CheckObjCARCUnavailableWeakConversion(OrigLHSType, RHSType))
Fariborz Jahanian7fcce682011-07-07 23:04:17 +00005748 result = IncompatibleObjCWeakRef;
Fariborz Jahanian6f472e82011-07-07 18:55:47 +00005749 return result;
John McCalle5255932011-01-31 22:28:28 +00005750 }
5751
5752 // int or null -> A*
Richard Trieude4958f2011-09-06 20:30:53 +00005753 if (RHSType->isIntegerType()) {
John McCall8cb679e2010-11-15 09:13:47 +00005754 Kind = CK_IntegralToPointer; // FIXME: null
Steve Naroff7cae42b2009-07-10 23:34:53 +00005755 return IntToPointer;
John McCall8cb679e2010-11-15 09:13:47 +00005756 }
5757
John McCalle5255932011-01-31 22:28:28 +00005758 // In general, C pointers are not compatible with ObjC object pointers,
5759 // with two exceptions:
Richard Trieude4958f2011-09-06 20:30:53 +00005760 if (isa<PointerType>(RHSType)) {
John McCall9320b872011-09-09 05:25:32 +00005761 Kind = CK_CPointerToObjCPointerCast;
5762
John McCalle5255932011-01-31 22:28:28 +00005763 // - conversions from 'void*'
Richard Trieude4958f2011-09-06 20:30:53 +00005764 if (RHSType->isVoidPointerType()) {
Steve Naroffaccc4882009-07-20 17:56:53 +00005765 return Compatible;
John McCalle5255932011-01-31 22:28:28 +00005766 }
5767
5768 // - conversions to 'Class' from its redefinition type
Richard Trieude4958f2011-09-06 20:30:53 +00005769 if (LHSType->isObjCClassType() &&
5770 Context.hasSameType(RHSType,
Douglas Gregor97673472011-08-11 20:58:55 +00005771 Context.getObjCClassRedefinitionType())) {
John McCalle5255932011-01-31 22:28:28 +00005772 return Compatible;
5773 }
5774
Steve Naroffaccc4882009-07-20 17:56:53 +00005775 return IncompatiblePointer;
Steve Naroff7cae42b2009-07-10 23:34:53 +00005776 }
John McCalle5255932011-01-31 22:28:28 +00005777
5778 // T^ -> A*
Richard Trieude4958f2011-09-06 20:30:53 +00005779 if (RHSType->isBlockPointerType()) {
John McCallcd78e802011-09-10 01:16:55 +00005780 maybeExtendBlockObject(*this, RHS);
John McCall9320b872011-09-09 05:25:32 +00005781 Kind = CK_BlockPointerToObjCPointerCast;
Steve Naroff7cae42b2009-07-10 23:34:53 +00005782 return Compatible;
John McCalle5255932011-01-31 22:28:28 +00005783 }
5784
Steve Naroff7cae42b2009-07-10 23:34:53 +00005785 return Incompatible;
5786 }
John McCalle5255932011-01-31 22:28:28 +00005787
5788 // Conversions from pointers that are not covered by the above.
Richard Trieude4958f2011-09-06 20:30:53 +00005789 if (isa<PointerType>(RHSType)) {
John McCalle5255932011-01-31 22:28:28 +00005790 // T* -> _Bool
Richard Trieude4958f2011-09-06 20:30:53 +00005791 if (LHSType == Context.BoolTy) {
John McCall8cb679e2010-11-15 09:13:47 +00005792 Kind = CK_PointerToBoolean;
Eli Friedman3360d892008-05-30 18:07:22 +00005793 return Compatible;
John McCall8cb679e2010-11-15 09:13:47 +00005794 }
Eli Friedman3360d892008-05-30 18:07:22 +00005795
John McCalle5255932011-01-31 22:28:28 +00005796 // T* -> int
Richard Trieude4958f2011-09-06 20:30:53 +00005797 if (LHSType->isIntegerType()) {
John McCall8cb679e2010-11-15 09:13:47 +00005798 Kind = CK_PointerToIntegral;
Chris Lattner940cfeb2008-01-04 18:22:42 +00005799 return PointerToInt;
John McCall8cb679e2010-11-15 09:13:47 +00005800 }
Mike Stump4e1f26a2009-02-19 03:04:26 +00005801
Chris Lattnera52c2f22008-01-04 23:18:45 +00005802 return Incompatible;
Chris Lattnera52c2f22008-01-04 23:18:45 +00005803 }
John McCalle5255932011-01-31 22:28:28 +00005804
5805 // Conversions from Objective-C pointers that are not covered by the above.
Richard Trieude4958f2011-09-06 20:30:53 +00005806 if (isa<ObjCObjectPointerType>(RHSType)) {
John McCalle5255932011-01-31 22:28:28 +00005807 // T* -> _Bool
Richard Trieude4958f2011-09-06 20:30:53 +00005808 if (LHSType == Context.BoolTy) {
John McCall8cb679e2010-11-15 09:13:47 +00005809 Kind = CK_PointerToBoolean;
Steve Naroff7cae42b2009-07-10 23:34:53 +00005810 return Compatible;
John McCall8cb679e2010-11-15 09:13:47 +00005811 }
Steve Naroff7cae42b2009-07-10 23:34:53 +00005812
John McCalle5255932011-01-31 22:28:28 +00005813 // T* -> int
Richard Trieude4958f2011-09-06 20:30:53 +00005814 if (LHSType->isIntegerType()) {
John McCall8cb679e2010-11-15 09:13:47 +00005815 Kind = CK_PointerToIntegral;
Steve Naroff7cae42b2009-07-10 23:34:53 +00005816 return PointerToInt;
John McCall8cb679e2010-11-15 09:13:47 +00005817 }
5818
Steve Naroff7cae42b2009-07-10 23:34:53 +00005819 return Incompatible;
5820 }
Eli Friedman3360d892008-05-30 18:07:22 +00005821
John McCalle5255932011-01-31 22:28:28 +00005822 // struct A -> struct B
Richard Trieude4958f2011-09-06 20:30:53 +00005823 if (isa<TagType>(LHSType) && isa<TagType>(RHSType)) {
5824 if (Context.typesAreCompatible(LHSType, RHSType)) {
John McCall8cb679e2010-11-15 09:13:47 +00005825 Kind = CK_NoOp;
Steve Naroff98cf3e92007-06-06 18:38:38 +00005826 return Compatible;
John McCall8cb679e2010-11-15 09:13:47 +00005827 }
Bill Wendling216423b2007-05-30 06:30:29 +00005828 }
John McCalle5255932011-01-31 22:28:28 +00005829
Steve Naroff98cf3e92007-06-06 18:38:38 +00005830 return Incompatible;
Steve Naroff9eb24652007-05-02 21:58:15 +00005831}
5832
Douglas Gregor0cfbdab2009-04-29 22:16:16 +00005833/// \brief Constructs a transparent union from an expression that is
5834/// used to initialize the transparent union.
Richard Trieucfc491d2011-08-02 04:35:43 +00005835static void ConstructTransparentUnion(Sema &S, ASTContext &C,
5836 ExprResult &EResult, QualType UnionType,
5837 FieldDecl *Field) {
Douglas Gregor0cfbdab2009-04-29 22:16:16 +00005838 // Build an initializer list that designates the appropriate member
5839 // of the transparent union.
John Wiegley01296292011-04-08 18:41:53 +00005840 Expr *E = EResult.take();
Ted Kremenekac034612010-04-13 23:39:13 +00005841 InitListExpr *Initializer = new (C) InitListExpr(C, SourceLocation(),
Benjamin Kramerc215e762012-08-24 11:54:20 +00005842 E, SourceLocation());
Douglas Gregor0cfbdab2009-04-29 22:16:16 +00005843 Initializer->setType(UnionType);
5844 Initializer->setInitializedFieldInUnion(Field);
5845
5846 // Build a compound literal constructing a value of the transparent
5847 // union type from this initializer list.
John McCalle15bbff2010-01-18 19:35:47 +00005848 TypeSourceInfo *unionTInfo = C.getTrivialTypeSourceInfo(UnionType);
John Wiegley01296292011-04-08 18:41:53 +00005849 EResult = S.Owned(
5850 new (C) CompoundLiteralExpr(SourceLocation(), unionTInfo, UnionType,
5851 VK_RValue, Initializer, false));
Douglas Gregor0cfbdab2009-04-29 22:16:16 +00005852}
5853
5854Sema::AssignConvertType
Richard Trieucfc491d2011-08-02 04:35:43 +00005855Sema::CheckTransparentUnionArgumentConstraints(QualType ArgType,
Richard Trieueb299142011-09-06 20:40:12 +00005856 ExprResult &RHS) {
5857 QualType RHSType = RHS.get()->getType();
Douglas Gregor0cfbdab2009-04-29 22:16:16 +00005858
Mike Stump11289f42009-09-09 15:08:12 +00005859 // If the ArgType is a Union type, we want to handle a potential
Douglas Gregor0cfbdab2009-04-29 22:16:16 +00005860 // transparent_union GCC extension.
5861 const RecordType *UT = ArgType->getAsUnionType();
Argyrios Kyrtzidisb4b64ca2009-06-30 02:34:44 +00005862 if (!UT || !UT->getDecl()->hasAttr<TransparentUnionAttr>())
Douglas Gregor0cfbdab2009-04-29 22:16:16 +00005863 return Incompatible;
5864
5865 // The field to initialize within the transparent union.
5866 RecordDecl *UD = UT->getDecl();
5867 FieldDecl *InitField = 0;
5868 // It's compatible if the expression matches any of the fields.
Argyrios Kyrtzidiscfbfe782009-06-30 02:36:12 +00005869 for (RecordDecl::field_iterator it = UD->field_begin(),
5870 itend = UD->field_end();
Douglas Gregor0cfbdab2009-04-29 22:16:16 +00005871 it != itend; ++it) {
5872 if (it->getType()->isPointerType()) {
5873 // If the transparent union contains a pointer type, we allow:
5874 // 1) void pointer
5875 // 2) null pointer constant
Richard Trieueb299142011-09-06 20:40:12 +00005876 if (RHSType->isPointerType())
John McCall9320b872011-09-09 05:25:32 +00005877 if (RHSType->castAs<PointerType>()->getPointeeType()->isVoidType()) {
Richard Trieueb299142011-09-06 20:40:12 +00005878 RHS = ImpCastExprToType(RHS.take(), it->getType(), CK_BitCast);
David Blaikie40ed2972012-06-06 20:45:41 +00005879 InitField = *it;
Douglas Gregor0cfbdab2009-04-29 22:16:16 +00005880 break;
5881 }
Mike Stump11289f42009-09-09 15:08:12 +00005882
Richard Trieueb299142011-09-06 20:40:12 +00005883 if (RHS.get()->isNullPointerConstant(Context,
5884 Expr::NPC_ValueDependentIsNull)) {
5885 RHS = ImpCastExprToType(RHS.take(), it->getType(),
5886 CK_NullToPointer);
David Blaikie40ed2972012-06-06 20:45:41 +00005887 InitField = *it;
Douglas Gregor0cfbdab2009-04-29 22:16:16 +00005888 break;
5889 }
5890 }
5891
John McCall8cb679e2010-11-15 09:13:47 +00005892 CastKind Kind = CK_Invalid;
Richard Trieueb299142011-09-06 20:40:12 +00005893 if (CheckAssignmentConstraints(it->getType(), RHS, Kind)
Douglas Gregor0cfbdab2009-04-29 22:16:16 +00005894 == Compatible) {
Richard Trieueb299142011-09-06 20:40:12 +00005895 RHS = ImpCastExprToType(RHS.take(), it->getType(), Kind);
David Blaikie40ed2972012-06-06 20:45:41 +00005896 InitField = *it;
Douglas Gregor0cfbdab2009-04-29 22:16:16 +00005897 break;
5898 }
5899 }
5900
5901 if (!InitField)
5902 return Incompatible;
5903
Richard Trieueb299142011-09-06 20:40:12 +00005904 ConstructTransparentUnion(*this, Context, RHS, ArgType, InitField);
Douglas Gregor0cfbdab2009-04-29 22:16:16 +00005905 return Compatible;
5906}
5907
Chris Lattner9bad62c2008-01-04 18:04:52 +00005908Sema::AssignConvertType
Sebastian Redlb49c46c2011-09-24 17:48:00 +00005909Sema::CheckSingleAssignmentConstraints(QualType LHSType, ExprResult &RHS,
5910 bool Diagnose) {
David Blaikiebbafb8a2012-03-11 07:00:24 +00005911 if (getLangOpts().CPlusPlus) {
Eli Friedman0dfb8892011-10-06 23:00:33 +00005912 if (!LHSType->isRecordType() && !LHSType->isAtomicType()) {
Douglas Gregor9a657932008-10-21 23:43:52 +00005913 // C++ 5.17p3: If the left operand is not of class type, the
5914 // expression is implicitly converted (C++ 4) to the
5915 // cv-unqualified type of the left operand.
Sebastian Redlcc152642011-10-16 18:19:06 +00005916 ExprResult Res;
5917 if (Diagnose) {
5918 Res = PerformImplicitConversion(RHS.get(), LHSType.getUnqualifiedType(),
5919 AA_Assigning);
5920 } else {
5921 ImplicitConversionSequence ICS =
5922 TryImplicitConversion(RHS.get(), LHSType.getUnqualifiedType(),
5923 /*SuppressUserConversions=*/false,
5924 /*AllowExplicit=*/false,
5925 /*InOverloadResolution=*/false,
5926 /*CStyle=*/false,
5927 /*AllowObjCWritebackConversion=*/false);
5928 if (ICS.isFailure())
5929 return Incompatible;
5930 Res = PerformImplicitConversion(RHS.get(), LHSType.getUnqualifiedType(),
5931 ICS, AA_Assigning);
5932 }
John Wiegley01296292011-04-08 18:41:53 +00005933 if (Res.isInvalid())
Douglas Gregor9a657932008-10-21 23:43:52 +00005934 return Incompatible;
Fariborz Jahanian7fcce682011-07-07 23:04:17 +00005935 Sema::AssignConvertType result = Compatible;
David Blaikiebbafb8a2012-03-11 07:00:24 +00005936 if (getLangOpts().ObjCAutoRefCount &&
Richard Trieueb299142011-09-06 20:40:12 +00005937 !CheckObjCARCUnavailableWeakConversion(LHSType,
5938 RHS.get()->getType()))
Fariborz Jahanian7fcce682011-07-07 23:04:17 +00005939 result = IncompatibleObjCWeakRef;
Benjamin Kramer62b95d82012-08-23 21:35:17 +00005940 RHS = Res;
Fariborz Jahanian7fcce682011-07-07 23:04:17 +00005941 return result;
Douglas Gregor9a657932008-10-21 23:43:52 +00005942 }
5943
5944 // FIXME: Currently, we fall through and treat C++ classes like C
5945 // structures.
Eli Friedman0dfb8892011-10-06 23:00:33 +00005946 // FIXME: We also fall through for atomics; not sure what should
5947 // happen there, though.
Sebastian Redlb49c46c2011-09-24 17:48:00 +00005948 }
Douglas Gregor9a657932008-10-21 23:43:52 +00005949
Steve Naroff0ee0b0a2007-11-27 17:58:44 +00005950 // C99 6.5.16.1p1: the left operand is a pointer and the right is
5951 // a null pointer constant.
Richard Trieueb299142011-09-06 20:40:12 +00005952 if ((LHSType->isPointerType() ||
5953 LHSType->isObjCObjectPointerType() ||
5954 LHSType->isBlockPointerType())
5955 && RHS.get()->isNullPointerConstant(Context,
5956 Expr::NPC_ValueDependentIsNull)) {
5957 RHS = ImpCastExprToType(RHS.take(), LHSType, CK_NullToPointer);
Steve Naroff0ee0b0a2007-11-27 17:58:44 +00005958 return Compatible;
5959 }
Mike Stump4e1f26a2009-02-19 03:04:26 +00005960
Chris Lattnere6dcd502007-10-16 02:55:40 +00005961 // This check seems unnatural, however it is necessary to ensure the proper
Steve Naroffb8ea4fb2007-07-13 23:32:42 +00005962 // conversion of functions/arrays. If the conversion were done for all
Douglas Gregora121b752009-11-03 16:56:39 +00005963 // DeclExpr's (created by ActOnIdExpression), it would mess up the unary
Nick Lewyckyef7c0ff2010-08-05 06:27:49 +00005964 // expressions that suppress this implicit conversion (&, sizeof).
Chris Lattnere6dcd502007-10-16 02:55:40 +00005965 //
Mike Stump4e1f26a2009-02-19 03:04:26 +00005966 // Suppress this for references: C++ 8.5.3p5.
Richard Trieueb299142011-09-06 20:40:12 +00005967 if (!LHSType->isReferenceType()) {
5968 RHS = DefaultFunctionArrayLvalueConversion(RHS.take());
5969 if (RHS.isInvalid())
John Wiegley01296292011-04-08 18:41:53 +00005970 return Incompatible;
5971 }
Steve Naroff0c1c7ed2007-08-24 22:33:52 +00005972
John McCall8cb679e2010-11-15 09:13:47 +00005973 CastKind Kind = CK_Invalid;
Chris Lattner9bad62c2008-01-04 18:04:52 +00005974 Sema::AssignConvertType result =
Richard Trieueb299142011-09-06 20:40:12 +00005975 CheckAssignmentConstraints(LHSType, RHS, Kind);
Mike Stump4e1f26a2009-02-19 03:04:26 +00005976
Steve Naroff0c1c7ed2007-08-24 22:33:52 +00005977 // C99 6.5.16.1p2: The value of the right operand is converted to the
5978 // type of the assignment expression.
Douglas Gregor6b754842008-10-28 00:22:11 +00005979 // CheckAssignmentConstraints allows the left-hand side to be a reference,
5980 // so that we can use references in built-in functions even in C.
5981 // The getNonReferenceType() call makes sure that the resulting expression
5982 // does not have reference type.
Richard Trieueb299142011-09-06 20:40:12 +00005983 if (result != Incompatible && RHS.get()->getType() != LHSType)
5984 RHS = ImpCastExprToType(RHS.take(),
5985 LHSType.getNonLValueExprType(Context), Kind);
Steve Naroff0c1c7ed2007-08-24 22:33:52 +00005986 return result;
Steve Naroffb8ea4fb2007-07-13 23:32:42 +00005987}
5988
Richard Trieueb299142011-09-06 20:40:12 +00005989QualType Sema::InvalidOperands(SourceLocation Loc, ExprResult &LHS,
5990 ExprResult &RHS) {
Chris Lattner377d1f82008-11-18 22:52:51 +00005991 Diag(Loc, diag::err_typecheck_invalid_operands)
Richard Trieueb299142011-09-06 20:40:12 +00005992 << LHS.get()->getType() << RHS.get()->getType()
5993 << LHS.get()->getSourceRange() << RHS.get()->getSourceRange();
Chris Lattner5c11c412007-12-12 05:47:28 +00005994 return QualType();
Steve Naroff6f49f5d2007-05-29 14:23:36 +00005995}
5996
Richard Trieu859d23f2011-09-06 21:01:04 +00005997QualType Sema::CheckVectorOperands(ExprResult &LHS, ExprResult &RHS,
Richard Trieuba63ce62011-09-09 01:45:06 +00005998 SourceLocation Loc, bool IsCompAssign) {
Richard Smith508ebf32011-10-28 03:31:48 +00005999 if (!IsCompAssign) {
6000 LHS = DefaultFunctionArrayLvalueConversion(LHS.take());
6001 if (LHS.isInvalid())
6002 return QualType();
6003 }
6004 RHS = DefaultFunctionArrayLvalueConversion(RHS.take());
6005 if (RHS.isInvalid())
6006 return QualType();
6007
Mike Stump4e1f26a2009-02-19 03:04:26 +00006008 // For conversion purposes, we ignore any qualifiers.
Nate Begeman002e4bd2008-04-04 01:30:25 +00006009 // For example, "const float" and "float" are equivalent.
Richard Trieu859d23f2011-09-06 21:01:04 +00006010 QualType LHSType =
6011 Context.getCanonicalType(LHS.get()->getType()).getUnqualifiedType();
6012 QualType RHSType =
6013 Context.getCanonicalType(RHS.get()->getType()).getUnqualifiedType();
Mike Stump4e1f26a2009-02-19 03:04:26 +00006014
Nate Begeman191a6b12008-07-14 18:02:46 +00006015 // If the vector types are identical, return.
Richard Trieu859d23f2011-09-06 21:01:04 +00006016 if (LHSType == RHSType)
6017 return LHSType;
Nate Begeman330aaa72007-12-30 02:59:45 +00006018
Douglas Gregor59e8b3b2010-08-06 10:14:59 +00006019 // Handle the case of equivalent AltiVec and GCC vector types
Richard Trieu859d23f2011-09-06 21:01:04 +00006020 if (LHSType->isVectorType() && RHSType->isVectorType() &&
6021 Context.areCompatibleVectorTypes(LHSType, RHSType)) {
6022 if (LHSType->isExtVectorType()) {
6023 RHS = ImpCastExprToType(RHS.take(), LHSType, CK_BitCast);
6024 return LHSType;
Eli Friedman1408bc92011-06-23 18:10:35 +00006025 }
6026
Richard Trieuba63ce62011-09-09 01:45:06 +00006027 if (!IsCompAssign)
Richard Trieu859d23f2011-09-06 21:01:04 +00006028 LHS = ImpCastExprToType(LHS.take(), RHSType, CK_BitCast);
6029 return RHSType;
Douglas Gregor59e8b3b2010-08-06 10:14:59 +00006030 }
6031
David Blaikiebbafb8a2012-03-11 07:00:24 +00006032 if (getLangOpts().LaxVectorConversions &&
Richard Trieu859d23f2011-09-06 21:01:04 +00006033 Context.getTypeSize(LHSType) == Context.getTypeSize(RHSType)) {
Eli Friedman1408bc92011-06-23 18:10:35 +00006034 // If we are allowing lax vector conversions, and LHS and RHS are both
6035 // vectors, the total size only needs to be the same. This is a
6036 // bitcast; no bits are changed but the result type is different.
6037 // FIXME: Should we really be allowing this?
Richard Trieu859d23f2011-09-06 21:01:04 +00006038 RHS = ImpCastExprToType(RHS.take(), LHSType, CK_BitCast);
6039 return LHSType;
Eli Friedman1408bc92011-06-23 18:10:35 +00006040 }
6041
Nate Begemanbd956c42009-06-28 02:36:38 +00006042 // Canonicalize the ExtVector to the LHS, remember if we swapped so we can
6043 // swap back (so that we don't reverse the inputs to a subtract, for instance.
6044 bool swapped = false;
Richard Trieuba63ce62011-09-09 01:45:06 +00006045 if (RHSType->isExtVectorType() && !IsCompAssign) {
Nate Begemanbd956c42009-06-28 02:36:38 +00006046 swapped = true;
Richard Trieu859d23f2011-09-06 21:01:04 +00006047 std::swap(RHS, LHS);
6048 std::swap(RHSType, LHSType);
Nate Begemanbd956c42009-06-28 02:36:38 +00006049 }
Mike Stump11289f42009-09-09 15:08:12 +00006050
Nate Begeman886448d2009-06-28 19:12:57 +00006051 // Handle the case of an ext vector and scalar.
Richard Trieu859d23f2011-09-06 21:01:04 +00006052 if (const ExtVectorType *LV = LHSType->getAs<ExtVectorType>()) {
Nate Begemanbd956c42009-06-28 02:36:38 +00006053 QualType EltTy = LV->getElementType();
Richard Trieu859d23f2011-09-06 21:01:04 +00006054 if (EltTy->isIntegralType(Context) && RHSType->isIntegralType(Context)) {
6055 int order = Context.getIntegerTypeOrder(EltTy, RHSType);
John McCall8cb679e2010-11-15 09:13:47 +00006056 if (order > 0)
Richard Trieu859d23f2011-09-06 21:01:04 +00006057 RHS = ImpCastExprToType(RHS.take(), EltTy, CK_IntegralCast);
John McCall8cb679e2010-11-15 09:13:47 +00006058 if (order >= 0) {
Richard Trieu859d23f2011-09-06 21:01:04 +00006059 RHS = ImpCastExprToType(RHS.take(), LHSType, CK_VectorSplat);
6060 if (swapped) std::swap(RHS, LHS);
6061 return LHSType;
Nate Begemanbd956c42009-06-28 02:36:38 +00006062 }
6063 }
Richard Trieu859d23f2011-09-06 21:01:04 +00006064 if (EltTy->isRealFloatingType() && RHSType->isScalarType() &&
6065 RHSType->isRealFloatingType()) {
6066 int order = Context.getFloatingTypeOrder(EltTy, RHSType);
John McCall8cb679e2010-11-15 09:13:47 +00006067 if (order > 0)
Richard Trieu859d23f2011-09-06 21:01:04 +00006068 RHS = ImpCastExprToType(RHS.take(), EltTy, CK_FloatingCast);
John McCall8cb679e2010-11-15 09:13:47 +00006069 if (order >= 0) {
Richard Trieu859d23f2011-09-06 21:01:04 +00006070 RHS = ImpCastExprToType(RHS.take(), LHSType, CK_VectorSplat);
6071 if (swapped) std::swap(RHS, LHS);
6072 return LHSType;
Nate Begemanbd956c42009-06-28 02:36:38 +00006073 }
Nate Begeman330aaa72007-12-30 02:59:45 +00006074 }
6075 }
Mike Stump11289f42009-09-09 15:08:12 +00006076
Nate Begeman886448d2009-06-28 19:12:57 +00006077 // Vectors of different size or scalar and non-ext-vector are errors.
Richard Trieu859d23f2011-09-06 21:01:04 +00006078 if (swapped) std::swap(RHS, LHS);
Chris Lattner377d1f82008-11-18 22:52:51 +00006079 Diag(Loc, diag::err_typecheck_vector_not_convertable)
Richard Trieu859d23f2011-09-06 21:01:04 +00006080 << LHS.get()->getType() << RHS.get()->getType()
6081 << LHS.get()->getSourceRange() << RHS.get()->getSourceRange();
Steve Naroff84ff4b42007-07-09 21:31:10 +00006082 return QualType();
Sebastian Redl112a97662009-02-07 00:15:38 +00006083}
6084
Richard Trieuf8916e12011-09-16 00:53:10 +00006085// checkArithmeticNull - Detect when a NULL constant is used improperly in an
6086// expression. These are mainly cases where the null pointer is used as an
6087// integer instead of a pointer.
6088static void checkArithmeticNull(Sema &S, ExprResult &LHS, ExprResult &RHS,
6089 SourceLocation Loc, bool IsCompare) {
6090 // The canonical way to check for a GNU null is with isNullPointerConstant,
6091 // but we use a bit of a hack here for speed; this is a relatively
6092 // hot path, and isNullPointerConstant is slow.
6093 bool LHSNull = isa<GNUNullExpr>(LHS.get()->IgnoreParenImpCasts());
6094 bool RHSNull = isa<GNUNullExpr>(RHS.get()->IgnoreParenImpCasts());
6095
6096 QualType NonNullType = LHSNull ? RHS.get()->getType() : LHS.get()->getType();
6097
6098 // Avoid analyzing cases where the result will either be invalid (and
6099 // diagnosed as such) or entirely valid and not something to warn about.
6100 if ((!LHSNull && !RHSNull) || NonNullType->isBlockPointerType() ||
6101 NonNullType->isMemberPointerType() || NonNullType->isFunctionType())
6102 return;
6103
6104 // Comparison operations would not make sense with a null pointer no matter
6105 // what the other expression is.
6106 if (!IsCompare) {
6107 S.Diag(Loc, diag::warn_null_in_arithmetic_operation)
6108 << (LHSNull ? LHS.get()->getSourceRange() : SourceRange())
6109 << (RHSNull ? RHS.get()->getSourceRange() : SourceRange());
6110 return;
6111 }
6112
6113 // The rest of the operations only make sense with a null pointer
6114 // if the other expression is a pointer.
6115 if (LHSNull == RHSNull || NonNullType->isAnyPointerType() ||
6116 NonNullType->canDecayToPointerType())
6117 return;
6118
6119 S.Diag(Loc, diag::warn_null_in_comparison_operation)
6120 << LHSNull /* LHS is NULL */ << NonNullType
6121 << LHS.get()->getSourceRange() << RHS.get()->getSourceRange();
6122}
6123
Richard Trieu859d23f2011-09-06 21:01:04 +00006124QualType Sema::CheckMultiplyDivideOperands(ExprResult &LHS, ExprResult &RHS,
Richard Trieucfc491d2011-08-02 04:35:43 +00006125 SourceLocation Loc,
Richard Trieuba63ce62011-09-09 01:45:06 +00006126 bool IsCompAssign, bool IsDiv) {
Richard Trieuf8916e12011-09-16 00:53:10 +00006127 checkArithmeticNull(*this, LHS, RHS, Loc, /*isCompare=*/false);
6128
Richard Trieu859d23f2011-09-06 21:01:04 +00006129 if (LHS.get()->getType()->isVectorType() ||
6130 RHS.get()->getType()->isVectorType())
Richard Trieuba63ce62011-09-09 01:45:06 +00006131 return CheckVectorOperands(LHS, RHS, Loc, IsCompAssign);
Mike Stump4e1f26a2009-02-19 03:04:26 +00006132
Richard Trieuba63ce62011-09-09 01:45:06 +00006133 QualType compType = UsualArithmeticConversions(LHS, RHS, IsCompAssign);
Richard Trieu859d23f2011-09-06 21:01:04 +00006134 if (LHS.isInvalid() || RHS.isInvalid())
John Wiegley01296292011-04-08 18:41:53 +00006135 return QualType();
Mike Stump4e1f26a2009-02-19 03:04:26 +00006136
David Chisnallfa35df62012-01-16 17:27:18 +00006137
Eli Friedman93ee5ca2012-06-16 02:19:17 +00006138 if (compType.isNull() || !compType->isArithmeticType())
Richard Trieu859d23f2011-09-06 21:01:04 +00006139 return InvalidOperands(Loc, LHS, RHS);
Kovarththanan Rajaratnamba2c6522010-03-13 10:17:05 +00006140
Chris Lattnerfaa54172010-01-12 21:23:57 +00006141 // Check for division by zero.
Richard Trieuba63ce62011-09-09 01:45:06 +00006142 if (IsDiv &&
Richard Trieu859d23f2011-09-06 21:01:04 +00006143 RHS.get()->isNullPointerConstant(Context,
Richard Trieucfc491d2011-08-02 04:35:43 +00006144 Expr::NPC_ValueDependentIsNotNull))
Richard Trieu859d23f2011-09-06 21:01:04 +00006145 DiagRuntimeBehavior(Loc, RHS.get(), PDiag(diag::warn_division_by_zero)
6146 << RHS.get()->getSourceRange());
Kovarththanan Rajaratnamba2c6522010-03-13 10:17:05 +00006147
Chris Lattnerfaa54172010-01-12 21:23:57 +00006148 return compType;
Steve Naroff26c8ea52007-03-21 21:08:52 +00006149}
6150
Chris Lattnerfaa54172010-01-12 21:23:57 +00006151QualType Sema::CheckRemainderOperands(
Richard Trieuba63ce62011-09-09 01:45:06 +00006152 ExprResult &LHS, ExprResult &RHS, SourceLocation Loc, bool IsCompAssign) {
Richard Trieuf8916e12011-09-16 00:53:10 +00006153 checkArithmeticNull(*this, LHS, RHS, Loc, /*isCompare=*/false);
6154
Richard Trieu859d23f2011-09-06 21:01:04 +00006155 if (LHS.get()->getType()->isVectorType() ||
6156 RHS.get()->getType()->isVectorType()) {
6157 if (LHS.get()->getType()->hasIntegerRepresentation() &&
6158 RHS.get()->getType()->hasIntegerRepresentation())
Richard Trieuba63ce62011-09-09 01:45:06 +00006159 return CheckVectorOperands(LHS, RHS, Loc, IsCompAssign);
Richard Trieu859d23f2011-09-06 21:01:04 +00006160 return InvalidOperands(Loc, LHS, RHS);
Daniel Dunbar0d2bfec2009-01-05 22:55:36 +00006161 }
Steve Naroffb8ea4fb2007-07-13 23:32:42 +00006162
Richard Trieuba63ce62011-09-09 01:45:06 +00006163 QualType compType = UsualArithmeticConversions(LHS, RHS, IsCompAssign);
Richard Trieu859d23f2011-09-06 21:01:04 +00006164 if (LHS.isInvalid() || RHS.isInvalid())
John Wiegley01296292011-04-08 18:41:53 +00006165 return QualType();
Mike Stump4e1f26a2009-02-19 03:04:26 +00006166
Eli Friedman93ee5ca2012-06-16 02:19:17 +00006167 if (compType.isNull() || !compType->isIntegerType())
Richard Trieu859d23f2011-09-06 21:01:04 +00006168 return InvalidOperands(Loc, LHS, RHS);
Kovarththanan Rajaratnamba2c6522010-03-13 10:17:05 +00006169
Chris Lattnerfaa54172010-01-12 21:23:57 +00006170 // Check for remainder by zero.
Richard Trieu859d23f2011-09-06 21:01:04 +00006171 if (RHS.get()->isNullPointerConstant(Context,
Richard Trieucfc491d2011-08-02 04:35:43 +00006172 Expr::NPC_ValueDependentIsNotNull))
Richard Trieu859d23f2011-09-06 21:01:04 +00006173 DiagRuntimeBehavior(Loc, RHS.get(), PDiag(diag::warn_remainder_by_zero)
6174 << RHS.get()->getSourceRange());
Kovarththanan Rajaratnamba2c6522010-03-13 10:17:05 +00006175
Chris Lattnerfaa54172010-01-12 21:23:57 +00006176 return compType;
Steve Naroff218bc2b2007-05-04 21:54:46 +00006177}
6178
Chandler Carruthc9332212011-06-27 08:02:19 +00006179/// \brief Diagnose invalid arithmetic on two void pointers.
6180static void diagnoseArithmeticOnTwoVoidPointers(Sema &S, SourceLocation Loc,
Richard Trieu4ae7e972011-09-06 21:13:51 +00006181 Expr *LHSExpr, Expr *RHSExpr) {
David Blaikiebbafb8a2012-03-11 07:00:24 +00006182 S.Diag(Loc, S.getLangOpts().CPlusPlus
Chandler Carruthc9332212011-06-27 08:02:19 +00006183 ? diag::err_typecheck_pointer_arith_void_type
6184 : diag::ext_gnu_void_ptr)
Richard Trieu4ae7e972011-09-06 21:13:51 +00006185 << 1 /* two pointers */ << LHSExpr->getSourceRange()
6186 << RHSExpr->getSourceRange();
Chandler Carruthc9332212011-06-27 08:02:19 +00006187}
6188
6189/// \brief Diagnose invalid arithmetic on a void pointer.
6190static void diagnoseArithmeticOnVoidPointer(Sema &S, SourceLocation Loc,
6191 Expr *Pointer) {
David Blaikiebbafb8a2012-03-11 07:00:24 +00006192 S.Diag(Loc, S.getLangOpts().CPlusPlus
Chandler Carruthc9332212011-06-27 08:02:19 +00006193 ? diag::err_typecheck_pointer_arith_void_type
6194 : diag::ext_gnu_void_ptr)
6195 << 0 /* one pointer */ << Pointer->getSourceRange();
6196}
6197
6198/// \brief Diagnose invalid arithmetic on two function pointers.
6199static void diagnoseArithmeticOnTwoFunctionPointers(Sema &S, SourceLocation Loc,
6200 Expr *LHS, Expr *RHS) {
6201 assert(LHS->getType()->isAnyPointerType());
6202 assert(RHS->getType()->isAnyPointerType());
David Blaikiebbafb8a2012-03-11 07:00:24 +00006203 S.Diag(Loc, S.getLangOpts().CPlusPlus
Chandler Carruthc9332212011-06-27 08:02:19 +00006204 ? diag::err_typecheck_pointer_arith_function_type
6205 : diag::ext_gnu_ptr_func_arith)
6206 << 1 /* two pointers */ << LHS->getType()->getPointeeType()
6207 // We only show the second type if it differs from the first.
6208 << (unsigned)!S.Context.hasSameUnqualifiedType(LHS->getType(),
6209 RHS->getType())
6210 << RHS->getType()->getPointeeType()
6211 << LHS->getSourceRange() << RHS->getSourceRange();
6212}
6213
6214/// \brief Diagnose invalid arithmetic on a function pointer.
6215static void diagnoseArithmeticOnFunctionPointer(Sema &S, SourceLocation Loc,
6216 Expr *Pointer) {
6217 assert(Pointer->getType()->isAnyPointerType());
David Blaikiebbafb8a2012-03-11 07:00:24 +00006218 S.Diag(Loc, S.getLangOpts().CPlusPlus
Chandler Carruthc9332212011-06-27 08:02:19 +00006219 ? diag::err_typecheck_pointer_arith_function_type
6220 : diag::ext_gnu_ptr_func_arith)
6221 << 0 /* one pointer */ << Pointer->getType()->getPointeeType()
6222 << 0 /* one pointer, so only one type */
6223 << Pointer->getSourceRange();
6224}
6225
Richard Trieu993f3ab2011-09-12 18:08:02 +00006226/// \brief Emit error if Operand is incomplete pointer type
Richard Trieuaba22802011-09-02 02:15:37 +00006227///
6228/// \returns True if pointer has incomplete type
6229static bool checkArithmeticIncompletePointerType(Sema &S, SourceLocation Loc,
6230 Expr *Operand) {
John McCallf2538342012-07-31 05:14:30 +00006231 assert(Operand->getType()->isAnyPointerType() &&
6232 !Operand->getType()->isDependentType());
6233 QualType PointeeTy = Operand->getType()->getPointeeType();
6234 return S.RequireCompleteType(Loc, PointeeTy,
6235 diag::err_typecheck_arithmetic_incomplete_type,
6236 PointeeTy, Operand->getSourceRange());
Richard Trieuaba22802011-09-02 02:15:37 +00006237}
6238
Chandler Carruthc9332212011-06-27 08:02:19 +00006239/// \brief Check the validity of an arithmetic pointer operand.
6240///
6241/// If the operand has pointer type, this code will check for pointer types
6242/// which are invalid in arithmetic operations. These will be diagnosed
6243/// appropriately, including whether or not the use is supported as an
6244/// extension.
6245///
6246/// \returns True when the operand is valid to use (even if as an extension).
6247static bool checkArithmeticOpPointerOperand(Sema &S, SourceLocation Loc,
6248 Expr *Operand) {
6249 if (!Operand->getType()->isAnyPointerType()) return true;
6250
6251 QualType PointeeTy = Operand->getType()->getPointeeType();
6252 if (PointeeTy->isVoidType()) {
6253 diagnoseArithmeticOnVoidPointer(S, Loc, Operand);
David Blaikiebbafb8a2012-03-11 07:00:24 +00006254 return !S.getLangOpts().CPlusPlus;
Chandler Carruthc9332212011-06-27 08:02:19 +00006255 }
6256 if (PointeeTy->isFunctionType()) {
6257 diagnoseArithmeticOnFunctionPointer(S, Loc, Operand);
David Blaikiebbafb8a2012-03-11 07:00:24 +00006258 return !S.getLangOpts().CPlusPlus;
Chandler Carruthc9332212011-06-27 08:02:19 +00006259 }
6260
Richard Trieuaba22802011-09-02 02:15:37 +00006261 if (checkArithmeticIncompletePointerType(S, Loc, Operand)) return false;
Chandler Carruthc9332212011-06-27 08:02:19 +00006262
6263 return true;
6264}
6265
6266/// \brief Check the validity of a binary arithmetic operation w.r.t. pointer
6267/// operands.
6268///
6269/// This routine will diagnose any invalid arithmetic on pointer operands much
6270/// like \see checkArithmeticOpPointerOperand. However, it has special logic
6271/// for emitting a single diagnostic even for operations where both LHS and RHS
6272/// are (potentially problematic) pointers.
6273///
6274/// \returns True when the operand is valid to use (even if as an extension).
6275static bool checkArithmeticBinOpPointerOperands(Sema &S, SourceLocation Loc,
Richard Trieu4ae7e972011-09-06 21:13:51 +00006276 Expr *LHSExpr, Expr *RHSExpr) {
6277 bool isLHSPointer = LHSExpr->getType()->isAnyPointerType();
6278 bool isRHSPointer = RHSExpr->getType()->isAnyPointerType();
Chandler Carruthc9332212011-06-27 08:02:19 +00006279 if (!isLHSPointer && !isRHSPointer) return true;
6280
6281 QualType LHSPointeeTy, RHSPointeeTy;
Richard Trieu4ae7e972011-09-06 21:13:51 +00006282 if (isLHSPointer) LHSPointeeTy = LHSExpr->getType()->getPointeeType();
6283 if (isRHSPointer) RHSPointeeTy = RHSExpr->getType()->getPointeeType();
Chandler Carruthc9332212011-06-27 08:02:19 +00006284
6285 // Check for arithmetic on pointers to incomplete types.
6286 bool isLHSVoidPtr = isLHSPointer && LHSPointeeTy->isVoidType();
6287 bool isRHSVoidPtr = isRHSPointer && RHSPointeeTy->isVoidType();
6288 if (isLHSVoidPtr || isRHSVoidPtr) {
Richard Trieu4ae7e972011-09-06 21:13:51 +00006289 if (!isRHSVoidPtr) diagnoseArithmeticOnVoidPointer(S, Loc, LHSExpr);
6290 else if (!isLHSVoidPtr) diagnoseArithmeticOnVoidPointer(S, Loc, RHSExpr);
6291 else diagnoseArithmeticOnTwoVoidPointers(S, Loc, LHSExpr, RHSExpr);
Chandler Carruthc9332212011-06-27 08:02:19 +00006292
David Blaikiebbafb8a2012-03-11 07:00:24 +00006293 return !S.getLangOpts().CPlusPlus;
Chandler Carruthc9332212011-06-27 08:02:19 +00006294 }
6295
6296 bool isLHSFuncPtr = isLHSPointer && LHSPointeeTy->isFunctionType();
6297 bool isRHSFuncPtr = isRHSPointer && RHSPointeeTy->isFunctionType();
6298 if (isLHSFuncPtr || isRHSFuncPtr) {
Richard Trieu4ae7e972011-09-06 21:13:51 +00006299 if (!isRHSFuncPtr) diagnoseArithmeticOnFunctionPointer(S, Loc, LHSExpr);
6300 else if (!isLHSFuncPtr) diagnoseArithmeticOnFunctionPointer(S, Loc,
6301 RHSExpr);
6302 else diagnoseArithmeticOnTwoFunctionPointers(S, Loc, LHSExpr, RHSExpr);
Chandler Carruthc9332212011-06-27 08:02:19 +00006303
David Blaikiebbafb8a2012-03-11 07:00:24 +00006304 return !S.getLangOpts().CPlusPlus;
Chandler Carruthc9332212011-06-27 08:02:19 +00006305 }
6306
John McCallf2538342012-07-31 05:14:30 +00006307 if (isLHSPointer && checkArithmeticIncompletePointerType(S, Loc, LHSExpr))
6308 return false;
6309 if (isRHSPointer && checkArithmeticIncompletePointerType(S, Loc, RHSExpr))
6310 return false;
Richard Trieuaba22802011-09-02 02:15:37 +00006311
Chandler Carruthc9332212011-06-27 08:02:19 +00006312 return true;
6313}
6314
Nico Weberccec40d2012-03-02 22:01:22 +00006315/// diagnoseStringPlusInt - Emit a warning when adding an integer to a string
6316/// literal.
6317static void diagnoseStringPlusInt(Sema &Self, SourceLocation OpLoc,
6318 Expr *LHSExpr, Expr *RHSExpr) {
6319 StringLiteral* StrExpr = dyn_cast<StringLiteral>(LHSExpr->IgnoreImpCasts());
6320 Expr* IndexExpr = RHSExpr;
6321 if (!StrExpr) {
6322 StrExpr = dyn_cast<StringLiteral>(RHSExpr->IgnoreImpCasts());
6323 IndexExpr = LHSExpr;
6324 }
6325
6326 bool IsStringPlusInt = StrExpr &&
6327 IndexExpr->getType()->isIntegralOrUnscopedEnumerationType();
6328 if (!IsStringPlusInt)
6329 return;
6330
6331 llvm::APSInt index;
6332 if (IndexExpr->EvaluateAsInt(index, Self.getASTContext())) {
6333 unsigned StrLenWithNull = StrExpr->getLength() + 1;
6334 if (index.isNonNegative() &&
6335 index <= llvm::APSInt(llvm::APInt(index.getBitWidth(), StrLenWithNull),
6336 index.isUnsigned()))
6337 return;
6338 }
6339
6340 SourceRange DiagRange(LHSExpr->getLocStart(), RHSExpr->getLocEnd());
6341 Self.Diag(OpLoc, diag::warn_string_plus_int)
6342 << DiagRange << IndexExpr->IgnoreImpCasts()->getType();
6343
6344 // Only print a fixit for "str" + int, not for int + "str".
6345 if (IndexExpr == RHSExpr) {
6346 SourceLocation EndLoc = Self.PP.getLocForEndOfToken(RHSExpr->getLocEnd());
6347 Self.Diag(OpLoc, diag::note_string_plus_int_silence)
6348 << FixItHint::CreateInsertion(LHSExpr->getLocStart(), "&")
6349 << FixItHint::CreateReplacement(SourceRange(OpLoc), "[")
6350 << FixItHint::CreateInsertion(EndLoc, "]");
6351 } else
6352 Self.Diag(OpLoc, diag::note_string_plus_int_silence);
6353}
6354
Richard Trieu993f3ab2011-09-12 18:08:02 +00006355/// \brief Emit error when two pointers are incompatible.
Richard Trieub10c6312011-09-01 22:53:23 +00006356static void diagnosePointerIncompatibility(Sema &S, SourceLocation Loc,
Richard Trieu4ae7e972011-09-06 21:13:51 +00006357 Expr *LHSExpr, Expr *RHSExpr) {
6358 assert(LHSExpr->getType()->isAnyPointerType());
6359 assert(RHSExpr->getType()->isAnyPointerType());
Richard Trieub10c6312011-09-01 22:53:23 +00006360 S.Diag(Loc, diag::err_typecheck_sub_ptr_compatible)
Richard Trieu4ae7e972011-09-06 21:13:51 +00006361 << LHSExpr->getType() << RHSExpr->getType() << LHSExpr->getSourceRange()
6362 << RHSExpr->getSourceRange();
Richard Trieub10c6312011-09-01 22:53:23 +00006363}
6364
Chris Lattnerfaa54172010-01-12 21:23:57 +00006365QualType Sema::CheckAdditionOperands( // C99 6.5.6
Nico Weberccec40d2012-03-02 22:01:22 +00006366 ExprResult &LHS, ExprResult &RHS, SourceLocation Loc, unsigned Opc,
6367 QualType* CompLHSTy) {
Richard Trieuf8916e12011-09-16 00:53:10 +00006368 checkArithmeticNull(*this, LHS, RHS, Loc, /*isCompare=*/false);
6369
Richard Trieu4ae7e972011-09-06 21:13:51 +00006370 if (LHS.get()->getType()->isVectorType() ||
6371 RHS.get()->getType()->isVectorType()) {
6372 QualType compType = CheckVectorOperands(LHS, RHS, Loc, CompLHSTy);
Eli Friedman8b7b1b12009-03-28 01:22:36 +00006373 if (CompLHSTy) *CompLHSTy = compType;
6374 return compType;
6375 }
Steve Naroff7a5af782007-07-13 16:58:59 +00006376
Richard Trieu4ae7e972011-09-06 21:13:51 +00006377 QualType compType = UsualArithmeticConversions(LHS, RHS, CompLHSTy);
6378 if (LHS.isInvalid() || RHS.isInvalid())
John Wiegley01296292011-04-08 18:41:53 +00006379 return QualType();
Eli Friedman8e122982008-05-18 18:08:51 +00006380
Nico Weberccec40d2012-03-02 22:01:22 +00006381 // Diagnose "string literal" '+' int.
6382 if (Opc == BO_Add)
6383 diagnoseStringPlusInt(*this, Loc, LHS.get(), RHS.get());
6384
Steve Naroffe4718892007-04-27 18:30:00 +00006385 // handle the common case first (both operands are arithmetic).
Eli Friedman93ee5ca2012-06-16 02:19:17 +00006386 if (!compType.isNull() && compType->isArithmeticType()) {
Eli Friedman8b7b1b12009-03-28 01:22:36 +00006387 if (CompLHSTy) *CompLHSTy = compType;
Steve Naroffbe4c4d12007-08-24 19:07:16 +00006388 return compType;
Eli Friedman8b7b1b12009-03-28 01:22:36 +00006389 }
Steve Naroff218bc2b2007-05-04 21:54:46 +00006390
John McCallf2538342012-07-31 05:14:30 +00006391 // Type-checking. Ultimately the pointer's going to be in PExp;
6392 // note that we bias towards the LHS being the pointer.
6393 Expr *PExp = LHS.get(), *IExp = RHS.get();
Eli Friedman8e122982008-05-18 18:08:51 +00006394
John McCallf2538342012-07-31 05:14:30 +00006395 bool isObjCPointer;
6396 if (PExp->getType()->isPointerType()) {
6397 isObjCPointer = false;
6398 } else if (PExp->getType()->isObjCObjectPointerType()) {
6399 isObjCPointer = true;
6400 } else {
6401 std::swap(PExp, IExp);
6402 if (PExp->getType()->isPointerType()) {
6403 isObjCPointer = false;
6404 } else if (PExp->getType()->isObjCObjectPointerType()) {
6405 isObjCPointer = true;
6406 } else {
6407 return InvalidOperands(Loc, LHS, RHS);
6408 }
6409 }
6410 assert(PExp->getType()->isAnyPointerType());
Chandler Carruthc9332212011-06-27 08:02:19 +00006411
Richard Trieub420bca2011-09-12 18:37:54 +00006412 if (!IExp->getType()->isIntegerType())
6413 return InvalidOperands(Loc, LHS, RHS);
Mike Stump11289f42009-09-09 15:08:12 +00006414
Richard Trieub420bca2011-09-12 18:37:54 +00006415 if (!checkArithmeticOpPointerOperand(*this, Loc, PExp))
6416 return QualType();
Kaelyn Uhrain2e7aa5a2011-08-05 23:18:04 +00006417
John McCallf2538342012-07-31 05:14:30 +00006418 if (isObjCPointer && checkArithmeticOnObjCPointer(*this, Loc, PExp))
Richard Trieub420bca2011-09-12 18:37:54 +00006419 return QualType();
6420
6421 // Check array bounds for pointer arithemtic
6422 CheckArrayAccess(PExp, IExp);
6423
6424 if (CompLHSTy) {
6425 QualType LHSTy = Context.isPromotableBitField(LHS.get());
6426 if (LHSTy.isNull()) {
6427 LHSTy = LHS.get()->getType();
6428 if (LHSTy->isPromotableIntegerType())
6429 LHSTy = Context.getPromotedIntegerType(LHSTy);
Eli Friedman8e122982008-05-18 18:08:51 +00006430 }
Richard Trieub420bca2011-09-12 18:37:54 +00006431 *CompLHSTy = LHSTy;
Eli Friedman8e122982008-05-18 18:08:51 +00006432 }
6433
Richard Trieub420bca2011-09-12 18:37:54 +00006434 return PExp->getType();
Steve Naroff26c8ea52007-03-21 21:08:52 +00006435}
6436
Chris Lattner2a3569b2008-04-07 05:30:13 +00006437// C99 6.5.6
Richard Trieu4ae7e972011-09-06 21:13:51 +00006438QualType Sema::CheckSubtractionOperands(ExprResult &LHS, ExprResult &RHS,
Richard Trieucfc491d2011-08-02 04:35:43 +00006439 SourceLocation Loc,
6440 QualType* CompLHSTy) {
Richard Trieuf8916e12011-09-16 00:53:10 +00006441 checkArithmeticNull(*this, LHS, RHS, Loc, /*isCompare=*/false);
6442
Richard Trieu4ae7e972011-09-06 21:13:51 +00006443 if (LHS.get()->getType()->isVectorType() ||
6444 RHS.get()->getType()->isVectorType()) {
6445 QualType compType = CheckVectorOperands(LHS, RHS, Loc, CompLHSTy);
Eli Friedman8b7b1b12009-03-28 01:22:36 +00006446 if (CompLHSTy) *CompLHSTy = compType;
6447 return compType;
6448 }
Mike Stump4e1f26a2009-02-19 03:04:26 +00006449
Richard Trieu4ae7e972011-09-06 21:13:51 +00006450 QualType compType = UsualArithmeticConversions(LHS, RHS, CompLHSTy);
6451 if (LHS.isInvalid() || RHS.isInvalid())
John Wiegley01296292011-04-08 18:41:53 +00006452 return QualType();
Mike Stump4e1f26a2009-02-19 03:04:26 +00006453
Chris Lattner4d62f422007-12-09 21:53:25 +00006454 // Enforce type constraints: C99 6.5.6p3.
Mike Stump4e1f26a2009-02-19 03:04:26 +00006455
Chris Lattner4d62f422007-12-09 21:53:25 +00006456 // Handle the common case first (both operands are arithmetic).
Eli Friedman93ee5ca2012-06-16 02:19:17 +00006457 if (!compType.isNull() && compType->isArithmeticType()) {
Eli Friedman8b7b1b12009-03-28 01:22:36 +00006458 if (CompLHSTy) *CompLHSTy = compType;
Steve Naroffbe4c4d12007-08-24 19:07:16 +00006459 return compType;
Eli Friedman8b7b1b12009-03-28 01:22:36 +00006460 }
Mike Stump11289f42009-09-09 15:08:12 +00006461
Chris Lattner4d62f422007-12-09 21:53:25 +00006462 // Either ptr - int or ptr - ptr.
Richard Trieu4ae7e972011-09-06 21:13:51 +00006463 if (LHS.get()->getType()->isAnyPointerType()) {
6464 QualType lpointee = LHS.get()->getType()->getPointeeType();
Mike Stump4e1f26a2009-02-19 03:04:26 +00006465
Chris Lattner12bdebb2009-04-24 23:50:08 +00006466 // Diagnose bad cases where we step over interface counts.
John McCallf2538342012-07-31 05:14:30 +00006467 if (LHS.get()->getType()->isObjCObjectPointerType() &&
6468 checkArithmeticOnObjCPointer(*this, Loc, LHS.get()))
Chris Lattner12bdebb2009-04-24 23:50:08 +00006469 return QualType();
Mike Stump11289f42009-09-09 15:08:12 +00006470
Chris Lattner4d62f422007-12-09 21:53:25 +00006471 // The result type of a pointer-int computation is the pointer type.
Richard Trieu4ae7e972011-09-06 21:13:51 +00006472 if (RHS.get()->getType()->isIntegerType()) {
6473 if (!checkArithmeticOpPointerOperand(*this, Loc, LHS.get()))
Chandler Carruthc9332212011-06-27 08:02:19 +00006474 return QualType();
Douglas Gregorac1fb652009-03-24 19:52:54 +00006475
Kaelyn Uhrain2e7aa5a2011-08-05 23:18:04 +00006476 // Check array bounds for pointer arithemtic
Richard Smith13f67182011-12-16 19:31:14 +00006477 CheckArrayAccess(LHS.get(), RHS.get(), /*ArraySubscriptExpr*/0,
6478 /*AllowOnePastEnd*/true, /*IndexNegated*/true);
Kaelyn Uhrain2e7aa5a2011-08-05 23:18:04 +00006479
Richard Trieu4ae7e972011-09-06 21:13:51 +00006480 if (CompLHSTy) *CompLHSTy = LHS.get()->getType();
6481 return LHS.get()->getType();
Douglas Gregorac1fb652009-03-24 19:52:54 +00006482 }
Mike Stump4e1f26a2009-02-19 03:04:26 +00006483
Chris Lattner4d62f422007-12-09 21:53:25 +00006484 // Handle pointer-pointer subtractions.
Richard Trieucfc491d2011-08-02 04:35:43 +00006485 if (const PointerType *RHSPTy
Richard Trieu4ae7e972011-09-06 21:13:51 +00006486 = RHS.get()->getType()->getAs<PointerType>()) {
Eli Friedman1974e532008-02-08 01:19:44 +00006487 QualType rpointee = RHSPTy->getPointeeType();
Mike Stump4e1f26a2009-02-19 03:04:26 +00006488
David Blaikiebbafb8a2012-03-11 07:00:24 +00006489 if (getLangOpts().CPlusPlus) {
Eli Friedman168fe152009-05-16 13:54:38 +00006490 // Pointee types must be the same: C++ [expr.add]
6491 if (!Context.hasSameUnqualifiedType(lpointee, rpointee)) {
Richard Trieu4ae7e972011-09-06 21:13:51 +00006492 diagnosePointerIncompatibility(*this, Loc, LHS.get(), RHS.get());
Eli Friedman168fe152009-05-16 13:54:38 +00006493 }
6494 } else {
6495 // Pointee types must be compatible C99 6.5.6p3
6496 if (!Context.typesAreCompatible(
6497 Context.getCanonicalType(lpointee).getUnqualifiedType(),
6498 Context.getCanonicalType(rpointee).getUnqualifiedType())) {
Richard Trieu4ae7e972011-09-06 21:13:51 +00006499 diagnosePointerIncompatibility(*this, Loc, LHS.get(), RHS.get());
Eli Friedman168fe152009-05-16 13:54:38 +00006500 return QualType();
6501 }
Chris Lattner4d62f422007-12-09 21:53:25 +00006502 }
Mike Stump4e1f26a2009-02-19 03:04:26 +00006503
Chandler Carruthc9332212011-06-27 08:02:19 +00006504 if (!checkArithmeticBinOpPointerOperands(*this, Loc,
Richard Trieu4ae7e972011-09-06 21:13:51 +00006505 LHS.get(), RHS.get()))
Chandler Carruthc9332212011-06-27 08:02:19 +00006506 return QualType();
Eli Friedman8b7b1b12009-03-28 01:22:36 +00006507
Richard Trieu4ae7e972011-09-06 21:13:51 +00006508 if (CompLHSTy) *CompLHSTy = LHS.get()->getType();
Chris Lattner4d62f422007-12-09 21:53:25 +00006509 return Context.getPointerDiffType();
6510 }
6511 }
Mike Stump4e1f26a2009-02-19 03:04:26 +00006512
Richard Trieu4ae7e972011-09-06 21:13:51 +00006513 return InvalidOperands(Loc, LHS, RHS);
Steve Naroff218bc2b2007-05-04 21:54:46 +00006514}
6515
Douglas Gregor0bf31402010-10-08 23:50:27 +00006516static bool isScopedEnumerationType(QualType T) {
6517 if (const EnumType *ET = dyn_cast<EnumType>(T))
6518 return ET->getDecl()->isScoped();
6519 return false;
6520}
6521
Richard Trieue4a19fb2011-09-06 21:21:28 +00006522static void DiagnoseBadShiftValues(Sema& S, ExprResult &LHS, ExprResult &RHS,
Chandler Carruth4c6fdca2011-02-23 23:34:11 +00006523 SourceLocation Loc, unsigned Opc,
Richard Trieue4a19fb2011-09-06 21:21:28 +00006524 QualType LHSType) {
Chandler Carruth4c6fdca2011-02-23 23:34:11 +00006525 llvm::APSInt Right;
6526 // Check right/shifter operand
Richard Trieue4a19fb2011-09-06 21:21:28 +00006527 if (RHS.get()->isValueDependent() ||
6528 !RHS.get()->isIntegerConstantExpr(Right, S.Context))
Chandler Carruth4c6fdca2011-02-23 23:34:11 +00006529 return;
6530
6531 if (Right.isNegative()) {
Richard Trieue4a19fb2011-09-06 21:21:28 +00006532 S.DiagRuntimeBehavior(Loc, RHS.get(),
Ted Kremenek63657fe2011-03-01 18:09:31 +00006533 S.PDiag(diag::warn_shift_negative)
Richard Trieue4a19fb2011-09-06 21:21:28 +00006534 << RHS.get()->getSourceRange());
Chandler Carruth4c6fdca2011-02-23 23:34:11 +00006535 return;
6536 }
6537 llvm::APInt LeftBits(Right.getBitWidth(),
Richard Trieue4a19fb2011-09-06 21:21:28 +00006538 S.Context.getTypeSize(LHS.get()->getType()));
Chandler Carruth4c6fdca2011-02-23 23:34:11 +00006539 if (Right.uge(LeftBits)) {
Richard Trieue4a19fb2011-09-06 21:21:28 +00006540 S.DiagRuntimeBehavior(Loc, RHS.get(),
Ted Kremenek26bbc3d2011-03-01 19:13:22 +00006541 S.PDiag(diag::warn_shift_gt_typewidth)
Richard Trieue4a19fb2011-09-06 21:21:28 +00006542 << RHS.get()->getSourceRange());
Chandler Carruth4c6fdca2011-02-23 23:34:11 +00006543 return;
6544 }
6545 if (Opc != BO_Shl)
6546 return;
6547
6548 // When left shifting an ICE which is signed, we can check for overflow which
6549 // according to C++ has undefined behavior ([expr.shift] 5.8/2). Unsigned
6550 // integers have defined behavior modulo one more than the maximum value
6551 // representable in the result type, so never warn for those.
6552 llvm::APSInt Left;
Richard Trieue4a19fb2011-09-06 21:21:28 +00006553 if (LHS.get()->isValueDependent() ||
6554 !LHS.get()->isIntegerConstantExpr(Left, S.Context) ||
6555 LHSType->hasUnsignedIntegerRepresentation())
Chandler Carruth4c6fdca2011-02-23 23:34:11 +00006556 return;
6557 llvm::APInt ResultBits =
6558 static_cast<llvm::APInt&>(Right) + Left.getMinSignedBits();
6559 if (LeftBits.uge(ResultBits))
6560 return;
6561 llvm::APSInt Result = Left.extend(ResultBits.getLimitedValue());
6562 Result = Result.shl(Right);
6563
Ted Kremenek70f05fd2011-06-15 00:54:52 +00006564 // Print the bit representation of the signed integer as an unsigned
6565 // hexadecimal number.
Dylan Noblesmith2c1dd272012-02-05 02:13:05 +00006566 SmallString<40> HexResult;
Ted Kremenek70f05fd2011-06-15 00:54:52 +00006567 Result.toString(HexResult, 16, /*Signed =*/false, /*Literal =*/true);
6568
Chandler Carruth4c6fdca2011-02-23 23:34:11 +00006569 // If we are only missing a sign bit, this is less likely to result in actual
6570 // bugs -- if the result is cast back to an unsigned type, it will have the
6571 // expected value. Thus we place this behind a different warning that can be
6572 // turned off separately if needed.
6573 if (LeftBits == ResultBits - 1) {
Ted Kremenek70f05fd2011-06-15 00:54:52 +00006574 S.Diag(Loc, diag::warn_shift_result_sets_sign_bit)
Richard Trieue4a19fb2011-09-06 21:21:28 +00006575 << HexResult.str() << LHSType
6576 << LHS.get()->getSourceRange() << RHS.get()->getSourceRange();
Chandler Carruth4c6fdca2011-02-23 23:34:11 +00006577 return;
6578 }
6579
6580 S.Diag(Loc, diag::warn_shift_result_gt_typewidth)
Richard Trieue4a19fb2011-09-06 21:21:28 +00006581 << HexResult.str() << Result.getMinSignedBits() << LHSType
6582 << Left.getBitWidth() << LHS.get()->getSourceRange()
6583 << RHS.get()->getSourceRange();
Chandler Carruth4c6fdca2011-02-23 23:34:11 +00006584}
6585
Chris Lattner2a3569b2008-04-07 05:30:13 +00006586// C99 6.5.7
Richard Trieue4a19fb2011-09-06 21:21:28 +00006587QualType Sema::CheckShiftOperands(ExprResult &LHS, ExprResult &RHS,
Richard Trieucfc491d2011-08-02 04:35:43 +00006588 SourceLocation Loc, unsigned Opc,
Richard Trieuba63ce62011-09-09 01:45:06 +00006589 bool IsCompAssign) {
Richard Trieuf8916e12011-09-16 00:53:10 +00006590 checkArithmeticNull(*this, LHS, RHS, Loc, /*isCompare=*/false);
6591
Chris Lattner5c11c412007-12-12 05:47:28 +00006592 // C99 6.5.7p2: Each of the operands shall have integer type.
Richard Trieue4a19fb2011-09-06 21:21:28 +00006593 if (!LHS.get()->getType()->hasIntegerRepresentation() ||
6594 !RHS.get()->getType()->hasIntegerRepresentation())
6595 return InvalidOperands(Loc, LHS, RHS);
Mike Stump4e1f26a2009-02-19 03:04:26 +00006596
Douglas Gregor0bf31402010-10-08 23:50:27 +00006597 // C++0x: Don't allow scoped enums. FIXME: Use something better than
6598 // hasIntegerRepresentation() above instead of this.
Richard Trieue4a19fb2011-09-06 21:21:28 +00006599 if (isScopedEnumerationType(LHS.get()->getType()) ||
6600 isScopedEnumerationType(RHS.get()->getType())) {
6601 return InvalidOperands(Loc, LHS, RHS);
Douglas Gregor0bf31402010-10-08 23:50:27 +00006602 }
6603
Nate Begemane46ee9a2009-10-25 02:26:48 +00006604 // Vector shifts promote their scalar inputs to vector type.
Richard Trieue4a19fb2011-09-06 21:21:28 +00006605 if (LHS.get()->getType()->isVectorType() ||
6606 RHS.get()->getType()->isVectorType())
Richard Trieuba63ce62011-09-09 01:45:06 +00006607 return CheckVectorOperands(LHS, RHS, Loc, IsCompAssign);
Nate Begemane46ee9a2009-10-25 02:26:48 +00006608
Chris Lattner5c11c412007-12-12 05:47:28 +00006609 // Shifts don't perform usual arithmetic conversions, they just do integer
6610 // promotions on each operand. C99 6.5.7p3
Eli Friedman8b7b1b12009-03-28 01:22:36 +00006611
John McCall57cdd882010-12-16 19:28:59 +00006612 // For the LHS, do usual unary conversions, but then reset them away
6613 // if this is a compound assignment.
Richard Trieue4a19fb2011-09-06 21:21:28 +00006614 ExprResult OldLHS = LHS;
6615 LHS = UsualUnaryConversions(LHS.take());
6616 if (LHS.isInvalid())
John Wiegley01296292011-04-08 18:41:53 +00006617 return QualType();
Richard Trieue4a19fb2011-09-06 21:21:28 +00006618 QualType LHSType = LHS.get()->getType();
Richard Trieuba63ce62011-09-09 01:45:06 +00006619 if (IsCompAssign) LHS = OldLHS;
John McCall57cdd882010-12-16 19:28:59 +00006620
6621 // The RHS is simpler.
Richard Trieue4a19fb2011-09-06 21:21:28 +00006622 RHS = UsualUnaryConversions(RHS.take());
6623 if (RHS.isInvalid())
John Wiegley01296292011-04-08 18:41:53 +00006624 return QualType();
Mike Stump4e1f26a2009-02-19 03:04:26 +00006625
Ryan Flynnf53fab82009-08-07 16:20:20 +00006626 // Sanity-check shift operands
Richard Trieue4a19fb2011-09-06 21:21:28 +00006627 DiagnoseBadShiftValues(*this, LHS, RHS, Loc, Opc, LHSType);
Ryan Flynnf53fab82009-08-07 16:20:20 +00006628
Chris Lattner5c11c412007-12-12 05:47:28 +00006629 // "The type of the result is that of the promoted left operand."
Richard Trieue4a19fb2011-09-06 21:21:28 +00006630 return LHSType;
Steve Naroff26c8ea52007-03-21 21:08:52 +00006631}
6632
Chandler Carruth17773fc2010-07-10 12:30:03 +00006633static bool IsWithinTemplateSpecialization(Decl *D) {
6634 if (DeclContext *DC = D->getDeclContext()) {
6635 if (isa<ClassTemplateSpecializationDecl>(DC))
6636 return true;
6637 if (FunctionDecl *FD = dyn_cast<FunctionDecl>(DC))
6638 return FD->isFunctionTemplateSpecialization();
6639 }
6640 return false;
6641}
6642
Richard Trieueea56f72011-09-02 03:48:46 +00006643/// If two different enums are compared, raise a warning.
Richard Trieu1762d7c2011-09-06 21:27:33 +00006644static void checkEnumComparison(Sema &S, SourceLocation Loc, ExprResult &LHS,
6645 ExprResult &RHS) {
6646 QualType LHSStrippedType = LHS.get()->IgnoreParenImpCasts()->getType();
6647 QualType RHSStrippedType = RHS.get()->IgnoreParenImpCasts()->getType();
Richard Trieueea56f72011-09-02 03:48:46 +00006648
6649 const EnumType *LHSEnumType = LHSStrippedType->getAs<EnumType>();
6650 if (!LHSEnumType)
6651 return;
6652 const EnumType *RHSEnumType = RHSStrippedType->getAs<EnumType>();
6653 if (!RHSEnumType)
6654 return;
6655
6656 // Ignore anonymous enums.
6657 if (!LHSEnumType->getDecl()->getIdentifier())
6658 return;
6659 if (!RHSEnumType->getDecl()->getIdentifier())
6660 return;
6661
6662 if (S.Context.hasSameUnqualifiedType(LHSStrippedType, RHSStrippedType))
6663 return;
6664
6665 S.Diag(Loc, diag::warn_comparison_of_mixed_enum_types)
6666 << LHSStrippedType << RHSStrippedType
Richard Trieu1762d7c2011-09-06 21:27:33 +00006667 << LHS.get()->getSourceRange() << RHS.get()->getSourceRange();
Richard Trieueea56f72011-09-02 03:48:46 +00006668}
6669
Richard Trieudd82a5c2011-09-02 02:55:45 +00006670/// \brief Diagnose bad pointer comparisons.
6671static void diagnoseDistinctPointerComparison(Sema &S, SourceLocation Loc,
Richard Trieu1762d7c2011-09-06 21:27:33 +00006672 ExprResult &LHS, ExprResult &RHS,
Richard Trieuba63ce62011-09-09 01:45:06 +00006673 bool IsError) {
6674 S.Diag(Loc, IsError ? diag::err_typecheck_comparison_of_distinct_pointers
Richard Trieudd82a5c2011-09-02 02:55:45 +00006675 : diag::ext_typecheck_comparison_of_distinct_pointers)
Richard Trieu1762d7c2011-09-06 21:27:33 +00006676 << LHS.get()->getType() << RHS.get()->getType()
6677 << LHS.get()->getSourceRange() << RHS.get()->getSourceRange();
Richard Trieudd82a5c2011-09-02 02:55:45 +00006678}
6679
6680/// \brief Returns false if the pointers are converted to a composite type,
6681/// true otherwise.
6682static bool convertPointersToCompositeType(Sema &S, SourceLocation Loc,
Richard Trieu1762d7c2011-09-06 21:27:33 +00006683 ExprResult &LHS, ExprResult &RHS) {
Richard Trieudd82a5c2011-09-02 02:55:45 +00006684 // C++ [expr.rel]p2:
6685 // [...] Pointer conversions (4.10) and qualification
6686 // conversions (4.4) are performed on pointer operands (or on
6687 // a pointer operand and a null pointer constant) to bring
6688 // them to their composite pointer type. [...]
6689 //
6690 // C++ [expr.eq]p1 uses the same notion for (in)equality
6691 // comparisons of pointers.
6692
6693 // C++ [expr.eq]p2:
6694 // In addition, pointers to members can be compared, or a pointer to
6695 // member and a null pointer constant. Pointer to member conversions
6696 // (4.11) and qualification conversions (4.4) are performed to bring
6697 // them to a common type. If one operand is a null pointer constant,
6698 // the common type is the type of the other operand. Otherwise, the
6699 // common type is a pointer to member type similar (4.4) to the type
6700 // of one of the operands, with a cv-qualification signature (4.4)
6701 // that is the union of the cv-qualification signatures of the operand
6702 // types.
6703
Richard Trieu1762d7c2011-09-06 21:27:33 +00006704 QualType LHSType = LHS.get()->getType();
6705 QualType RHSType = RHS.get()->getType();
6706 assert((LHSType->isPointerType() && RHSType->isPointerType()) ||
6707 (LHSType->isMemberPointerType() && RHSType->isMemberPointerType()));
Richard Trieudd82a5c2011-09-02 02:55:45 +00006708
6709 bool NonStandardCompositeType = false;
Richard Trieu48277e52011-09-02 21:44:27 +00006710 bool *BoolPtr = S.isSFINAEContext() ? 0 : &NonStandardCompositeType;
Richard Trieu1762d7c2011-09-06 21:27:33 +00006711 QualType T = S.FindCompositePointerType(Loc, LHS, RHS, BoolPtr);
Richard Trieudd82a5c2011-09-02 02:55:45 +00006712 if (T.isNull()) {
Richard Trieu1762d7c2011-09-06 21:27:33 +00006713 diagnoseDistinctPointerComparison(S, Loc, LHS, RHS, /*isError*/true);
Richard Trieudd82a5c2011-09-02 02:55:45 +00006714 return true;
6715 }
6716
6717 if (NonStandardCompositeType)
6718 S.Diag(Loc, diag::ext_typecheck_comparison_of_distinct_pointers_nonstandard)
Richard Trieu1762d7c2011-09-06 21:27:33 +00006719 << LHSType << RHSType << T << LHS.get()->getSourceRange()
6720 << RHS.get()->getSourceRange();
Richard Trieudd82a5c2011-09-02 02:55:45 +00006721
Richard Trieu1762d7c2011-09-06 21:27:33 +00006722 LHS = S.ImpCastExprToType(LHS.take(), T, CK_BitCast);
6723 RHS = S.ImpCastExprToType(RHS.take(), T, CK_BitCast);
Richard Trieudd82a5c2011-09-02 02:55:45 +00006724 return false;
6725}
6726
6727static void diagnoseFunctionPointerToVoidComparison(Sema &S, SourceLocation Loc,
Richard Trieu1762d7c2011-09-06 21:27:33 +00006728 ExprResult &LHS,
6729 ExprResult &RHS,
Richard Trieuba63ce62011-09-09 01:45:06 +00006730 bool IsError) {
6731 S.Diag(Loc, IsError ? diag::err_typecheck_comparison_of_fptr_to_void
6732 : diag::ext_typecheck_comparison_of_fptr_to_void)
Richard Trieu1762d7c2011-09-06 21:27:33 +00006733 << LHS.get()->getType() << RHS.get()->getType()
6734 << LHS.get()->getSourceRange() << RHS.get()->getSourceRange();
Richard Trieudd82a5c2011-09-02 02:55:45 +00006735}
6736
Jordan Rosed49a33e2012-06-08 21:14:25 +00006737static bool isObjCObjectLiteral(ExprResult &E) {
6738 switch (E.get()->getStmtClass()) {
6739 case Stmt::ObjCArrayLiteralClass:
6740 case Stmt::ObjCDictionaryLiteralClass:
6741 case Stmt::ObjCStringLiteralClass:
6742 case Stmt::ObjCBoxedExprClass:
6743 return true;
6744 default:
6745 // Note that ObjCBoolLiteral is NOT an object literal!
6746 return false;
6747 }
6748}
6749
Jordan Rose7660f782012-07-17 17:46:40 +00006750static bool hasIsEqualMethod(Sema &S, const Expr *LHS, const Expr *RHS) {
6751 // Get the LHS object's interface type.
6752 QualType Type = LHS->getType();
6753 QualType InterfaceType;
6754 if (const ObjCObjectPointerType *PTy = Type->getAs<ObjCObjectPointerType>()) {
6755 InterfaceType = PTy->getPointeeType();
6756 if (const ObjCObjectType *iQFaceTy =
6757 InterfaceType->getAsObjCQualifiedInterfaceType())
6758 InterfaceType = iQFaceTy->getBaseType();
6759 } else {
6760 // If this is not actually an Objective-C object, bail out.
6761 return false;
6762 }
6763
6764 // If the RHS isn't an Objective-C object, bail out.
6765 if (!RHS->getType()->isObjCObjectPointerType())
6766 return false;
6767
6768 // Try to find the -isEqual: method.
6769 Selector IsEqualSel = S.NSAPIObj->getIsEqualSelector();
6770 ObjCMethodDecl *Method = S.LookupMethodInObjectType(IsEqualSel,
6771 InterfaceType,
6772 /*instance=*/true);
6773 if (!Method) {
6774 if (Type->isObjCIdType()) {
6775 // For 'id', just check the global pool.
6776 Method = S.LookupInstanceMethodInGlobalPool(IsEqualSel, SourceRange(),
6777 /*receiverId=*/true,
6778 /*warn=*/false);
6779 } else {
6780 // Check protocols.
6781 Method = S.LookupMethodInQualifiedType(IsEqualSel,
6782 cast<ObjCObjectPointerType>(Type),
6783 /*instance=*/true);
6784 }
6785 }
6786
6787 if (!Method)
6788 return false;
6789
6790 QualType T = Method->param_begin()[0]->getType();
6791 if (!T->isObjCObjectPointerType())
6792 return false;
6793
6794 QualType R = Method->getResultType();
6795 if (!R->isScalarType())
6796 return false;
6797
6798 return true;
6799}
6800
6801static void diagnoseObjCLiteralComparison(Sema &S, SourceLocation Loc,
6802 ExprResult &LHS, ExprResult &RHS,
6803 BinaryOperator::Opcode Opc){
Jordan Rose63ffaa82012-07-17 17:46:48 +00006804 Expr *Literal;
6805 Expr *Other;
6806 if (isObjCObjectLiteral(LHS)) {
6807 Literal = LHS.get();
6808 Other = RHS.get();
6809 } else {
6810 Literal = RHS.get();
6811 Other = LHS.get();
6812 }
6813
6814 // Don't warn on comparisons against nil.
6815 Other = Other->IgnoreParenCasts();
6816 if (Other->isNullPointerConstant(S.getASTContext(),
6817 Expr::NPC_ValueDependentIsNotNull))
6818 return;
Jordan Rosed49a33e2012-06-08 21:14:25 +00006819
Jordan Roseea70bf72012-07-17 17:46:44 +00006820 // This should be kept in sync with warn_objc_literal_comparison.
Jordan Rose63ffaa82012-07-17 17:46:48 +00006821 // LK_String should always be last, since it has its own warning flag.
Jordan Roseea70bf72012-07-17 17:46:44 +00006822 enum {
6823 LK_Array,
6824 LK_Dictionary,
6825 LK_Numeric,
6826 LK_Boxed,
6827 LK_String
6828 } LiteralKind;
6829
Jordan Rosed49a33e2012-06-08 21:14:25 +00006830 switch (Literal->getStmtClass()) {
6831 case Stmt::ObjCStringLiteralClass:
6832 // "string literal"
Jordan Roseea70bf72012-07-17 17:46:44 +00006833 LiteralKind = LK_String;
Jordan Rosed49a33e2012-06-08 21:14:25 +00006834 break;
6835 case Stmt::ObjCArrayLiteralClass:
6836 // "array literal"
Jordan Roseea70bf72012-07-17 17:46:44 +00006837 LiteralKind = LK_Array;
Jordan Rosed49a33e2012-06-08 21:14:25 +00006838 break;
6839 case Stmt::ObjCDictionaryLiteralClass:
6840 // "dictionary literal"
Jordan Roseea70bf72012-07-17 17:46:44 +00006841 LiteralKind = LK_Dictionary;
Jordan Rosed49a33e2012-06-08 21:14:25 +00006842 break;
6843 case Stmt::ObjCBoxedExprClass: {
6844 Expr *Inner = cast<ObjCBoxedExpr>(Literal)->getSubExpr();
6845 switch (Inner->getStmtClass()) {
6846 case Stmt::IntegerLiteralClass:
6847 case Stmt::FloatingLiteralClass:
6848 case Stmt::CharacterLiteralClass:
6849 case Stmt::ObjCBoolLiteralExprClass:
6850 case Stmt::CXXBoolLiteralExprClass:
6851 // "numeric literal"
Jordan Roseea70bf72012-07-17 17:46:44 +00006852 LiteralKind = LK_Numeric;
Jordan Rosed49a33e2012-06-08 21:14:25 +00006853 break;
6854 case Stmt::ImplicitCastExprClass: {
6855 CastKind CK = cast<CastExpr>(Inner)->getCastKind();
6856 // Boolean literals can be represented by implicit casts.
6857 if (CK == CK_IntegralToBoolean || CK == CK_IntegralCast) {
Jordan Roseea70bf72012-07-17 17:46:44 +00006858 LiteralKind = LK_Numeric;
Jordan Rosed49a33e2012-06-08 21:14:25 +00006859 break;
6860 }
6861 // FALLTHROUGH
6862 }
6863 default:
6864 // "boxed expression"
Jordan Roseea70bf72012-07-17 17:46:44 +00006865 LiteralKind = LK_Boxed;
Jordan Rosed49a33e2012-06-08 21:14:25 +00006866 break;
6867 }
6868 break;
6869 }
6870 default:
6871 llvm_unreachable("Unknown Objective-C object literal kind");
6872 }
6873
Jordan Roseea70bf72012-07-17 17:46:44 +00006874 if (LiteralKind == LK_String)
6875 S.Diag(Loc, diag::warn_objc_string_literal_comparison)
6876 << Literal->getSourceRange();
6877 else
6878 S.Diag(Loc, diag::warn_objc_literal_comparison)
6879 << LiteralKind << Literal->getSourceRange();
Jordan Rosed49a33e2012-06-08 21:14:25 +00006880
Jordan Rose7660f782012-07-17 17:46:40 +00006881 if (BinaryOperator::isEqualityOp(Opc) &&
6882 hasIsEqualMethod(S, LHS.get(), RHS.get())) {
6883 SourceLocation Start = LHS.get()->getLocStart();
6884 SourceLocation End = S.PP.getLocForEndOfToken(RHS.get()->getLocEnd());
6885 SourceRange OpRange(Loc, S.PP.getLocForEndOfToken(Loc));
Jordan Rosef9198032012-07-09 16:54:44 +00006886
Jordan Rose7660f782012-07-17 17:46:40 +00006887 S.Diag(Loc, diag::note_objc_literal_comparison_isequal)
6888 << FixItHint::CreateInsertion(Start, Opc == BO_EQ ? "[" : "![")
6889 << FixItHint::CreateReplacement(OpRange, "isEqual:")
6890 << FixItHint::CreateInsertion(End, "]");
Jordan Rosed49a33e2012-06-08 21:14:25 +00006891 }
Jordan Rosed49a33e2012-06-08 21:14:25 +00006892}
6893
Douglas Gregor5b07c7e2009-05-04 06:07:12 +00006894// C99 6.5.8, C++ [expr.rel]
Richard Trieub80728f2011-09-06 21:43:51 +00006895QualType Sema::CheckCompareOperands(ExprResult &LHS, ExprResult &RHS,
Richard Trieucfc491d2011-08-02 04:35:43 +00006896 SourceLocation Loc, unsigned OpaqueOpc,
Richard Trieuba63ce62011-09-09 01:45:06 +00006897 bool IsRelational) {
Richard Trieuf8916e12011-09-16 00:53:10 +00006898 checkArithmeticNull(*this, LHS, RHS, Loc, /*isCompare=*/true);
6899
John McCalle3027922010-08-25 11:45:40 +00006900 BinaryOperatorKind Opc = (BinaryOperatorKind) OpaqueOpc;
Douglas Gregor7a5bc762009-04-06 18:45:53 +00006901
Chris Lattner9a152e22009-12-05 05:40:13 +00006902 // Handle vector comparisons separately.
Richard Trieub80728f2011-09-06 21:43:51 +00006903 if (LHS.get()->getType()->isVectorType() ||
6904 RHS.get()->getType()->isVectorType())
Richard Trieuba63ce62011-09-09 01:45:06 +00006905 return CheckVectorCompareOperands(LHS, RHS, Loc, IsRelational);
Mike Stump4e1f26a2009-02-19 03:04:26 +00006906
Richard Trieub80728f2011-09-06 21:43:51 +00006907 QualType LHSType = LHS.get()->getType();
6908 QualType RHSType = RHS.get()->getType();
Benjamin Kramera66aaa92011-09-03 08:46:20 +00006909
Richard Trieub80728f2011-09-06 21:43:51 +00006910 Expr *LHSStripped = LHS.get()->IgnoreParenImpCasts();
6911 Expr *RHSStripped = RHS.get()->IgnoreParenImpCasts();
Chandler Carruth712563b2011-02-17 08:37:06 +00006912
Richard Trieub80728f2011-09-06 21:43:51 +00006913 checkEnumComparison(*this, Loc, LHS, RHS);
Chandler Carruth712563b2011-02-17 08:37:06 +00006914
Richard Trieub80728f2011-09-06 21:43:51 +00006915 if (!LHSType->hasFloatingRepresentation() &&
Richard Trieuba63ce62011-09-09 01:45:06 +00006916 !(LHSType->isBlockPointerType() && IsRelational) &&
Richard Trieub80728f2011-09-06 21:43:51 +00006917 !LHS.get()->getLocStart().isMacroID() &&
6918 !RHS.get()->getLocStart().isMacroID()) {
Chris Lattner222b8bd2009-03-08 19:39:53 +00006919 // For non-floating point types, check for self-comparisons of the form
6920 // x == x, x != x, x < x, etc. These always evaluate to a constant, and
6921 // often indicate logic errors in the program.
Chandler Carruth65a38182010-07-12 06:23:38 +00006922 //
6923 // NOTE: Don't warn about comparison expressions resulting from macro
6924 // expansion. Also don't warn about comparisons which are only self
6925 // comparisons within a template specialization. The warnings should catch
6926 // obvious cases in the definition of the template anyways. The idea is to
6927 // warn when the typed comparison operator will always evaluate to the same
6928 // result.
Chandler Carruth17773fc2010-07-10 12:30:03 +00006929 if (DeclRefExpr* DRL = dyn_cast<DeclRefExpr>(LHSStripped)) {
Douglas Gregorec170db2010-06-08 19:50:34 +00006930 if (DeclRefExpr* DRR = dyn_cast<DeclRefExpr>(RHSStripped)) {
Ted Kremenek853734e2010-09-16 00:03:01 +00006931 if (DRL->getDecl() == DRR->getDecl() &&
Chandler Carruth17773fc2010-07-10 12:30:03 +00006932 !IsWithinTemplateSpecialization(DRL->getDecl())) {
Ted Kremenek3427fac2011-02-23 01:52:04 +00006933 DiagRuntimeBehavior(Loc, 0, PDiag(diag::warn_comparison_always)
Douglas Gregorec170db2010-06-08 19:50:34 +00006934 << 0 // self-
John McCalle3027922010-08-25 11:45:40 +00006935 << (Opc == BO_EQ
6936 || Opc == BO_LE
6937 || Opc == BO_GE));
Richard Trieub80728f2011-09-06 21:43:51 +00006938 } else if (LHSType->isArrayType() && RHSType->isArrayType() &&
Douglas Gregorec170db2010-06-08 19:50:34 +00006939 !DRL->getDecl()->getType()->isReferenceType() &&
6940 !DRR->getDecl()->getType()->isReferenceType()) {
6941 // what is it always going to eval to?
6942 char always_evals_to;
6943 switch(Opc) {
John McCalle3027922010-08-25 11:45:40 +00006944 case BO_EQ: // e.g. array1 == array2
Douglas Gregorec170db2010-06-08 19:50:34 +00006945 always_evals_to = 0; // false
6946 break;
John McCalle3027922010-08-25 11:45:40 +00006947 case BO_NE: // e.g. array1 != array2
Douglas Gregorec170db2010-06-08 19:50:34 +00006948 always_evals_to = 1; // true
6949 break;
6950 default:
6951 // best we can say is 'a constant'
6952 always_evals_to = 2; // e.g. array1 <= array2
6953 break;
6954 }
Ted Kremenek3427fac2011-02-23 01:52:04 +00006955 DiagRuntimeBehavior(Loc, 0, PDiag(diag::warn_comparison_always)
Douglas Gregorec170db2010-06-08 19:50:34 +00006956 << 1 // array
6957 << always_evals_to);
6958 }
6959 }
Chandler Carruth17773fc2010-07-10 12:30:03 +00006960 }
Mike Stump11289f42009-09-09 15:08:12 +00006961
Chris Lattner222b8bd2009-03-08 19:39:53 +00006962 if (isa<CastExpr>(LHSStripped))
6963 LHSStripped = LHSStripped->IgnoreParenCasts();
6964 if (isa<CastExpr>(RHSStripped))
6965 RHSStripped = RHSStripped->IgnoreParenCasts();
Mike Stump11289f42009-09-09 15:08:12 +00006966
Chris Lattner222b8bd2009-03-08 19:39:53 +00006967 // Warn about comparisons against a string constant (unless the other
6968 // operand is null), the user probably wants strcmp.
Douglas Gregor7a5bc762009-04-06 18:45:53 +00006969 Expr *literalString = 0;
6970 Expr *literalStringStripped = 0;
Chris Lattner222b8bd2009-03-08 19:39:53 +00006971 if ((isa<StringLiteral>(LHSStripped) || isa<ObjCEncodeExpr>(LHSStripped)) &&
Kovarththanan Rajaratnamba2c6522010-03-13 10:17:05 +00006972 !RHSStripped->isNullPointerConstant(Context,
Douglas Gregor56751b52009-09-25 04:25:58 +00006973 Expr::NPC_ValueDependentIsNull)) {
Richard Trieub80728f2011-09-06 21:43:51 +00006974 literalString = LHS.get();
Douglas Gregor7a5bc762009-04-06 18:45:53 +00006975 literalStringStripped = LHSStripped;
Mike Stump12b8ce12009-08-04 21:02:39 +00006976 } else if ((isa<StringLiteral>(RHSStripped) ||
6977 isa<ObjCEncodeExpr>(RHSStripped)) &&
Kovarththanan Rajaratnamba2c6522010-03-13 10:17:05 +00006978 !LHSStripped->isNullPointerConstant(Context,
Douglas Gregor56751b52009-09-25 04:25:58 +00006979 Expr::NPC_ValueDependentIsNull)) {
Richard Trieub80728f2011-09-06 21:43:51 +00006980 literalString = RHS.get();
Douglas Gregor7a5bc762009-04-06 18:45:53 +00006981 literalStringStripped = RHSStripped;
6982 }
6983
6984 if (literalString) {
6985 std::string resultComparison;
6986 switch (Opc) {
John McCalle3027922010-08-25 11:45:40 +00006987 case BO_LT: resultComparison = ") < 0"; break;
6988 case BO_GT: resultComparison = ") > 0"; break;
6989 case BO_LE: resultComparison = ") <= 0"; break;
6990 case BO_GE: resultComparison = ") >= 0"; break;
6991 case BO_EQ: resultComparison = ") == 0"; break;
6992 case BO_NE: resultComparison = ") != 0"; break;
David Blaikie83d382b2011-09-23 05:06:16 +00006993 default: llvm_unreachable("Invalid comparison operator");
Douglas Gregor7a5bc762009-04-06 18:45:53 +00006994 }
Kovarththanan Rajaratnamba2c6522010-03-13 10:17:05 +00006995
Ted Kremenek3427fac2011-02-23 01:52:04 +00006996 DiagRuntimeBehavior(Loc, 0,
Douglas Gregor49862b82010-01-12 23:18:54 +00006997 PDiag(diag::warn_stringcompare)
6998 << isa<ObjCEncodeExpr>(literalStringStripped)
Ted Kremenek800b66b2010-04-09 20:26:53 +00006999 << literalString->getSourceRange());
Douglas Gregor7a5bc762009-04-06 18:45:53 +00007000 }
Ted Kremeneke451eae2007-10-29 16:58:49 +00007001 }
Mike Stump4e1f26a2009-02-19 03:04:26 +00007002
Douglas Gregorec170db2010-06-08 19:50:34 +00007003 // C99 6.5.8p3 / C99 6.5.9p4
Richard Trieub80728f2011-09-06 21:43:51 +00007004 if (LHS.get()->getType()->isArithmeticType() &&
7005 RHS.get()->getType()->isArithmeticType()) {
7006 UsualArithmeticConversions(LHS, RHS);
7007 if (LHS.isInvalid() || RHS.isInvalid())
John Wiegley01296292011-04-08 18:41:53 +00007008 return QualType();
7009 }
Douglas Gregorec170db2010-06-08 19:50:34 +00007010 else {
Richard Trieub80728f2011-09-06 21:43:51 +00007011 LHS = UsualUnaryConversions(LHS.take());
7012 if (LHS.isInvalid())
John Wiegley01296292011-04-08 18:41:53 +00007013 return QualType();
7014
Richard Trieub80728f2011-09-06 21:43:51 +00007015 RHS = UsualUnaryConversions(RHS.take());
7016 if (RHS.isInvalid())
John Wiegley01296292011-04-08 18:41:53 +00007017 return QualType();
Douglas Gregorec170db2010-06-08 19:50:34 +00007018 }
7019
Richard Trieub80728f2011-09-06 21:43:51 +00007020 LHSType = LHS.get()->getType();
7021 RHSType = RHS.get()->getType();
Douglas Gregorec170db2010-06-08 19:50:34 +00007022
Douglas Gregorca63811b2008-11-19 03:25:36 +00007023 // The result of comparisons is 'bool' in C++, 'int' in C.
Argyrios Kyrtzidis1bdd6882011-02-18 20:55:15 +00007024 QualType ResultTy = Context.getLogicalOperationType();
Douglas Gregorca63811b2008-11-19 03:25:36 +00007025
Richard Trieuba63ce62011-09-09 01:45:06 +00007026 if (IsRelational) {
Richard Trieub80728f2011-09-06 21:43:51 +00007027 if (LHSType->isRealType() && RHSType->isRealType())
Douglas Gregorca63811b2008-11-19 03:25:36 +00007028 return ResultTy;
Chris Lattnerb620c342007-08-26 01:18:55 +00007029 } else {
Ted Kremeneke2763b02007-10-29 17:13:39 +00007030 // Check for comparisons of floating point operands using != and ==.
Richard Trieub80728f2011-09-06 21:43:51 +00007031 if (LHSType->hasFloatingRepresentation())
7032 CheckFloatComparison(Loc, LHS.get(), RHS.get());
Mike Stump4e1f26a2009-02-19 03:04:26 +00007033
Richard Trieub80728f2011-09-06 21:43:51 +00007034 if (LHSType->isArithmeticType() && RHSType->isArithmeticType())
Douglas Gregorca63811b2008-11-19 03:25:36 +00007035 return ResultTy;
Chris Lattnerb620c342007-08-26 01:18:55 +00007036 }
Mike Stump4e1f26a2009-02-19 03:04:26 +00007037
Richard Trieub80728f2011-09-06 21:43:51 +00007038 bool LHSIsNull = LHS.get()->isNullPointerConstant(Context,
Douglas Gregor56751b52009-09-25 04:25:58 +00007039 Expr::NPC_ValueDependentIsNull);
Richard Trieub80728f2011-09-06 21:43:51 +00007040 bool RHSIsNull = RHS.get()->isNullPointerConstant(Context,
Douglas Gregor56751b52009-09-25 04:25:58 +00007041 Expr::NPC_ValueDependentIsNull);
Mike Stump4e1f26a2009-02-19 03:04:26 +00007042
Douglas Gregorf267edd2010-06-15 21:38:40 +00007043 // All of the following pointer-related warnings are GCC extensions, except
7044 // when handling null pointer constants.
Richard Trieub80728f2011-09-06 21:43:51 +00007045 if (LHSType->isPointerType() && RHSType->isPointerType()) { // C99 6.5.8p2
Chris Lattner3a0702e2008-04-03 05:07:25 +00007046 QualType LCanPointeeTy =
John McCall9320b872011-09-09 05:25:32 +00007047 LHSType->castAs<PointerType>()->getPointeeType().getCanonicalType();
Chris Lattner3a0702e2008-04-03 05:07:25 +00007048 QualType RCanPointeeTy =
John McCall9320b872011-09-09 05:25:32 +00007049 RHSType->castAs<PointerType>()->getPointeeType().getCanonicalType();
Mike Stump4e1f26a2009-02-19 03:04:26 +00007050
David Blaikiebbafb8a2012-03-11 07:00:24 +00007051 if (getLangOpts().CPlusPlus) {
Eli Friedman16c209612009-08-23 00:27:47 +00007052 if (LCanPointeeTy == RCanPointeeTy)
7053 return ResultTy;
Richard Trieuba63ce62011-09-09 01:45:06 +00007054 if (!IsRelational &&
Fariborz Jahanianffc420c2009-12-21 18:19:17 +00007055 (LCanPointeeTy->isVoidType() || RCanPointeeTy->isVoidType())) {
7056 // Valid unless comparison between non-null pointer and function pointer
7057 // This is a gcc extension compatibility comparison.
Douglas Gregorf267edd2010-06-15 21:38:40 +00007058 // In a SFINAE context, we treat this as a hard error to maintain
7059 // conformance with the C++ standard.
Fariborz Jahanianffc420c2009-12-21 18:19:17 +00007060 if ((LCanPointeeTy->isFunctionType() || RCanPointeeTy->isFunctionType())
7061 && !LHSIsNull && !RHSIsNull) {
Richard Trieudd82a5c2011-09-02 02:55:45 +00007062 diagnoseFunctionPointerToVoidComparison(
Richard Trieub80728f2011-09-06 21:43:51 +00007063 *this, Loc, LHS, RHS, /*isError*/ isSFINAEContext());
Douglas Gregorf267edd2010-06-15 21:38:40 +00007064
7065 if (isSFINAEContext())
7066 return QualType();
7067
Richard Trieub80728f2011-09-06 21:43:51 +00007068 RHS = ImpCastExprToType(RHS.take(), LHSType, CK_BitCast);
Fariborz Jahanianffc420c2009-12-21 18:19:17 +00007069 return ResultTy;
7070 }
7071 }
Anders Carlssona95069c2010-11-04 03:17:43 +00007072
Richard Trieub80728f2011-09-06 21:43:51 +00007073 if (convertPointersToCompositeType(*this, Loc, LHS, RHS))
Douglas Gregor5b07c7e2009-05-04 06:07:12 +00007074 return QualType();
Richard Trieudd82a5c2011-09-02 02:55:45 +00007075 else
7076 return ResultTy;
Douglas Gregor5b07c7e2009-05-04 06:07:12 +00007077 }
Eli Friedman16c209612009-08-23 00:27:47 +00007078 // C99 6.5.9p2 and C99 6.5.8p2
7079 if (Context.typesAreCompatible(LCanPointeeTy.getUnqualifiedType(),
7080 RCanPointeeTy.getUnqualifiedType())) {
7081 // Valid unless a relational comparison of function pointers
Richard Trieuba63ce62011-09-09 01:45:06 +00007082 if (IsRelational && LCanPointeeTy->isFunctionType()) {
Eli Friedman16c209612009-08-23 00:27:47 +00007083 Diag(Loc, diag::ext_typecheck_ordered_comparison_of_function_pointers)
Richard Trieub80728f2011-09-06 21:43:51 +00007084 << LHSType << RHSType << LHS.get()->getSourceRange()
7085 << RHS.get()->getSourceRange();
Eli Friedman16c209612009-08-23 00:27:47 +00007086 }
Richard Trieuba63ce62011-09-09 01:45:06 +00007087 } else if (!IsRelational &&
Eli Friedman16c209612009-08-23 00:27:47 +00007088 (LCanPointeeTy->isVoidType() || RCanPointeeTy->isVoidType())) {
7089 // Valid unless comparison between non-null pointer and function pointer
7090 if ((LCanPointeeTy->isFunctionType() || RCanPointeeTy->isFunctionType())
Richard Trieudd82a5c2011-09-02 02:55:45 +00007091 && !LHSIsNull && !RHSIsNull)
Richard Trieub80728f2011-09-06 21:43:51 +00007092 diagnoseFunctionPointerToVoidComparison(*this, Loc, LHS, RHS,
Richard Trieudd82a5c2011-09-02 02:55:45 +00007093 /*isError*/false);
Eli Friedman16c209612009-08-23 00:27:47 +00007094 } else {
7095 // Invalid
Richard Trieub80728f2011-09-06 21:43:51 +00007096 diagnoseDistinctPointerComparison(*this, Loc, LHS, RHS, /*isError*/false);
Steve Naroff75c17232007-06-13 21:41:08 +00007097 }
John McCall7684dde2011-03-11 04:25:25 +00007098 if (LCanPointeeTy != RCanPointeeTy) {
7099 if (LHSIsNull && !RHSIsNull)
Richard Trieub80728f2011-09-06 21:43:51 +00007100 LHS = ImpCastExprToType(LHS.take(), RHSType, CK_BitCast);
John McCall7684dde2011-03-11 04:25:25 +00007101 else
Richard Trieub80728f2011-09-06 21:43:51 +00007102 RHS = ImpCastExprToType(RHS.take(), LHSType, CK_BitCast);
John McCall7684dde2011-03-11 04:25:25 +00007103 }
Douglas Gregorca63811b2008-11-19 03:25:36 +00007104 return ResultTy;
Steve Naroffcdee44c2007-08-16 21:48:38 +00007105 }
Mike Stump11289f42009-09-09 15:08:12 +00007106
David Blaikiebbafb8a2012-03-11 07:00:24 +00007107 if (getLangOpts().CPlusPlus) {
Anders Carlssona95069c2010-11-04 03:17:43 +00007108 // Comparison of nullptr_t with itself.
Richard Trieub80728f2011-09-06 21:43:51 +00007109 if (LHSType->isNullPtrType() && RHSType->isNullPtrType())
Anders Carlssona95069c2010-11-04 03:17:43 +00007110 return ResultTy;
7111
Mike Stump11289f42009-09-09 15:08:12 +00007112 // Comparison of pointers with null pointer constants and equality
Douglas Gregorb00b10e2009-08-24 17:42:35 +00007113 // comparisons of member pointers to null pointer constants.
Mike Stump11289f42009-09-09 15:08:12 +00007114 if (RHSIsNull &&
Richard Trieub80728f2011-09-06 21:43:51 +00007115 ((LHSType->isAnyPointerType() || LHSType->isNullPtrType()) ||
Richard Trieuba63ce62011-09-09 01:45:06 +00007116 (!IsRelational &&
Richard Trieub80728f2011-09-06 21:43:51 +00007117 (LHSType->isMemberPointerType() || LHSType->isBlockPointerType())))) {
7118 RHS = ImpCastExprToType(RHS.take(), LHSType,
7119 LHSType->isMemberPointerType()
John McCalle3027922010-08-25 11:45:40 +00007120 ? CK_NullToMemberPointer
John McCalle84af4e2010-11-13 01:35:44 +00007121 : CK_NullToPointer);
Sebastian Redl576fd422009-05-10 18:38:11 +00007122 return ResultTy;
7123 }
Douglas Gregorb00b10e2009-08-24 17:42:35 +00007124 if (LHSIsNull &&
Richard Trieub80728f2011-09-06 21:43:51 +00007125 ((RHSType->isAnyPointerType() || RHSType->isNullPtrType()) ||
Richard Trieuba63ce62011-09-09 01:45:06 +00007126 (!IsRelational &&
Richard Trieub80728f2011-09-06 21:43:51 +00007127 (RHSType->isMemberPointerType() || RHSType->isBlockPointerType())))) {
7128 LHS = ImpCastExprToType(LHS.take(), RHSType,
7129 RHSType->isMemberPointerType()
John McCalle3027922010-08-25 11:45:40 +00007130 ? CK_NullToMemberPointer
John McCalle84af4e2010-11-13 01:35:44 +00007131 : CK_NullToPointer);
Sebastian Redl576fd422009-05-10 18:38:11 +00007132 return ResultTy;
7133 }
Douglas Gregorb00b10e2009-08-24 17:42:35 +00007134
7135 // Comparison of member pointers.
Richard Trieuba63ce62011-09-09 01:45:06 +00007136 if (!IsRelational &&
Richard Trieub80728f2011-09-06 21:43:51 +00007137 LHSType->isMemberPointerType() && RHSType->isMemberPointerType()) {
7138 if (convertPointersToCompositeType(*this, Loc, LHS, RHS))
Douglas Gregorb00b10e2009-08-24 17:42:35 +00007139 return QualType();
Richard Trieudd82a5c2011-09-02 02:55:45 +00007140 else
7141 return ResultTy;
Douglas Gregorb00b10e2009-08-24 17:42:35 +00007142 }
Douglas Gregor48e6bbf2011-03-01 17:16:20 +00007143
7144 // Handle scoped enumeration types specifically, since they don't promote
7145 // to integers.
Richard Trieub80728f2011-09-06 21:43:51 +00007146 if (LHS.get()->getType()->isEnumeralType() &&
7147 Context.hasSameUnqualifiedType(LHS.get()->getType(),
7148 RHS.get()->getType()))
Douglas Gregor48e6bbf2011-03-01 17:16:20 +00007149 return ResultTy;
Sebastian Redl576fd422009-05-10 18:38:11 +00007150 }
Mike Stump11289f42009-09-09 15:08:12 +00007151
Steve Naroff081c7422008-09-04 15:10:53 +00007152 // Handle block pointer types.
Richard Trieuba63ce62011-09-09 01:45:06 +00007153 if (!IsRelational && LHSType->isBlockPointerType() &&
Richard Trieub80728f2011-09-06 21:43:51 +00007154 RHSType->isBlockPointerType()) {
John McCall9320b872011-09-09 05:25:32 +00007155 QualType lpointee = LHSType->castAs<BlockPointerType>()->getPointeeType();
7156 QualType rpointee = RHSType->castAs<BlockPointerType>()->getPointeeType();
Mike Stump4e1f26a2009-02-19 03:04:26 +00007157
Steve Naroff081c7422008-09-04 15:10:53 +00007158 if (!LHSIsNull && !RHSIsNull &&
Eli Friedmana6638ca2009-06-08 05:08:54 +00007159 !Context.typesAreCompatible(lpointee, rpointee)) {
Chris Lattner377d1f82008-11-18 22:52:51 +00007160 Diag(Loc, diag::err_typecheck_comparison_of_distinct_blocks)
Richard Trieub80728f2011-09-06 21:43:51 +00007161 << LHSType << RHSType << LHS.get()->getSourceRange()
7162 << RHS.get()->getSourceRange();
Steve Naroff081c7422008-09-04 15:10:53 +00007163 }
Richard Trieub80728f2011-09-06 21:43:51 +00007164 RHS = ImpCastExprToType(RHS.take(), LHSType, CK_BitCast);
Douglas Gregorca63811b2008-11-19 03:25:36 +00007165 return ResultTy;
Steve Naroff081c7422008-09-04 15:10:53 +00007166 }
John Wiegley01296292011-04-08 18:41:53 +00007167
Steve Naroffe18f94c2008-09-28 01:11:11 +00007168 // Allow block pointers to be compared with null pointer constants.
Richard Trieuba63ce62011-09-09 01:45:06 +00007169 if (!IsRelational
Richard Trieub80728f2011-09-06 21:43:51 +00007170 && ((LHSType->isBlockPointerType() && RHSType->isPointerType())
7171 || (LHSType->isPointerType() && RHSType->isBlockPointerType()))) {
Steve Naroffe18f94c2008-09-28 01:11:11 +00007172 if (!LHSIsNull && !RHSIsNull) {
Richard Trieub80728f2011-09-06 21:43:51 +00007173 if (!((RHSType->isPointerType() && RHSType->castAs<PointerType>()
Mike Stump1b821b42009-05-07 03:14:14 +00007174 ->getPointeeType()->isVoidType())
Richard Trieub80728f2011-09-06 21:43:51 +00007175 || (LHSType->isPointerType() && LHSType->castAs<PointerType>()
Mike Stump1b821b42009-05-07 03:14:14 +00007176 ->getPointeeType()->isVoidType())))
7177 Diag(Loc, diag::err_typecheck_comparison_of_distinct_blocks)
Richard Trieub80728f2011-09-06 21:43:51 +00007178 << LHSType << RHSType << LHS.get()->getSourceRange()
7179 << RHS.get()->getSourceRange();
Steve Naroffe18f94c2008-09-28 01:11:11 +00007180 }
John McCall7684dde2011-03-11 04:25:25 +00007181 if (LHSIsNull && !RHSIsNull)
John McCall9320b872011-09-09 05:25:32 +00007182 LHS = ImpCastExprToType(LHS.take(), RHSType,
7183 RHSType->isPointerType() ? CK_BitCast
7184 : CK_AnyPointerToBlockPointerCast);
John McCall7684dde2011-03-11 04:25:25 +00007185 else
John McCall9320b872011-09-09 05:25:32 +00007186 RHS = ImpCastExprToType(RHS.take(), LHSType,
7187 LHSType->isPointerType() ? CK_BitCast
7188 : CK_AnyPointerToBlockPointerCast);
Douglas Gregorca63811b2008-11-19 03:25:36 +00007189 return ResultTy;
Steve Naroffe18f94c2008-09-28 01:11:11 +00007190 }
Steve Naroff081c7422008-09-04 15:10:53 +00007191
Richard Trieub80728f2011-09-06 21:43:51 +00007192 if (LHSType->isObjCObjectPointerType() ||
7193 RHSType->isObjCObjectPointerType()) {
7194 const PointerType *LPT = LHSType->getAs<PointerType>();
7195 const PointerType *RPT = RHSType->getAs<PointerType>();
John McCall7684dde2011-03-11 04:25:25 +00007196 if (LPT || RPT) {
7197 bool LPtrToVoid = LPT ? LPT->getPointeeType()->isVoidType() : false;
7198 bool RPtrToVoid = RPT ? RPT->getPointeeType()->isVoidType() : false;
Mike Stump4e1f26a2009-02-19 03:04:26 +00007199
Steve Naroff753567f2008-11-17 19:49:16 +00007200 if (!LPtrToVoid && !RPtrToVoid &&
Richard Trieub80728f2011-09-06 21:43:51 +00007201 !Context.typesAreCompatible(LHSType, RHSType)) {
7202 diagnoseDistinctPointerComparison(*this, Loc, LHS, RHS,
Richard Trieudd82a5c2011-09-02 02:55:45 +00007203 /*isError*/false);
Steve Naroff1d4a9a32008-10-27 10:33:19 +00007204 }
John McCall7684dde2011-03-11 04:25:25 +00007205 if (LHSIsNull && !RHSIsNull)
John McCall9320b872011-09-09 05:25:32 +00007206 LHS = ImpCastExprToType(LHS.take(), RHSType,
7207 RPT ? CK_BitCast :CK_CPointerToObjCPointerCast);
John McCall7684dde2011-03-11 04:25:25 +00007208 else
John McCall9320b872011-09-09 05:25:32 +00007209 RHS = ImpCastExprToType(RHS.take(), LHSType,
7210 LPT ? CK_BitCast :CK_CPointerToObjCPointerCast);
Douglas Gregorca63811b2008-11-19 03:25:36 +00007211 return ResultTy;
Steve Naroffea54d9e2008-10-20 18:19:10 +00007212 }
Richard Trieub80728f2011-09-06 21:43:51 +00007213 if (LHSType->isObjCObjectPointerType() &&
7214 RHSType->isObjCObjectPointerType()) {
7215 if (!Context.areComparableObjCPointerTypes(LHSType, RHSType))
7216 diagnoseDistinctPointerComparison(*this, Loc, LHS, RHS,
Richard Trieudd82a5c2011-09-02 02:55:45 +00007217 /*isError*/false);
Jordan Rosed49a33e2012-06-08 21:14:25 +00007218 if (isObjCObjectLiteral(LHS) || isObjCObjectLiteral(RHS))
Jordan Rose7660f782012-07-17 17:46:40 +00007219 diagnoseObjCLiteralComparison(*this, Loc, LHS, RHS, Opc);
Jordan Rosed49a33e2012-06-08 21:14:25 +00007220
John McCall7684dde2011-03-11 04:25:25 +00007221 if (LHSIsNull && !RHSIsNull)
Richard Trieub80728f2011-09-06 21:43:51 +00007222 LHS = ImpCastExprToType(LHS.take(), RHSType, CK_BitCast);
John McCall7684dde2011-03-11 04:25:25 +00007223 else
Richard Trieub80728f2011-09-06 21:43:51 +00007224 RHS = ImpCastExprToType(RHS.take(), LHSType, CK_BitCast);
Douglas Gregorca63811b2008-11-19 03:25:36 +00007225 return ResultTy;
Steve Naroffb788d9b2008-06-03 14:04:54 +00007226 }
Fariborz Jahanian134cbef2007-12-20 01:06:58 +00007227 }
Richard Trieub80728f2011-09-06 21:43:51 +00007228 if ((LHSType->isAnyPointerType() && RHSType->isIntegerType()) ||
7229 (LHSType->isIntegerType() && RHSType->isAnyPointerType())) {
Chris Lattnerd99bd522009-08-23 00:03:44 +00007230 unsigned DiagID = 0;
Douglas Gregorf267edd2010-06-15 21:38:40 +00007231 bool isError = false;
Douglas Gregor0064c592012-09-14 04:35:37 +00007232 if (LangOpts.DebuggerSupport) {
7233 // Under a debugger, allow the comparison of pointers to integers,
7234 // since users tend to want to compare addresses.
7235 } else if ((LHSIsNull && LHSType->isIntegerType()) ||
Richard Trieub80728f2011-09-06 21:43:51 +00007236 (RHSIsNull && RHSType->isIntegerType())) {
David Blaikiebbafb8a2012-03-11 07:00:24 +00007237 if (IsRelational && !getLangOpts().CPlusPlus)
Chris Lattnerd99bd522009-08-23 00:03:44 +00007238 DiagID = diag::ext_typecheck_ordered_comparison_of_pointer_and_zero;
David Blaikiebbafb8a2012-03-11 07:00:24 +00007239 } else if (IsRelational && !getLangOpts().CPlusPlus)
Chris Lattnerd99bd522009-08-23 00:03:44 +00007240 DiagID = diag::ext_typecheck_ordered_comparison_of_pointer_integer;
David Blaikiebbafb8a2012-03-11 07:00:24 +00007241 else if (getLangOpts().CPlusPlus) {
Douglas Gregorf267edd2010-06-15 21:38:40 +00007242 DiagID = diag::err_typecheck_comparison_of_pointer_integer;
7243 isError = true;
7244 } else
Chris Lattnerd99bd522009-08-23 00:03:44 +00007245 DiagID = diag::ext_typecheck_comparison_of_pointer_integer;
Mike Stump11289f42009-09-09 15:08:12 +00007246
Chris Lattnerd99bd522009-08-23 00:03:44 +00007247 if (DiagID) {
Chris Lattnerf8344db2009-08-22 18:58:31 +00007248 Diag(Loc, DiagID)
Richard Trieub80728f2011-09-06 21:43:51 +00007249 << LHSType << RHSType << LHS.get()->getSourceRange()
7250 << RHS.get()->getSourceRange();
Douglas Gregorf267edd2010-06-15 21:38:40 +00007251 if (isError)
7252 return QualType();
Chris Lattnerf8344db2009-08-22 18:58:31 +00007253 }
Douglas Gregorf267edd2010-06-15 21:38:40 +00007254
Richard Trieub80728f2011-09-06 21:43:51 +00007255 if (LHSType->isIntegerType())
7256 LHS = ImpCastExprToType(LHS.take(), RHSType,
John McCalle84af4e2010-11-13 01:35:44 +00007257 LHSIsNull ? CK_NullToPointer : CK_IntegralToPointer);
Chris Lattnerd99bd522009-08-23 00:03:44 +00007258 else
Richard Trieub80728f2011-09-06 21:43:51 +00007259 RHS = ImpCastExprToType(RHS.take(), LHSType,
John McCalle84af4e2010-11-13 01:35:44 +00007260 RHSIsNull ? CK_NullToPointer : CK_IntegralToPointer);
Douglas Gregorca63811b2008-11-19 03:25:36 +00007261 return ResultTy;
Steve Naroff043d45d2007-05-15 02:32:35 +00007262 }
Douglas Gregorf267edd2010-06-15 21:38:40 +00007263
Steve Naroff4b191572008-09-04 16:56:14 +00007264 // Handle block pointers.
Richard Trieuba63ce62011-09-09 01:45:06 +00007265 if (!IsRelational && RHSIsNull
Richard Trieub80728f2011-09-06 21:43:51 +00007266 && LHSType->isBlockPointerType() && RHSType->isIntegerType()) {
7267 RHS = ImpCastExprToType(RHS.take(), LHSType, CK_NullToPointer);
Douglas Gregorca63811b2008-11-19 03:25:36 +00007268 return ResultTy;
Steve Naroff4b191572008-09-04 16:56:14 +00007269 }
Richard Trieuba63ce62011-09-09 01:45:06 +00007270 if (!IsRelational && LHSIsNull
Richard Trieub80728f2011-09-06 21:43:51 +00007271 && LHSType->isIntegerType() && RHSType->isBlockPointerType()) {
7272 LHS = ImpCastExprToType(LHS.take(), RHSType, CK_NullToPointer);
Douglas Gregorca63811b2008-11-19 03:25:36 +00007273 return ResultTy;
Steve Naroff4b191572008-09-04 16:56:14 +00007274 }
Douglas Gregor48e6bbf2011-03-01 17:16:20 +00007275
Richard Trieub80728f2011-09-06 21:43:51 +00007276 return InvalidOperands(Loc, LHS, RHS);
Steve Naroff26c8ea52007-03-21 21:08:52 +00007277}
7278
Tanya Lattner20248222012-01-16 21:02:28 +00007279
7280// Return a signed type that is of identical size and number of elements.
7281// For floating point vectors, return an integer type of identical size
7282// and number of elements.
7283QualType Sema::GetSignedVectorType(QualType V) {
7284 const VectorType *VTy = V->getAs<VectorType>();
7285 unsigned TypeSize = Context.getTypeSize(VTy->getElementType());
7286 if (TypeSize == Context.getTypeSize(Context.CharTy))
7287 return Context.getExtVectorType(Context.CharTy, VTy->getNumElements());
7288 else if (TypeSize == Context.getTypeSize(Context.ShortTy))
7289 return Context.getExtVectorType(Context.ShortTy, VTy->getNumElements());
7290 else if (TypeSize == Context.getTypeSize(Context.IntTy))
7291 return Context.getExtVectorType(Context.IntTy, VTy->getNumElements());
7292 else if (TypeSize == Context.getTypeSize(Context.LongTy))
7293 return Context.getExtVectorType(Context.LongTy, VTy->getNumElements());
7294 assert(TypeSize == Context.getTypeSize(Context.LongLongTy) &&
7295 "Unhandled vector element size in vector compare");
7296 return Context.getExtVectorType(Context.LongLongTy, VTy->getNumElements());
7297}
7298
Nate Begeman191a6b12008-07-14 18:02:46 +00007299/// CheckVectorCompareOperands - vector comparisons are a clang extension that
Mike Stump4e1f26a2009-02-19 03:04:26 +00007300/// operates on extended vector types. Instead of producing an IntTy result,
Nate Begeman191a6b12008-07-14 18:02:46 +00007301/// like a scalar comparison, a vector comparison produces a vector of integer
7302/// types.
Richard Trieubcce2f72011-09-07 01:19:57 +00007303QualType Sema::CheckVectorCompareOperands(ExprResult &LHS, ExprResult &RHS,
Chris Lattner326f7572008-11-18 01:30:42 +00007304 SourceLocation Loc,
Richard Trieuba63ce62011-09-09 01:45:06 +00007305 bool IsRelational) {
Nate Begeman191a6b12008-07-14 18:02:46 +00007306 // Check to make sure we're operating on vectors of the same type and width,
7307 // Allowing one side to be a scalar of element type.
Richard Trieubcce2f72011-09-07 01:19:57 +00007308 QualType vType = CheckVectorOperands(LHS, RHS, Loc, /*isCompAssign*/false);
Nate Begeman191a6b12008-07-14 18:02:46 +00007309 if (vType.isNull())
7310 return vType;
Mike Stump4e1f26a2009-02-19 03:04:26 +00007311
Richard Trieubcce2f72011-09-07 01:19:57 +00007312 QualType LHSType = LHS.get()->getType();
Mike Stump4e1f26a2009-02-19 03:04:26 +00007313
Anton Yartsev530deb92011-03-27 15:36:07 +00007314 // If AltiVec, the comparison results in a numeric type, i.e.
7315 // bool for C++, int for C
Anton Yartsev93900c72011-03-28 21:00:05 +00007316 if (vType->getAs<VectorType>()->getVectorKind() == VectorType::AltiVecVector)
Anton Yartsev530deb92011-03-27 15:36:07 +00007317 return Context.getLogicalOperationType();
7318
Nate Begeman191a6b12008-07-14 18:02:46 +00007319 // For non-floating point types, check for self-comparisons of the form
7320 // x == x, x != x, x < x, etc. These always evaluate to a constant, and
7321 // often indicate logic errors in the program.
Richard Trieubcce2f72011-09-07 01:19:57 +00007322 if (!LHSType->hasFloatingRepresentation()) {
Richard Smith508ebf32011-10-28 03:31:48 +00007323 if (DeclRefExpr* DRL
7324 = dyn_cast<DeclRefExpr>(LHS.get()->IgnoreParenImpCasts()))
7325 if (DeclRefExpr* DRR
7326 = dyn_cast<DeclRefExpr>(RHS.get()->IgnoreParenImpCasts()))
Nate Begeman191a6b12008-07-14 18:02:46 +00007327 if (DRL->getDecl() == DRR->getDecl())
Ted Kremenek3427fac2011-02-23 01:52:04 +00007328 DiagRuntimeBehavior(Loc, 0,
Douglas Gregorec170db2010-06-08 19:50:34 +00007329 PDiag(diag::warn_comparison_always)
7330 << 0 // self-
7331 << 2 // "a constant"
7332 );
Nate Begeman191a6b12008-07-14 18:02:46 +00007333 }
Mike Stump4e1f26a2009-02-19 03:04:26 +00007334
Nate Begeman191a6b12008-07-14 18:02:46 +00007335 // Check for comparisons of floating point operands using != and ==.
Richard Trieuba63ce62011-09-09 01:45:06 +00007336 if (!IsRelational && LHSType->hasFloatingRepresentation()) {
David Blaikieca043222012-01-16 05:16:03 +00007337 assert (RHS.get()->getType()->hasFloatingRepresentation());
Richard Trieubcce2f72011-09-07 01:19:57 +00007338 CheckFloatComparison(Loc, LHS.get(), RHS.get());
Nate Begeman191a6b12008-07-14 18:02:46 +00007339 }
Tanya Lattner20248222012-01-16 21:02:28 +00007340
7341 // Return a signed type for the vector.
7342 return GetSignedVectorType(LHSType);
7343}
Mike Stump4e1f26a2009-02-19 03:04:26 +00007344
Tanya Lattner3dd33b22012-01-19 01:16:16 +00007345QualType Sema::CheckVectorLogicalOperands(ExprResult &LHS, ExprResult &RHS,
7346 SourceLocation Loc) {
Tanya Lattner20248222012-01-16 21:02:28 +00007347 // Ensure that either both operands are of the same vector type, or
7348 // one operand is of a vector type and the other is of its element type.
7349 QualType vType = CheckVectorOperands(LHS, RHS, Loc, false);
7350 if (vType.isNull() || vType->isFloatingType())
7351 return InvalidOperands(Loc, LHS, RHS);
7352
7353 return GetSignedVectorType(LHS.get()->getType());
Nate Begeman191a6b12008-07-14 18:02:46 +00007354}
7355
Steve Naroff218bc2b2007-05-04 21:54:46 +00007356inline QualType Sema::CheckBitwiseOperands(
Richard Trieuba63ce62011-09-09 01:45:06 +00007357 ExprResult &LHS, ExprResult &RHS, SourceLocation Loc, bool IsCompAssign) {
Richard Trieuf8916e12011-09-16 00:53:10 +00007358 checkArithmeticNull(*this, LHS, RHS, Loc, /*isCompare=*/false);
7359
Richard Trieubcce2f72011-09-07 01:19:57 +00007360 if (LHS.get()->getType()->isVectorType() ||
7361 RHS.get()->getType()->isVectorType()) {
7362 if (LHS.get()->getType()->hasIntegerRepresentation() &&
7363 RHS.get()->getType()->hasIntegerRepresentation())
Richard Trieuba63ce62011-09-09 01:45:06 +00007364 return CheckVectorOperands(LHS, RHS, Loc, IsCompAssign);
Douglas Gregor5cc2c8b2010-07-23 15:58:24 +00007365
Richard Trieubcce2f72011-09-07 01:19:57 +00007366 return InvalidOperands(Loc, LHS, RHS);
Douglas Gregor5cc2c8b2010-07-23 15:58:24 +00007367 }
Steve Naroffb8ea4fb2007-07-13 23:32:42 +00007368
Richard Trieubcce2f72011-09-07 01:19:57 +00007369 ExprResult LHSResult = Owned(LHS), RHSResult = Owned(RHS);
7370 QualType compType = UsualArithmeticConversions(LHSResult, RHSResult,
Richard Trieuba63ce62011-09-09 01:45:06 +00007371 IsCompAssign);
Richard Trieubcce2f72011-09-07 01:19:57 +00007372 if (LHSResult.isInvalid() || RHSResult.isInvalid())
John Wiegley01296292011-04-08 18:41:53 +00007373 return QualType();
Richard Trieubcce2f72011-09-07 01:19:57 +00007374 LHS = LHSResult.take();
7375 RHS = RHSResult.take();
Mike Stump4e1f26a2009-02-19 03:04:26 +00007376
Eli Friedman93ee5ca2012-06-16 02:19:17 +00007377 if (!compType.isNull() && compType->isIntegralOrUnscopedEnumerationType())
Steve Naroffbe4c4d12007-08-24 19:07:16 +00007378 return compType;
Richard Trieubcce2f72011-09-07 01:19:57 +00007379 return InvalidOperands(Loc, LHS, RHS);
Steve Naroff26c8ea52007-03-21 21:08:52 +00007380}
7381
Steve Naroff218bc2b2007-05-04 21:54:46 +00007382inline QualType Sema::CheckLogicalOperands( // C99 6.5.[13,14]
Richard Trieubcce2f72011-09-07 01:19:57 +00007383 ExprResult &LHS, ExprResult &RHS, SourceLocation Loc, unsigned Opc) {
Chris Lattner8406c512010-07-13 19:41:32 +00007384
Tanya Lattner20248222012-01-16 21:02:28 +00007385 // Check vector operands differently.
7386 if (LHS.get()->getType()->isVectorType() || RHS.get()->getType()->isVectorType())
7387 return CheckVectorLogicalOperands(LHS, RHS, Loc);
7388
Chris Lattner8406c512010-07-13 19:41:32 +00007389 // Diagnose cases where the user write a logical and/or but probably meant a
7390 // bitwise one. We do this when the LHS is a non-bool integer and the RHS
7391 // is a constant.
Richard Trieubcce2f72011-09-07 01:19:57 +00007392 if (LHS.get()->getType()->isIntegerType() &&
7393 !LHS.get()->getType()->isBooleanType() &&
7394 RHS.get()->getType()->isIntegerType() && !RHS.get()->isValueDependent() &&
Richard Trieucfe39262011-07-15 00:00:51 +00007395 // Don't warn in macros or template instantiations.
7396 !Loc.isMacroID() && ActiveTemplateInstantiations.empty()) {
Chris Lattner938533d2010-07-24 01:10:11 +00007397 // If the RHS can be constant folded, and if it constant folds to something
7398 // that isn't 0 or 1 (which indicate a potential logical operation that
7399 // happened to fold to true/false) then warn.
Chandler Carruthe54ff6c2011-05-31 05:41:42 +00007400 // Parens on the RHS are ignored.
Richard Smith00ab3ae2011-10-16 23:01:09 +00007401 llvm::APSInt Result;
7402 if (RHS.get()->EvaluateAsInt(Result, Context))
David Blaikiebbafb8a2012-03-11 07:00:24 +00007403 if ((getLangOpts().Bool && !RHS.get()->getType()->isBooleanType()) ||
Richard Smith00ab3ae2011-10-16 23:01:09 +00007404 (Result != 0 && Result != 1)) {
Chandler Carruthe54ff6c2011-05-31 05:41:42 +00007405 Diag(Loc, diag::warn_logical_instead_of_bitwise)
Richard Trieubcce2f72011-09-07 01:19:57 +00007406 << RHS.get()->getSourceRange()
Matt Beaumont-Gay0a0ba9d2011-08-15 17:50:06 +00007407 << (Opc == BO_LAnd ? "&&" : "||");
7408 // Suggest replacing the logical operator with the bitwise version
7409 Diag(Loc, diag::note_logical_instead_of_bitwise_change_operator)
7410 << (Opc == BO_LAnd ? "&" : "|")
7411 << FixItHint::CreateReplacement(SourceRange(
7412 Loc, Lexer::getLocForEndOfToken(Loc, 0, getSourceManager(),
David Blaikiebbafb8a2012-03-11 07:00:24 +00007413 getLangOpts())),
Matt Beaumont-Gay0a0ba9d2011-08-15 17:50:06 +00007414 Opc == BO_LAnd ? "&" : "|");
7415 if (Opc == BO_LAnd)
7416 // Suggest replacing "Foo() && kNonZero" with "Foo()"
7417 Diag(Loc, diag::note_logical_instead_of_bitwise_remove_constant)
7418 << FixItHint::CreateRemoval(
7419 SourceRange(
Richard Trieubcce2f72011-09-07 01:19:57 +00007420 Lexer::getLocForEndOfToken(LHS.get()->getLocEnd(),
Matt Beaumont-Gay0a0ba9d2011-08-15 17:50:06 +00007421 0, getSourceManager(),
David Blaikiebbafb8a2012-03-11 07:00:24 +00007422 getLangOpts()),
Richard Trieubcce2f72011-09-07 01:19:57 +00007423 RHS.get()->getLocEnd()));
Matt Beaumont-Gay0a0ba9d2011-08-15 17:50:06 +00007424 }
Chris Lattner938533d2010-07-24 01:10:11 +00007425 }
Chris Lattner8406c512010-07-13 19:41:32 +00007426
David Blaikiebbafb8a2012-03-11 07:00:24 +00007427 if (!Context.getLangOpts().CPlusPlus) {
Richard Trieubcce2f72011-09-07 01:19:57 +00007428 LHS = UsualUnaryConversions(LHS.take());
7429 if (LHS.isInvalid())
John Wiegley01296292011-04-08 18:41:53 +00007430 return QualType();
Mike Stump4e1f26a2009-02-19 03:04:26 +00007431
Richard Trieubcce2f72011-09-07 01:19:57 +00007432 RHS = UsualUnaryConversions(RHS.take());
7433 if (RHS.isInvalid())
John Wiegley01296292011-04-08 18:41:53 +00007434 return QualType();
7435
Richard Trieubcce2f72011-09-07 01:19:57 +00007436 if (!LHS.get()->getType()->isScalarType() ||
7437 !RHS.get()->getType()->isScalarType())
7438 return InvalidOperands(Loc, LHS, RHS);
Kovarththanan Rajaratnamba2c6522010-03-13 10:17:05 +00007439
Anders Carlsson2e7bc112009-11-23 21:47:44 +00007440 return Context.IntTy;
Anders Carlsson35a99d92009-10-16 01:44:21 +00007441 }
Kovarththanan Rajaratnamba2c6522010-03-13 10:17:05 +00007442
John McCall4a2429a2010-06-04 00:29:51 +00007443 // The following is safe because we only use this method for
7444 // non-overloadable operands.
7445
Anders Carlsson2e7bc112009-11-23 21:47:44 +00007446 // C++ [expr.log.and]p1
7447 // C++ [expr.log.or]p1
John McCall4a2429a2010-06-04 00:29:51 +00007448 // The operands are both contextually converted to type bool.
Richard Trieubcce2f72011-09-07 01:19:57 +00007449 ExprResult LHSRes = PerformContextuallyConvertToBool(LHS.get());
7450 if (LHSRes.isInvalid())
7451 return InvalidOperands(Loc, LHS, RHS);
Benjamin Kramer62b95d82012-08-23 21:35:17 +00007452 LHS = LHSRes;
John Wiegley01296292011-04-08 18:41:53 +00007453
Richard Trieubcce2f72011-09-07 01:19:57 +00007454 ExprResult RHSRes = PerformContextuallyConvertToBool(RHS.get());
7455 if (RHSRes.isInvalid())
7456 return InvalidOperands(Loc, LHS, RHS);
Benjamin Kramer62b95d82012-08-23 21:35:17 +00007457 RHS = RHSRes;
Kovarththanan Rajaratnamba2c6522010-03-13 10:17:05 +00007458
Anders Carlsson2e7bc112009-11-23 21:47:44 +00007459 // C++ [expr.log.and]p2
7460 // C++ [expr.log.or]p2
7461 // The result is a bool.
7462 return Context.BoolTy;
Steve Naroffae4143e2007-04-26 20:39:23 +00007463}
7464
Fariborz Jahanian8e1555c2009-01-12 19:55:42 +00007465/// IsReadonlyProperty - Verify that otherwise a valid l-value expression
7466/// is a read-only property; return true if so. A readonly property expression
7467/// depends on various declarations and thus must be treated specially.
7468///
Mike Stump11289f42009-09-09 15:08:12 +00007469static bool IsReadonlyProperty(Expr *E, Sema &S) {
John McCall526ab472011-10-25 17:37:35 +00007470 const ObjCPropertyRefExpr *PropExpr = dyn_cast<ObjCPropertyRefExpr>(E);
7471 if (!PropExpr) return false;
7472 if (PropExpr->isImplicitProperty()) return false;
John McCallb7bd14f2010-12-02 01:19:52 +00007473
John McCall526ab472011-10-25 17:37:35 +00007474 ObjCPropertyDecl *PDecl = PropExpr->getExplicitProperty();
7475 QualType BaseType = PropExpr->isSuperReceiver() ?
John McCallb7bd14f2010-12-02 01:19:52 +00007476 PropExpr->getSuperReceiverType() :
Fariborz Jahanian681c0752010-10-14 16:04:05 +00007477 PropExpr->getBase()->getType();
7478
John McCall526ab472011-10-25 17:37:35 +00007479 if (const ObjCObjectPointerType *OPT =
7480 BaseType->getAsObjCInterfacePointerType())
7481 if (ObjCInterfaceDecl *IFace = OPT->getInterfaceDecl())
7482 if (S.isPropertyReadonly(PDecl, IFace))
7483 return true;
Fariborz Jahanian8e1555c2009-01-12 19:55:42 +00007484 return false;
7485}
7486
Fariborz Jahanian071caef2011-03-26 19:48:30 +00007487static bool IsReadonlyMessage(Expr *E, Sema &S) {
John McCall526ab472011-10-25 17:37:35 +00007488 const MemberExpr *ME = dyn_cast<MemberExpr>(E);
7489 if (!ME) return false;
7490 if (!isa<FieldDecl>(ME->getMemberDecl())) return false;
7491 ObjCMessageExpr *Base =
7492 dyn_cast<ObjCMessageExpr>(ME->getBase()->IgnoreParenImpCasts());
7493 if (!Base) return false;
7494 return Base->getMethodDecl() != 0;
Fariborz Jahanian071caef2011-03-26 19:48:30 +00007495}
7496
John McCall5fa2ef42012-03-13 00:37:01 +00007497/// Is the given expression (which must be 'const') a reference to a
7498/// variable which was originally non-const, but which has become
7499/// 'const' due to being captured within a block?
7500enum NonConstCaptureKind { NCCK_None, NCCK_Block, NCCK_Lambda };
7501static NonConstCaptureKind isReferenceToNonConstCapture(Sema &S, Expr *E) {
7502 assert(E->isLValue() && E->getType().isConstQualified());
7503 E = E->IgnoreParens();
7504
7505 // Must be a reference to a declaration from an enclosing scope.
7506 DeclRefExpr *DRE = dyn_cast<DeclRefExpr>(E);
7507 if (!DRE) return NCCK_None;
7508 if (!DRE->refersToEnclosingLocal()) return NCCK_None;
7509
7510 // The declaration must be a variable which is not declared 'const'.
7511 VarDecl *var = dyn_cast<VarDecl>(DRE->getDecl());
7512 if (!var) return NCCK_None;
7513 if (var->getType().isConstQualified()) return NCCK_None;
7514 assert(var->hasLocalStorage() && "capture added 'const' to non-local?");
7515
7516 // Decide whether the first capture was for a block or a lambda.
7517 DeclContext *DC = S.CurContext;
7518 while (DC->getParent() != var->getDeclContext())
7519 DC = DC->getParent();
7520 return (isa<BlockDecl>(DC) ? NCCK_Block : NCCK_Lambda);
7521}
7522
Chris Lattner30bd3272008-11-18 01:22:49 +00007523/// CheckForModifiableLvalue - Verify that E is a modifiable lvalue. If not,
7524/// emit an error and return true. If so, return false.
7525static bool CheckForModifiableLvalue(Expr *E, SourceLocation Loc, Sema &S) {
Fariborz Jahanianca5c5972012-04-10 17:30:10 +00007526 assert(!E->hasPlaceholderType(BuiltinType::PseudoObject));
Daniel Dunbarc2223ab2009-04-15 00:08:05 +00007527 SourceLocation OrigLoc = Loc;
Mike Stump11289f42009-09-09 15:08:12 +00007528 Expr::isModifiableLvalueResult IsLV = E->isModifiableLvalue(S.Context,
Daniel Dunbarc2223ab2009-04-15 00:08:05 +00007529 &Loc);
Fariborz Jahanian8e1555c2009-01-12 19:55:42 +00007530 if (IsLV == Expr::MLV_Valid && IsReadonlyProperty(E, S))
7531 IsLV = Expr::MLV_ReadonlyProperty;
Fariborz Jahanian071caef2011-03-26 19:48:30 +00007532 else if (IsLV == Expr::MLV_ClassTemporary && IsReadonlyMessage(E, S))
7533 IsLV = Expr::MLV_InvalidMessageExpression;
Chris Lattner30bd3272008-11-18 01:22:49 +00007534 if (IsLV == Expr::MLV_Valid)
7535 return false;
Mike Stump4e1f26a2009-02-19 03:04:26 +00007536
Chris Lattner30bd3272008-11-18 01:22:49 +00007537 unsigned Diag = 0;
7538 bool NeedType = false;
7539 switch (IsLV) { // C99 6.5.16p2
John McCall31168b02011-06-15 23:02:42 +00007540 case Expr::MLV_ConstQualified:
7541 Diag = diag::err_typecheck_assign_const;
7542
John McCall5fa2ef42012-03-13 00:37:01 +00007543 // Use a specialized diagnostic when we're assigning to an object
7544 // from an enclosing function or block.
7545 if (NonConstCaptureKind NCCK = isReferenceToNonConstCapture(S, E)) {
7546 if (NCCK == NCCK_Block)
7547 Diag = diag::err_block_decl_ref_not_modifiable_lvalue;
7548 else
7549 Diag = diag::err_lambda_decl_ref_not_modifiable_lvalue;
7550 break;
7551 }
7552
John McCalld4631322011-06-17 06:42:21 +00007553 // In ARC, use some specialized diagnostics for occasions where we
7554 // infer 'const'. These are always pseudo-strong variables.
David Blaikiebbafb8a2012-03-11 07:00:24 +00007555 if (S.getLangOpts().ObjCAutoRefCount) {
John McCall31168b02011-06-15 23:02:42 +00007556 DeclRefExpr *declRef = dyn_cast<DeclRefExpr>(E->IgnoreParenCasts());
7557 if (declRef && isa<VarDecl>(declRef->getDecl())) {
7558 VarDecl *var = cast<VarDecl>(declRef->getDecl());
7559
John McCalld4631322011-06-17 06:42:21 +00007560 // Use the normal diagnostic if it's pseudo-__strong but the
7561 // user actually wrote 'const'.
7562 if (var->isARCPseudoStrong() &&
7563 (!var->getTypeSourceInfo() ||
7564 !var->getTypeSourceInfo()->getType().isConstQualified())) {
7565 // There are two pseudo-strong cases:
7566 // - self
John McCall31168b02011-06-15 23:02:42 +00007567 ObjCMethodDecl *method = S.getCurMethodDecl();
7568 if (method && var == method->getSelfDecl())
Ted Kremenek1fcdaa92011-11-14 21:59:25 +00007569 Diag = method->isClassMethod()
7570 ? diag::err_typecheck_arc_assign_self_class_method
7571 : diag::err_typecheck_arc_assign_self;
John McCalld4631322011-06-17 06:42:21 +00007572
7573 // - fast enumeration variables
7574 else
John McCall31168b02011-06-15 23:02:42 +00007575 Diag = diag::err_typecheck_arr_assign_enumeration;
John McCalld4631322011-06-17 06:42:21 +00007576
John McCall31168b02011-06-15 23:02:42 +00007577 SourceRange Assign;
7578 if (Loc != OrigLoc)
7579 Assign = SourceRange(OrigLoc, OrigLoc);
7580 S.Diag(Loc, Diag) << E->getSourceRange() << Assign;
7581 // We need to preserve the AST regardless, so migration tool
7582 // can do its job.
7583 return false;
7584 }
7585 }
7586 }
7587
7588 break;
Mike Stump4e1f26a2009-02-19 03:04:26 +00007589 case Expr::MLV_ArrayType:
Richard Smitheb3cad52012-06-04 22:27:30 +00007590 case Expr::MLV_ArrayTemporary:
Chris Lattner30bd3272008-11-18 01:22:49 +00007591 Diag = diag::err_typecheck_array_not_modifiable_lvalue;
7592 NeedType = true;
7593 break;
Mike Stump4e1f26a2009-02-19 03:04:26 +00007594 case Expr::MLV_NotObjectType:
Chris Lattner30bd3272008-11-18 01:22:49 +00007595 Diag = diag::err_typecheck_non_object_not_modifiable_lvalue;
7596 NeedType = true;
7597 break;
Chris Lattner9b3bbe92008-11-17 19:51:54 +00007598 case Expr::MLV_LValueCast:
Chris Lattner30bd3272008-11-18 01:22:49 +00007599 Diag = diag::err_typecheck_lvalue_casts_not_supported;
7600 break;
Douglas Gregorb154fdc2010-02-16 21:39:57 +00007601 case Expr::MLV_Valid:
7602 llvm_unreachable("did not take early return for MLV_Valid");
Chris Lattner9bad62c2008-01-04 18:04:52 +00007603 case Expr::MLV_InvalidExpression:
Douglas Gregorb154fdc2010-02-16 21:39:57 +00007604 case Expr::MLV_MemberFunction:
7605 case Expr::MLV_ClassTemporary:
Chris Lattner30bd3272008-11-18 01:22:49 +00007606 Diag = diag::err_typecheck_expression_not_modifiable_lvalue;
7607 break;
Chris Lattner9bad62c2008-01-04 18:04:52 +00007608 case Expr::MLV_IncompleteType:
7609 case Expr::MLV_IncompleteVoidType:
Douglas Gregored0cfbd2009-03-09 16:13:40 +00007610 return S.RequireCompleteType(Loc, E->getType(),
Douglas Gregor7bfb2d02012-05-04 16:32:21 +00007611 diag::err_typecheck_incomplete_type_not_modifiable_lvalue, E);
Chris Lattner9bad62c2008-01-04 18:04:52 +00007612 case Expr::MLV_DuplicateVectorComponents:
Chris Lattner30bd3272008-11-18 01:22:49 +00007613 Diag = diag::err_typecheck_duplicate_vector_components_not_mlvalue;
7614 break;
Fariborz Jahanian8a1810f2008-11-22 18:39:36 +00007615 case Expr::MLV_ReadonlyProperty:
Fariborz Jahanian5118c412008-11-22 20:25:50 +00007616 case Expr::MLV_NoSetterProperty:
John McCall526ab472011-10-25 17:37:35 +00007617 llvm_unreachable("readonly properties should be processed differently");
Fariborz Jahanian071caef2011-03-26 19:48:30 +00007618 case Expr::MLV_InvalidMessageExpression:
7619 Diag = diag::error_readonly_message_assignment;
7620 break;
Fariborz Jahaniane8d28902009-12-15 23:59:41 +00007621 case Expr::MLV_SubObjCPropertySetting:
7622 Diag = diag::error_no_subobject_property_setting;
7623 break;
Steve Naroff218bc2b2007-05-04 21:54:46 +00007624 }
Steve Naroffad373bd2007-07-31 12:34:36 +00007625
Daniel Dunbarc2223ab2009-04-15 00:08:05 +00007626 SourceRange Assign;
7627 if (Loc != OrigLoc)
7628 Assign = SourceRange(OrigLoc, OrigLoc);
Chris Lattner30bd3272008-11-18 01:22:49 +00007629 if (NeedType)
Daniel Dunbarc2223ab2009-04-15 00:08:05 +00007630 S.Diag(Loc, Diag) << E->getType() << E->getSourceRange() << Assign;
Chris Lattner30bd3272008-11-18 01:22:49 +00007631 else
Mike Stump11289f42009-09-09 15:08:12 +00007632 S.Diag(Loc, Diag) << E->getSourceRange() << Assign;
Chris Lattner30bd3272008-11-18 01:22:49 +00007633 return true;
7634}
7635
Nico Weberb8124d12012-07-03 02:03:06 +00007636static void CheckIdentityFieldAssignment(Expr *LHSExpr, Expr *RHSExpr,
7637 SourceLocation Loc,
7638 Sema &Sema) {
7639 // C / C++ fields
Nico Weber33fd5232012-06-28 23:53:12 +00007640 MemberExpr *ML = dyn_cast<MemberExpr>(LHSExpr);
7641 MemberExpr *MR = dyn_cast<MemberExpr>(RHSExpr);
7642 if (ML && MR && ML->getMemberDecl() == MR->getMemberDecl()) {
7643 if (isa<CXXThisExpr>(ML->getBase()) && isa<CXXThisExpr>(MR->getBase()))
Nico Weberb8124d12012-07-03 02:03:06 +00007644 Sema.Diag(Loc, diag::warn_identity_field_assign) << 0;
Nico Weber33fd5232012-06-28 23:53:12 +00007645 }
Chris Lattner30bd3272008-11-18 01:22:49 +00007646
Nico Weberb8124d12012-07-03 02:03:06 +00007647 // Objective-C instance variables
Nico Weber33fd5232012-06-28 23:53:12 +00007648 ObjCIvarRefExpr *OL = dyn_cast<ObjCIvarRefExpr>(LHSExpr);
7649 ObjCIvarRefExpr *OR = dyn_cast<ObjCIvarRefExpr>(RHSExpr);
7650 if (OL && OR && OL->getDecl() == OR->getDecl()) {
7651 DeclRefExpr *RL = dyn_cast<DeclRefExpr>(OL->getBase()->IgnoreImpCasts());
7652 DeclRefExpr *RR = dyn_cast<DeclRefExpr>(OR->getBase()->IgnoreImpCasts());
7653 if (RL && RR && RL->getDecl() == RR->getDecl())
Nico Weberb8124d12012-07-03 02:03:06 +00007654 Sema.Diag(Loc, diag::warn_identity_field_assign) << 1;
Nico Weber33fd5232012-06-28 23:53:12 +00007655 }
7656}
Chris Lattner30bd3272008-11-18 01:22:49 +00007657
7658// C99 6.5.16.1
Richard Trieuda4f43a62011-09-07 01:33:52 +00007659QualType Sema::CheckAssignmentOperands(Expr *LHSExpr, ExprResult &RHS,
Chris Lattner326f7572008-11-18 01:30:42 +00007660 SourceLocation Loc,
7661 QualType CompoundType) {
John McCall526ab472011-10-25 17:37:35 +00007662 assert(!LHSExpr->hasPlaceholderType(BuiltinType::PseudoObject));
7663
Chris Lattner326f7572008-11-18 01:30:42 +00007664 // Verify that LHS is a modifiable lvalue, and emit error if not.
Richard Trieuda4f43a62011-09-07 01:33:52 +00007665 if (CheckForModifiableLvalue(LHSExpr, Loc, *this))
Chris Lattner30bd3272008-11-18 01:22:49 +00007666 return QualType();
Chris Lattner326f7572008-11-18 01:30:42 +00007667
Richard Trieuda4f43a62011-09-07 01:33:52 +00007668 QualType LHSType = LHSExpr->getType();
Richard Trieucfc491d2011-08-02 04:35:43 +00007669 QualType RHSType = CompoundType.isNull() ? RHS.get()->getType() :
7670 CompoundType;
Chris Lattner9bad62c2008-01-04 18:04:52 +00007671 AssignConvertType ConvTy;
Chris Lattner326f7572008-11-18 01:30:42 +00007672 if (CompoundType.isNull()) {
Nico Weber33fd5232012-06-28 23:53:12 +00007673 Expr *RHSCheck = RHS.get();
7674
Nico Weberb8124d12012-07-03 02:03:06 +00007675 CheckIdentityFieldAssignment(LHSExpr, RHSCheck, Loc, *this);
Nico Weber33fd5232012-06-28 23:53:12 +00007676
Fariborz Jahanianbe21aa32010-06-07 22:02:01 +00007677 QualType LHSTy(LHSType);
Fariborz Jahanianbe21aa32010-06-07 22:02:01 +00007678 ConvTy = CheckSingleAssignmentConstraints(LHSTy, RHS);
John Wiegley01296292011-04-08 18:41:53 +00007679 if (RHS.isInvalid())
7680 return QualType();
Fariborz Jahanian255c0952009-01-13 23:34:40 +00007681 // Special case of NSObject attributes on c-style pointer types.
7682 if (ConvTy == IncompatiblePointer &&
7683 ((Context.isObjCNSObjectType(LHSType) &&
Steve Naroff79d12152009-07-16 15:41:00 +00007684 RHSType->isObjCObjectPointerType()) ||
Fariborz Jahanian255c0952009-01-13 23:34:40 +00007685 (Context.isObjCNSObjectType(RHSType) &&
Steve Naroff79d12152009-07-16 15:41:00 +00007686 LHSType->isObjCObjectPointerType())))
Fariborz Jahanian255c0952009-01-13 23:34:40 +00007687 ConvTy = Compatible;
Mike Stump4e1f26a2009-02-19 03:04:26 +00007688
John McCall7decc9e2010-11-18 06:31:45 +00007689 if (ConvTy == Compatible &&
Fariborz Jahaniane2a77762012-01-24 19:40:13 +00007690 LHSType->isObjCObjectType())
Fariborz Jahanian3c4225a2012-01-24 18:05:45 +00007691 Diag(Loc, diag::err_objc_object_assignment)
7692 << LHSType;
John McCall7decc9e2010-11-18 06:31:45 +00007693
Chris Lattnerea714382008-08-21 18:04:13 +00007694 // If the RHS is a unary plus or minus, check to see if they = and + are
7695 // right next to each other. If so, the user may have typo'd "x =+ 4"
7696 // instead of "x += 4".
Chris Lattnerea714382008-08-21 18:04:13 +00007697 if (ImplicitCastExpr *ICE = dyn_cast<ImplicitCastExpr>(RHSCheck))
7698 RHSCheck = ICE->getSubExpr();
7699 if (UnaryOperator *UO = dyn_cast<UnaryOperator>(RHSCheck)) {
John McCalle3027922010-08-25 11:45:40 +00007700 if ((UO->getOpcode() == UO_Plus ||
7701 UO->getOpcode() == UO_Minus) &&
Chris Lattner326f7572008-11-18 01:30:42 +00007702 Loc.isFileID() && UO->getOperatorLoc().isFileID() &&
Chris Lattnerea714382008-08-21 18:04:13 +00007703 // Only if the two operators are exactly adjacent.
Argyrios Kyrtzidise6e67de2011-09-19 20:40:19 +00007704 Loc.getLocWithOffset(1) == UO->getOperatorLoc() &&
Chris Lattner36c39c92009-03-08 06:51:10 +00007705 // And there is a space or other character before the subexpr of the
7706 // unary +/-. We don't want to warn on "x=-1".
Argyrios Kyrtzidise6e67de2011-09-19 20:40:19 +00007707 Loc.getLocWithOffset(2) != UO->getSubExpr()->getLocStart() &&
Chris Lattnered9f14c2009-03-09 07:11:10 +00007708 UO->getSubExpr()->getLocStart().isFileID()) {
Chris Lattner29e812b2008-11-20 06:06:08 +00007709 Diag(Loc, diag::warn_not_compound_assign)
John McCalle3027922010-08-25 11:45:40 +00007710 << (UO->getOpcode() == UO_Plus ? "+" : "-")
Chris Lattner29e812b2008-11-20 06:06:08 +00007711 << SourceRange(UO->getOperatorLoc(), UO->getOperatorLoc());
Chris Lattner36c39c92009-03-08 06:51:10 +00007712 }
Chris Lattnerea714382008-08-21 18:04:13 +00007713 }
John McCall31168b02011-06-15 23:02:42 +00007714
7715 if (ConvTy == Compatible) {
Jordan Rosefa9e4ba2012-09-15 02:48:31 +00007716 if (LHSType.getObjCLifetime() == Qualifiers::OCL_Strong) {
7717 // Warn about retain cycles where a block captures the LHS, but
7718 // not if the LHS is a simple variable into which the block is
7719 // being stored...unless that variable can be captured by reference!
7720 const Expr *InnerLHS = LHSExpr->IgnoreParenCasts();
7721 const DeclRefExpr *DRE = dyn_cast<DeclRefExpr>(InnerLHS);
7722 if (!DRE || DRE->getDecl()->hasAttr<BlocksAttr>())
7723 checkRetainCycles(LHSExpr, RHS.get());
7724
7725 } else if (getLangOpts().ObjCAutoRefCount) {
Richard Trieuda4f43a62011-09-07 01:33:52 +00007726 checkUnsafeExprAssigns(Loc, LHSExpr, RHS.get());
Jordan Rosefa9e4ba2012-09-15 02:48:31 +00007727 }
John McCall31168b02011-06-15 23:02:42 +00007728 }
Chris Lattnerea714382008-08-21 18:04:13 +00007729 } else {
7730 // Compound assignment "x += y"
Douglas Gregorc03a1082011-01-28 02:26:04 +00007731 ConvTy = CheckAssignmentConstraints(Loc, LHSType, RHSType);
Chris Lattnerea714382008-08-21 18:04:13 +00007732 }
Chris Lattner9bad62c2008-01-04 18:04:52 +00007733
Chris Lattner326f7572008-11-18 01:30:42 +00007734 if (DiagnoseAssignmentResult(ConvTy, Loc, LHSType, RHSType,
John Wiegley01296292011-04-08 18:41:53 +00007735 RHS.get(), AA_Assigning))
Chris Lattner9bad62c2008-01-04 18:04:52 +00007736 return QualType();
Mike Stump4e1f26a2009-02-19 03:04:26 +00007737
Richard Trieuda4f43a62011-09-07 01:33:52 +00007738 CheckForNullPointerDereference(*this, LHSExpr);
Kaelyn Uhrain2e7aa5a2011-08-05 23:18:04 +00007739
Steve Naroff98cf3e92007-06-06 18:38:38 +00007740 // C99 6.5.16p3: The type of an assignment expression is the type of the
7741 // left operand unless the left operand has qualified type, in which case
Mike Stump4e1f26a2009-02-19 03:04:26 +00007742 // it is the unqualified version of the type of the left operand.
Steve Naroff98cf3e92007-06-06 18:38:38 +00007743 // C99 6.5.16.1p2: In simple assignment, the value of the right operand
7744 // is converted to the type of the assignment expression (above).
Chris Lattnerf17bd422007-08-30 17:45:32 +00007745 // C++ 5.17p1: the type of the assignment expression is that of its left
Douglas Gregord2c2d172009-05-02 00:36:19 +00007746 // operand.
David Blaikiebbafb8a2012-03-11 07:00:24 +00007747 return (getLangOpts().CPlusPlus
John McCall01cbf2d2010-10-12 02:19:57 +00007748 ? LHSType : LHSType.getUnqualifiedType());
Steve Naroffae4143e2007-04-26 20:39:23 +00007749}
7750
Chris Lattner326f7572008-11-18 01:30:42 +00007751// C99 6.5.17
John Wiegley01296292011-04-08 18:41:53 +00007752static QualType CheckCommaOperands(Sema &S, ExprResult &LHS, ExprResult &RHS,
John McCall4bc41ae2010-11-18 19:01:18 +00007753 SourceLocation Loc) {
John McCall3aef3d82011-04-10 19:13:55 +00007754 LHS = S.CheckPlaceholderExpr(LHS.take());
7755 RHS = S.CheckPlaceholderExpr(RHS.take());
John Wiegley01296292011-04-08 18:41:53 +00007756 if (LHS.isInvalid() || RHS.isInvalid())
Douglas Gregor0124e9b2010-11-09 21:07:58 +00007757 return QualType();
7758
John McCall73d36182010-10-12 07:14:40 +00007759 // C's comma performs lvalue conversion (C99 6.3.2.1) on both its
7760 // operands, but not unary promotions.
7761 // C++'s comma does not do any conversions at all (C++ [expr.comma]p1).
Eli Friedmanba961a92009-03-23 00:24:07 +00007762
John McCall34376a62010-12-04 03:47:34 +00007763 // So we treat the LHS as a ignored value, and in C++ we allow the
7764 // containing site to determine what should be done with the RHS.
John Wiegley01296292011-04-08 18:41:53 +00007765 LHS = S.IgnoredValueConversions(LHS.take());
7766 if (LHS.isInvalid())
7767 return QualType();
John McCall34376a62010-12-04 03:47:34 +00007768
Eli Friedmanc11535c2012-05-24 00:47:05 +00007769 S.DiagnoseUnusedExprResult(LHS.get());
7770
David Blaikiebbafb8a2012-03-11 07:00:24 +00007771 if (!S.getLangOpts().CPlusPlus) {
John Wiegley01296292011-04-08 18:41:53 +00007772 RHS = S.DefaultFunctionArrayLvalueConversion(RHS.take());
7773 if (RHS.isInvalid())
7774 return QualType();
7775 if (!RHS.get()->getType()->isVoidType())
Richard Trieucfc491d2011-08-02 04:35:43 +00007776 S.RequireCompleteType(Loc, RHS.get()->getType(),
7777 diag::err_incomplete_type);
John McCall73d36182010-10-12 07:14:40 +00007778 }
Eli Friedmanba961a92009-03-23 00:24:07 +00007779
John Wiegley01296292011-04-08 18:41:53 +00007780 return RHS.get()->getType();
Steve Naroff95af0132007-03-30 23:47:58 +00007781}
7782
Steve Naroff7a5af782007-07-13 16:58:59 +00007783/// CheckIncrementDecrementOperand - unlike most "Check" methods, this routine
7784/// doesn't need to call UsualUnaryConversions or UsualArithmeticConversions.
John McCall4bc41ae2010-11-18 19:01:18 +00007785static QualType CheckIncrementDecrementOperand(Sema &S, Expr *Op,
7786 ExprValueKind &VK,
7787 SourceLocation OpLoc,
Richard Trieuba63ce62011-09-09 01:45:06 +00007788 bool IsInc, bool IsPrefix) {
Sebastian Redl8d2ccae2009-02-26 14:39:58 +00007789 if (Op->isTypeDependent())
John McCall4bc41ae2010-11-18 19:01:18 +00007790 return S.Context.DependentTy;
Sebastian Redl8d2ccae2009-02-26 14:39:58 +00007791
Chris Lattner6b0cf142008-11-21 07:05:48 +00007792 QualType ResType = Op->getType();
David Chisnallfa35df62012-01-16 17:27:18 +00007793 // Atomic types can be used for increment / decrement where the non-atomic
7794 // versions can, so ignore the _Atomic() specifier for the purpose of
7795 // checking.
7796 if (const AtomicType *ResAtomicType = ResType->getAs<AtomicType>())
7797 ResType = ResAtomicType->getValueType();
7798
Chris Lattner6b0cf142008-11-21 07:05:48 +00007799 assert(!ResType.isNull() && "no type for increment/decrement expression");
Steve Naroffd50c88e2007-04-05 21:15:20 +00007800
David Blaikiebbafb8a2012-03-11 07:00:24 +00007801 if (S.getLangOpts().CPlusPlus && ResType->isBooleanType()) {
Sebastian Redle10c2c32008-12-20 09:35:34 +00007802 // Decrement of bool is not allowed.
Richard Trieuba63ce62011-09-09 01:45:06 +00007803 if (!IsInc) {
John McCall4bc41ae2010-11-18 19:01:18 +00007804 S.Diag(OpLoc, diag::err_decrement_bool) << Op->getSourceRange();
Sebastian Redle10c2c32008-12-20 09:35:34 +00007805 return QualType();
7806 }
7807 // Increment of bool sets it to true, but is deprecated.
John McCall4bc41ae2010-11-18 19:01:18 +00007808 S.Diag(OpLoc, diag::warn_increment_bool) << Op->getSourceRange();
Sebastian Redle10c2c32008-12-20 09:35:34 +00007809 } else if (ResType->isRealType()) {
Chris Lattner6b0cf142008-11-21 07:05:48 +00007810 // OK!
John McCallf2538342012-07-31 05:14:30 +00007811 } else if (ResType->isPointerType()) {
Chris Lattner6b0cf142008-11-21 07:05:48 +00007812 // C99 6.5.2.4p2, 6.5.6p2
Chandler Carruthc9332212011-06-27 08:02:19 +00007813 if (!checkArithmeticOpPointerOperand(S, OpLoc, Op))
Douglas Gregordd430f72009-01-19 19:26:10 +00007814 return QualType();
John McCallf2538342012-07-31 05:14:30 +00007815 } else if (ResType->isObjCObjectPointerType()) {
7816 // On modern runtimes, ObjC pointer arithmetic is forbidden.
7817 // Otherwise, we just need a complete type.
7818 if (checkArithmeticIncompletePointerType(S, OpLoc, Op) ||
7819 checkArithmeticOnObjCPointer(S, OpLoc, Op))
7820 return QualType();
Eli Friedman090addd2010-01-03 00:20:48 +00007821 } else if (ResType->isAnyComplexType()) {
Chris Lattner6b0cf142008-11-21 07:05:48 +00007822 // C99 does not support ++/-- on complex types, we allow as an extension.
John McCall4bc41ae2010-11-18 19:01:18 +00007823 S.Diag(OpLoc, diag::ext_integer_increment_complex)
Chris Lattner1e5665e2008-11-24 06:25:27 +00007824 << ResType << Op->getSourceRange();
John McCall36226622010-10-12 02:09:17 +00007825 } else if (ResType->isPlaceholderType()) {
John McCall3aef3d82011-04-10 19:13:55 +00007826 ExprResult PR = S.CheckPlaceholderExpr(Op);
John McCall36226622010-10-12 02:09:17 +00007827 if (PR.isInvalid()) return QualType();
John McCall4bc41ae2010-11-18 19:01:18 +00007828 return CheckIncrementDecrementOperand(S, PR.take(), VK, OpLoc,
Richard Trieuba63ce62011-09-09 01:45:06 +00007829 IsInc, IsPrefix);
David Blaikiebbafb8a2012-03-11 07:00:24 +00007830 } else if (S.getLangOpts().AltiVec && ResType->isVectorType()) {
Anton Yartsev85129b82011-02-07 02:17:30 +00007831 // OK! ( C/C++ Language Extensions for CBEA(Version 2.6) 10.3 )
Chris Lattner6b0cf142008-11-21 07:05:48 +00007832 } else {
John McCall4bc41ae2010-11-18 19:01:18 +00007833 S.Diag(OpLoc, diag::err_typecheck_illegal_increment_decrement)
Richard Trieuba63ce62011-09-09 01:45:06 +00007834 << ResType << int(IsInc) << Op->getSourceRange();
Chris Lattner6b0cf142008-11-21 07:05:48 +00007835 return QualType();
Steve Naroff46ba1eb2007-04-03 23:13:13 +00007836 }
Mike Stump4e1f26a2009-02-19 03:04:26 +00007837 // At this point, we know we have a real, complex or pointer type.
Steve Naroff9e1e5512007-08-23 21:37:33 +00007838 // Now make sure the operand is a modifiable lvalue.
John McCall4bc41ae2010-11-18 19:01:18 +00007839 if (CheckForModifiableLvalue(Op, OpLoc, S))
Steve Naroff35d85152007-05-07 00:24:15 +00007840 return QualType();
Alexis Huntc46382e2010-04-28 23:02:27 +00007841 // In C++, a prefix increment is the same type as the operand. Otherwise
7842 // (in C or with postfix), the increment is the unqualified type of the
7843 // operand.
David Blaikiebbafb8a2012-03-11 07:00:24 +00007844 if (IsPrefix && S.getLangOpts().CPlusPlus) {
John McCall4bc41ae2010-11-18 19:01:18 +00007845 VK = VK_LValue;
7846 return ResType;
7847 } else {
7848 VK = VK_RValue;
7849 return ResType.getUnqualifiedType();
7850 }
Steve Naroff26c8ea52007-03-21 21:08:52 +00007851}
Fariborz Jahanian805b74e2010-09-14 23:02:38 +00007852
7853
Anders Carlsson806700f2008-02-01 07:15:58 +00007854/// getPrimaryDecl - Helper function for CheckAddressOfOperand().
Steve Naroff47500512007-04-19 23:00:49 +00007855/// This routine allows us to typecheck complex/recursive expressions
Daniel Dunbarb692ef42008-08-04 20:02:37 +00007856/// where the declaration is needed for type checking. We only need to
7857/// handle cases when the expression references a function designator
7858/// or is an lvalue. Here are some examples:
7859/// - &(x) => x
7860/// - &*****f => f for f a function designator.
7861/// - &s.xx => s
7862/// - &s.zz[1].yy -> s, if zz is an array
7863/// - *(x + 1) -> x, if x is an array
7864/// - &"123"[2] -> 0
7865/// - & __real__ x -> x
John McCallf3a88602011-02-03 08:15:49 +00007866static ValueDecl *getPrimaryDecl(Expr *E) {
Chris Lattner24d5bfe2008-04-02 04:24:33 +00007867 switch (E->getStmtClass()) {
Steve Naroff47500512007-04-19 23:00:49 +00007868 case Stmt::DeclRefExprClass:
Chris Lattner24d5bfe2008-04-02 04:24:33 +00007869 return cast<DeclRefExpr>(E)->getDecl();
Steve Naroff47500512007-04-19 23:00:49 +00007870 case Stmt::MemberExprClass:
Eli Friedman3a1e6922009-04-20 08:23:18 +00007871 // If this is an arrow operator, the address is an offset from
7872 // the base's value, so the object the base refers to is
7873 // irrelevant.
Chris Lattner24d5bfe2008-04-02 04:24:33 +00007874 if (cast<MemberExpr>(E)->isArrow())
Chris Lattner48d52842007-11-16 17:46:48 +00007875 return 0;
Eli Friedman3a1e6922009-04-20 08:23:18 +00007876 // Otherwise, the expression refers to a part of the base
Chris Lattner24d5bfe2008-04-02 04:24:33 +00007877 return getPrimaryDecl(cast<MemberExpr>(E)->getBase());
Anders Carlsson806700f2008-02-01 07:15:58 +00007878 case Stmt::ArraySubscriptExprClass: {
Mike Stump87c57ac2009-05-16 07:39:55 +00007879 // FIXME: This code shouldn't be necessary! We should catch the implicit
7880 // promotion of register arrays earlier.
Eli Friedman3a1e6922009-04-20 08:23:18 +00007881 Expr* Base = cast<ArraySubscriptExpr>(E)->getBase();
7882 if (ImplicitCastExpr* ICE = dyn_cast<ImplicitCastExpr>(Base)) {
7883 if (ICE->getSubExpr()->getType()->isArrayType())
7884 return getPrimaryDecl(ICE->getSubExpr());
7885 }
7886 return 0;
Anders Carlsson806700f2008-02-01 07:15:58 +00007887 }
Daniel Dunbarb692ef42008-08-04 20:02:37 +00007888 case Stmt::UnaryOperatorClass: {
7889 UnaryOperator *UO = cast<UnaryOperator>(E);
Mike Stump4e1f26a2009-02-19 03:04:26 +00007890
Daniel Dunbarb692ef42008-08-04 20:02:37 +00007891 switch(UO->getOpcode()) {
John McCalle3027922010-08-25 11:45:40 +00007892 case UO_Real:
7893 case UO_Imag:
7894 case UO_Extension:
Daniel Dunbarb692ef42008-08-04 20:02:37 +00007895 return getPrimaryDecl(UO->getSubExpr());
7896 default:
7897 return 0;
7898 }
7899 }
Steve Naroff47500512007-04-19 23:00:49 +00007900 case Stmt::ParenExprClass:
Chris Lattner24d5bfe2008-04-02 04:24:33 +00007901 return getPrimaryDecl(cast<ParenExpr>(E)->getSubExpr());
Chris Lattner48d52842007-11-16 17:46:48 +00007902 case Stmt::ImplicitCastExprClass:
Eli Friedman3a1e6922009-04-20 08:23:18 +00007903 // If the result of an implicit cast is an l-value, we care about
7904 // the sub-expression; otherwise, the result here doesn't matter.
Chris Lattner24d5bfe2008-04-02 04:24:33 +00007905 return getPrimaryDecl(cast<ImplicitCastExpr>(E)->getSubExpr());
Steve Naroff47500512007-04-19 23:00:49 +00007906 default:
7907 return 0;
7908 }
7909}
7910
Richard Trieu5f376f62011-09-07 21:46:33 +00007911namespace {
7912 enum {
7913 AO_Bit_Field = 0,
7914 AO_Vector_Element = 1,
7915 AO_Property_Expansion = 2,
7916 AO_Register_Variable = 3,
7917 AO_No_Error = 4
7918 };
7919}
Richard Trieu3fd7bb82011-09-02 00:47:55 +00007920/// \brief Diagnose invalid operand for address of operations.
7921///
7922/// \param Type The type of operand which cannot have its address taken.
Richard Trieu3fd7bb82011-09-02 00:47:55 +00007923static void diagnoseAddressOfInvalidType(Sema &S, SourceLocation Loc,
7924 Expr *E, unsigned Type) {
7925 S.Diag(Loc, diag::err_typecheck_address_of) << Type << E->getSourceRange();
7926}
7927
Steve Naroff47500512007-04-19 23:00:49 +00007928/// CheckAddressOfOperand - The operand of & must be either a function
Mike Stump4e1f26a2009-02-19 03:04:26 +00007929/// designator or an lvalue designating an object. If it is an lvalue, the
Steve Naroff47500512007-04-19 23:00:49 +00007930/// object cannot be declared with storage class register or be a bit field.
Mike Stump4e1f26a2009-02-19 03:04:26 +00007931/// Note: The usual conversions are *not* applied to the operand of the &
Steve Naroffa78fe7e2007-05-16 19:47:19 +00007932/// operator (C99 6.3.2.1p[2-4]), and its result is never an lvalue.
Mike Stump4e1f26a2009-02-19 03:04:26 +00007933/// In C++, the operand might be an overloaded function name, in which case
Douglas Gregorcd695e52008-11-10 20:40:00 +00007934/// we allow the '&' but retain the overloaded-function type.
John McCall526ab472011-10-25 17:37:35 +00007935static QualType CheckAddressOfOperand(Sema &S, ExprResult &OrigOp,
John McCall4bc41ae2010-11-18 19:01:18 +00007936 SourceLocation OpLoc) {
John McCall526ab472011-10-25 17:37:35 +00007937 if (const BuiltinType *PTy = OrigOp.get()->getType()->getAsPlaceholderType()){
7938 if (PTy->getKind() == BuiltinType::Overload) {
7939 if (!isa<OverloadExpr>(OrigOp.get()->IgnoreParens())) {
7940 S.Diag(OpLoc, diag::err_typecheck_invalid_lvalue_addrof)
7941 << OrigOp.get()->getSourceRange();
7942 return QualType();
7943 }
7944
7945 return S.Context.OverloadTy;
7946 }
7947
7948 if (PTy->getKind() == BuiltinType::UnknownAny)
7949 return S.Context.UnknownAnyTy;
7950
7951 if (PTy->getKind() == BuiltinType::BoundMember) {
7952 S.Diag(OpLoc, diag::err_invalid_form_pointer_member_function)
7953 << OrigOp.get()->getSourceRange();
Douglas Gregor668d3622011-10-09 19:10:41 +00007954 return QualType();
7955 }
John McCall526ab472011-10-25 17:37:35 +00007956
7957 OrigOp = S.CheckPlaceholderExpr(OrigOp.take());
7958 if (OrigOp.isInvalid()) return QualType();
John McCall0009fcc2011-04-26 20:42:42 +00007959 }
John McCall8d08b9b2010-08-27 09:08:28 +00007960
John McCall526ab472011-10-25 17:37:35 +00007961 if (OrigOp.get()->isTypeDependent())
7962 return S.Context.DependentTy;
7963
7964 assert(!OrigOp.get()->getType()->isPlaceholderType());
John McCall36226622010-10-12 02:09:17 +00007965
John McCall8d08b9b2010-08-27 09:08:28 +00007966 // Make sure to ignore parentheses in subsequent checks
John McCall526ab472011-10-25 17:37:35 +00007967 Expr *op = OrigOp.get()->IgnoreParens();
Douglas Gregor19b8c4f2008-12-17 22:52:20 +00007968
David Blaikiebbafb8a2012-03-11 07:00:24 +00007969 if (S.getLangOpts().C99) {
Steve Naroff826e91a2008-01-13 17:10:08 +00007970 // Implement C99-only parts of addressof rules.
7971 if (UnaryOperator* uOp = dyn_cast<UnaryOperator>(op)) {
John McCalle3027922010-08-25 11:45:40 +00007972 if (uOp->getOpcode() == UO_Deref)
Steve Naroff826e91a2008-01-13 17:10:08 +00007973 // Per C99 6.5.3.2, the address of a deref always returns a valid result
7974 // (assuming the deref expression is valid).
7975 return uOp->getSubExpr()->getType();
7976 }
7977 // Technically, there should be a check for array subscript
7978 // expressions here, but the result of one is always an lvalue anyway.
7979 }
John McCallf3a88602011-02-03 08:15:49 +00007980 ValueDecl *dcl = getPrimaryDecl(op);
John McCall086a4642010-11-24 05:12:34 +00007981 Expr::LValueClassification lval = op->ClassifyLValue(S.Context);
Richard Trieu5f376f62011-09-07 21:46:33 +00007982 unsigned AddressOfError = AO_No_Error;
Nuno Lopes17f345f2008-12-16 22:59:47 +00007983
Fariborz Jahanian071caef2011-03-26 19:48:30 +00007984 if (lval == Expr::LV_ClassTemporary) {
John McCall4bc41ae2010-11-18 19:01:18 +00007985 bool sfinae = S.isSFINAEContext();
7986 S.Diag(OpLoc, sfinae ? diag::err_typecheck_addrof_class_temporary
7987 : diag::ext_typecheck_addrof_class_temporary)
Douglas Gregorb154fdc2010-02-16 21:39:57 +00007988 << op->getType() << op->getSourceRange();
John McCall4bc41ae2010-11-18 19:01:18 +00007989 if (sfinae)
Douglas Gregorb154fdc2010-02-16 21:39:57 +00007990 return QualType();
John McCall8d08b9b2010-08-27 09:08:28 +00007991 } else if (isa<ObjCSelectorExpr>(op)) {
John McCall4bc41ae2010-11-18 19:01:18 +00007992 return S.Context.getPointerType(op->getType());
John McCall8d08b9b2010-08-27 09:08:28 +00007993 } else if (lval == Expr::LV_MemberFunction) {
7994 // If it's an instance method, make a member pointer.
7995 // The expression must have exactly the form &A::foo.
7996
7997 // If the underlying expression isn't a decl ref, give up.
7998 if (!isa<DeclRefExpr>(op)) {
John McCall4bc41ae2010-11-18 19:01:18 +00007999 S.Diag(OpLoc, diag::err_invalid_form_pointer_member_function)
John McCall526ab472011-10-25 17:37:35 +00008000 << OrigOp.get()->getSourceRange();
John McCall8d08b9b2010-08-27 09:08:28 +00008001 return QualType();
8002 }
8003 DeclRefExpr *DRE = cast<DeclRefExpr>(op);
8004 CXXMethodDecl *MD = cast<CXXMethodDecl>(DRE->getDecl());
8005
8006 // The id-expression was parenthesized.
John McCall526ab472011-10-25 17:37:35 +00008007 if (OrigOp.get() != DRE) {
John McCall4bc41ae2010-11-18 19:01:18 +00008008 S.Diag(OpLoc, diag::err_parens_pointer_member_function)
John McCall526ab472011-10-25 17:37:35 +00008009 << OrigOp.get()->getSourceRange();
John McCall8d08b9b2010-08-27 09:08:28 +00008010
8011 // The method was named without a qualifier.
8012 } else if (!DRE->getQualifier()) {
John McCall4bc41ae2010-11-18 19:01:18 +00008013 S.Diag(OpLoc, diag::err_unqualified_pointer_member_function)
John McCall8d08b9b2010-08-27 09:08:28 +00008014 << op->getSourceRange();
8015 }
8016
John McCall4bc41ae2010-11-18 19:01:18 +00008017 return S.Context.getMemberPointerType(op->getType(),
8018 S.Context.getTypeDeclType(MD->getParent()).getTypePtr());
John McCall8d08b9b2010-08-27 09:08:28 +00008019 } else if (lval != Expr::LV_Valid && lval != Expr::LV_IncompleteVoidType) {
Eli Friedmance7f9002009-05-16 23:27:50 +00008020 // C99 6.5.3.2p1
Eli Friedman3a1e6922009-04-20 08:23:18 +00008021 // The operand must be either an l-value or a function designator
Eli Friedmance7f9002009-05-16 23:27:50 +00008022 if (!op->getType()->isFunctionType()) {
John McCall526ab472011-10-25 17:37:35 +00008023 // Use a special diagnostic for loads from property references.
John McCallfe96e0b2011-11-06 09:01:30 +00008024 if (isa<PseudoObjectExpr>(op)) {
John McCall526ab472011-10-25 17:37:35 +00008025 AddressOfError = AO_Property_Expansion;
8026 } else {
8027 // FIXME: emit more specific diag...
8028 S.Diag(OpLoc, diag::err_typecheck_invalid_lvalue_addrof)
8029 << op->getSourceRange();
8030 return QualType();
8031 }
Steve Naroff35d85152007-05-07 00:24:15 +00008032 }
John McCall086a4642010-11-24 05:12:34 +00008033 } else if (op->getObjectKind() == OK_BitField) { // C99 6.5.3.2p1
Eli Friedman3a1e6922009-04-20 08:23:18 +00008034 // The operand cannot be a bit-field
Richard Trieu5f376f62011-09-07 21:46:33 +00008035 AddressOfError = AO_Bit_Field;
John McCall086a4642010-11-24 05:12:34 +00008036 } else if (op->getObjectKind() == OK_VectorComponent) {
Eli Friedman3a1e6922009-04-20 08:23:18 +00008037 // The operand cannot be an element of a vector
Richard Trieu5f376f62011-09-07 21:46:33 +00008038 AddressOfError = AO_Vector_Element;
Steve Naroffb96e4ab62008-02-29 23:30:25 +00008039 } else if (dcl) { // C99 6.5.3.2p1
Mike Stump4e1f26a2009-02-19 03:04:26 +00008040 // We have an lvalue with a decl. Make sure the decl is not declared
Steve Naroff47500512007-04-19 23:00:49 +00008041 // with the register storage-class specifier.
8042 if (const VarDecl *vd = dyn_cast<VarDecl>(dcl)) {
Fariborz Jahaniane0fd5a92010-08-24 22:21:48 +00008043 // in C++ it is not error to take address of a register
8044 // variable (c++03 7.1.1P3)
John McCall8e7d6562010-08-26 03:08:43 +00008045 if (vd->getStorageClass() == SC_Register &&
David Blaikiebbafb8a2012-03-11 07:00:24 +00008046 !S.getLangOpts().CPlusPlus) {
Richard Trieu5f376f62011-09-07 21:46:33 +00008047 AddressOfError = AO_Register_Variable;
Steve Naroff35d85152007-05-07 00:24:15 +00008048 }
John McCalld14a8642009-11-21 08:51:07 +00008049 } else if (isa<FunctionTemplateDecl>(dcl)) {
John McCall4bc41ae2010-11-18 19:01:18 +00008050 return S.Context.OverloadTy;
John McCallf3a88602011-02-03 08:15:49 +00008051 } else if (isa<FieldDecl>(dcl) || isa<IndirectFieldDecl>(dcl)) {
Douglas Gregor9aa8b552008-12-10 21:26:49 +00008052 // Okay: we can take the address of a field.
Sebastian Redl3d3f75a2009-02-03 20:19:35 +00008053 // Could be a pointer to member, though, if there is an explicit
8054 // scope qualifier for the class.
Douglas Gregor4bd90e52009-10-23 18:54:35 +00008055 if (isa<DeclRefExpr>(op) && cast<DeclRefExpr>(op)->getQualifier()) {
Sebastian Redl3d3f75a2009-02-03 20:19:35 +00008056 DeclContext *Ctx = dcl->getDeclContext();
Anders Carlsson0b675f52009-07-08 21:45:58 +00008057 if (Ctx && Ctx->isRecord()) {
John McCallf3a88602011-02-03 08:15:49 +00008058 if (dcl->getType()->isReferenceType()) {
John McCall4bc41ae2010-11-18 19:01:18 +00008059 S.Diag(OpLoc,
8060 diag::err_cannot_form_pointer_to_member_of_reference_type)
John McCallf3a88602011-02-03 08:15:49 +00008061 << dcl->getDeclName() << dcl->getType();
Anders Carlsson0b675f52009-07-08 21:45:58 +00008062 return QualType();
8063 }
Mike Stump11289f42009-09-09 15:08:12 +00008064
Argyrios Kyrtzidis8322b422011-01-31 07:04:29 +00008065 while (cast<RecordDecl>(Ctx)->isAnonymousStructOrUnion())
8066 Ctx = Ctx->getParent();
John McCall4bc41ae2010-11-18 19:01:18 +00008067 return S.Context.getMemberPointerType(op->getType(),
8068 S.Context.getTypeDeclType(cast<RecordDecl>(Ctx)).getTypePtr());
Anders Carlsson0b675f52009-07-08 21:45:58 +00008069 }
Sebastian Redl3d3f75a2009-02-03 20:19:35 +00008070 }
Eli Friedman755c0c92011-08-26 20:28:17 +00008071 } else if (!isa<FunctionDecl>(dcl) && !isa<NonTypeTemplateParmDecl>(dcl))
David Blaikie83d382b2011-09-23 05:06:16 +00008072 llvm_unreachable("Unknown/unexpected decl type");
Steve Naroff47500512007-04-19 23:00:49 +00008073 }
Sebastian Redl18f8ff62009-02-04 21:23:32 +00008074
Richard Trieu5f376f62011-09-07 21:46:33 +00008075 if (AddressOfError != AO_No_Error) {
8076 diagnoseAddressOfInvalidType(S, OpLoc, op, AddressOfError);
8077 return QualType();
8078 }
8079
Eli Friedmance7f9002009-05-16 23:27:50 +00008080 if (lval == Expr::LV_IncompleteVoidType) {
8081 // Taking the address of a void variable is technically illegal, but we
8082 // allow it in cases which are otherwise valid.
8083 // Example: "extern void x; void* y = &x;".
John McCall4bc41ae2010-11-18 19:01:18 +00008084 S.Diag(OpLoc, diag::ext_typecheck_addrof_void) << op->getSourceRange();
Eli Friedmance7f9002009-05-16 23:27:50 +00008085 }
8086
Steve Naroff47500512007-04-19 23:00:49 +00008087 // If the operand has type "type", the result has type "pointer to type".
Douglas Gregor0bdcb8a2010-07-29 16:05:45 +00008088 if (op->getType()->isObjCObjectType())
John McCall4bc41ae2010-11-18 19:01:18 +00008089 return S.Context.getObjCObjectPointerType(op->getType());
8090 return S.Context.getPointerType(op->getType());
Steve Naroff47500512007-04-19 23:00:49 +00008091}
8092
Chris Lattner9156f1b2010-07-05 19:17:26 +00008093/// CheckIndirectionOperand - Type check unary indirection (prefix '*').
John McCall4bc41ae2010-11-18 19:01:18 +00008094static QualType CheckIndirectionOperand(Sema &S, Expr *Op, ExprValueKind &VK,
8095 SourceLocation OpLoc) {
Sebastian Redl8d2ccae2009-02-26 14:39:58 +00008096 if (Op->isTypeDependent())
John McCall4bc41ae2010-11-18 19:01:18 +00008097 return S.Context.DependentTy;
Sebastian Redl8d2ccae2009-02-26 14:39:58 +00008098
John Wiegley01296292011-04-08 18:41:53 +00008099 ExprResult ConvResult = S.UsualUnaryConversions(Op);
8100 if (ConvResult.isInvalid())
8101 return QualType();
8102 Op = ConvResult.take();
Chris Lattner9156f1b2010-07-05 19:17:26 +00008103 QualType OpTy = Op->getType();
8104 QualType Result;
Argyrios Kyrtzidis69a2c922011-05-02 18:21:19 +00008105
8106 if (isa<CXXReinterpretCastExpr>(Op)) {
8107 QualType OpOrigType = Op->IgnoreParenCasts()->getType();
8108 S.CheckCompatibleReinterpretCast(OpOrigType, OpTy, /*IsDereference*/true,
8109 Op->getSourceRange());
8110 }
8111
Chris Lattner9156f1b2010-07-05 19:17:26 +00008112 // Note that per both C89 and C99, indirection is always legal, even if OpTy
8113 // is an incomplete type or void. It would be possible to warn about
8114 // dereferencing a void pointer, but it's completely well-defined, and such a
8115 // warning is unlikely to catch any mistakes.
8116 if (const PointerType *PT = OpTy->getAs<PointerType>())
8117 Result = PT->getPointeeType();
8118 else if (const ObjCObjectPointerType *OPT =
8119 OpTy->getAs<ObjCObjectPointerType>())
8120 Result = OPT->getPointeeType();
John McCall36226622010-10-12 02:09:17 +00008121 else {
John McCall3aef3d82011-04-10 19:13:55 +00008122 ExprResult PR = S.CheckPlaceholderExpr(Op);
John McCall36226622010-10-12 02:09:17 +00008123 if (PR.isInvalid()) return QualType();
John McCall4bc41ae2010-11-18 19:01:18 +00008124 if (PR.take() != Op)
8125 return CheckIndirectionOperand(S, PR.take(), VK, OpLoc);
John McCall36226622010-10-12 02:09:17 +00008126 }
Mike Stump4e1f26a2009-02-19 03:04:26 +00008127
Chris Lattner9156f1b2010-07-05 19:17:26 +00008128 if (Result.isNull()) {
John McCall4bc41ae2010-11-18 19:01:18 +00008129 S.Diag(OpLoc, diag::err_typecheck_indirection_requires_pointer)
Chris Lattner9156f1b2010-07-05 19:17:26 +00008130 << OpTy << Op->getSourceRange();
8131 return QualType();
8132 }
John McCall4bc41ae2010-11-18 19:01:18 +00008133
8134 // Dereferences are usually l-values...
8135 VK = VK_LValue;
8136
8137 // ...except that certain expressions are never l-values in C.
David Blaikiebbafb8a2012-03-11 07:00:24 +00008138 if (!S.getLangOpts().CPlusPlus && Result.isCForbiddenLValueType())
John McCall4bc41ae2010-11-18 19:01:18 +00008139 VK = VK_RValue;
Chris Lattner9156f1b2010-07-05 19:17:26 +00008140
8141 return Result;
Steve Naroff1926c832007-04-24 00:23:05 +00008142}
Steve Naroff218bc2b2007-05-04 21:54:46 +00008143
John McCalle3027922010-08-25 11:45:40 +00008144static inline BinaryOperatorKind ConvertTokenKindToBinaryOpcode(
Steve Naroff218bc2b2007-05-04 21:54:46 +00008145 tok::TokenKind Kind) {
John McCalle3027922010-08-25 11:45:40 +00008146 BinaryOperatorKind Opc;
Steve Naroff218bc2b2007-05-04 21:54:46 +00008147 switch (Kind) {
David Blaikie83d382b2011-09-23 05:06:16 +00008148 default: llvm_unreachable("Unknown binop!");
John McCalle3027922010-08-25 11:45:40 +00008149 case tok::periodstar: Opc = BO_PtrMemD; break;
8150 case tok::arrowstar: Opc = BO_PtrMemI; break;
8151 case tok::star: Opc = BO_Mul; break;
8152 case tok::slash: Opc = BO_Div; break;
8153 case tok::percent: Opc = BO_Rem; break;
8154 case tok::plus: Opc = BO_Add; break;
8155 case tok::minus: Opc = BO_Sub; break;
8156 case tok::lessless: Opc = BO_Shl; break;
8157 case tok::greatergreater: Opc = BO_Shr; break;
8158 case tok::lessequal: Opc = BO_LE; break;
8159 case tok::less: Opc = BO_LT; break;
8160 case tok::greaterequal: Opc = BO_GE; break;
8161 case tok::greater: Opc = BO_GT; break;
8162 case tok::exclaimequal: Opc = BO_NE; break;
8163 case tok::equalequal: Opc = BO_EQ; break;
8164 case tok::amp: Opc = BO_And; break;
8165 case tok::caret: Opc = BO_Xor; break;
8166 case tok::pipe: Opc = BO_Or; break;
8167 case tok::ampamp: Opc = BO_LAnd; break;
8168 case tok::pipepipe: Opc = BO_LOr; break;
8169 case tok::equal: Opc = BO_Assign; break;
8170 case tok::starequal: Opc = BO_MulAssign; break;
8171 case tok::slashequal: Opc = BO_DivAssign; break;
8172 case tok::percentequal: Opc = BO_RemAssign; break;
8173 case tok::plusequal: Opc = BO_AddAssign; break;
8174 case tok::minusequal: Opc = BO_SubAssign; break;
8175 case tok::lesslessequal: Opc = BO_ShlAssign; break;
8176 case tok::greatergreaterequal: Opc = BO_ShrAssign; break;
8177 case tok::ampequal: Opc = BO_AndAssign; break;
8178 case tok::caretequal: Opc = BO_XorAssign; break;
8179 case tok::pipeequal: Opc = BO_OrAssign; break;
8180 case tok::comma: Opc = BO_Comma; break;
Steve Naroff218bc2b2007-05-04 21:54:46 +00008181 }
8182 return Opc;
8183}
8184
John McCalle3027922010-08-25 11:45:40 +00008185static inline UnaryOperatorKind ConvertTokenKindToUnaryOpcode(
Steve Naroff35d85152007-05-07 00:24:15 +00008186 tok::TokenKind Kind) {
John McCalle3027922010-08-25 11:45:40 +00008187 UnaryOperatorKind Opc;
Steve Naroff35d85152007-05-07 00:24:15 +00008188 switch (Kind) {
David Blaikie83d382b2011-09-23 05:06:16 +00008189 default: llvm_unreachable("Unknown unary op!");
John McCalle3027922010-08-25 11:45:40 +00008190 case tok::plusplus: Opc = UO_PreInc; break;
8191 case tok::minusminus: Opc = UO_PreDec; break;
8192 case tok::amp: Opc = UO_AddrOf; break;
8193 case tok::star: Opc = UO_Deref; break;
8194 case tok::plus: Opc = UO_Plus; break;
8195 case tok::minus: Opc = UO_Minus; break;
8196 case tok::tilde: Opc = UO_Not; break;
8197 case tok::exclaim: Opc = UO_LNot; break;
8198 case tok::kw___real: Opc = UO_Real; break;
8199 case tok::kw___imag: Opc = UO_Imag; break;
8200 case tok::kw___extension__: Opc = UO_Extension; break;
Steve Naroff35d85152007-05-07 00:24:15 +00008201 }
8202 return Opc;
8203}
8204
Chandler Carruthe0cee6a2011-01-04 06:52:15 +00008205/// DiagnoseSelfAssignment - Emits a warning if a value is assigned to itself.
8206/// This warning is only emitted for builtin assignment operations. It is also
8207/// suppressed in the event of macro expansions.
Richard Trieuda4f43a62011-09-07 01:33:52 +00008208static void DiagnoseSelfAssignment(Sema &S, Expr *LHSExpr, Expr *RHSExpr,
Chandler Carruthe0cee6a2011-01-04 06:52:15 +00008209 SourceLocation OpLoc) {
8210 if (!S.ActiveTemplateInstantiations.empty())
8211 return;
8212 if (OpLoc.isInvalid() || OpLoc.isMacroID())
8213 return;
Richard Trieuda4f43a62011-09-07 01:33:52 +00008214 LHSExpr = LHSExpr->IgnoreParenImpCasts();
8215 RHSExpr = RHSExpr->IgnoreParenImpCasts();
8216 const DeclRefExpr *LHSDeclRef = dyn_cast<DeclRefExpr>(LHSExpr);
8217 const DeclRefExpr *RHSDeclRef = dyn_cast<DeclRefExpr>(RHSExpr);
8218 if (!LHSDeclRef || !RHSDeclRef ||
8219 LHSDeclRef->getLocation().isMacroID() ||
8220 RHSDeclRef->getLocation().isMacroID())
Chandler Carruthe0cee6a2011-01-04 06:52:15 +00008221 return;
Richard Trieuda4f43a62011-09-07 01:33:52 +00008222 const ValueDecl *LHSDecl =
8223 cast<ValueDecl>(LHSDeclRef->getDecl()->getCanonicalDecl());
8224 const ValueDecl *RHSDecl =
8225 cast<ValueDecl>(RHSDeclRef->getDecl()->getCanonicalDecl());
8226 if (LHSDecl != RHSDecl)
Chandler Carruthe0cee6a2011-01-04 06:52:15 +00008227 return;
Richard Trieuda4f43a62011-09-07 01:33:52 +00008228 if (LHSDecl->getType().isVolatileQualified())
Chandler Carruthe0cee6a2011-01-04 06:52:15 +00008229 return;
Richard Trieuda4f43a62011-09-07 01:33:52 +00008230 if (const ReferenceType *RefTy = LHSDecl->getType()->getAs<ReferenceType>())
Chandler Carruthe0cee6a2011-01-04 06:52:15 +00008231 if (RefTy->getPointeeType().isVolatileQualified())
8232 return;
8233
8234 S.Diag(OpLoc, diag::warn_self_assignment)
Richard Trieuda4f43a62011-09-07 01:33:52 +00008235 << LHSDeclRef->getType()
8236 << LHSExpr->getSourceRange() << RHSExpr->getSourceRange();
Chandler Carruthe0cee6a2011-01-04 06:52:15 +00008237}
8238
Douglas Gregor7d5fc7e2008-11-06 23:29:22 +00008239/// CreateBuiltinBinOp - Creates a new built-in binary operation with
8240/// operator @p Opc at location @c TokLoc. This routine only supports
8241/// built-in operations; ActOnBinOp handles overloaded operators.
John McCalldadc5752010-08-24 06:29:42 +00008242ExprResult Sema::CreateBuiltinBinOp(SourceLocation OpLoc,
Argyrios Kyrtzidis7a808c02011-01-05 20:09:36 +00008243 BinaryOperatorKind Opc,
Richard Trieu4a287fb2011-09-07 01:49:20 +00008244 Expr *LHSExpr, Expr *RHSExpr) {
David Blaikiebbafb8a2012-03-11 07:00:24 +00008245 if (getLangOpts().CPlusPlus0x && isa<InitListExpr>(RHSExpr)) {
Sebastian Redl67766732012-02-27 20:34:02 +00008246 // The syntax only allows initializer lists on the RHS of assignment,
8247 // so we don't need to worry about accepting invalid code for
8248 // non-assignment operators.
8249 // C++11 5.17p9:
8250 // The meaning of x = {v} [...] is that of x = T(v) [...]. The meaning
8251 // of x = {} is x = T().
8252 InitializationKind Kind =
8253 InitializationKind::CreateDirectList(RHSExpr->getLocStart());
8254 InitializedEntity Entity =
8255 InitializedEntity::InitializeTemporary(LHSExpr->getType());
8256 InitializationSequence InitSeq(*this, Entity, Kind, &RHSExpr, 1);
Benjamin Kramercc4c49d2012-08-23 23:38:35 +00008257 ExprResult Init = InitSeq.Perform(*this, Entity, Kind, RHSExpr);
Sebastian Redl67766732012-02-27 20:34:02 +00008258 if (Init.isInvalid())
8259 return Init;
8260 RHSExpr = Init.take();
8261 }
8262
Richard Trieu4a287fb2011-09-07 01:49:20 +00008263 ExprResult LHS = Owned(LHSExpr), RHS = Owned(RHSExpr);
Eli Friedman8b7b1b12009-03-28 01:22:36 +00008264 QualType ResultTy; // Result type of the binary operator.
Eli Friedman8b7b1b12009-03-28 01:22:36 +00008265 // The following two variables are used for compound assignment operators
8266 QualType CompLHSTy; // Type of LHS after promotions for computation
8267 QualType CompResultTy; // Type of computation result
John McCall7decc9e2010-11-18 06:31:45 +00008268 ExprValueKind VK = VK_RValue;
8269 ExprObjectKind OK = OK_Ordinary;
Douglas Gregor7d5fc7e2008-11-06 23:29:22 +00008270
8271 switch (Opc) {
John McCalle3027922010-08-25 11:45:40 +00008272 case BO_Assign:
Richard Trieu4a287fb2011-09-07 01:49:20 +00008273 ResultTy = CheckAssignmentOperands(LHS.get(), RHS, OpLoc, QualType());
David Blaikiebbafb8a2012-03-11 07:00:24 +00008274 if (getLangOpts().CPlusPlus &&
Richard Trieu4a287fb2011-09-07 01:49:20 +00008275 LHS.get()->getObjectKind() != OK_ObjCProperty) {
8276 VK = LHS.get()->getValueKind();
8277 OK = LHS.get()->getObjectKind();
John McCall7decc9e2010-11-18 06:31:45 +00008278 }
Chandler Carruthe0cee6a2011-01-04 06:52:15 +00008279 if (!ResultTy.isNull())
Richard Trieu4a287fb2011-09-07 01:49:20 +00008280 DiagnoseSelfAssignment(*this, LHS.get(), RHS.get(), OpLoc);
Douglas Gregor7d5fc7e2008-11-06 23:29:22 +00008281 break;
John McCalle3027922010-08-25 11:45:40 +00008282 case BO_PtrMemD:
8283 case BO_PtrMemI:
Richard Trieu4a287fb2011-09-07 01:49:20 +00008284 ResultTy = CheckPointerToMemberOperands(LHS, RHS, VK, OpLoc,
John McCalle3027922010-08-25 11:45:40 +00008285 Opc == BO_PtrMemI);
Sebastian Redl112a97662009-02-07 00:15:38 +00008286 break;
John McCalle3027922010-08-25 11:45:40 +00008287 case BO_Mul:
8288 case BO_Div:
Richard Trieu4a287fb2011-09-07 01:49:20 +00008289 ResultTy = CheckMultiplyDivideOperands(LHS, RHS, OpLoc, false,
John McCalle3027922010-08-25 11:45:40 +00008290 Opc == BO_Div);
Douglas Gregor7d5fc7e2008-11-06 23:29:22 +00008291 break;
John McCalle3027922010-08-25 11:45:40 +00008292 case BO_Rem:
Richard Trieu4a287fb2011-09-07 01:49:20 +00008293 ResultTy = CheckRemainderOperands(LHS, RHS, OpLoc);
Douglas Gregor7d5fc7e2008-11-06 23:29:22 +00008294 break;
John McCalle3027922010-08-25 11:45:40 +00008295 case BO_Add:
Nico Weberccec40d2012-03-02 22:01:22 +00008296 ResultTy = CheckAdditionOperands(LHS, RHS, OpLoc, Opc);
Douglas Gregor7d5fc7e2008-11-06 23:29:22 +00008297 break;
John McCalle3027922010-08-25 11:45:40 +00008298 case BO_Sub:
Richard Trieu4a287fb2011-09-07 01:49:20 +00008299 ResultTy = CheckSubtractionOperands(LHS, RHS, OpLoc);
Douglas Gregor7d5fc7e2008-11-06 23:29:22 +00008300 break;
John McCalle3027922010-08-25 11:45:40 +00008301 case BO_Shl:
8302 case BO_Shr:
Richard Trieu4a287fb2011-09-07 01:49:20 +00008303 ResultTy = CheckShiftOperands(LHS, RHS, OpLoc, Opc);
Douglas Gregor7d5fc7e2008-11-06 23:29:22 +00008304 break;
John McCalle3027922010-08-25 11:45:40 +00008305 case BO_LE:
8306 case BO_LT:
8307 case BO_GE:
8308 case BO_GT:
Richard Trieu4a287fb2011-09-07 01:49:20 +00008309 ResultTy = CheckCompareOperands(LHS, RHS, OpLoc, Opc, true);
Douglas Gregor7d5fc7e2008-11-06 23:29:22 +00008310 break;
John McCalle3027922010-08-25 11:45:40 +00008311 case BO_EQ:
8312 case BO_NE:
Richard Trieu4a287fb2011-09-07 01:49:20 +00008313 ResultTy = CheckCompareOperands(LHS, RHS, OpLoc, Opc, false);
Douglas Gregor7d5fc7e2008-11-06 23:29:22 +00008314 break;
John McCalle3027922010-08-25 11:45:40 +00008315 case BO_And:
8316 case BO_Xor:
8317 case BO_Or:
Richard Trieu4a287fb2011-09-07 01:49:20 +00008318 ResultTy = CheckBitwiseOperands(LHS, RHS, OpLoc);
Douglas Gregor7d5fc7e2008-11-06 23:29:22 +00008319 break;
John McCalle3027922010-08-25 11:45:40 +00008320 case BO_LAnd:
8321 case BO_LOr:
Richard Trieu4a287fb2011-09-07 01:49:20 +00008322 ResultTy = CheckLogicalOperands(LHS, RHS, OpLoc, Opc);
Douglas Gregor7d5fc7e2008-11-06 23:29:22 +00008323 break;
John McCalle3027922010-08-25 11:45:40 +00008324 case BO_MulAssign:
8325 case BO_DivAssign:
Richard Trieu4a287fb2011-09-07 01:49:20 +00008326 CompResultTy = CheckMultiplyDivideOperands(LHS, RHS, OpLoc, true,
John McCall7decc9e2010-11-18 06:31:45 +00008327 Opc == BO_DivAssign);
Eli Friedman8b7b1b12009-03-28 01:22:36 +00008328 CompLHSTy = CompResultTy;
Richard Trieu4a287fb2011-09-07 01:49:20 +00008329 if (!CompResultTy.isNull() && !LHS.isInvalid() && !RHS.isInvalid())
8330 ResultTy = CheckAssignmentOperands(LHS.get(), RHS, OpLoc, CompResultTy);
Douglas Gregor7d5fc7e2008-11-06 23:29:22 +00008331 break;
John McCalle3027922010-08-25 11:45:40 +00008332 case BO_RemAssign:
Richard Trieu4a287fb2011-09-07 01:49:20 +00008333 CompResultTy = CheckRemainderOperands(LHS, RHS, OpLoc, true);
Eli Friedman8b7b1b12009-03-28 01:22:36 +00008334 CompLHSTy = CompResultTy;
Richard Trieu4a287fb2011-09-07 01:49:20 +00008335 if (!CompResultTy.isNull() && !LHS.isInvalid() && !RHS.isInvalid())
8336 ResultTy = CheckAssignmentOperands(LHS.get(), RHS, OpLoc, CompResultTy);
Douglas Gregor7d5fc7e2008-11-06 23:29:22 +00008337 break;
John McCalle3027922010-08-25 11:45:40 +00008338 case BO_AddAssign:
Nico Weberccec40d2012-03-02 22:01:22 +00008339 CompResultTy = CheckAdditionOperands(LHS, RHS, OpLoc, Opc, &CompLHSTy);
Richard Trieu4a287fb2011-09-07 01:49:20 +00008340 if (!CompResultTy.isNull() && !LHS.isInvalid() && !RHS.isInvalid())
8341 ResultTy = CheckAssignmentOperands(LHS.get(), RHS, OpLoc, CompResultTy);
Douglas Gregor7d5fc7e2008-11-06 23:29:22 +00008342 break;
John McCalle3027922010-08-25 11:45:40 +00008343 case BO_SubAssign:
Richard Trieu4a287fb2011-09-07 01:49:20 +00008344 CompResultTy = CheckSubtractionOperands(LHS, RHS, OpLoc, &CompLHSTy);
8345 if (!CompResultTy.isNull() && !LHS.isInvalid() && !RHS.isInvalid())
8346 ResultTy = CheckAssignmentOperands(LHS.get(), RHS, OpLoc, CompResultTy);
Douglas Gregor7d5fc7e2008-11-06 23:29:22 +00008347 break;
John McCalle3027922010-08-25 11:45:40 +00008348 case BO_ShlAssign:
8349 case BO_ShrAssign:
Richard Trieu4a287fb2011-09-07 01:49:20 +00008350 CompResultTy = CheckShiftOperands(LHS, RHS, OpLoc, Opc, true);
Eli Friedman8b7b1b12009-03-28 01:22:36 +00008351 CompLHSTy = CompResultTy;
Richard Trieu4a287fb2011-09-07 01:49:20 +00008352 if (!CompResultTy.isNull() && !LHS.isInvalid() && !RHS.isInvalid())
8353 ResultTy = CheckAssignmentOperands(LHS.get(), RHS, OpLoc, CompResultTy);
Douglas Gregor7d5fc7e2008-11-06 23:29:22 +00008354 break;
John McCalle3027922010-08-25 11:45:40 +00008355 case BO_AndAssign:
8356 case BO_XorAssign:
8357 case BO_OrAssign:
Richard Trieu4a287fb2011-09-07 01:49:20 +00008358 CompResultTy = CheckBitwiseOperands(LHS, RHS, OpLoc, true);
Eli Friedman8b7b1b12009-03-28 01:22:36 +00008359 CompLHSTy = CompResultTy;
Richard Trieu4a287fb2011-09-07 01:49:20 +00008360 if (!CompResultTy.isNull() && !LHS.isInvalid() && !RHS.isInvalid())
8361 ResultTy = CheckAssignmentOperands(LHS.get(), RHS, OpLoc, CompResultTy);
Douglas Gregor7d5fc7e2008-11-06 23:29:22 +00008362 break;
John McCalle3027922010-08-25 11:45:40 +00008363 case BO_Comma:
Richard Trieu4a287fb2011-09-07 01:49:20 +00008364 ResultTy = CheckCommaOperands(*this, LHS, RHS, OpLoc);
David Blaikiebbafb8a2012-03-11 07:00:24 +00008365 if (getLangOpts().CPlusPlus && !RHS.isInvalid()) {
Richard Trieu4a287fb2011-09-07 01:49:20 +00008366 VK = RHS.get()->getValueKind();
8367 OK = RHS.get()->getObjectKind();
John McCall7decc9e2010-11-18 06:31:45 +00008368 }
Douglas Gregor7d5fc7e2008-11-06 23:29:22 +00008369 break;
8370 }
Richard Trieu4a287fb2011-09-07 01:49:20 +00008371 if (ResultTy.isNull() || LHS.isInvalid() || RHS.isInvalid())
Sebastian Redlb5d49352009-01-19 22:31:54 +00008372 return ExprError();
Kaelyn Uhrain2e7aa5a2011-08-05 23:18:04 +00008373
8374 // Check for array bounds violations for both sides of the BinaryOperator
Richard Trieu4a287fb2011-09-07 01:49:20 +00008375 CheckArrayAccess(LHS.get());
8376 CheckArrayAccess(RHS.get());
Kaelyn Uhrain2e7aa5a2011-08-05 23:18:04 +00008377
Eli Friedman8b7b1b12009-03-28 01:22:36 +00008378 if (CompResultTy.isNull())
Richard Trieu4a287fb2011-09-07 01:49:20 +00008379 return Owned(new (Context) BinaryOperator(LHS.take(), RHS.take(), Opc,
John Wiegley01296292011-04-08 18:41:53 +00008380 ResultTy, VK, OK, OpLoc));
David Blaikiebbafb8a2012-03-11 07:00:24 +00008381 if (getLangOpts().CPlusPlus && LHS.get()->getObjectKind() !=
Richard Trieucfc491d2011-08-02 04:35:43 +00008382 OK_ObjCProperty) {
John McCall7decc9e2010-11-18 06:31:45 +00008383 VK = VK_LValue;
Richard Trieu4a287fb2011-09-07 01:49:20 +00008384 OK = LHS.get()->getObjectKind();
John McCall7decc9e2010-11-18 06:31:45 +00008385 }
Richard Trieu4a287fb2011-09-07 01:49:20 +00008386 return Owned(new (Context) CompoundAssignOperator(LHS.take(), RHS.take(), Opc,
John Wiegley01296292011-04-08 18:41:53 +00008387 ResultTy, VK, OK, CompLHSTy,
John McCall7decc9e2010-11-18 06:31:45 +00008388 CompResultTy, OpLoc));
Douglas Gregor7d5fc7e2008-11-06 23:29:22 +00008389}
8390
Sebastian Redl44615072009-10-27 12:10:02 +00008391/// DiagnoseBitwisePrecedence - Emit a warning when bitwise and comparison
8392/// operators are mixed in a way that suggests that the programmer forgot that
8393/// comparison operators have higher precedence. The most typical example of
8394/// such code is "flags & 0x0020 != 0", which is equivalent to "flags & 1".
John McCalle3027922010-08-25 11:45:40 +00008395static void DiagnoseBitwisePrecedence(Sema &Self, BinaryOperatorKind Opc,
Richard Trieu4a287fb2011-09-07 01:49:20 +00008396 SourceLocation OpLoc, Expr *LHSExpr,
8397 Expr *RHSExpr) {
Sebastian Redl44615072009-10-27 12:10:02 +00008398 typedef BinaryOperator BinOp;
Richard Trieu4a287fb2011-09-07 01:49:20 +00008399 BinOp::Opcode LHSopc = static_cast<BinOp::Opcode>(-1),
8400 RHSopc = static_cast<BinOp::Opcode>(-1);
8401 if (BinOp *BO = dyn_cast<BinOp>(LHSExpr))
8402 LHSopc = BO->getOpcode();
8403 if (BinOp *BO = dyn_cast<BinOp>(RHSExpr))
8404 RHSopc = BO->getOpcode();
Sebastian Redl43028242009-10-26 15:24:15 +00008405
8406 // Subs are not binary operators.
Richard Trieu4a287fb2011-09-07 01:49:20 +00008407 if (LHSopc == -1 && RHSopc == -1)
Sebastian Redl43028242009-10-26 15:24:15 +00008408 return;
8409
8410 // Bitwise operations are sometimes used as eager logical ops.
8411 // Don't diagnose this.
Richard Trieu4a287fb2011-09-07 01:49:20 +00008412 if ((BinOp::isComparisonOp(LHSopc) || BinOp::isBitwiseOp(LHSopc)) &&
8413 (BinOp::isComparisonOp(RHSopc) || BinOp::isBitwiseOp(RHSopc)))
Sebastian Redl43028242009-10-26 15:24:15 +00008414 return;
8415
Richard Trieu4a287fb2011-09-07 01:49:20 +00008416 bool isLeftComp = BinOp::isComparisonOp(LHSopc);
8417 bool isRightComp = BinOp::isComparisonOp(RHSopc);
Richard Trieu73088052011-08-10 22:41:34 +00008418 if (!isLeftComp && !isRightComp) return;
8419
Richard Trieu4a287fb2011-09-07 01:49:20 +00008420 SourceRange DiagRange = isLeftComp ? SourceRange(LHSExpr->getLocStart(),
8421 OpLoc)
8422 : SourceRange(OpLoc, RHSExpr->getLocEnd());
8423 std::string OpStr = isLeftComp ? BinOp::getOpcodeStr(LHSopc)
8424 : BinOp::getOpcodeStr(RHSopc);
Richard Trieu73088052011-08-10 22:41:34 +00008425 SourceRange ParensRange = isLeftComp ?
Richard Trieu4a287fb2011-09-07 01:49:20 +00008426 SourceRange(cast<BinOp>(LHSExpr)->getRHS()->getLocStart(),
8427 RHSExpr->getLocEnd())
8428 : SourceRange(LHSExpr->getLocStart(),
8429 cast<BinOp>(RHSExpr)->getLHS()->getLocStart());
Richard Trieu73088052011-08-10 22:41:34 +00008430
8431 Self.Diag(OpLoc, diag::warn_precedence_bitwise_rel)
8432 << DiagRange << BinOp::getOpcodeStr(Opc) << OpStr;
8433 SuggestParentheses(Self, OpLoc,
8434 Self.PDiag(diag::note_precedence_bitwise_silence) << OpStr,
Nico Webercdfb1ae2012-06-03 07:07:00 +00008435 (isLeftComp ? LHSExpr : RHSExpr)->getSourceRange());
Richard Trieu73088052011-08-10 22:41:34 +00008436 SuggestParentheses(Self, OpLoc,
8437 Self.PDiag(diag::note_precedence_bitwise_first) << BinOp::getOpcodeStr(Opc),
8438 ParensRange);
Sebastian Redl43028242009-10-26 15:24:15 +00008439}
8440
Argyrios Kyrtzidis01bf7772011-06-20 18:41:26 +00008441/// \brief It accepts a '&' expr that is inside a '|' one.
8442/// Emit a diagnostic together with a fixit hint that wraps the '&' expression
8443/// in parentheses.
8444static void
8445EmitDiagnosticForBitwiseAndInBitwiseOr(Sema &Self, SourceLocation OpLoc,
8446 BinaryOperator *Bop) {
8447 assert(Bop->getOpcode() == BO_And);
8448 Self.Diag(Bop->getOperatorLoc(), diag::warn_bitwise_and_in_bitwise_or)
8449 << Bop->getSourceRange() << OpLoc;
8450 SuggestParentheses(Self, Bop->getOperatorLoc(),
8451 Self.PDiag(diag::note_bitwise_and_in_bitwise_or_silence),
8452 Bop->getSourceRange());
8453}
8454
Argyrios Kyrtzidis14a96622010-11-17 18:26:36 +00008455/// \brief It accepts a '&&' expr that is inside a '||' one.
8456/// Emit a diagnostic together with a fixit hint that wraps the '&&' expression
8457/// in parentheses.
8458static void
8459EmitDiagnosticForLogicalAndInLogicalOr(Sema &Self, SourceLocation OpLoc,
Argyrios Kyrtzidisad8b4d42011-04-22 19:16:27 +00008460 BinaryOperator *Bop) {
8461 assert(Bop->getOpcode() == BO_LAnd);
Chandler Carruthb00e8c02011-06-16 01:05:14 +00008462 Self.Diag(Bop->getOperatorLoc(), diag::warn_logical_and_in_logical_or)
8463 << Bop->getSourceRange() << OpLoc;
Argyrios Kyrtzidisad8b4d42011-04-22 19:16:27 +00008464 SuggestParentheses(Self, Bop->getOperatorLoc(),
Argyrios Kyrtzidis14a96622010-11-17 18:26:36 +00008465 Self.PDiag(diag::note_logical_and_in_logical_or_silence),
Chandler Carruthb00e8c02011-06-16 01:05:14 +00008466 Bop->getSourceRange());
Argyrios Kyrtzidis14a96622010-11-17 18:26:36 +00008467}
8468
8469/// \brief Returns true if the given expression can be evaluated as a constant
8470/// 'true'.
8471static bool EvaluatesAsTrue(Sema &S, Expr *E) {
8472 bool Res;
8473 return E->EvaluateAsBooleanCondition(Res, S.getASTContext()) && Res;
8474}
8475
Argyrios Kyrtzidis56e879d2010-11-17 19:18:19 +00008476/// \brief Returns true if the given expression can be evaluated as a constant
8477/// 'false'.
8478static bool EvaluatesAsFalse(Sema &S, Expr *E) {
8479 bool Res;
8480 return E->EvaluateAsBooleanCondition(Res, S.getASTContext()) && !Res;
8481}
8482
Argyrios Kyrtzidis14a96622010-11-17 18:26:36 +00008483/// \brief Look for '&&' in the left hand of a '||' expr.
8484static void DiagnoseLogicalAndInLogicalOrLHS(Sema &S, SourceLocation OpLoc,
Richard Trieuf9bd0f52011-09-07 02:02:10 +00008485 Expr *LHSExpr, Expr *RHSExpr) {
8486 if (BinaryOperator *Bop = dyn_cast<BinaryOperator>(LHSExpr)) {
Argyrios Kyrtzidisf89a56c2010-11-16 21:00:12 +00008487 if (Bop->getOpcode() == BO_LAnd) {
Argyrios Kyrtzidis56e879d2010-11-17 19:18:19 +00008488 // If it's "a && b || 0" don't warn since the precedence doesn't matter.
Richard Trieuf9bd0f52011-09-07 02:02:10 +00008489 if (EvaluatesAsFalse(S, RHSExpr))
Argyrios Kyrtzidis56e879d2010-11-17 19:18:19 +00008490 return;
Argyrios Kyrtzidis14a96622010-11-17 18:26:36 +00008491 // If it's "1 && a || b" don't warn since the precedence doesn't matter.
8492 if (!EvaluatesAsTrue(S, Bop->getLHS()))
8493 return EmitDiagnosticForLogicalAndInLogicalOr(S, OpLoc, Bop);
8494 } else if (Bop->getOpcode() == BO_LOr) {
8495 if (BinaryOperator *RBop = dyn_cast<BinaryOperator>(Bop->getRHS())) {
8496 // If it's "a || b && 1 || c" we didn't warn earlier for
8497 // "a || b && 1", but warn now.
8498 if (RBop->getOpcode() == BO_LAnd && EvaluatesAsTrue(S, RBop->getRHS()))
8499 return EmitDiagnosticForLogicalAndInLogicalOr(S, OpLoc, RBop);
8500 }
8501 }
8502 }
8503}
8504
8505/// \brief Look for '&&' in the right hand of a '||' expr.
8506static void DiagnoseLogicalAndInLogicalOrRHS(Sema &S, SourceLocation OpLoc,
Richard Trieuf9bd0f52011-09-07 02:02:10 +00008507 Expr *LHSExpr, Expr *RHSExpr) {
8508 if (BinaryOperator *Bop = dyn_cast<BinaryOperator>(RHSExpr)) {
Argyrios Kyrtzidis14a96622010-11-17 18:26:36 +00008509 if (Bop->getOpcode() == BO_LAnd) {
Argyrios Kyrtzidis56e879d2010-11-17 19:18:19 +00008510 // If it's "0 || a && b" don't warn since the precedence doesn't matter.
Richard Trieuf9bd0f52011-09-07 02:02:10 +00008511 if (EvaluatesAsFalse(S, LHSExpr))
Argyrios Kyrtzidis56e879d2010-11-17 19:18:19 +00008512 return;
Argyrios Kyrtzidis14a96622010-11-17 18:26:36 +00008513 // If it's "a || b && 1" don't warn since the precedence doesn't matter.
8514 if (!EvaluatesAsTrue(S, Bop->getRHS()))
8515 return EmitDiagnosticForLogicalAndInLogicalOr(S, OpLoc, Bop);
Argyrios Kyrtzidisf89a56c2010-11-16 21:00:12 +00008516 }
8517 }
8518}
8519
Argyrios Kyrtzidis01bf7772011-06-20 18:41:26 +00008520/// \brief Look for '&' in the left or right hand of a '|' expr.
8521static void DiagnoseBitwiseAndInBitwiseOr(Sema &S, SourceLocation OpLoc,
8522 Expr *OrArg) {
8523 if (BinaryOperator *Bop = dyn_cast<BinaryOperator>(OrArg)) {
8524 if (Bop->getOpcode() == BO_And)
8525 return EmitDiagnosticForBitwiseAndInBitwiseOr(S, OpLoc, Bop);
8526 }
8527}
8528
Sebastian Redl43028242009-10-26 15:24:15 +00008529/// DiagnoseBinOpPrecedence - Emit warnings for expressions with tricky
Argyrios Kyrtzidisf89a56c2010-11-16 21:00:12 +00008530/// precedence.
John McCalle3027922010-08-25 11:45:40 +00008531static void DiagnoseBinOpPrecedence(Sema &Self, BinaryOperatorKind Opc,
Richard Trieuf9bd0f52011-09-07 02:02:10 +00008532 SourceLocation OpLoc, Expr *LHSExpr,
8533 Expr *RHSExpr){
Argyrios Kyrtzidisf89a56c2010-11-16 21:00:12 +00008534 // Diagnose "arg1 'bitwise' arg2 'eq' arg3".
Sebastian Redl44615072009-10-27 12:10:02 +00008535 if (BinaryOperator::isBitwiseOp(Opc))
Richard Trieuf9bd0f52011-09-07 02:02:10 +00008536 DiagnoseBitwisePrecedence(Self, Opc, OpLoc, LHSExpr, RHSExpr);
Argyrios Kyrtzidis01bf7772011-06-20 18:41:26 +00008537
8538 // Diagnose "arg1 & arg2 | arg3"
8539 if (Opc == BO_Or && !OpLoc.isMacroID()/* Don't warn in macros. */) {
Richard Trieuf9bd0f52011-09-07 02:02:10 +00008540 DiagnoseBitwiseAndInBitwiseOr(Self, OpLoc, LHSExpr);
8541 DiagnoseBitwiseAndInBitwiseOr(Self, OpLoc, RHSExpr);
Argyrios Kyrtzidis01bf7772011-06-20 18:41:26 +00008542 }
Argyrios Kyrtzidisf89a56c2010-11-16 21:00:12 +00008543
Argyrios Kyrtzidis14a96622010-11-17 18:26:36 +00008544 // Warn about arg1 || arg2 && arg3, as GCC 4.3+ does.
8545 // We don't warn for 'assert(a || b && "bad")' since this is safe.
Argyrios Kyrtzidisb94e5a32010-11-17 18:54:22 +00008546 if (Opc == BO_LOr && !OpLoc.isMacroID()/* Don't warn in macros. */) {
Richard Trieuf9bd0f52011-09-07 02:02:10 +00008547 DiagnoseLogicalAndInLogicalOrLHS(Self, OpLoc, LHSExpr, RHSExpr);
8548 DiagnoseLogicalAndInLogicalOrRHS(Self, OpLoc, LHSExpr, RHSExpr);
Argyrios Kyrtzidisf89a56c2010-11-16 21:00:12 +00008549 }
Sebastian Redl43028242009-10-26 15:24:15 +00008550}
8551
Steve Naroff218bc2b2007-05-04 21:54:46 +00008552// Binary Operators. 'Tok' is the token for the operator.
John McCalldadc5752010-08-24 06:29:42 +00008553ExprResult Sema::ActOnBinOp(Scope *S, SourceLocation TokLoc,
John McCalle3027922010-08-25 11:45:40 +00008554 tok::TokenKind Kind,
Richard Trieuf9bd0f52011-09-07 02:02:10 +00008555 Expr *LHSExpr, Expr *RHSExpr) {
John McCalle3027922010-08-25 11:45:40 +00008556 BinaryOperatorKind Opc = ConvertTokenKindToBinaryOpcode(Kind);
Richard Trieuf9bd0f52011-09-07 02:02:10 +00008557 assert((LHSExpr != 0) && "ActOnBinOp(): missing left expression");
8558 assert((RHSExpr != 0) && "ActOnBinOp(): missing right expression");
Steve Naroff218bc2b2007-05-04 21:54:46 +00008559
Sebastian Redl43028242009-10-26 15:24:15 +00008560 // Emit warnings for tricky precedence issues, e.g. "bitfield & 0x4 == 0"
Richard Trieuf9bd0f52011-09-07 02:02:10 +00008561 DiagnoseBinOpPrecedence(*this, Opc, TokLoc, LHSExpr, RHSExpr);
Sebastian Redl43028242009-10-26 15:24:15 +00008562
Richard Trieuf9bd0f52011-09-07 02:02:10 +00008563 return BuildBinOp(S, TokLoc, Opc, LHSExpr, RHSExpr);
Douglas Gregor5287f092009-11-05 00:51:44 +00008564}
8565
John McCall526ab472011-10-25 17:37:35 +00008566/// Build an overloaded binary operator expression in the given scope.
8567static ExprResult BuildOverloadedBinOp(Sema &S, Scope *Sc, SourceLocation OpLoc,
8568 BinaryOperatorKind Opc,
8569 Expr *LHS, Expr *RHS) {
8570 // Find all of the overloaded operators visible from this
8571 // point. We perform both an operator-name lookup from the local
8572 // scope and an argument-dependent lookup based on the types of
8573 // the arguments.
8574 UnresolvedSet<16> Functions;
8575 OverloadedOperatorKind OverOp
8576 = BinaryOperator::getOverloadedOperator(Opc);
8577 if (Sc && OverOp != OO_None)
8578 S.LookupOverloadedOperatorName(OverOp, Sc, LHS->getType(),
8579 RHS->getType(), Functions);
8580
8581 // Build the (potentially-overloaded, potentially-dependent)
8582 // binary operation.
8583 return S.CreateOverloadedBinOp(OpLoc, Opc, Functions, LHS, RHS);
8584}
8585
John McCalldadc5752010-08-24 06:29:42 +00008586ExprResult Sema::BuildBinOp(Scope *S, SourceLocation OpLoc,
John McCalle3027922010-08-25 11:45:40 +00008587 BinaryOperatorKind Opc,
Richard Trieuf9bd0f52011-09-07 02:02:10 +00008588 Expr *LHSExpr, Expr *RHSExpr) {
John McCall9a43e122011-10-28 01:04:34 +00008589 // We want to end up calling one of checkPseudoObjectAssignment
8590 // (if the LHS is a pseudo-object), BuildOverloadedBinOp (if
8591 // both expressions are overloadable or either is type-dependent),
8592 // or CreateBuiltinBinOp (in any other case). We also want to get
8593 // any placeholder types out of the way.
8594
John McCall526ab472011-10-25 17:37:35 +00008595 // Handle pseudo-objects in the LHS.
8596 if (const BuiltinType *pty = LHSExpr->getType()->getAsPlaceholderType()) {
8597 // Assignments with a pseudo-object l-value need special analysis.
8598 if (pty->getKind() == BuiltinType::PseudoObject &&
8599 BinaryOperator::isAssignmentOp(Opc))
8600 return checkPseudoObjectAssignment(S, OpLoc, Opc, LHSExpr, RHSExpr);
8601
8602 // Don't resolve overloads if the other type is overloadable.
8603 if (pty->getKind() == BuiltinType::Overload) {
8604 // We can't actually test that if we still have a placeholder,
8605 // though. Fortunately, none of the exceptions we see in that
John McCall9a43e122011-10-28 01:04:34 +00008606 // code below are valid when the LHS is an overload set. Note
8607 // that an overload set can be dependently-typed, but it never
8608 // instantiates to having an overloadable type.
John McCall526ab472011-10-25 17:37:35 +00008609 ExprResult resolvedRHS = CheckPlaceholderExpr(RHSExpr);
8610 if (resolvedRHS.isInvalid()) return ExprError();
8611 RHSExpr = resolvedRHS.take();
8612
John McCall9a43e122011-10-28 01:04:34 +00008613 if (RHSExpr->isTypeDependent() ||
8614 RHSExpr->getType()->isOverloadableType())
John McCall526ab472011-10-25 17:37:35 +00008615 return BuildOverloadedBinOp(*this, S, OpLoc, Opc, LHSExpr, RHSExpr);
8616 }
8617
8618 ExprResult LHS = CheckPlaceholderExpr(LHSExpr);
8619 if (LHS.isInvalid()) return ExprError();
8620 LHSExpr = LHS.take();
8621 }
8622
8623 // Handle pseudo-objects in the RHS.
8624 if (const BuiltinType *pty = RHSExpr->getType()->getAsPlaceholderType()) {
8625 // An overload in the RHS can potentially be resolved by the type
8626 // being assigned to.
John McCall9a43e122011-10-28 01:04:34 +00008627 if (Opc == BO_Assign && pty->getKind() == BuiltinType::Overload) {
8628 if (LHSExpr->isTypeDependent() || RHSExpr->isTypeDependent())
8629 return BuildOverloadedBinOp(*this, S, OpLoc, Opc, LHSExpr, RHSExpr);
8630
Eli Friedman419b1ff2012-01-17 21:27:43 +00008631 if (LHSExpr->getType()->isOverloadableType())
8632 return BuildOverloadedBinOp(*this, S, OpLoc, Opc, LHSExpr, RHSExpr);
8633
John McCall526ab472011-10-25 17:37:35 +00008634 return CreateBuiltinBinOp(OpLoc, Opc, LHSExpr, RHSExpr);
John McCall9a43e122011-10-28 01:04:34 +00008635 }
John McCall526ab472011-10-25 17:37:35 +00008636
8637 // Don't resolve overloads if the other type is overloadable.
8638 if (pty->getKind() == BuiltinType::Overload &&
8639 LHSExpr->getType()->isOverloadableType())
8640 return BuildOverloadedBinOp(*this, S, OpLoc, Opc, LHSExpr, RHSExpr);
8641
8642 ExprResult resolvedRHS = CheckPlaceholderExpr(RHSExpr);
8643 if (!resolvedRHS.isUsable()) return ExprError();
8644 RHSExpr = resolvedRHS.take();
8645 }
8646
David Blaikiebbafb8a2012-03-11 07:00:24 +00008647 if (getLangOpts().CPlusPlus) {
John McCall9a43e122011-10-28 01:04:34 +00008648 // If either expression is type-dependent, always build an
8649 // overloaded op.
8650 if (LHSExpr->isTypeDependent() || RHSExpr->isTypeDependent())
8651 return BuildOverloadedBinOp(*this, S, OpLoc, Opc, LHSExpr, RHSExpr);
Kovarththanan Rajaratnamba2c6522010-03-13 10:17:05 +00008652
John McCall9a43e122011-10-28 01:04:34 +00008653 // Otherwise, build an overloaded op if either expression has an
8654 // overloadable type.
8655 if (LHSExpr->getType()->isOverloadableType() ||
8656 RHSExpr->getType()->isOverloadableType())
John McCall526ab472011-10-25 17:37:35 +00008657 return BuildOverloadedBinOp(*this, S, OpLoc, Opc, LHSExpr, RHSExpr);
Sebastian Redlb5d49352009-01-19 22:31:54 +00008658 }
Kovarththanan Rajaratnamba2c6522010-03-13 10:17:05 +00008659
Douglas Gregor7d5fc7e2008-11-06 23:29:22 +00008660 // Build a built-in binary operation.
Richard Trieuf9bd0f52011-09-07 02:02:10 +00008661 return CreateBuiltinBinOp(OpLoc, Opc, LHSExpr, RHSExpr);
Steve Naroff218bc2b2007-05-04 21:54:46 +00008662}
8663
John McCalldadc5752010-08-24 06:29:42 +00008664ExprResult Sema::CreateBuiltinUnaryOp(SourceLocation OpLoc,
Argyrios Kyrtzidis7a808c02011-01-05 20:09:36 +00008665 UnaryOperatorKind Opc,
John Wiegley01296292011-04-08 18:41:53 +00008666 Expr *InputExpr) {
8667 ExprResult Input = Owned(InputExpr);
John McCall7decc9e2010-11-18 06:31:45 +00008668 ExprValueKind VK = VK_RValue;
8669 ExprObjectKind OK = OK_Ordinary;
Steve Naroff35d85152007-05-07 00:24:15 +00008670 QualType resultType;
8671 switch (Opc) {
John McCalle3027922010-08-25 11:45:40 +00008672 case UO_PreInc:
8673 case UO_PreDec:
8674 case UO_PostInc:
8675 case UO_PostDec:
John Wiegley01296292011-04-08 18:41:53 +00008676 resultType = CheckIncrementDecrementOperand(*this, Input.get(), VK, OpLoc,
John McCalle3027922010-08-25 11:45:40 +00008677 Opc == UO_PreInc ||
8678 Opc == UO_PostInc,
8679 Opc == UO_PreInc ||
8680 Opc == UO_PreDec);
Steve Naroff35d85152007-05-07 00:24:15 +00008681 break;
John McCalle3027922010-08-25 11:45:40 +00008682 case UO_AddrOf:
John McCall526ab472011-10-25 17:37:35 +00008683 resultType = CheckAddressOfOperand(*this, Input, OpLoc);
Steve Naroff35d85152007-05-07 00:24:15 +00008684 break;
John McCall31996342011-04-07 08:22:57 +00008685 case UO_Deref: {
John Wiegley01296292011-04-08 18:41:53 +00008686 Input = DefaultFunctionArrayLvalueConversion(Input.take());
Eli Friedman34866c72012-08-31 00:14:07 +00008687 if (Input.isInvalid()) return ExprError();
John Wiegley01296292011-04-08 18:41:53 +00008688 resultType = CheckIndirectionOperand(*this, Input.get(), VK, OpLoc);
Steve Naroff35d85152007-05-07 00:24:15 +00008689 break;
John McCall31996342011-04-07 08:22:57 +00008690 }
John McCalle3027922010-08-25 11:45:40 +00008691 case UO_Plus:
8692 case UO_Minus:
John Wiegley01296292011-04-08 18:41:53 +00008693 Input = UsualUnaryConversions(Input.take());
8694 if (Input.isInvalid()) return ExprError();
8695 resultType = Input.get()->getType();
Sebastian Redl8d2ccae2009-02-26 14:39:58 +00008696 if (resultType->isDependentType())
8697 break;
Douglas Gregora3208f92010-06-22 23:41:02 +00008698 if (resultType->isArithmeticType() || // C99 6.5.3.3p1
8699 resultType->isVectorType())
Douglas Gregord08452f2008-11-19 15:42:04 +00008700 break;
David Blaikiebbafb8a2012-03-11 07:00:24 +00008701 else if (getLangOpts().CPlusPlus && // C++ [expr.unary.op]p6-7
Douglas Gregord08452f2008-11-19 15:42:04 +00008702 resultType->isEnumeralType())
8703 break;
David Blaikiebbafb8a2012-03-11 07:00:24 +00008704 else if (getLangOpts().CPlusPlus && // C++ [expr.unary.op]p6
John McCalle3027922010-08-25 11:45:40 +00008705 Opc == UO_Plus &&
Douglas Gregord08452f2008-11-19 15:42:04 +00008706 resultType->isPointerType())
8707 break;
8708
Sebastian Redlc215cfc2009-01-19 00:08:26 +00008709 return ExprError(Diag(OpLoc, diag::err_typecheck_unary_expr)
John Wiegley01296292011-04-08 18:41:53 +00008710 << resultType << Input.get()->getSourceRange());
8711
John McCalle3027922010-08-25 11:45:40 +00008712 case UO_Not: // bitwise complement
John Wiegley01296292011-04-08 18:41:53 +00008713 Input = UsualUnaryConversions(Input.take());
8714 if (Input.isInvalid()) return ExprError();
8715 resultType = Input.get()->getType();
Sebastian Redl8d2ccae2009-02-26 14:39:58 +00008716 if (resultType->isDependentType())
8717 break;
Chris Lattner0d707612008-07-25 23:52:49 +00008718 // C99 6.5.3.3p1. We allow complex int and float as a GCC extension.
8719 if (resultType->isComplexType() || resultType->isComplexIntegerType())
8720 // C99 does not support '~' for complex conjugation.
Chris Lattner29e812b2008-11-20 06:06:08 +00008721 Diag(OpLoc, diag::ext_integer_complement_complex)
John Wiegley01296292011-04-08 18:41:53 +00008722 << resultType << Input.get()->getSourceRange();
John McCall36226622010-10-12 02:09:17 +00008723 else if (resultType->hasIntegerRepresentation())
8724 break;
John McCall526ab472011-10-25 17:37:35 +00008725 else {
Sebastian Redlc215cfc2009-01-19 00:08:26 +00008726 return ExprError(Diag(OpLoc, diag::err_typecheck_unary_expr)
John Wiegley01296292011-04-08 18:41:53 +00008727 << resultType << Input.get()->getSourceRange());
John McCall36226622010-10-12 02:09:17 +00008728 }
Steve Naroff35d85152007-05-07 00:24:15 +00008729 break;
John Wiegley01296292011-04-08 18:41:53 +00008730
John McCalle3027922010-08-25 11:45:40 +00008731 case UO_LNot: // logical negation
Steve Naroff71b59a92007-06-04 22:22:31 +00008732 // Unlike +/-/~, integer promotions aren't done here (C99 6.5.3.3p5).
John Wiegley01296292011-04-08 18:41:53 +00008733 Input = DefaultFunctionArrayLvalueConversion(Input.take());
8734 if (Input.isInvalid()) return ExprError();
8735 resultType = Input.get()->getType();
Anton Korobeynikovf0c267e2011-10-14 23:23:15 +00008736
8737 // Though we still have to promote half FP to float...
8738 if (resultType->isHalfType()) {
8739 Input = ImpCastExprToType(Input.take(), Context.FloatTy, CK_FloatingCast).take();
8740 resultType = Context.FloatTy;
8741 }
8742
Sebastian Redl8d2ccae2009-02-26 14:39:58 +00008743 if (resultType->isDependentType())
8744 break;
Abramo Bagnara7ccce982011-04-07 09:26:19 +00008745 if (resultType->isScalarType()) {
8746 // C99 6.5.3.3p1: ok, fallthrough;
David Blaikiebbafb8a2012-03-11 07:00:24 +00008747 if (Context.getLangOpts().CPlusPlus) {
Abramo Bagnara7ccce982011-04-07 09:26:19 +00008748 // C++03 [expr.unary.op]p8, C++0x [expr.unary.op]p9:
8749 // operand contextually converted to bool.
John Wiegley01296292011-04-08 18:41:53 +00008750 Input = ImpCastExprToType(Input.take(), Context.BoolTy,
8751 ScalarTypeToBooleanCastKind(resultType));
Abramo Bagnara7ccce982011-04-07 09:26:19 +00008752 }
Tanya Lattner3dd33b22012-01-19 01:16:16 +00008753 } else if (resultType->isExtVectorType()) {
Tanya Lattner20248222012-01-16 21:02:28 +00008754 // Vector logical not returns the signed variant of the operand type.
8755 resultType = GetSignedVectorType(resultType);
8756 break;
John McCall36226622010-10-12 02:09:17 +00008757 } else {
Sebastian Redlc215cfc2009-01-19 00:08:26 +00008758 return ExprError(Diag(OpLoc, diag::err_typecheck_unary_expr)
John Wiegley01296292011-04-08 18:41:53 +00008759 << resultType << Input.get()->getSourceRange());
John McCall36226622010-10-12 02:09:17 +00008760 }
Douglas Gregordb8c6fd2010-09-20 17:13:33 +00008761
Chris Lattnerbe31ed82007-06-02 19:11:33 +00008762 // LNot always has type int. C99 6.5.3.3p5.
Sebastian Redlc215cfc2009-01-19 00:08:26 +00008763 // In C++, it's bool. C++ 5.3.1p8
Argyrios Kyrtzidis1bdd6882011-02-18 20:55:15 +00008764 resultType = Context.getLogicalOperationType();
Steve Naroff35d85152007-05-07 00:24:15 +00008765 break;
John McCalle3027922010-08-25 11:45:40 +00008766 case UO_Real:
8767 case UO_Imag:
John McCall4bc41ae2010-11-18 19:01:18 +00008768 resultType = CheckRealImagOperand(*this, Input, OpLoc, Opc == UO_Real);
Richard Smith0b6b8e42012-02-18 20:53:32 +00008769 // _Real maps ordinary l-values into ordinary l-values. _Imag maps ordinary
8770 // complex l-values to ordinary l-values and all other values to r-values.
John Wiegley01296292011-04-08 18:41:53 +00008771 if (Input.isInvalid()) return ExprError();
Richard Smith0b6b8e42012-02-18 20:53:32 +00008772 if (Opc == UO_Real || Input.get()->getType()->isAnyComplexType()) {
8773 if (Input.get()->getValueKind() != VK_RValue &&
8774 Input.get()->getObjectKind() == OK_Ordinary)
8775 VK = Input.get()->getValueKind();
David Blaikiebbafb8a2012-03-11 07:00:24 +00008776 } else if (!getLangOpts().CPlusPlus) {
Richard Smith0b6b8e42012-02-18 20:53:32 +00008777 // In C, a volatile scalar is read by __imag. In C++, it is not.
8778 Input = DefaultLvalueConversion(Input.take());
8779 }
Chris Lattner30b5dd02007-08-24 21:16:53 +00008780 break;
John McCalle3027922010-08-25 11:45:40 +00008781 case UO_Extension:
John Wiegley01296292011-04-08 18:41:53 +00008782 resultType = Input.get()->getType();
8783 VK = Input.get()->getValueKind();
8784 OK = Input.get()->getObjectKind();
Steve Naroff043d45d2007-05-15 02:32:35 +00008785 break;
Steve Naroff35d85152007-05-07 00:24:15 +00008786 }
John Wiegley01296292011-04-08 18:41:53 +00008787 if (resultType.isNull() || Input.isInvalid())
Sebastian Redlc215cfc2009-01-19 00:08:26 +00008788 return ExprError();
Douglas Gregor084d8552009-03-13 23:49:33 +00008789
Kaelyn Uhrain2e7aa5a2011-08-05 23:18:04 +00008790 // Check for array bounds violations in the operand of the UnaryOperator,
8791 // except for the '*' and '&' operators that have to be handled specially
8792 // by CheckArrayAccess (as there are special cases like &array[arraysize]
8793 // that are explicitly defined as valid by the standard).
8794 if (Opc != UO_AddrOf && Opc != UO_Deref)
8795 CheckArrayAccess(Input.get());
8796
John Wiegley01296292011-04-08 18:41:53 +00008797 return Owned(new (Context) UnaryOperator(Input.take(), Opc, resultType,
John McCall7decc9e2010-11-18 06:31:45 +00008798 VK, OK, OpLoc));
Steve Naroff35d85152007-05-07 00:24:15 +00008799}
Chris Lattnereefa10e2007-05-28 06:56:27 +00008800
Douglas Gregor72341032011-12-14 21:23:13 +00008801/// \brief Determine whether the given expression is a qualified member
8802/// access expression, of a form that could be turned into a pointer to member
8803/// with the address-of operator.
8804static bool isQualifiedMemberAccess(Expr *E) {
8805 if (DeclRefExpr *DRE = dyn_cast<DeclRefExpr>(E)) {
8806 if (!DRE->getQualifier())
8807 return false;
8808
8809 ValueDecl *VD = DRE->getDecl();
8810 if (!VD->isCXXClassMember())
8811 return false;
8812
8813 if (isa<FieldDecl>(VD) || isa<IndirectFieldDecl>(VD))
8814 return true;
8815 if (CXXMethodDecl *Method = dyn_cast<CXXMethodDecl>(VD))
8816 return Method->isInstance();
8817
8818 return false;
8819 }
8820
8821 if (UnresolvedLookupExpr *ULE = dyn_cast<UnresolvedLookupExpr>(E)) {
8822 if (!ULE->getQualifier())
8823 return false;
8824
8825 for (UnresolvedLookupExpr::decls_iterator D = ULE->decls_begin(),
8826 DEnd = ULE->decls_end();
8827 D != DEnd; ++D) {
8828 if (CXXMethodDecl *Method = dyn_cast<CXXMethodDecl>(*D)) {
8829 if (Method->isInstance())
8830 return true;
8831 } else {
8832 // Overload set does not contain methods.
8833 break;
8834 }
8835 }
8836
8837 return false;
8838 }
8839
8840 return false;
8841}
8842
John McCalldadc5752010-08-24 06:29:42 +00008843ExprResult Sema::BuildUnaryOp(Scope *S, SourceLocation OpLoc,
Richard Trieuba63ce62011-09-09 01:45:06 +00008844 UnaryOperatorKind Opc, Expr *Input) {
John McCall526ab472011-10-25 17:37:35 +00008845 // First things first: handle placeholders so that the
8846 // overloaded-operator check considers the right type.
8847 if (const BuiltinType *pty = Input->getType()->getAsPlaceholderType()) {
8848 // Increment and decrement of pseudo-object references.
8849 if (pty->getKind() == BuiltinType::PseudoObject &&
8850 UnaryOperator::isIncrementDecrementOp(Opc))
8851 return checkPseudoObjectIncDec(S, OpLoc, Opc, Input);
8852
8853 // extension is always a builtin operator.
8854 if (Opc == UO_Extension)
8855 return CreateBuiltinUnaryOp(OpLoc, Opc, Input);
8856
8857 // & gets special logic for several kinds of placeholder.
8858 // The builtin code knows what to do.
8859 if (Opc == UO_AddrOf &&
8860 (pty->getKind() == BuiltinType::Overload ||
8861 pty->getKind() == BuiltinType::UnknownAny ||
8862 pty->getKind() == BuiltinType::BoundMember))
8863 return CreateBuiltinUnaryOp(OpLoc, Opc, Input);
8864
8865 // Anything else needs to be handled now.
8866 ExprResult Result = CheckPlaceholderExpr(Input);
8867 if (Result.isInvalid()) return ExprError();
8868 Input = Result.take();
8869 }
8870
David Blaikiebbafb8a2012-03-11 07:00:24 +00008871 if (getLangOpts().CPlusPlus && Input->getType()->isOverloadableType() &&
Douglas Gregor72341032011-12-14 21:23:13 +00008872 UnaryOperator::getOverloadedOperator(Opc) != OO_None &&
8873 !(Opc == UO_AddrOf && isQualifiedMemberAccess(Input))) {
Douglas Gregor084d8552009-03-13 23:49:33 +00008874 // Find all of the overloaded operators visible from this
8875 // point. We perform both an operator-name lookup from the local
8876 // scope and an argument-dependent lookup based on the types of
8877 // the arguments.
John McCall4c4c1df2010-01-26 03:27:55 +00008878 UnresolvedSet<16> Functions;
Douglas Gregor084d8552009-03-13 23:49:33 +00008879 OverloadedOperatorKind OverOp = UnaryOperator::getOverloadedOperator(Opc);
John McCall4c4c1df2010-01-26 03:27:55 +00008880 if (S && OverOp != OO_None)
8881 LookupOverloadedOperatorName(OverOp, S, Input->getType(), QualType(),
8882 Functions);
Kovarththanan Rajaratnamba2c6522010-03-13 10:17:05 +00008883
John McCallb268a282010-08-23 23:25:46 +00008884 return CreateOverloadedUnaryOp(OpLoc, Opc, Functions, Input);
Douglas Gregor084d8552009-03-13 23:49:33 +00008885 }
Kovarththanan Rajaratnamba2c6522010-03-13 10:17:05 +00008886
John McCallb268a282010-08-23 23:25:46 +00008887 return CreateBuiltinUnaryOp(OpLoc, Opc, Input);
Douglas Gregor084d8552009-03-13 23:49:33 +00008888}
8889
Douglas Gregor5287f092009-11-05 00:51:44 +00008890// Unary Operators. 'Tok' is the token for the operator.
John McCalldadc5752010-08-24 06:29:42 +00008891ExprResult Sema::ActOnUnaryOp(Scope *S, SourceLocation OpLoc,
John McCall424cec92011-01-19 06:33:43 +00008892 tok::TokenKind Op, Expr *Input) {
John McCallb268a282010-08-23 23:25:46 +00008893 return BuildUnaryOp(S, OpLoc, ConvertTokenKindToUnaryOpcode(Op), Input);
Douglas Gregor5287f092009-11-05 00:51:44 +00008894}
8895
Steve Naroff66356bd2007-09-16 14:56:35 +00008896/// ActOnAddrLabel - Parse the GNU address of label extension: "&&foo".
Chris Lattnerc8e630e2011-02-17 07:39:24 +00008897ExprResult Sema::ActOnAddrLabel(SourceLocation OpLoc, SourceLocation LabLoc,
Chris Lattnercab02a62011-02-17 20:34:02 +00008898 LabelDecl *TheDecl) {
Chris Lattnerc8e630e2011-02-17 07:39:24 +00008899 TheDecl->setUsed();
Chris Lattnereefa10e2007-05-28 06:56:27 +00008900 // Create the AST node. The address of a label always has type 'void*'.
Chris Lattnerc8e630e2011-02-17 07:39:24 +00008901 return Owned(new (Context) AddrLabelExpr(OpLoc, LabLoc, TheDecl,
Sebastian Redl6d4256c2009-03-15 17:47:39 +00008902 Context.getPointerType(Context.VoidTy)));
Chris Lattnereefa10e2007-05-28 06:56:27 +00008903}
8904
John McCall31168b02011-06-15 23:02:42 +00008905/// Given the last statement in a statement-expression, check whether
8906/// the result is a producing expression (like a call to an
8907/// ns_returns_retained function) and, if so, rebuild it to hoist the
8908/// release out of the full-expression. Otherwise, return null.
8909/// Cannot fail.
Richard Trieuba63ce62011-09-09 01:45:06 +00008910static Expr *maybeRebuildARCConsumingStmt(Stmt *Statement) {
John McCall31168b02011-06-15 23:02:42 +00008911 // Should always be wrapped with one of these.
Richard Trieuba63ce62011-09-09 01:45:06 +00008912 ExprWithCleanups *cleanups = dyn_cast<ExprWithCleanups>(Statement);
John McCall31168b02011-06-15 23:02:42 +00008913 if (!cleanups) return 0;
8914
8915 ImplicitCastExpr *cast = dyn_cast<ImplicitCastExpr>(cleanups->getSubExpr());
John McCall2d637d22011-09-10 06:18:15 +00008916 if (!cast || cast->getCastKind() != CK_ARCConsumeObject)
John McCall31168b02011-06-15 23:02:42 +00008917 return 0;
8918
8919 // Splice out the cast. This shouldn't modify any interesting
8920 // features of the statement.
8921 Expr *producer = cast->getSubExpr();
8922 assert(producer->getType() == cast->getType());
8923 assert(producer->getValueKind() == cast->getValueKind());
8924 cleanups->setSubExpr(producer);
8925 return cleanups;
8926}
8927
John McCall3abee492012-04-04 01:27:53 +00008928void Sema::ActOnStartStmtExpr() {
8929 PushExpressionEvaluationContext(ExprEvalContexts.back().Context);
8930}
8931
8932void Sema::ActOnStmtExprError() {
John McCalled7b2782012-04-06 18:20:53 +00008933 // Note that function is also called by TreeTransform when leaving a
8934 // StmtExpr scope without rebuilding anything.
8935
John McCall3abee492012-04-04 01:27:53 +00008936 DiscardCleanupsInEvaluationContext();
8937 PopExpressionEvaluationContext();
8938}
8939
John McCalldadc5752010-08-24 06:29:42 +00008940ExprResult
John McCallb268a282010-08-23 23:25:46 +00008941Sema::ActOnStmtExpr(SourceLocation LPLoc, Stmt *SubStmt,
Sebastian Redl6d4256c2009-03-15 17:47:39 +00008942 SourceLocation RPLoc) { // "({..})"
Chris Lattner366727f2007-07-24 16:58:17 +00008943 assert(SubStmt && isa<CompoundStmt>(SubStmt) && "Invalid action invocation!");
8944 CompoundStmt *Compound = cast<CompoundStmt>(SubStmt);
8945
John McCall3abee492012-04-04 01:27:53 +00008946 if (hasAnyUnrecoverableErrorsInThisFunction())
8947 DiscardCleanupsInEvaluationContext();
8948 assert(!ExprNeedsCleanups && "cleanups within StmtExpr not correctly bound!");
8949 PopExpressionEvaluationContext();
8950
Douglas Gregor6cf3f3c2010-03-10 04:54:39 +00008951 bool isFileScope
8952 = (getCurFunctionOrMethodDecl() == 0) && (getCurBlock() == 0);
Chris Lattnera69b0762009-04-25 19:11:05 +00008953 if (isFileScope)
Sebastian Redl6d4256c2009-03-15 17:47:39 +00008954 return ExprError(Diag(LPLoc, diag::err_stmtexpr_file_scope));
Eli Friedman52cc0162009-01-24 23:09:00 +00008955
Chris Lattner366727f2007-07-24 16:58:17 +00008956 // FIXME: there are a variety of strange constraints to enforce here, for
8957 // example, it is not possible to goto into a stmt expression apparently.
8958 // More semantic analysis is needed.
Mike Stump4e1f26a2009-02-19 03:04:26 +00008959
Chris Lattner366727f2007-07-24 16:58:17 +00008960 // If there are sub stmts in the compound stmt, take the type of the last one
8961 // as the type of the stmtexpr.
8962 QualType Ty = Context.VoidTy;
Fariborz Jahanian56143ae2010-10-25 23:27:26 +00008963 bool StmtExprMayBindToTemp = false;
Chris Lattner944d3062008-07-26 19:51:01 +00008964 if (!Compound->body_empty()) {
8965 Stmt *LastStmt = Compound->body_back();
Fariborz Jahanian56143ae2010-10-25 23:27:26 +00008966 LabelStmt *LastLabelStmt = 0;
Chris Lattner944d3062008-07-26 19:51:01 +00008967 // If LastStmt is a label, skip down through into the body.
Fariborz Jahanian56143ae2010-10-25 23:27:26 +00008968 while (LabelStmt *Label = dyn_cast<LabelStmt>(LastStmt)) {
8969 LastLabelStmt = Label;
Chris Lattner944d3062008-07-26 19:51:01 +00008970 LastStmt = Label->getSubStmt();
Fariborz Jahanian56143ae2010-10-25 23:27:26 +00008971 }
John McCall31168b02011-06-15 23:02:42 +00008972
John Wiegley01296292011-04-08 18:41:53 +00008973 if (Expr *LastE = dyn_cast<Expr>(LastStmt)) {
John McCall34376a62010-12-04 03:47:34 +00008974 // Do function/array conversion on the last expression, but not
8975 // lvalue-to-rvalue. However, initialize an unqualified type.
John Wiegley01296292011-04-08 18:41:53 +00008976 ExprResult LastExpr = DefaultFunctionArrayConversion(LastE);
8977 if (LastExpr.isInvalid())
8978 return ExprError();
8979 Ty = LastExpr.get()->getType().getUnqualifiedType();
John McCall34376a62010-12-04 03:47:34 +00008980
John Wiegley01296292011-04-08 18:41:53 +00008981 if (!Ty->isDependentType() && !LastExpr.get()->isTypeDependent()) {
John McCall31168b02011-06-15 23:02:42 +00008982 // In ARC, if the final expression ends in a consume, splice
8983 // the consume out and bind it later. In the alternate case
8984 // (when dealing with a retainable type), the result
8985 // initialization will create a produce. In both cases the
8986 // result will be +1, and we'll need to balance that out with
8987 // a bind.
8988 if (Expr *rebuiltLastStmt
8989 = maybeRebuildARCConsumingStmt(LastExpr.get())) {
8990 LastExpr = rebuiltLastStmt;
8991 } else {
8992 LastExpr = PerformCopyInitialization(
Fariborz Jahanian56143ae2010-10-25 23:27:26 +00008993 InitializedEntity::InitializeResult(LPLoc,
8994 Ty,
8995 false),
8996 SourceLocation(),
John McCall31168b02011-06-15 23:02:42 +00008997 LastExpr);
8998 }
8999
John Wiegley01296292011-04-08 18:41:53 +00009000 if (LastExpr.isInvalid())
Fariborz Jahanian56143ae2010-10-25 23:27:26 +00009001 return ExprError();
John Wiegley01296292011-04-08 18:41:53 +00009002 if (LastExpr.get() != 0) {
Fariborz Jahanian56143ae2010-10-25 23:27:26 +00009003 if (!LastLabelStmt)
John Wiegley01296292011-04-08 18:41:53 +00009004 Compound->setLastStmt(LastExpr.take());
Fariborz Jahanian56143ae2010-10-25 23:27:26 +00009005 else
John Wiegley01296292011-04-08 18:41:53 +00009006 LastLabelStmt->setSubStmt(LastExpr.take());
Fariborz Jahanian56143ae2010-10-25 23:27:26 +00009007 StmtExprMayBindToTemp = true;
9008 }
9009 }
9010 }
Chris Lattner944d3062008-07-26 19:51:01 +00009011 }
Mike Stump4e1f26a2009-02-19 03:04:26 +00009012
Eli Friedmanba961a92009-03-23 00:24:07 +00009013 // FIXME: Check that expression type is complete/non-abstract; statement
9014 // expressions are not lvalues.
Fariborz Jahanian56143ae2010-10-25 23:27:26 +00009015 Expr *ResStmtExpr = new (Context) StmtExpr(Compound, Ty, LPLoc, RPLoc);
9016 if (StmtExprMayBindToTemp)
9017 return MaybeBindToTemporary(ResStmtExpr);
9018 return Owned(ResStmtExpr);
Chris Lattner366727f2007-07-24 16:58:17 +00009019}
Steve Naroff78864672007-08-01 22:05:33 +00009020
John McCalldadc5752010-08-24 06:29:42 +00009021ExprResult Sema::BuildBuiltinOffsetOf(SourceLocation BuiltinLoc,
John McCall36226622010-10-12 02:09:17 +00009022 TypeSourceInfo *TInfo,
9023 OffsetOfComponent *CompPtr,
9024 unsigned NumComponents,
9025 SourceLocation RParenLoc) {
Douglas Gregor882211c2010-04-28 22:16:22 +00009026 QualType ArgTy = TInfo->getType();
Sebastian Redl8d2ccae2009-02-26 14:39:58 +00009027 bool Dependent = ArgTy->isDependentType();
Abramo Bagnara1108e7b2010-05-20 10:00:11 +00009028 SourceRange TypeRange = TInfo->getTypeLoc().getLocalSourceRange();
Douglas Gregor882211c2010-04-28 22:16:22 +00009029
Chris Lattnerf17bd422007-08-30 17:45:32 +00009030 // We must have at least one component that refers to the type, and the first
9031 // one is known to be a field designator. Verify that the ArgTy represents
9032 // a struct/union/class.
Sebastian Redl8d2ccae2009-02-26 14:39:58 +00009033 if (!Dependent && !ArgTy->isRecordType())
Douglas Gregor882211c2010-04-28 22:16:22 +00009034 return ExprError(Diag(BuiltinLoc, diag::err_offsetof_record_type)
9035 << ArgTy << TypeRange);
9036
9037 // Type must be complete per C99 7.17p3 because a declaring a variable
9038 // with an incomplete type would be ill-formed.
9039 if (!Dependent
9040 && RequireCompleteType(BuiltinLoc, ArgTy,
Douglas Gregor7bfb2d02012-05-04 16:32:21 +00009041 diag::err_offsetof_incomplete_type, TypeRange))
Douglas Gregor882211c2010-04-28 22:16:22 +00009042 return ExprError();
9043
Chris Lattner78502cf2007-08-31 21:49:13 +00009044 // offsetof with non-identifier designators (e.g. "offsetof(x, a.b[c])") are a
9045 // GCC extension, diagnose them.
Eli Friedman988a16b2009-02-27 06:44:11 +00009046 // FIXME: This diagnostic isn't actually visible because the location is in
9047 // a system header!
Chris Lattner78502cf2007-08-31 21:49:13 +00009048 if (NumComponents != 1)
Chris Lattnerf490e152008-11-19 05:27:50 +00009049 Diag(BuiltinLoc, diag::ext_offsetof_extended_field_designator)
9050 << SourceRange(CompPtr[1].LocStart, CompPtr[NumComponents-1].LocEnd);
Douglas Gregor882211c2010-04-28 22:16:22 +00009051
9052 bool DidWarnAboutNonPOD = false;
9053 QualType CurrentType = ArgTy;
9054 typedef OffsetOfExpr::OffsetOfNode OffsetOfNode;
Chris Lattner0e62c1c2011-07-23 10:55:15 +00009055 SmallVector<OffsetOfNode, 4> Comps;
9056 SmallVector<Expr*, 4> Exprs;
Douglas Gregor882211c2010-04-28 22:16:22 +00009057 for (unsigned i = 0; i != NumComponents; ++i) {
9058 const OffsetOfComponent &OC = CompPtr[i];
9059 if (OC.isBrackets) {
9060 // Offset of an array sub-field. TODO: Should we allow vector elements?
9061 if (!CurrentType->isDependentType()) {
9062 const ArrayType *AT = Context.getAsArrayType(CurrentType);
9063 if(!AT)
9064 return ExprError(Diag(OC.LocEnd, diag::err_offsetof_array_type)
9065 << CurrentType);
9066 CurrentType = AT->getElementType();
9067 } else
9068 CurrentType = Context.DependentTy;
9069
Richard Smith9fcc5c32011-10-17 23:29:39 +00009070 ExprResult IdxRval = DefaultLvalueConversion(static_cast<Expr*>(OC.U.E));
9071 if (IdxRval.isInvalid())
9072 return ExprError();
9073 Expr *Idx = IdxRval.take();
9074
Douglas Gregor882211c2010-04-28 22:16:22 +00009075 // The expression must be an integral expression.
9076 // FIXME: An integral constant expression?
Douglas Gregor882211c2010-04-28 22:16:22 +00009077 if (!Idx->isTypeDependent() && !Idx->isValueDependent() &&
9078 !Idx->getType()->isIntegerType())
9079 return ExprError(Diag(Idx->getLocStart(),
9080 diag::err_typecheck_subscript_not_integer)
9081 << Idx->getSourceRange());
Richard Smitheda612882011-10-17 05:48:07 +00009082
Douglas Gregor882211c2010-04-28 22:16:22 +00009083 // Record this array index.
9084 Comps.push_back(OffsetOfNode(OC.LocStart, Exprs.size(), OC.LocEnd));
Richard Smith9fcc5c32011-10-17 23:29:39 +00009085 Exprs.push_back(Idx);
Douglas Gregor882211c2010-04-28 22:16:22 +00009086 continue;
9087 }
9088
9089 // Offset of a field.
9090 if (CurrentType->isDependentType()) {
9091 // We have the offset of a field, but we can't look into the dependent
9092 // type. Just record the identifier of the field.
9093 Comps.push_back(OffsetOfNode(OC.LocStart, OC.U.IdentInfo, OC.LocEnd));
9094 CurrentType = Context.DependentTy;
9095 continue;
9096 }
9097
9098 // We need to have a complete type to look into.
9099 if (RequireCompleteType(OC.LocStart, CurrentType,
9100 diag::err_offsetof_incomplete_type))
9101 return ExprError();
9102
9103 // Look for the designated field.
9104 const RecordType *RC = CurrentType->getAs<RecordType>();
9105 if (!RC)
9106 return ExprError(Diag(OC.LocEnd, diag::err_offsetof_record_type)
9107 << CurrentType);
9108 RecordDecl *RD = RC->getDecl();
9109
9110 // C++ [lib.support.types]p5:
9111 // The macro offsetof accepts a restricted set of type arguments in this
9112 // International Standard. type shall be a POD structure or a POD union
9113 // (clause 9).
Benjamin Kramer9e7876b2012-04-28 11:14:51 +00009114 // C++11 [support.types]p4:
9115 // If type is not a standard-layout class (Clause 9), the results are
9116 // undefined.
Douglas Gregor882211c2010-04-28 22:16:22 +00009117 if (CXXRecordDecl *CRD = dyn_cast<CXXRecordDecl>(RD)) {
Benjamin Kramer9e7876b2012-04-28 11:14:51 +00009118 bool IsSafe = LangOpts.CPlusPlus0x? CRD->isStandardLayout() : CRD->isPOD();
9119 unsigned DiagID =
9120 LangOpts.CPlusPlus0x? diag::warn_offsetof_non_standardlayout_type
9121 : diag::warn_offsetof_non_pod_type;
9122
9123 if (!IsSafe && !DidWarnAboutNonPOD &&
Ted Kremenek55ae3192011-02-23 01:51:43 +00009124 DiagRuntimeBehavior(BuiltinLoc, 0,
Benjamin Kramer9e7876b2012-04-28 11:14:51 +00009125 PDiag(DiagID)
Douglas Gregor882211c2010-04-28 22:16:22 +00009126 << SourceRange(CompPtr[0].LocStart, OC.LocEnd)
9127 << CurrentType))
9128 DidWarnAboutNonPOD = true;
9129 }
9130
9131 // Look for the field.
9132 LookupResult R(*this, OC.U.IdentInfo, OC.LocStart, LookupMemberName);
9133 LookupQualifiedName(R, RD);
9134 FieldDecl *MemberDecl = R.getAsSingle<FieldDecl>();
Francois Pichet783dd6e2010-11-21 06:08:52 +00009135 IndirectFieldDecl *IndirectMemberDecl = 0;
9136 if (!MemberDecl) {
Benjamin Kramer39593702010-11-21 14:11:41 +00009137 if ((IndirectMemberDecl = R.getAsSingle<IndirectFieldDecl>()))
Francois Pichet783dd6e2010-11-21 06:08:52 +00009138 MemberDecl = IndirectMemberDecl->getAnonField();
9139 }
9140
Douglas Gregor882211c2010-04-28 22:16:22 +00009141 if (!MemberDecl)
9142 return ExprError(Diag(BuiltinLoc, diag::err_no_member)
9143 << OC.U.IdentInfo << RD << SourceRange(OC.LocStart,
9144 OC.LocEnd));
9145
Douglas Gregor10982ea2010-04-28 22:36:06 +00009146 // C99 7.17p3:
9147 // (If the specified member is a bit-field, the behavior is undefined.)
9148 //
9149 // We diagnose this as an error.
Richard Smithcaf33902011-10-10 18:28:20 +00009150 if (MemberDecl->isBitField()) {
Douglas Gregor10982ea2010-04-28 22:36:06 +00009151 Diag(OC.LocEnd, diag::err_offsetof_bitfield)
9152 << MemberDecl->getDeclName()
9153 << SourceRange(BuiltinLoc, RParenLoc);
9154 Diag(MemberDecl->getLocation(), diag::note_bitfield_decl);
9155 return ExprError();
9156 }
Eli Friedman74ef7cf2010-08-05 10:11:36 +00009157
9158 RecordDecl *Parent = MemberDecl->getParent();
Francois Pichet783dd6e2010-11-21 06:08:52 +00009159 if (IndirectMemberDecl)
9160 Parent = cast<RecordDecl>(IndirectMemberDecl->getDeclContext());
Eli Friedman74ef7cf2010-08-05 10:11:36 +00009161
Douglas Gregord1702062010-04-29 00:18:15 +00009162 // If the member was found in a base class, introduce OffsetOfNodes for
9163 // the base class indirections.
9164 CXXBasePaths Paths(/*FindAmbiguities=*/true, /*RecordPaths=*/true,
9165 /*DetectVirtual=*/false);
Eli Friedman74ef7cf2010-08-05 10:11:36 +00009166 if (IsDerivedFrom(CurrentType, Context.getTypeDeclType(Parent), Paths)) {
Douglas Gregord1702062010-04-29 00:18:15 +00009167 CXXBasePath &Path = Paths.front();
9168 for (CXXBasePath::iterator B = Path.begin(), BEnd = Path.end();
9169 B != BEnd; ++B)
9170 Comps.push_back(OffsetOfNode(B->Base));
9171 }
Eli Friedman74ef7cf2010-08-05 10:11:36 +00009172
Francois Pichet783dd6e2010-11-21 06:08:52 +00009173 if (IndirectMemberDecl) {
9174 for (IndirectFieldDecl::chain_iterator FI =
9175 IndirectMemberDecl->chain_begin(),
9176 FEnd = IndirectMemberDecl->chain_end(); FI != FEnd; FI++) {
9177 assert(isa<FieldDecl>(*FI));
9178 Comps.push_back(OffsetOfNode(OC.LocStart,
9179 cast<FieldDecl>(*FI), OC.LocEnd));
9180 }
9181 } else
Douglas Gregor882211c2010-04-28 22:16:22 +00009182 Comps.push_back(OffsetOfNode(OC.LocStart, MemberDecl, OC.LocEnd));
Francois Pichet783dd6e2010-11-21 06:08:52 +00009183
Douglas Gregor882211c2010-04-28 22:16:22 +00009184 CurrentType = MemberDecl->getType().getNonReferenceType();
9185 }
9186
9187 return Owned(OffsetOfExpr::Create(Context, Context.getSizeType(), BuiltinLoc,
Benjamin Kramerc215e762012-08-24 11:54:20 +00009188 TInfo, Comps, Exprs, RParenLoc));
Douglas Gregor882211c2010-04-28 22:16:22 +00009189}
Mike Stump4e1f26a2009-02-19 03:04:26 +00009190
John McCalldadc5752010-08-24 06:29:42 +00009191ExprResult Sema::ActOnBuiltinOffsetOf(Scope *S,
John McCall36226622010-10-12 02:09:17 +00009192 SourceLocation BuiltinLoc,
9193 SourceLocation TypeLoc,
Richard Trieuba63ce62011-09-09 01:45:06 +00009194 ParsedType ParsedArgTy,
John McCall36226622010-10-12 02:09:17 +00009195 OffsetOfComponent *CompPtr,
9196 unsigned NumComponents,
Richard Trieuba63ce62011-09-09 01:45:06 +00009197 SourceLocation RParenLoc) {
John McCall36226622010-10-12 02:09:17 +00009198
Douglas Gregor882211c2010-04-28 22:16:22 +00009199 TypeSourceInfo *ArgTInfo;
Richard Trieuba63ce62011-09-09 01:45:06 +00009200 QualType ArgTy = GetTypeFromParser(ParsedArgTy, &ArgTInfo);
Douglas Gregor882211c2010-04-28 22:16:22 +00009201 if (ArgTy.isNull())
9202 return ExprError();
9203
Eli Friedman06dcfd92010-08-05 10:15:45 +00009204 if (!ArgTInfo)
9205 ArgTInfo = Context.getTrivialTypeSourceInfo(ArgTy, TypeLoc);
9206
9207 return BuildBuiltinOffsetOf(BuiltinLoc, ArgTInfo, CompPtr, NumComponents,
Richard Trieuba63ce62011-09-09 01:45:06 +00009208 RParenLoc);
Chris Lattnerf17bd422007-08-30 17:45:32 +00009209}
9210
9211
John McCalldadc5752010-08-24 06:29:42 +00009212ExprResult Sema::ActOnChooseExpr(SourceLocation BuiltinLoc,
John McCall36226622010-10-12 02:09:17 +00009213 Expr *CondExpr,
9214 Expr *LHSExpr, Expr *RHSExpr,
9215 SourceLocation RPLoc) {
Steve Naroff9efdabc2007-08-03 21:21:27 +00009216 assert((CondExpr && LHSExpr && RHSExpr) && "Missing type argument(s)");
9217
John McCall7decc9e2010-11-18 06:31:45 +00009218 ExprValueKind VK = VK_RValue;
9219 ExprObjectKind OK = OK_Ordinary;
Sebastian Redl8d2ccae2009-02-26 14:39:58 +00009220 QualType resType;
Douglas Gregor56751b52009-09-25 04:25:58 +00009221 bool ValueDependent = false;
Douglas Gregor0df91122009-05-19 22:43:30 +00009222 if (CondExpr->isTypeDependent() || CondExpr->isValueDependent()) {
Sebastian Redl8d2ccae2009-02-26 14:39:58 +00009223 resType = Context.DependentTy;
Douglas Gregor56751b52009-09-25 04:25:58 +00009224 ValueDependent = true;
Sebastian Redl8d2ccae2009-02-26 14:39:58 +00009225 } else {
9226 // The conditional expression is required to be a constant expression.
9227 llvm::APSInt condEval(32);
Douglas Gregore2b37442012-05-04 22:38:52 +00009228 ExprResult CondICE
9229 = VerifyIntegerConstantExpression(CondExpr, &condEval,
9230 diag::err_typecheck_choose_expr_requires_constant, false);
Richard Smithf4c51d92012-02-04 09:53:13 +00009231 if (CondICE.isInvalid())
9232 return ExprError();
9233 CondExpr = CondICE.take();
Steve Naroff9efdabc2007-08-03 21:21:27 +00009234
Sebastian Redl8d2ccae2009-02-26 14:39:58 +00009235 // If the condition is > zero, then the AST type is the same as the LSHExpr.
John McCall7decc9e2010-11-18 06:31:45 +00009236 Expr *ActiveExpr = condEval.getZExtValue() ? LHSExpr : RHSExpr;
9237
9238 resType = ActiveExpr->getType();
9239 ValueDependent = ActiveExpr->isValueDependent();
9240 VK = ActiveExpr->getValueKind();
9241 OK = ActiveExpr->getObjectKind();
Sebastian Redl8d2ccae2009-02-26 14:39:58 +00009242 }
9243
Sebastian Redl6d4256c2009-03-15 17:47:39 +00009244 return Owned(new (Context) ChooseExpr(BuiltinLoc, CondExpr, LHSExpr, RHSExpr,
John McCall7decc9e2010-11-18 06:31:45 +00009245 resType, VK, OK, RPLoc,
Douglas Gregor56751b52009-09-25 04:25:58 +00009246 resType->isDependentType(),
9247 ValueDependent));
Steve Naroff9efdabc2007-08-03 21:21:27 +00009248}
9249
Steve Naroffc540d662008-09-03 18:15:37 +00009250//===----------------------------------------------------------------------===//
9251// Clang Extensions.
9252//===----------------------------------------------------------------------===//
9253
9254/// ActOnBlockStart - This callback is invoked when a block literal is started.
Richard Trieuba63ce62011-09-09 01:45:06 +00009255void Sema::ActOnBlockStart(SourceLocation CaretLoc, Scope *CurScope) {
Douglas Gregor9a28e842010-03-01 23:15:13 +00009256 BlockDecl *Block = BlockDecl::Create(Context, CurContext, CaretLoc);
Richard Trieuba63ce62011-09-09 01:45:06 +00009257 PushBlockScope(CurScope, Block);
Douglas Gregor9a28e842010-03-01 23:15:13 +00009258 CurContext->addDecl(Block);
Richard Trieuba63ce62011-09-09 01:45:06 +00009259 if (CurScope)
9260 PushDeclContext(CurScope, Block);
Fariborz Jahanian1babe772010-07-09 18:44:02 +00009261 else
9262 CurContext = Block;
John McCallf1a3c2a2011-11-11 03:19:12 +00009263
Eli Friedman34b49062012-01-26 03:00:14 +00009264 getCurBlock()->HasImplicitReturnType = true;
9265
John McCallf1a3c2a2011-11-11 03:19:12 +00009266 // Enter a new evaluation context to insulate the block from any
9267 // cleanups from the enclosing full-expression.
9268 PushExpressionEvaluationContext(PotentiallyEvaluated);
Steve Naroff1d95e5a2008-10-10 01:28:17 +00009269}
9270
Douglas Gregor7efd007c2012-06-15 16:59:29 +00009271void Sema::ActOnBlockArguments(SourceLocation CaretLoc, Declarator &ParamInfo,
9272 Scope *CurScope) {
Mike Stumpf70bcf72009-05-07 18:43:07 +00009273 assert(ParamInfo.getIdentifier()==0 && "block-id should have no identifier!");
John McCall3882ace2011-01-05 12:14:39 +00009274 assert(ParamInfo.getContext() == Declarator::BlockLiteralContext);
Douglas Gregor9a28e842010-03-01 23:15:13 +00009275 BlockScopeInfo *CurBlock = getCurBlock();
Kovarththanan Rajaratnamba2c6522010-03-13 10:17:05 +00009276
John McCall8cb7bdf2010-06-04 23:28:52 +00009277 TypeSourceInfo *Sig = GetTypeForDeclarator(ParamInfo, CurScope);
John McCall8cb7bdf2010-06-04 23:28:52 +00009278 QualType T = Sig->getType();
Mike Stump82f071f2009-02-04 22:31:32 +00009279
Douglas Gregor7efd007c2012-06-15 16:59:29 +00009280 // FIXME: We should allow unexpanded parameter packs here, but that would,
9281 // in turn, make the block expression contain unexpanded parameter packs.
9282 if (DiagnoseUnexpandedParameterPack(CaretLoc, Sig, UPPC_Block)) {
9283 // Drop the parameters.
9284 FunctionProtoType::ExtProtoInfo EPI;
9285 EPI.HasTrailingReturn = false;
9286 EPI.TypeQuals |= DeclSpec::TQ_const;
9287 T = Context.getFunctionType(Context.DependentTy, /*Args=*/0, /*NumArgs=*/0,
9288 EPI);
9289 Sig = Context.getTrivialTypeSourceInfo(T);
9290 }
9291
John McCall3882ace2011-01-05 12:14:39 +00009292 // GetTypeForDeclarator always produces a function type for a block
9293 // literal signature. Furthermore, it is always a FunctionProtoType
9294 // unless the function was written with a typedef.
9295 assert(T->isFunctionType() &&
9296 "GetTypeForDeclarator made a non-function block signature");
9297
9298 // Look for an explicit signature in that function type.
9299 FunctionProtoTypeLoc ExplicitSignature;
9300
9301 TypeLoc tmp = Sig->getTypeLoc().IgnoreParens();
9302 if (isa<FunctionProtoTypeLoc>(tmp)) {
9303 ExplicitSignature = cast<FunctionProtoTypeLoc>(tmp);
9304
9305 // Check whether that explicit signature was synthesized by
9306 // GetTypeForDeclarator. If so, don't save that as part of the
9307 // written signature.
Abramo Bagnaraf2a79d92011-03-12 11:17:06 +00009308 if (ExplicitSignature.getLocalRangeBegin() ==
9309 ExplicitSignature.getLocalRangeEnd()) {
John McCall3882ace2011-01-05 12:14:39 +00009310 // This would be much cheaper if we stored TypeLocs instead of
9311 // TypeSourceInfos.
9312 TypeLoc Result = ExplicitSignature.getResultLoc();
9313 unsigned Size = Result.getFullDataSize();
9314 Sig = Context.CreateTypeSourceInfo(Result.getType(), Size);
9315 Sig->getTypeLoc().initializeFullCopy(Result, Size);
9316
9317 ExplicitSignature = FunctionProtoTypeLoc();
9318 }
John McCalla3ccba02010-06-04 11:21:44 +00009319 }
Mike Stump11289f42009-09-09 15:08:12 +00009320
John McCall3882ace2011-01-05 12:14:39 +00009321 CurBlock->TheDecl->setSignatureAsWritten(Sig);
9322 CurBlock->FunctionType = T;
9323
9324 const FunctionType *Fn = T->getAs<FunctionType>();
9325 QualType RetTy = Fn->getResultType();
9326 bool isVariadic =
9327 (isa<FunctionProtoType>(Fn) && cast<FunctionProtoType>(Fn)->isVariadic());
9328
John McCall8e346702010-06-04 19:02:56 +00009329 CurBlock->TheDecl->setIsVariadic(isVariadic);
Douglas Gregorb92a1562010-02-03 00:27:59 +00009330
John McCalla3ccba02010-06-04 11:21:44 +00009331 // Don't allow returning a objc interface by value.
9332 if (RetTy->isObjCObjectType()) {
Daniel Dunbar62ee6412012-03-09 18:35:03 +00009333 Diag(ParamInfo.getLocStart(),
John McCalla3ccba02010-06-04 11:21:44 +00009334 diag::err_object_cannot_be_passed_returned_by_value) << 0 << RetTy;
9335 return;
9336 }
Mike Stump4e1f26a2009-02-19 03:04:26 +00009337
John McCalla3ccba02010-06-04 11:21:44 +00009338 // Context.DependentTy is used as a placeholder for a missing block
John McCall8e346702010-06-04 19:02:56 +00009339 // return type. TODO: what should we do with declarators like:
9340 // ^ * { ... }
9341 // If the answer is "apply template argument deduction"....
Fariborz Jahaniandd5eb9d2011-12-03 17:47:53 +00009342 if (RetTy != Context.DependentTy) {
John McCalla3ccba02010-06-04 11:21:44 +00009343 CurBlock->ReturnType = RetTy;
Fariborz Jahaniandd5eb9d2011-12-03 17:47:53 +00009344 CurBlock->TheDecl->setBlockMissingReturnType(false);
Eli Friedman34b49062012-01-26 03:00:14 +00009345 CurBlock->HasImplicitReturnType = false;
Fariborz Jahaniandd5eb9d2011-12-03 17:47:53 +00009346 }
Mike Stump4e1f26a2009-02-19 03:04:26 +00009347
John McCalla3ccba02010-06-04 11:21:44 +00009348 // Push block parameters from the declarator if we had them.
Chris Lattner0e62c1c2011-07-23 10:55:15 +00009349 SmallVector<ParmVarDecl*, 8> Params;
John McCall3882ace2011-01-05 12:14:39 +00009350 if (ExplicitSignature) {
9351 for (unsigned I = 0, E = ExplicitSignature.getNumArgs(); I != E; ++I) {
9352 ParmVarDecl *Param = ExplicitSignature.getArg(I);
Fariborz Jahanian5ec502e2010-02-12 21:53:14 +00009353 if (Param->getIdentifier() == 0 &&
9354 !Param->isImplicit() &&
9355 !Param->isInvalidDecl() &&
David Blaikiebbafb8a2012-03-11 07:00:24 +00009356 !getLangOpts().CPlusPlus)
Fariborz Jahanian5ec502e2010-02-12 21:53:14 +00009357 Diag(Param->getLocation(), diag::err_parameter_name_omitted);
John McCall8e346702010-06-04 19:02:56 +00009358 Params.push_back(Param);
Fariborz Jahanian5ec502e2010-02-12 21:53:14 +00009359 }
John McCalla3ccba02010-06-04 11:21:44 +00009360
9361 // Fake up parameter variables if we have a typedef, like
9362 // ^ fntype { ... }
9363 } else if (const FunctionProtoType *Fn = T->getAs<FunctionProtoType>()) {
9364 for (FunctionProtoType::arg_type_iterator
9365 I = Fn->arg_type_begin(), E = Fn->arg_type_end(); I != E; ++I) {
9366 ParmVarDecl *Param =
9367 BuildParmVarDeclForTypedef(CurBlock->TheDecl,
Daniel Dunbar62ee6412012-03-09 18:35:03 +00009368 ParamInfo.getLocStart(),
John McCalla3ccba02010-06-04 11:21:44 +00009369 *I);
John McCall8e346702010-06-04 19:02:56 +00009370 Params.push_back(Param);
John McCalla3ccba02010-06-04 11:21:44 +00009371 }
Steve Naroffc540d662008-09-03 18:15:37 +00009372 }
John McCalla3ccba02010-06-04 11:21:44 +00009373
John McCall8e346702010-06-04 19:02:56 +00009374 // Set the parameters on the block decl.
Douglas Gregorb524d902010-11-01 18:37:59 +00009375 if (!Params.empty()) {
David Blaikie9c70e042011-09-21 18:16:56 +00009376 CurBlock->TheDecl->setParams(Params);
Douglas Gregorb524d902010-11-01 18:37:59 +00009377 CheckParmsForFunctionDef(CurBlock->TheDecl->param_begin(),
9378 CurBlock->TheDecl->param_end(),
9379 /*CheckParameterNames=*/false);
9380 }
9381
John McCalla3ccba02010-06-04 11:21:44 +00009382 // Finally we can process decl attributes.
Douglas Gregor758a8692009-06-17 21:51:59 +00009383 ProcessDeclAttributes(CurScope, CurBlock->TheDecl, ParamInfo);
John McCalldf8b37c2010-03-22 09:20:08 +00009384
John McCalla3ccba02010-06-04 11:21:44 +00009385 // Put the parameter variables in scope. We can bail out immediately
9386 // if we don't have any.
John McCall8e346702010-06-04 19:02:56 +00009387 if (Params.empty())
John McCalla3ccba02010-06-04 11:21:44 +00009388 return;
9389
Steve Naroff1d95e5a2008-10-10 01:28:17 +00009390 for (BlockDecl::param_iterator AI = CurBlock->TheDecl->param_begin(),
John McCallf7b2fb52010-01-22 00:28:27 +00009391 E = CurBlock->TheDecl->param_end(); AI != E; ++AI) {
9392 (*AI)->setOwningFunction(CurBlock->TheDecl);
9393
Steve Naroff1d95e5a2008-10-10 01:28:17 +00009394 // If this has an identifier, add it to the scope stack.
John McCalldf8b37c2010-03-22 09:20:08 +00009395 if ((*AI)->getIdentifier()) {
Argyrios Kyrtzidis1cb0de12010-12-15 18:44:22 +00009396 CheckShadow(CurBlock->TheScope, *AI);
John McCalldf8b37c2010-03-22 09:20:08 +00009397
Steve Naroff1d95e5a2008-10-10 01:28:17 +00009398 PushOnScopeChains(*AI, CurBlock->TheScope);
John McCalldf8b37c2010-03-22 09:20:08 +00009399 }
John McCallf7b2fb52010-01-22 00:28:27 +00009400 }
Steve Naroffc540d662008-09-03 18:15:37 +00009401}
9402
9403/// ActOnBlockError - If there is an error parsing a block, this callback
9404/// is invoked to pop the information about the block from the action impl.
9405void Sema::ActOnBlockError(SourceLocation CaretLoc, Scope *CurScope) {
John McCallf1a3c2a2011-11-11 03:19:12 +00009406 // Leave the expression-evaluation context.
9407 DiscardCleanupsInEvaluationContext();
9408 PopExpressionEvaluationContext();
9409
Steve Naroffc540d662008-09-03 18:15:37 +00009410 // Pop off CurBlock, handle nested blocks.
Chris Lattner41b86942009-04-21 22:38:46 +00009411 PopDeclContext();
Eli Friedman71c80552012-01-05 03:35:19 +00009412 PopFunctionScopeInfo();
Steve Naroffc540d662008-09-03 18:15:37 +00009413}
9414
9415/// ActOnBlockStmtExpr - This is called when the body of a block statement
9416/// literal was successfully completed. ^(int x){...}
John McCalldadc5752010-08-24 06:29:42 +00009417ExprResult Sema::ActOnBlockStmtExpr(SourceLocation CaretLoc,
Chris Lattner60f84492011-02-17 23:58:47 +00009418 Stmt *Body, Scope *CurScope) {
Chris Lattner9eac9312009-03-27 04:18:06 +00009419 // If blocks are disabled, emit an error.
9420 if (!LangOpts.Blocks)
9421 Diag(CaretLoc, diag::err_blocks_disable);
Mike Stump11289f42009-09-09 15:08:12 +00009422
John McCallf1a3c2a2011-11-11 03:19:12 +00009423 // Leave the expression-evaluation context.
John McCall85110b42012-03-08 22:00:17 +00009424 if (hasAnyUnrecoverableErrorsInThisFunction())
9425 DiscardCleanupsInEvaluationContext();
John McCallf1a3c2a2011-11-11 03:19:12 +00009426 assert(!ExprNeedsCleanups && "cleanups within block not correctly bound!");
9427 PopExpressionEvaluationContext();
9428
Douglas Gregor9a28e842010-03-01 23:15:13 +00009429 BlockScopeInfo *BSI = cast<BlockScopeInfo>(FunctionScopes.back());
Jordan Rosed39e5f12012-07-02 21:19:23 +00009430
9431 if (BSI->HasImplicitReturnType)
9432 deduceClosureReturnType(*BSI);
9433
Steve Naroff1d95e5a2008-10-10 01:28:17 +00009434 PopDeclContext();
9435
Steve Naroffc540d662008-09-03 18:15:37 +00009436 QualType RetTy = Context.VoidTy;
Fariborz Jahanian3fd73102009-06-19 23:37:08 +00009437 if (!BSI->ReturnType.isNull())
9438 RetTy = BSI->ReturnType;
Mike Stump4e1f26a2009-02-19 03:04:26 +00009439
Mike Stump3bf1ab42009-07-28 22:04:01 +00009440 bool NoReturn = BSI->TheDecl->getAttr<NoReturnAttr>();
Steve Naroffc540d662008-09-03 18:15:37 +00009441 QualType BlockTy;
John McCall8e346702010-06-04 19:02:56 +00009442
John McCallc63de662011-02-02 13:00:07 +00009443 // Set the captured variables on the block.
Eli Friedman20139d32012-01-11 02:36:31 +00009444 // FIXME: Share capture structure between BlockDecl and CapturingScopeInfo!
9445 SmallVector<BlockDecl::Capture, 4> Captures;
9446 for (unsigned i = 0, e = BSI->Captures.size(); i != e; i++) {
9447 CapturingScopeInfo::Capture &Cap = BSI->Captures[i];
9448 if (Cap.isThisCapture())
9449 continue;
Eli Friedman24af8502012-02-03 22:47:37 +00009450 BlockDecl::Capture NewCap(Cap.getVariable(), Cap.isBlockCapture(),
Eli Friedman20139d32012-01-11 02:36:31 +00009451 Cap.isNested(), Cap.getCopyExpr());
9452 Captures.push_back(NewCap);
9453 }
9454 BSI->TheDecl->setCaptures(Context, Captures.begin(), Captures.end(),
9455 BSI->CXXThisCaptureIndex != 0);
John McCallc63de662011-02-02 13:00:07 +00009456
John McCall8e346702010-06-04 19:02:56 +00009457 // If the user wrote a function type in some form, try to use that.
9458 if (!BSI->FunctionType.isNull()) {
9459 const FunctionType *FTy = BSI->FunctionType->getAs<FunctionType>();
9460
9461 FunctionType::ExtInfo Ext = FTy->getExtInfo();
9462 if (NoReturn && !Ext.getNoReturn()) Ext = Ext.withNoReturn(true);
9463
9464 // Turn protoless block types into nullary block types.
9465 if (isa<FunctionNoProtoType>(FTy)) {
John McCalldb40c7f2010-12-14 08:05:40 +00009466 FunctionProtoType::ExtProtoInfo EPI;
9467 EPI.ExtInfo = Ext;
9468 BlockTy = Context.getFunctionType(RetTy, 0, 0, EPI);
John McCall8e346702010-06-04 19:02:56 +00009469
9470 // Otherwise, if we don't need to change anything about the function type,
9471 // preserve its sugar structure.
9472 } else if (FTy->getResultType() == RetTy &&
9473 (!NoReturn || FTy->getNoReturnAttr())) {
9474 BlockTy = BSI->FunctionType;
9475
9476 // Otherwise, make the minimal modifications to the function type.
9477 } else {
9478 const FunctionProtoType *FPT = cast<FunctionProtoType>(FTy);
John McCalldb40c7f2010-12-14 08:05:40 +00009479 FunctionProtoType::ExtProtoInfo EPI = FPT->getExtProtoInfo();
9480 EPI.TypeQuals = 0; // FIXME: silently?
9481 EPI.ExtInfo = Ext;
John McCall8e346702010-06-04 19:02:56 +00009482 BlockTy = Context.getFunctionType(RetTy,
9483 FPT->arg_type_begin(),
9484 FPT->getNumArgs(),
John McCalldb40c7f2010-12-14 08:05:40 +00009485 EPI);
John McCall8e346702010-06-04 19:02:56 +00009486 }
9487
9488 // If we don't have a function type, just build one from nothing.
9489 } else {
John McCalldb40c7f2010-12-14 08:05:40 +00009490 FunctionProtoType::ExtProtoInfo EPI;
John McCall31168b02011-06-15 23:02:42 +00009491 EPI.ExtInfo = FunctionType::ExtInfo().withNoReturn(NoReturn);
John McCalldb40c7f2010-12-14 08:05:40 +00009492 BlockTy = Context.getFunctionType(RetTy, 0, 0, EPI);
John McCall8e346702010-06-04 19:02:56 +00009493 }
Mike Stump4e1f26a2009-02-19 03:04:26 +00009494
John McCall8e346702010-06-04 19:02:56 +00009495 DiagnoseUnusedParameters(BSI->TheDecl->param_begin(),
9496 BSI->TheDecl->param_end());
Steve Naroffc540d662008-09-03 18:15:37 +00009497 BlockTy = Context.getBlockPointerType(BlockTy);
Mike Stump4e1f26a2009-02-19 03:04:26 +00009498
Chris Lattner45542ea2009-04-19 05:28:12 +00009499 // If needed, diagnose invalid gotos and switches in the block.
John McCall31168b02011-06-15 23:02:42 +00009500 if (getCurFunction()->NeedsScopeChecking() &&
Douglas Gregor5d944db2012-08-17 05:12:08 +00009501 !hasAnyUnrecoverableErrorsInThisFunction() &&
9502 !PP.isCodeCompletionEnabled())
John McCallb268a282010-08-23 23:25:46 +00009503 DiagnoseInvalidJumps(cast<CompoundStmt>(Body));
Mike Stump11289f42009-09-09 15:08:12 +00009504
Chris Lattner60f84492011-02-17 23:58:47 +00009505 BSI->TheDecl->setBody(cast<CompoundStmt>(Body));
Kovarththanan Rajaratnamba2c6522010-03-13 10:17:05 +00009506
Jordan Rosed39e5f12012-07-02 21:19:23 +00009507 // Try to apply the named return value optimization. We have to check again
9508 // if we can do this, though, because blocks keep return statements around
9509 // to deduce an implicit return type.
9510 if (getLangOpts().CPlusPlus && RetTy->isRecordType() &&
9511 !BSI->TheDecl->isDependentContext())
9512 computeNRVO(Body, getCurBlock());
Douglas Gregor49695f02011-09-06 20:46:03 +00009513
Benjamin Kramera4fb8362011-07-12 14:11:05 +00009514 BlockExpr *Result = new (Context) BlockExpr(BSI->TheDecl, BlockTy);
9515 const AnalysisBasedWarnings::Policy &WP = AnalysisWarnings.getDefaultPolicy();
Eli Friedman71c80552012-01-05 03:35:19 +00009516 PopFunctionScopeInfo(&WP, Result->getBlockDecl(), Result);
Benjamin Kramera4fb8362011-07-12 14:11:05 +00009517
John McCall28fc7092011-11-10 05:35:25 +00009518 // If the block isn't obviously global, i.e. it captures anything at
John McCalld2393872012-04-13 01:08:17 +00009519 // all, then we need to do a few things in the surrounding context:
John McCall28fc7092011-11-10 05:35:25 +00009520 if (Result->getBlockDecl()->hasCaptures()) {
John McCalld2393872012-04-13 01:08:17 +00009521 // First, this expression has a new cleanup object.
John McCall28fc7092011-11-10 05:35:25 +00009522 ExprCleanupObjects.push_back(Result->getBlockDecl());
9523 ExprNeedsCleanups = true;
John McCalld2393872012-04-13 01:08:17 +00009524
9525 // It also gets a branch-protected scope if any of the captured
9526 // variables needs destruction.
9527 for (BlockDecl::capture_const_iterator
9528 ci = Result->getBlockDecl()->capture_begin(),
9529 ce = Result->getBlockDecl()->capture_end(); ci != ce; ++ci) {
9530 const VarDecl *var = ci->getVariable();
9531 if (var->getType().isDestructedType() != QualType::DK_none) {
9532 getCurFunction()->setHasBranchProtectedScope();
9533 break;
9534 }
9535 }
John McCall28fc7092011-11-10 05:35:25 +00009536 }
Fariborz Jahanian197c68c2012-03-06 18:41:35 +00009537
Douglas Gregor9a28e842010-03-01 23:15:13 +00009538 return Owned(Result);
Steve Naroffc540d662008-09-03 18:15:37 +00009539}
9540
John McCalldadc5752010-08-24 06:29:42 +00009541ExprResult Sema::ActOnVAArg(SourceLocation BuiltinLoc,
Richard Trieuba63ce62011-09-09 01:45:06 +00009542 Expr *E, ParsedType Ty,
Sebastian Redl6d4256c2009-03-15 17:47:39 +00009543 SourceLocation RPLoc) {
Abramo Bagnara27db2392010-08-10 10:06:15 +00009544 TypeSourceInfo *TInfo;
Richard Trieuba63ce62011-09-09 01:45:06 +00009545 GetTypeFromParser(Ty, &TInfo);
9546 return BuildVAArgExpr(BuiltinLoc, E, TInfo, RPLoc);
Abramo Bagnara27db2392010-08-10 10:06:15 +00009547}
9548
John McCalldadc5752010-08-24 06:29:42 +00009549ExprResult Sema::BuildVAArgExpr(SourceLocation BuiltinLoc,
John McCall7decc9e2010-11-18 06:31:45 +00009550 Expr *E, TypeSourceInfo *TInfo,
9551 SourceLocation RPLoc) {
Chris Lattner56382aa2009-04-05 15:49:53 +00009552 Expr *OrigExpr = E;
Mike Stump11289f42009-09-09 15:08:12 +00009553
Eli Friedman121ba0c2008-08-09 23:32:40 +00009554 // Get the va_list type
9555 QualType VaListType = Context.getBuiltinVaListType();
Eli Friedmane2cad652009-05-16 12:46:54 +00009556 if (VaListType->isArrayType()) {
9557 // Deal with implicit array decay; for example, on x86-64,
9558 // va_list is an array, but it's supposed to decay to
9559 // a pointer for va_arg.
Eli Friedman121ba0c2008-08-09 23:32:40 +00009560 VaListType = Context.getArrayDecayedType(VaListType);
Eli Friedmane2cad652009-05-16 12:46:54 +00009561 // Make sure the input expression also decays appropriately.
John Wiegley01296292011-04-08 18:41:53 +00009562 ExprResult Result = UsualUnaryConversions(E);
9563 if (Result.isInvalid())
9564 return ExprError();
9565 E = Result.take();
Eli Friedmane2cad652009-05-16 12:46:54 +00009566 } else {
9567 // Otherwise, the va_list argument must be an l-value because
9568 // it is modified by va_arg.
Mike Stump11289f42009-09-09 15:08:12 +00009569 if (!E->isTypeDependent() &&
Douglas Gregorad3150c2009-05-19 23:10:31 +00009570 CheckForModifiableLvalue(E, BuiltinLoc, *this))
Eli Friedmane2cad652009-05-16 12:46:54 +00009571 return ExprError();
9572 }
Eli Friedman121ba0c2008-08-09 23:32:40 +00009573
Douglas Gregorad3150c2009-05-19 23:10:31 +00009574 if (!E->isTypeDependent() &&
9575 !Context.hasSameType(VaListType, E->getType())) {
Sebastian Redl6d4256c2009-03-15 17:47:39 +00009576 return ExprError(Diag(E->getLocStart(),
9577 diag::err_first_argument_to_va_arg_not_of_type_va_list)
Chris Lattner56382aa2009-04-05 15:49:53 +00009578 << OrigExpr->getType() << E->getSourceRange());
Chris Lattner3f5cd772009-04-05 00:59:53 +00009579 }
Mike Stump4e1f26a2009-02-19 03:04:26 +00009580
David Majnemerc75d1a12011-06-14 05:17:32 +00009581 if (!TInfo->getType()->isDependentType()) {
9582 if (RequireCompleteType(TInfo->getTypeLoc().getBeginLoc(), TInfo->getType(),
Douglas Gregor7bfb2d02012-05-04 16:32:21 +00009583 diag::err_second_parameter_to_va_arg_incomplete,
9584 TInfo->getTypeLoc()))
David Majnemerc75d1a12011-06-14 05:17:32 +00009585 return ExprError();
David Majnemer254a5c02011-06-13 06:37:03 +00009586
David Majnemerc75d1a12011-06-14 05:17:32 +00009587 if (RequireNonAbstractType(TInfo->getTypeLoc().getBeginLoc(),
Douglas Gregorae298422012-05-04 17:09:59 +00009588 TInfo->getType(),
9589 diag::err_second_parameter_to_va_arg_abstract,
9590 TInfo->getTypeLoc()))
David Majnemerc75d1a12011-06-14 05:17:32 +00009591 return ExprError();
9592
Douglas Gregor7e1eb932011-07-30 06:45:27 +00009593 if (!TInfo->getType().isPODType(Context)) {
David Majnemerc75d1a12011-06-14 05:17:32 +00009594 Diag(TInfo->getTypeLoc().getBeginLoc(),
Douglas Gregor7e1eb932011-07-30 06:45:27 +00009595 TInfo->getType()->isObjCLifetimeType()
9596 ? diag::warn_second_parameter_to_va_arg_ownership_qualified
9597 : diag::warn_second_parameter_to_va_arg_not_pod)
David Majnemerc75d1a12011-06-14 05:17:32 +00009598 << TInfo->getType()
9599 << TInfo->getTypeLoc().getSourceRange();
Douglas Gregor7e1eb932011-07-30 06:45:27 +00009600 }
Eli Friedman6290ae42011-07-11 21:45:59 +00009601
9602 // Check for va_arg where arguments of the given type will be promoted
9603 // (i.e. this va_arg is guaranteed to have undefined behavior).
9604 QualType PromoteType;
9605 if (TInfo->getType()->isPromotableIntegerType()) {
9606 PromoteType = Context.getPromotedIntegerType(TInfo->getType());
9607 if (Context.typesAreCompatible(PromoteType, TInfo->getType()))
9608 PromoteType = QualType();
9609 }
9610 if (TInfo->getType()->isSpecificBuiltinType(BuiltinType::Float))
9611 PromoteType = Context.DoubleTy;
9612 if (!PromoteType.isNull())
9613 Diag(TInfo->getTypeLoc().getBeginLoc(),
9614 diag::warn_second_parameter_to_va_arg_never_compatible)
9615 << TInfo->getType()
9616 << PromoteType
9617 << TInfo->getTypeLoc().getSourceRange();
David Majnemerc75d1a12011-06-14 05:17:32 +00009618 }
Mike Stump4e1f26a2009-02-19 03:04:26 +00009619
Abramo Bagnara27db2392010-08-10 10:06:15 +00009620 QualType T = TInfo->getType().getNonLValueExprType(Context);
9621 return Owned(new (Context) VAArgExpr(BuiltinLoc, E, TInfo, RPLoc, T));
Anders Carlsson7e13ab82007-10-15 20:28:48 +00009622}
9623
John McCalldadc5752010-08-24 06:29:42 +00009624ExprResult Sema::ActOnGNUNullExpr(SourceLocation TokenLoc) {
Douglas Gregor3be4b122008-11-29 04:51:27 +00009625 // The type of __null will be int or long, depending on the size of
9626 // pointers on the target.
9627 QualType Ty;
Douglas Gregore8bbc122011-09-02 00:18:52 +00009628 unsigned pw = Context.getTargetInfo().getPointerWidth(0);
9629 if (pw == Context.getTargetInfo().getIntWidth())
Douglas Gregor3be4b122008-11-29 04:51:27 +00009630 Ty = Context.IntTy;
Douglas Gregore8bbc122011-09-02 00:18:52 +00009631 else if (pw == Context.getTargetInfo().getLongWidth())
Douglas Gregor3be4b122008-11-29 04:51:27 +00009632 Ty = Context.LongTy;
Douglas Gregore8bbc122011-09-02 00:18:52 +00009633 else if (pw == Context.getTargetInfo().getLongLongWidth())
NAKAMURA Takumi0d13fd32011-01-19 00:11:41 +00009634 Ty = Context.LongLongTy;
9635 else {
David Blaikie83d382b2011-09-23 05:06:16 +00009636 llvm_unreachable("I don't know size of pointer!");
NAKAMURA Takumi0d13fd32011-01-19 00:11:41 +00009637 }
Douglas Gregor3be4b122008-11-29 04:51:27 +00009638
Sebastian Redl6d4256c2009-03-15 17:47:39 +00009639 return Owned(new (Context) GNUNullExpr(Ty, TokenLoc));
Douglas Gregor3be4b122008-11-29 04:51:27 +00009640}
9641
Alexis Huntc46382e2010-04-28 23:02:27 +00009642static void MakeObjCStringLiteralFixItHint(Sema& SemaRef, QualType DstType,
Douglas Gregora771f462010-03-31 17:46:05 +00009643 Expr *SrcExpr, FixItHint &Hint) {
David Blaikiebbafb8a2012-03-11 07:00:24 +00009644 if (!SemaRef.getLangOpts().ObjC1)
Anders Carlssonace5d072009-11-10 04:46:30 +00009645 return;
Kovarththanan Rajaratnamba2c6522010-03-13 10:17:05 +00009646
Anders Carlssonace5d072009-11-10 04:46:30 +00009647 const ObjCObjectPointerType *PT = DstType->getAs<ObjCObjectPointerType>();
9648 if (!PT)
9649 return;
9650
9651 // Check if the destination is of type 'id'.
9652 if (!PT->isObjCIdType()) {
9653 // Check if the destination is the 'NSString' interface.
9654 const ObjCInterfaceDecl *ID = PT->getInterfaceDecl();
9655 if (!ID || !ID->getIdentifier()->isStr("NSString"))
9656 return;
9657 }
Kovarththanan Rajaratnamba2c6522010-03-13 10:17:05 +00009658
John McCallfe96e0b2011-11-06 09:01:30 +00009659 // Ignore any parens, implicit casts (should only be
9660 // array-to-pointer decays), and not-so-opaque values. The last is
9661 // important for making this trigger for property assignments.
9662 SrcExpr = SrcExpr->IgnoreParenImpCasts();
9663 if (OpaqueValueExpr *OV = dyn_cast<OpaqueValueExpr>(SrcExpr))
9664 if (OV->getSourceExpr())
9665 SrcExpr = OV->getSourceExpr()->IgnoreParenImpCasts();
9666
9667 StringLiteral *SL = dyn_cast<StringLiteral>(SrcExpr);
Douglas Gregorfb65e592011-07-27 05:40:30 +00009668 if (!SL || !SL->isAscii())
Anders Carlssonace5d072009-11-10 04:46:30 +00009669 return;
Kovarththanan Rajaratnamba2c6522010-03-13 10:17:05 +00009670
Douglas Gregora771f462010-03-31 17:46:05 +00009671 Hint = FixItHint::CreateInsertion(SL->getLocStart(), "@");
Anders Carlssonace5d072009-11-10 04:46:30 +00009672}
9673
Chris Lattner9bad62c2008-01-04 18:04:52 +00009674bool Sema::DiagnoseAssignmentResult(AssignConvertType ConvTy,
9675 SourceLocation Loc,
9676 QualType DstType, QualType SrcType,
Douglas Gregor4f4946a2010-04-22 00:20:18 +00009677 Expr *SrcExpr, AssignmentAction Action,
9678 bool *Complained) {
9679 if (Complained)
9680 *Complained = false;
9681
Chris Lattner9bad62c2008-01-04 18:04:52 +00009682 // Decode the result (notice that AST's are still created for extensions).
Douglas Gregor33823722011-06-11 01:09:30 +00009683 bool CheckInferredResultType = false;
Chris Lattner9bad62c2008-01-04 18:04:52 +00009684 bool isInvalid = false;
Eli Friedman381f4312012-02-29 20:59:56 +00009685 unsigned DiagKind = 0;
Douglas Gregora771f462010-03-31 17:46:05 +00009686 FixItHint Hint;
Anna Zaks3b402712011-07-28 19:51:27 +00009687 ConversionFixItGenerator ConvHints;
9688 bool MayHaveConvFixit = false;
Richard Trieucaff2472011-11-23 22:32:32 +00009689 bool MayHaveFunctionDiff = false;
Kovarththanan Rajaratnamba2c6522010-03-13 10:17:05 +00009690
Chris Lattner9bad62c2008-01-04 18:04:52 +00009691 switch (ConvTy) {
Fariborz Jahanian268fec12012-07-17 18:00:08 +00009692 case Compatible:
9693 DiagnoseAssignmentEnum(DstType, SrcType, SrcExpr);
9694 return false;
9695
Chris Lattner940cfeb2008-01-04 18:22:42 +00009696 case PointerToInt:
Chris Lattner9bad62c2008-01-04 18:04:52 +00009697 DiagKind = diag::ext_typecheck_convert_pointer_int;
Anna Zaks3b402712011-07-28 19:51:27 +00009698 ConvHints.tryToFixConversion(SrcExpr, SrcType, DstType, *this);
9699 MayHaveConvFixit = true;
Chris Lattner9bad62c2008-01-04 18:04:52 +00009700 break;
Chris Lattner940cfeb2008-01-04 18:22:42 +00009701 case IntToPointer:
9702 DiagKind = diag::ext_typecheck_convert_int_pointer;
Anna Zaks3b402712011-07-28 19:51:27 +00009703 ConvHints.tryToFixConversion(SrcExpr, SrcType, DstType, *this);
9704 MayHaveConvFixit = true;
Chris Lattner940cfeb2008-01-04 18:22:42 +00009705 break;
Chris Lattner9bad62c2008-01-04 18:04:52 +00009706 case IncompatiblePointer:
Douglas Gregora771f462010-03-31 17:46:05 +00009707 MakeObjCStringLiteralFixItHint(*this, DstType, SrcExpr, Hint);
Chris Lattner9bad62c2008-01-04 18:04:52 +00009708 DiagKind = diag::ext_typecheck_convert_incompatible_pointer;
Douglas Gregor33823722011-06-11 01:09:30 +00009709 CheckInferredResultType = DstType->isObjCObjectPointerType() &&
9710 SrcType->isObjCObjectPointerType();
Anna Zaks3b402712011-07-28 19:51:27 +00009711 if (Hint.isNull() && !CheckInferredResultType) {
9712 ConvHints.tryToFixConversion(SrcExpr, SrcType, DstType, *this);
9713 }
9714 MayHaveConvFixit = true;
Chris Lattner9bad62c2008-01-04 18:04:52 +00009715 break;
Eli Friedman80160bd2009-03-22 23:59:44 +00009716 case IncompatiblePointerSign:
9717 DiagKind = diag::ext_typecheck_convert_incompatible_pointer_sign;
9718 break;
Chris Lattner9bad62c2008-01-04 18:04:52 +00009719 case FunctionVoidPointer:
9720 DiagKind = diag::ext_typecheck_convert_pointer_void_func;
9721 break;
John McCall4fff8f62011-02-01 00:10:29 +00009722 case IncompatiblePointerDiscardsQualifiers: {
John McCall71de91c2011-02-01 23:28:01 +00009723 // Perform array-to-pointer decay if necessary.
9724 if (SrcType->isArrayType()) SrcType = Context.getArrayDecayedType(SrcType);
9725
John McCall4fff8f62011-02-01 00:10:29 +00009726 Qualifiers lhq = SrcType->getPointeeType().getQualifiers();
9727 Qualifiers rhq = DstType->getPointeeType().getQualifiers();
9728 if (lhq.getAddressSpace() != rhq.getAddressSpace()) {
9729 DiagKind = diag::err_typecheck_incompatible_address_space;
9730 break;
John McCall31168b02011-06-15 23:02:42 +00009731
9732
9733 } else if (lhq.getObjCLifetime() != rhq.getObjCLifetime()) {
Argyrios Kyrtzidiscff00d92011-06-24 00:08:59 +00009734 DiagKind = diag::err_typecheck_incompatible_ownership;
John McCall31168b02011-06-15 23:02:42 +00009735 break;
John McCall4fff8f62011-02-01 00:10:29 +00009736 }
9737
9738 llvm_unreachable("unknown error case for discarding qualifiers!");
9739 // fallthrough
9740 }
Chris Lattner9bad62c2008-01-04 18:04:52 +00009741 case CompatiblePointerDiscardsQualifiers:
Douglas Gregoraa1e21d2008-09-12 00:47:35 +00009742 // If the qualifiers lost were because we were applying the
9743 // (deprecated) C++ conversion from a string literal to a char*
9744 // (or wchar_t*), then there was no error (C++ 4.2p2). FIXME:
9745 // Ideally, this check would be performed in
John McCallaba90822011-01-31 23:13:11 +00009746 // checkPointerTypesForAssignment. However, that would require a
Douglas Gregoraa1e21d2008-09-12 00:47:35 +00009747 // bit of refactoring (so that the second argument is an
9748 // expression, rather than a type), which should be done as part
John McCallaba90822011-01-31 23:13:11 +00009749 // of a larger effort to fix checkPointerTypesForAssignment for
Douglas Gregoraa1e21d2008-09-12 00:47:35 +00009750 // C++ semantics.
David Blaikiebbafb8a2012-03-11 07:00:24 +00009751 if (getLangOpts().CPlusPlus &&
Douglas Gregoraa1e21d2008-09-12 00:47:35 +00009752 IsStringLiteralToNonConstPointerConversion(SrcExpr, DstType))
9753 return false;
Chris Lattner9bad62c2008-01-04 18:04:52 +00009754 DiagKind = diag::ext_typecheck_convert_discards_qualifiers;
9755 break;
Alexis Hunt6f3de502009-11-08 07:46:34 +00009756 case IncompatibleNestedPointerQualifiers:
Fariborz Jahanianb98dade2009-11-09 22:16:37 +00009757 DiagKind = diag::ext_nested_pointer_qualifier_mismatch;
Fariborz Jahaniand7aa9d82009-11-07 20:20:40 +00009758 break;
Steve Naroff081c7422008-09-04 15:10:53 +00009759 case IntToBlockPointer:
9760 DiagKind = diag::err_int_to_block_pointer;
9761 break;
9762 case IncompatibleBlockPointer:
Mike Stumpd79b5a82009-04-21 22:51:42 +00009763 DiagKind = diag::err_typecheck_convert_incompatible_block_pointer;
Steve Naroff081c7422008-09-04 15:10:53 +00009764 break;
Steve Naroff8afa9892008-10-14 22:18:38 +00009765 case IncompatibleObjCQualifiedId:
Mike Stump4e1f26a2009-02-19 03:04:26 +00009766 // FIXME: Diagnose the problem in ObjCQualifiedIdTypesAreCompatible, since
Steve Naroff8afa9892008-10-14 22:18:38 +00009767 // it can give a more specific diagnostic.
9768 DiagKind = diag::warn_incompatible_qualified_id;
9769 break;
Anders Carlssondb5a9b62009-01-30 23:17:46 +00009770 case IncompatibleVectors:
9771 DiagKind = diag::warn_incompatible_vectors;
9772 break;
Fariborz Jahanian6f472e82011-07-07 18:55:47 +00009773 case IncompatibleObjCWeakRef:
9774 DiagKind = diag::err_arc_weak_unavailable_assign;
9775 break;
Chris Lattner9bad62c2008-01-04 18:04:52 +00009776 case Incompatible:
9777 DiagKind = diag::err_typecheck_convert_incompatible;
Anna Zaks3b402712011-07-28 19:51:27 +00009778 ConvHints.tryToFixConversion(SrcExpr, SrcType, DstType, *this);
9779 MayHaveConvFixit = true;
Chris Lattner9bad62c2008-01-04 18:04:52 +00009780 isInvalid = true;
Richard Trieucaff2472011-11-23 22:32:32 +00009781 MayHaveFunctionDiff = true;
Chris Lattner9bad62c2008-01-04 18:04:52 +00009782 break;
9783 }
Mike Stump4e1f26a2009-02-19 03:04:26 +00009784
Douglas Gregorc68e1402010-04-09 00:35:39 +00009785 QualType FirstType, SecondType;
9786 switch (Action) {
9787 case AA_Assigning:
9788 case AA_Initializing:
9789 // The destination type comes first.
9790 FirstType = DstType;
9791 SecondType = SrcType;
9792 break;
Alexis Huntc46382e2010-04-28 23:02:27 +00009793
Douglas Gregorc68e1402010-04-09 00:35:39 +00009794 case AA_Returning:
9795 case AA_Passing:
9796 case AA_Converting:
9797 case AA_Sending:
9798 case AA_Casting:
9799 // The source type comes first.
9800 FirstType = SrcType;
9801 SecondType = DstType;
9802 break;
9803 }
Alexis Huntc46382e2010-04-28 23:02:27 +00009804
Anna Zaks3b402712011-07-28 19:51:27 +00009805 PartialDiagnostic FDiag = PDiag(DiagKind);
9806 FDiag << FirstType << SecondType << Action << SrcExpr->getSourceRange();
9807
9808 // If we can fix the conversion, suggest the FixIts.
9809 assert(ConvHints.isNull() || Hint.isNull());
9810 if (!ConvHints.isNull()) {
Benjamin Kramer490afa62012-01-14 21:05:10 +00009811 for (std::vector<FixItHint>::iterator HI = ConvHints.Hints.begin(),
9812 HE = ConvHints.Hints.end(); HI != HE; ++HI)
Anna Zaks3b402712011-07-28 19:51:27 +00009813 FDiag << *HI;
9814 } else {
9815 FDiag << Hint;
9816 }
9817 if (MayHaveConvFixit) { FDiag << (unsigned) (ConvHints.Kind); }
9818
Richard Trieucaff2472011-11-23 22:32:32 +00009819 if (MayHaveFunctionDiff)
9820 HandleFunctionTypeMismatch(FDiag, SecondType, FirstType);
9821
Anna Zaks3b402712011-07-28 19:51:27 +00009822 Diag(Loc, FDiag);
9823
Richard Trieucaff2472011-11-23 22:32:32 +00009824 if (SecondType == Context.OverloadTy)
9825 NoteAllOverloadCandidates(OverloadExpr::find(SrcExpr).Expression,
9826 FirstType);
9827
Douglas Gregor33823722011-06-11 01:09:30 +00009828 if (CheckInferredResultType)
9829 EmitRelatedResultTypeNote(SrcExpr);
9830
Douglas Gregor4f4946a2010-04-22 00:20:18 +00009831 if (Complained)
9832 *Complained = true;
Chris Lattner9bad62c2008-01-04 18:04:52 +00009833 return isInvalid;
9834}
Anders Carlssone54e8a12008-11-30 19:50:32 +00009835
Richard Smithf4c51d92012-02-04 09:53:13 +00009836ExprResult Sema::VerifyIntegerConstantExpression(Expr *E,
9837 llvm::APSInt *Result) {
Douglas Gregore2b37442012-05-04 22:38:52 +00009838 class SimpleICEDiagnoser : public VerifyICEDiagnoser {
9839 public:
9840 virtual void diagnoseNotICE(Sema &S, SourceLocation Loc, SourceRange SR) {
9841 S.Diag(Loc, diag::err_expr_not_ice) << S.LangOpts.CPlusPlus << SR;
9842 }
9843 } Diagnoser;
9844
9845 return VerifyIntegerConstantExpression(E, Result, Diagnoser);
9846}
9847
9848ExprResult Sema::VerifyIntegerConstantExpression(Expr *E,
9849 llvm::APSInt *Result,
9850 unsigned DiagID,
9851 bool AllowFold) {
9852 class IDDiagnoser : public VerifyICEDiagnoser {
9853 unsigned DiagID;
9854
9855 public:
9856 IDDiagnoser(unsigned DiagID)
9857 : VerifyICEDiagnoser(DiagID == 0), DiagID(DiagID) { }
9858
9859 virtual void diagnoseNotICE(Sema &S, SourceLocation Loc, SourceRange SR) {
9860 S.Diag(Loc, DiagID) << SR;
9861 }
9862 } Diagnoser(DiagID);
9863
9864 return VerifyIntegerConstantExpression(E, Result, Diagnoser, AllowFold);
9865}
9866
9867void Sema::VerifyICEDiagnoser::diagnoseFold(Sema &S, SourceLocation Loc,
9868 SourceRange SR) {
9869 S.Diag(Loc, diag::ext_expr_not_ice) << SR << S.LangOpts.CPlusPlus;
Richard Smithf4c51d92012-02-04 09:53:13 +00009870}
9871
Benjamin Kramer33adaae2012-04-18 14:22:41 +00009872ExprResult
9873Sema::VerifyIntegerConstantExpression(Expr *E, llvm::APSInt *Result,
Douglas Gregore2b37442012-05-04 22:38:52 +00009874 VerifyICEDiagnoser &Diagnoser,
9875 bool AllowFold) {
Daniel Dunbar62ee6412012-03-09 18:35:03 +00009876 SourceLocation DiagLoc = E->getLocStart();
Richard Smithf4c51d92012-02-04 09:53:13 +00009877
David Blaikiebbafb8a2012-03-11 07:00:24 +00009878 if (getLangOpts().CPlusPlus0x) {
Richard Smithf4c51d92012-02-04 09:53:13 +00009879 // C++11 [expr.const]p5:
9880 // If an expression of literal class type is used in a context where an
9881 // integral constant expression is required, then that class type shall
9882 // have a single non-explicit conversion function to an integral or
9883 // unscoped enumeration type
9884 ExprResult Converted;
Douglas Gregore2b37442012-05-04 22:38:52 +00009885 if (!Diagnoser.Suppress) {
9886 class CXX11ConvertDiagnoser : public ICEConvertDiagnoser {
9887 public:
9888 CXX11ConvertDiagnoser() : ICEConvertDiagnoser(false, true) { }
9889
9890 virtual DiagnosticBuilder diagnoseNotInt(Sema &S, SourceLocation Loc,
9891 QualType T) {
9892 return S.Diag(Loc, diag::err_ice_not_integral) << T;
9893 }
9894
9895 virtual DiagnosticBuilder diagnoseIncomplete(Sema &S,
9896 SourceLocation Loc,
9897 QualType T) {
9898 return S.Diag(Loc, diag::err_ice_incomplete_type) << T;
9899 }
9900
9901 virtual DiagnosticBuilder diagnoseExplicitConv(Sema &S,
9902 SourceLocation Loc,
9903 QualType T,
9904 QualType ConvTy) {
9905 return S.Diag(Loc, diag::err_ice_explicit_conversion) << T << ConvTy;
9906 }
9907
9908 virtual DiagnosticBuilder noteExplicitConv(Sema &S,
9909 CXXConversionDecl *Conv,
9910 QualType ConvTy) {
9911 return S.Diag(Conv->getLocation(), diag::note_ice_conversion_here)
9912 << ConvTy->isEnumeralType() << ConvTy;
9913 }
9914
9915 virtual DiagnosticBuilder diagnoseAmbiguous(Sema &S, SourceLocation Loc,
9916 QualType T) {
9917 return S.Diag(Loc, diag::err_ice_ambiguous_conversion) << T;
9918 }
9919
9920 virtual DiagnosticBuilder noteAmbiguous(Sema &S,
9921 CXXConversionDecl *Conv,
9922 QualType ConvTy) {
9923 return S.Diag(Conv->getLocation(), diag::note_ice_conversion_here)
9924 << ConvTy->isEnumeralType() << ConvTy;
9925 }
9926
9927 virtual DiagnosticBuilder diagnoseConversion(Sema &S,
9928 SourceLocation Loc,
9929 QualType T,
9930 QualType ConvTy) {
9931 return DiagnosticBuilder::getEmpty();
9932 }
9933 } ConvertDiagnoser;
9934
9935 Converted = ConvertToIntegralOrEnumerationType(DiagLoc, E,
9936 ConvertDiagnoser,
9937 /*AllowScopedEnumerations*/ false);
Richard Smithf4c51d92012-02-04 09:53:13 +00009938 } else {
9939 // The caller wants to silently enquire whether this is an ICE. Don't
9940 // produce any diagnostics if it isn't.
Douglas Gregore2b37442012-05-04 22:38:52 +00009941 class SilentICEConvertDiagnoser : public ICEConvertDiagnoser {
9942 public:
9943 SilentICEConvertDiagnoser() : ICEConvertDiagnoser(true, true) { }
9944
9945 virtual DiagnosticBuilder diagnoseNotInt(Sema &S, SourceLocation Loc,
9946 QualType T) {
9947 return DiagnosticBuilder::getEmpty();
9948 }
9949
9950 virtual DiagnosticBuilder diagnoseIncomplete(Sema &S,
9951 SourceLocation Loc,
9952 QualType T) {
9953 return DiagnosticBuilder::getEmpty();
9954 }
9955
9956 virtual DiagnosticBuilder diagnoseExplicitConv(Sema &S,
9957 SourceLocation Loc,
9958 QualType T,
9959 QualType ConvTy) {
9960 return DiagnosticBuilder::getEmpty();
9961 }
9962
9963 virtual DiagnosticBuilder noteExplicitConv(Sema &S,
9964 CXXConversionDecl *Conv,
9965 QualType ConvTy) {
9966 return DiagnosticBuilder::getEmpty();
9967 }
9968
9969 virtual DiagnosticBuilder diagnoseAmbiguous(Sema &S, SourceLocation Loc,
9970 QualType T) {
9971 return DiagnosticBuilder::getEmpty();
9972 }
9973
9974 virtual DiagnosticBuilder noteAmbiguous(Sema &S,
9975 CXXConversionDecl *Conv,
9976 QualType ConvTy) {
9977 return DiagnosticBuilder::getEmpty();
9978 }
9979
9980 virtual DiagnosticBuilder diagnoseConversion(Sema &S,
9981 SourceLocation Loc,
9982 QualType T,
9983 QualType ConvTy) {
9984 return DiagnosticBuilder::getEmpty();
9985 }
9986 } ConvertDiagnoser;
9987
9988 Converted = ConvertToIntegralOrEnumerationType(DiagLoc, E,
9989 ConvertDiagnoser, false);
Richard Smithf4c51d92012-02-04 09:53:13 +00009990 }
9991 if (Converted.isInvalid())
9992 return Converted;
9993 E = Converted.take();
9994 if (!E->getType()->isIntegralOrUnscopedEnumerationType())
9995 return ExprError();
9996 } else if (!E->getType()->isIntegralOrUnscopedEnumerationType()) {
9997 // An ICE must be of integral or unscoped enumeration type.
Douglas Gregore2b37442012-05-04 22:38:52 +00009998 if (!Diagnoser.Suppress)
9999 Diagnoser.diagnoseNotICE(*this, DiagLoc, E->getSourceRange());
Richard Smithf4c51d92012-02-04 09:53:13 +000010000 return ExprError();
10001 }
10002
Richard Smith902ca212011-12-14 23:32:26 +000010003 // Circumvent ICE checking in C++11 to avoid evaluating the expression twice
10004 // in the non-ICE case.
David Blaikiebbafb8a2012-03-11 07:00:24 +000010005 if (!getLangOpts().CPlusPlus0x && E->isIntegerConstantExpr(Context)) {
Richard Smithf4c51d92012-02-04 09:53:13 +000010006 if (Result)
10007 *Result = E->EvaluateKnownConstInt(Context);
10008 return Owned(E);
Eli Friedmanbb967cc2009-04-25 22:26:58 +000010009 }
10010
Anders Carlssone54e8a12008-11-30 19:50:32 +000010011 Expr::EvalResult EvalResult;
Richard Smith92b1ce02011-12-12 09:28:41 +000010012 llvm::SmallVector<PartialDiagnosticAt, 8> Notes;
10013 EvalResult.Diag = &Notes;
Anders Carlssone54e8a12008-11-30 19:50:32 +000010014
Richard Smith902ca212011-12-14 23:32:26 +000010015 // Try to evaluate the expression, and produce diagnostics explaining why it's
10016 // not a constant expression as a side-effect.
10017 bool Folded = E->EvaluateAsRValue(EvalResult, Context) &&
10018 EvalResult.Val.isInt() && !EvalResult.HasSideEffects;
10019
10020 // In C++11, we can rely on diagnostics being produced for any expression
10021 // which is not a constant expression. If no diagnostics were produced, then
10022 // this is a constant expression.
David Blaikiebbafb8a2012-03-11 07:00:24 +000010023 if (Folded && getLangOpts().CPlusPlus0x && Notes.empty()) {
Richard Smith902ca212011-12-14 23:32:26 +000010024 if (Result)
10025 *Result = EvalResult.Val.getInt();
Richard Smithf4c51d92012-02-04 09:53:13 +000010026 return Owned(E);
10027 }
10028
10029 // If our only note is the usual "invalid subexpression" note, just point
10030 // the caret at its location rather than producing an essentially
10031 // redundant note.
10032 if (Notes.size() == 1 && Notes[0].second.getDiagID() ==
10033 diag::note_invalid_subexpr_in_const_expr) {
10034 DiagLoc = Notes[0].first;
10035 Notes.clear();
Richard Smith902ca212011-12-14 23:32:26 +000010036 }
10037
10038 if (!Folded || !AllowFold) {
Douglas Gregore2b37442012-05-04 22:38:52 +000010039 if (!Diagnoser.Suppress) {
10040 Diagnoser.diagnoseNotICE(*this, DiagLoc, E->getSourceRange());
Richard Smith92b1ce02011-12-12 09:28:41 +000010041 for (unsigned I = 0, N = Notes.size(); I != N; ++I)
10042 Diag(Notes[I].first, Notes[I].second);
Anders Carlssone54e8a12008-11-30 19:50:32 +000010043 }
Mike Stump4e1f26a2009-02-19 03:04:26 +000010044
Richard Smithf4c51d92012-02-04 09:53:13 +000010045 return ExprError();
Anders Carlssone54e8a12008-11-30 19:50:32 +000010046 }
10047
Douglas Gregore2b37442012-05-04 22:38:52 +000010048 Diagnoser.diagnoseFold(*this, DiagLoc, E->getSourceRange());
Richard Smith2ec40612012-01-15 03:51:30 +000010049 for (unsigned I = 0, N = Notes.size(); I != N; ++I)
10050 Diag(Notes[I].first, Notes[I].second);
Mike Stump4e1f26a2009-02-19 03:04:26 +000010051
Anders Carlssone54e8a12008-11-30 19:50:32 +000010052 if (Result)
10053 *Result = EvalResult.Val.getInt();
Richard Smithf4c51d92012-02-04 09:53:13 +000010054 return Owned(E);
Anders Carlssone54e8a12008-11-30 19:50:32 +000010055}
Douglas Gregorc9c02ed2009-06-19 23:52:42 +000010056
Eli Friedman456f0182012-01-20 01:26:23 +000010057namespace {
10058 // Handle the case where we conclude a expression which we speculatively
10059 // considered to be unevaluated is actually evaluated.
10060 class TransformToPE : public TreeTransform<TransformToPE> {
10061 typedef TreeTransform<TransformToPE> BaseTransform;
10062
10063 public:
10064 TransformToPE(Sema &SemaRef) : BaseTransform(SemaRef) { }
10065
10066 // Make sure we redo semantic analysis
10067 bool AlwaysRebuild() { return true; }
10068
Eli Friedman5f0ca242012-02-06 23:29:57 +000010069 // Make sure we handle LabelStmts correctly.
10070 // FIXME: This does the right thing, but maybe we need a more general
10071 // fix to TreeTransform?
10072 StmtResult TransformLabelStmt(LabelStmt *S) {
10073 S->getDecl()->setStmt(0);
10074 return BaseTransform::TransformLabelStmt(S);
10075 }
10076
Eli Friedman456f0182012-01-20 01:26:23 +000010077 // We need to special-case DeclRefExprs referring to FieldDecls which
10078 // are not part of a member pointer formation; normal TreeTransforming
10079 // doesn't catch this case because of the way we represent them in the AST.
10080 // FIXME: This is a bit ugly; is it really the best way to handle this
10081 // case?
10082 //
10083 // Error on DeclRefExprs referring to FieldDecls.
10084 ExprResult TransformDeclRefExpr(DeclRefExpr *E) {
10085 if (isa<FieldDecl>(E->getDecl()) &&
David Blaikie131fcb42012-08-06 22:47:24 +000010086 !SemaRef.isUnevaluatedContext())
Eli Friedman456f0182012-01-20 01:26:23 +000010087 return SemaRef.Diag(E->getLocation(),
10088 diag::err_invalid_non_static_member_use)
10089 << E->getDecl() << E->getSourceRange();
10090
10091 return BaseTransform::TransformDeclRefExpr(E);
10092 }
10093
10094 // Exception: filter out member pointer formation
10095 ExprResult TransformUnaryOperator(UnaryOperator *E) {
10096 if (E->getOpcode() == UO_AddrOf && E->getType()->isMemberPointerType())
10097 return E;
10098
10099 return BaseTransform::TransformUnaryOperator(E);
10100 }
10101
Douglas Gregor89625492012-02-09 08:14:43 +000010102 ExprResult TransformLambdaExpr(LambdaExpr *E) {
10103 // Lambdas never need to be transformed.
10104 return E;
10105 }
Eli Friedman456f0182012-01-20 01:26:23 +000010106 };
Eli Friedmanfbc0dff2012-01-18 01:05:54 +000010107}
10108
Eli Friedman456f0182012-01-20 01:26:23 +000010109ExprResult Sema::TranformToPotentiallyEvaluated(Expr *E) {
Eli Friedmane4f22df2012-02-29 04:03:55 +000010110 assert(ExprEvalContexts.back().Context == Unevaluated &&
10111 "Should only transform unevaluated expressions");
Eli Friedman456f0182012-01-20 01:26:23 +000010112 ExprEvalContexts.back().Context =
10113 ExprEvalContexts[ExprEvalContexts.size()-2].Context;
10114 if (ExprEvalContexts.back().Context == Unevaluated)
10115 return E;
10116 return TransformToPE(*this).TransformExpr(E);
Eli Friedmanfbc0dff2012-01-18 01:05:54 +000010117}
10118
Douglas Gregorff790f12009-11-26 00:44:06 +000010119void
Douglas Gregor7fcbd902012-02-21 00:37:24 +000010120Sema::PushExpressionEvaluationContext(ExpressionEvaluationContext NewContext,
Richard Smithfd555f62012-02-22 02:04:18 +000010121 Decl *LambdaContextDecl,
10122 bool IsDecltype) {
Douglas Gregorff790f12009-11-26 00:44:06 +000010123 ExprEvalContexts.push_back(
John McCall31168b02011-06-15 23:02:42 +000010124 ExpressionEvaluationContextRecord(NewContext,
John McCall28fc7092011-11-10 05:35:25 +000010125 ExprCleanupObjects.size(),
Douglas Gregor7fcbd902012-02-21 00:37:24 +000010126 ExprNeedsCleanups,
Richard Smithfd555f62012-02-22 02:04:18 +000010127 LambdaContextDecl,
10128 IsDecltype));
John McCall31168b02011-06-15 23:02:42 +000010129 ExprNeedsCleanups = false;
Eli Friedman3bda6b12012-02-02 23:15:15 +000010130 if (!MaybeODRUseExprs.empty())
10131 std::swap(MaybeODRUseExprs, ExprEvalContexts.back().SavedMaybeODRUseExprs);
Douglas Gregor0b6a6242009-06-22 20:57:11 +000010132}
10133
Richard Trieucfc491d2011-08-02 04:35:43 +000010134void Sema::PopExpressionEvaluationContext() {
Eli Friedmanfa0df832012-02-02 03:46:19 +000010135 ExpressionEvaluationContextRecord& Rec = ExprEvalContexts.back();
Douglas Gregor0b6a6242009-06-22 20:57:11 +000010136
Douglas Gregor89625492012-02-09 08:14:43 +000010137 if (!Rec.Lambdas.empty()) {
10138 if (Rec.Context == Unevaluated) {
10139 // C++11 [expr.prim.lambda]p2:
10140 // A lambda-expression shall not appear in an unevaluated operand
10141 // (Clause 5).
10142 for (unsigned I = 0, N = Rec.Lambdas.size(); I != N; ++I)
10143 Diag(Rec.Lambdas[I]->getLocStart(),
10144 diag::err_lambda_unevaluated_operand);
10145 } else {
10146 // Mark the capture expressions odr-used. This was deferred
10147 // during lambda expression creation.
10148 for (unsigned I = 0, N = Rec.Lambdas.size(); I != N; ++I) {
10149 LambdaExpr *Lambda = Rec.Lambdas[I];
10150 for (LambdaExpr::capture_init_iterator
10151 C = Lambda->capture_init_begin(),
10152 CEnd = Lambda->capture_init_end();
10153 C != CEnd; ++C) {
10154 MarkDeclarationsReferencedInExpr(*C);
10155 }
10156 }
10157 }
10158 }
10159
Douglas Gregorff790f12009-11-26 00:44:06 +000010160 // When are coming out of an unevaluated context, clear out any
10161 // temporaries that we may have created as part of the evaluation of
10162 // the expression in that context: they aren't relevant because they
10163 // will never be constructed.
Richard Smith764d2fe2011-12-20 02:08:33 +000010164 if (Rec.Context == Unevaluated || Rec.Context == ConstantEvaluated) {
John McCall28fc7092011-11-10 05:35:25 +000010165 ExprCleanupObjects.erase(ExprCleanupObjects.begin() + Rec.NumCleanupObjects,
10166 ExprCleanupObjects.end());
John McCall31168b02011-06-15 23:02:42 +000010167 ExprNeedsCleanups = Rec.ParentNeedsCleanups;
Eli Friedman3bda6b12012-02-02 23:15:15 +000010168 CleanupVarDeclMarking();
10169 std::swap(MaybeODRUseExprs, Rec.SavedMaybeODRUseExprs);
John McCall31168b02011-06-15 23:02:42 +000010170 // Otherwise, merge the contexts together.
10171 } else {
10172 ExprNeedsCleanups |= Rec.ParentNeedsCleanups;
Eli Friedman3bda6b12012-02-02 23:15:15 +000010173 MaybeODRUseExprs.insert(Rec.SavedMaybeODRUseExprs.begin(),
10174 Rec.SavedMaybeODRUseExprs.end());
John McCall31168b02011-06-15 23:02:42 +000010175 }
Eli Friedmanfa0df832012-02-02 03:46:19 +000010176
10177 // Pop the current expression evaluation context off the stack.
10178 ExprEvalContexts.pop_back();
Douglas Gregor0b6a6242009-06-22 20:57:11 +000010179}
Douglas Gregorc9c02ed2009-06-19 23:52:42 +000010180
John McCall31168b02011-06-15 23:02:42 +000010181void Sema::DiscardCleanupsInEvaluationContext() {
John McCall28fc7092011-11-10 05:35:25 +000010182 ExprCleanupObjects.erase(
10183 ExprCleanupObjects.begin() + ExprEvalContexts.back().NumCleanupObjects,
10184 ExprCleanupObjects.end());
John McCall31168b02011-06-15 23:02:42 +000010185 ExprNeedsCleanups = false;
Eli Friedman3bda6b12012-02-02 23:15:15 +000010186 MaybeODRUseExprs.clear();
John McCall31168b02011-06-15 23:02:42 +000010187}
10188
Eli Friedmane0afc982012-01-21 01:01:51 +000010189ExprResult Sema::HandleExprEvaluationContextForTypeof(Expr *E) {
10190 if (!E->getType()->isVariablyModifiedType())
10191 return E;
10192 return TranformToPotentiallyEvaluated(E);
10193}
10194
Benjamin Kramerbf8da9d2012-02-06 11:13:08 +000010195static bool IsPotentiallyEvaluatedContext(Sema &SemaRef) {
Douglas Gregorc9c02ed2009-06-19 23:52:42 +000010196 // Do not mark anything as "used" within a dependent context; wait for
10197 // an instantiation.
Eli Friedmanfa0df832012-02-02 03:46:19 +000010198 if (SemaRef.CurContext->isDependentContext())
10199 return false;
Mike Stump11289f42009-09-09 15:08:12 +000010200
Eli Friedmanfa0df832012-02-02 03:46:19 +000010201 switch (SemaRef.ExprEvalContexts.back().Context) {
10202 case Sema::Unevaluated:
Douglas Gregor0b6a6242009-06-22 20:57:11 +000010203 // We are in an expression that is not potentially evaluated; do nothing.
Eli Friedman02b58512012-01-21 04:44:06 +000010204 // (Depending on how you read the standard, we actually do need to do
10205 // something here for null pointer constants, but the standard's
10206 // definition of a null pointer constant is completely crazy.)
Eli Friedmanfa0df832012-02-02 03:46:19 +000010207 return false;
Mike Stump11289f42009-09-09 15:08:12 +000010208
Eli Friedmanfa0df832012-02-02 03:46:19 +000010209 case Sema::ConstantEvaluated:
10210 case Sema::PotentiallyEvaluated:
Eli Friedman02b58512012-01-21 04:44:06 +000010211 // We are in a potentially evaluated expression (or a constant-expression
10212 // in C++03); we need to do implicit template instantiation, implicitly
10213 // define class members, and mark most declarations as used.
Eli Friedmanfa0df832012-02-02 03:46:19 +000010214 return true;
Mike Stump11289f42009-09-09 15:08:12 +000010215
Eli Friedmanfa0df832012-02-02 03:46:19 +000010216 case Sema::PotentiallyEvaluatedIfUsed:
Douglas Gregor8a01b2a2010-09-11 20:24:53 +000010217 // Referenced declarations will only be used if the construct in the
10218 // containing expression is used.
Eli Friedmanfa0df832012-02-02 03:46:19 +000010219 return false;
Douglas Gregor0b6a6242009-06-22 20:57:11 +000010220 }
Matt Beaumont-Gay248bc722012-02-02 18:35:35 +000010221 llvm_unreachable("Invalid context");
Eli Friedmanfa0df832012-02-02 03:46:19 +000010222}
10223
10224/// \brief Mark a function referenced, and check whether it is odr-used
10225/// (C++ [basic.def.odr]p2, C99 6.9p3)
10226void Sema::MarkFunctionReferenced(SourceLocation Loc, FunctionDecl *Func) {
10227 assert(Func && "No function?");
10228
10229 Func->setReferenced();
10230
Richard Smith4a941e22012-02-14 22:25:15 +000010231 // Don't mark this function as used multiple times, unless it's a constexpr
10232 // function which we need to instantiate.
10233 if (Func->isUsed(false) &&
10234 !(Func->isConstexpr() && !Func->getBody() &&
10235 Func->isImplicitlyInstantiable()))
Eli Friedmanfa0df832012-02-02 03:46:19 +000010236 return;
10237
10238 if (!IsPotentiallyEvaluatedContext(*this))
10239 return;
Mike Stump11289f42009-09-09 15:08:12 +000010240
Douglas Gregorc9c02ed2009-06-19 23:52:42 +000010241 // Note that this declaration has been used.
Eli Friedmanfa0df832012-02-02 03:46:19 +000010242 if (CXXConstructorDecl *Constructor = dyn_cast<CXXConstructorDecl>(Func)) {
Richard Smith273c4e92012-02-26 07:51:39 +000010243 if (Constructor->isDefaulted() && !Constructor->isDeleted()) {
Sebastian Redl22653ba2011-08-30 19:58:05 +000010244 if (Constructor->isDefaultConstructor()) {
10245 if (Constructor->isTrivial())
10246 return;
10247 if (!Constructor->isUsed(false))
10248 DefineImplicitDefaultConstructor(Loc, Constructor);
10249 } else if (Constructor->isCopyConstructor()) {
10250 if (!Constructor->isUsed(false))
10251 DefineImplicitCopyConstructor(Loc, Constructor);
10252 } else if (Constructor->isMoveConstructor()) {
10253 if (!Constructor->isUsed(false))
10254 DefineImplicitMoveConstructor(Loc, Constructor);
10255 }
Fariborz Jahanian477d2422009-06-22 23:34:40 +000010256 }
Kovarththanan Rajaratnamba2c6522010-03-13 10:17:05 +000010257
Douglas Gregor88d292c2010-05-13 16:44:06 +000010258 MarkVTableUsed(Loc, Constructor->getParent());
Eli Friedmanfa0df832012-02-02 03:46:19 +000010259 } else if (CXXDestructorDecl *Destructor =
10260 dyn_cast<CXXDestructorDecl>(Func)) {
Richard Smith273c4e92012-02-26 07:51:39 +000010261 if (Destructor->isDefaulted() && !Destructor->isDeleted() &&
10262 !Destructor->isUsed(false))
Fariborz Jahanian24a175b2009-06-26 23:49:16 +000010263 DefineImplicitDestructor(Loc, Destructor);
Douglas Gregor88d292c2010-05-13 16:44:06 +000010264 if (Destructor->isVirtual())
10265 MarkVTableUsed(Loc, Destructor->getParent());
Eli Friedmanfa0df832012-02-02 03:46:19 +000010266 } else if (CXXMethodDecl *MethodDecl = dyn_cast<CXXMethodDecl>(Func)) {
Richard Smith273c4e92012-02-26 07:51:39 +000010267 if (MethodDecl->isDefaulted() && !MethodDecl->isDeleted() &&
10268 MethodDecl->isOverloadedOperator() &&
Fariborz Jahanian41f79272009-06-25 21:45:19 +000010269 MethodDecl->getOverloadedOperator() == OO_Equal) {
Sebastian Redl22653ba2011-08-30 19:58:05 +000010270 if (!MethodDecl->isUsed(false)) {
10271 if (MethodDecl->isCopyAssignmentOperator())
10272 DefineImplicitCopyAssignment(Loc, MethodDecl);
10273 else
10274 DefineImplicitMoveAssignment(Loc, MethodDecl);
10275 }
Douglas Gregord3b672c2012-02-16 01:06:16 +000010276 } else if (isa<CXXConversionDecl>(MethodDecl) &&
10277 MethodDecl->getParent()->isLambda()) {
10278 CXXConversionDecl *Conversion = cast<CXXConversionDecl>(MethodDecl);
10279 if (Conversion->isLambdaToBlockPointerConversion())
10280 DefineImplicitLambdaToBlockPointerConversion(Loc, Conversion);
10281 else
10282 DefineImplicitLambdaToFunctionPointerConversion(Loc, Conversion);
Douglas Gregor88d292c2010-05-13 16:44:06 +000010283 } else if (MethodDecl->isVirtual())
10284 MarkVTableUsed(Loc, MethodDecl->getParent());
Fariborz Jahanian41f79272009-06-25 21:45:19 +000010285 }
John McCall83779672011-02-19 02:53:41 +000010286
Eli Friedmanfa0df832012-02-02 03:46:19 +000010287 // Recursive functions should be marked when used from another function.
10288 // FIXME: Is this really right?
10289 if (CurContext == Func) return;
Kovarththanan Rajaratnamba2c6522010-03-13 10:17:05 +000010290
Richard Smithd3b5c9082012-07-27 04:22:15 +000010291 // Resolve the exception specification for any function which is
Richard Smithf623c962012-04-17 00:58:00 +000010292 // used: CodeGen will need it.
Richard Smithd3729422012-04-19 00:08:28 +000010293 const FunctionProtoType *FPT = Func->getType()->getAs<FunctionProtoType>();
Richard Smithd3b5c9082012-07-27 04:22:15 +000010294 if (FPT && isUnresolvedExceptionSpec(FPT->getExceptionSpecType()))
10295 ResolveExceptionSpec(Loc, FPT);
Richard Smithf623c962012-04-17 00:58:00 +000010296
Eli Friedmanfa0df832012-02-02 03:46:19 +000010297 // Implicit instantiation of function templates and member functions of
10298 // class templates.
10299 if (Func->isImplicitlyInstantiable()) {
10300 bool AlreadyInstantiated = false;
Richard Smith4a941e22012-02-14 22:25:15 +000010301 SourceLocation PointOfInstantiation = Loc;
Eli Friedmanfa0df832012-02-02 03:46:19 +000010302 if (FunctionTemplateSpecializationInfo *SpecInfo
10303 = Func->getTemplateSpecializationInfo()) {
10304 if (SpecInfo->getPointOfInstantiation().isInvalid())
10305 SpecInfo->setPointOfInstantiation(Loc);
10306 else if (SpecInfo->getTemplateSpecializationKind()
Richard Smith4a941e22012-02-14 22:25:15 +000010307 == TSK_ImplicitInstantiation) {
Eli Friedmanfa0df832012-02-02 03:46:19 +000010308 AlreadyInstantiated = true;
Richard Smith4a941e22012-02-14 22:25:15 +000010309 PointOfInstantiation = SpecInfo->getPointOfInstantiation();
10310 }
Eli Friedmanfa0df832012-02-02 03:46:19 +000010311 } else if (MemberSpecializationInfo *MSInfo
10312 = Func->getMemberSpecializationInfo()) {
10313 if (MSInfo->getPointOfInstantiation().isInvalid())
Douglas Gregor06db9f52009-10-12 20:18:28 +000010314 MSInfo->setPointOfInstantiation(Loc);
Eli Friedmanfa0df832012-02-02 03:46:19 +000010315 else if (MSInfo->getTemplateSpecializationKind()
Richard Smith4a941e22012-02-14 22:25:15 +000010316 == TSK_ImplicitInstantiation) {
Eli Friedmanfa0df832012-02-02 03:46:19 +000010317 AlreadyInstantiated = true;
Richard Smith4a941e22012-02-14 22:25:15 +000010318 PointOfInstantiation = MSInfo->getPointOfInstantiation();
10319 }
Douglas Gregor06db9f52009-10-12 20:18:28 +000010320 }
Mike Stump11289f42009-09-09 15:08:12 +000010321
Richard Smith4a941e22012-02-14 22:25:15 +000010322 if (!AlreadyInstantiated || Func->isConstexpr()) {
Eli Friedmanfa0df832012-02-02 03:46:19 +000010323 if (isa<CXXRecordDecl>(Func->getDeclContext()) &&
10324 cast<CXXRecordDecl>(Func->getDeclContext())->isLocalClass())
Richard Smith4a941e22012-02-14 22:25:15 +000010325 PendingLocalImplicitInstantiations.push_back(
10326 std::make_pair(Func, PointOfInstantiation));
10327 else if (Func->isConstexpr())
Eli Friedmanfa0df832012-02-02 03:46:19 +000010328 // Do not defer instantiations of constexpr functions, to avoid the
10329 // expression evaluator needing to call back into Sema if it sees a
10330 // call to such a function.
Richard Smith4a941e22012-02-14 22:25:15 +000010331 InstantiateFunctionDefinition(PointOfInstantiation, Func);
Argyrios Kyrtzidise5dc5b32012-02-10 20:10:44 +000010332 else {
Richard Smith4a941e22012-02-14 22:25:15 +000010333 PendingInstantiations.push_back(std::make_pair(Func,
10334 PointOfInstantiation));
Argyrios Kyrtzidise5dc5b32012-02-10 20:10:44 +000010335 // Notify the consumer that a function was implicitly instantiated.
10336 Consumer.HandleCXXImplicitFunctionInstantiation(Func);
10337 }
John McCall83779672011-02-19 02:53:41 +000010338 }
Eli Friedmanfa0df832012-02-02 03:46:19 +000010339 } else {
10340 // Walk redefinitions, as some of them may be instantiable.
10341 for (FunctionDecl::redecl_iterator i(Func->redecls_begin()),
10342 e(Func->redecls_end()); i != e; ++i) {
10343 if (!i->isUsed(false) && i->isImplicitlyInstantiable())
10344 MarkFunctionReferenced(Loc, *i);
10345 }
Sam Weinigbae69142009-09-11 03:29:30 +000010346 }
Eli Friedmanfa0df832012-02-02 03:46:19 +000010347
10348 // Keep track of used but undefined functions.
10349 if (!Func->isPure() && !Func->hasBody() &&
10350 Func->getLinkage() != ExternalLinkage) {
10351 SourceLocation &old = UndefinedInternals[Func->getCanonicalDecl()];
10352 if (old.isInvalid()) old = Loc;
10353 }
10354
10355 Func->setUsed(true);
10356}
10357
Eli Friedman9bb33f52012-02-03 02:04:35 +000010358static void
10359diagnoseUncapturableValueReference(Sema &S, SourceLocation loc,
10360 VarDecl *var, DeclContext *DC) {
Eli Friedmandd053f62012-02-07 00:15:00 +000010361 DeclContext *VarDC = var->getDeclContext();
10362
Eli Friedman9bb33f52012-02-03 02:04:35 +000010363 // If the parameter still belongs to the translation unit, then
10364 // we're actually just using one parameter in the declaration of
10365 // the next.
10366 if (isa<ParmVarDecl>(var) &&
Eli Friedmandd053f62012-02-07 00:15:00 +000010367 isa<TranslationUnitDecl>(VarDC))
Eli Friedman9bb33f52012-02-03 02:04:35 +000010368 return;
10369
Eli Friedmandd053f62012-02-07 00:15:00 +000010370 // For C code, don't diagnose about capture if we're not actually in code
10371 // right now; it's impossible to write a non-constant expression outside of
10372 // function context, so we'll get other (more useful) diagnostics later.
10373 //
10374 // For C++, things get a bit more nasty... it would be nice to suppress this
10375 // diagnostic for certain cases like using a local variable in an array bound
10376 // for a member of a local class, but the correct predicate is not obvious.
David Blaikiebbafb8a2012-03-11 07:00:24 +000010377 if (!S.getLangOpts().CPlusPlus && !S.CurContext->isFunctionOrMethod())
Eli Friedman9bb33f52012-02-03 02:04:35 +000010378 return;
10379
Eli Friedmandd053f62012-02-07 00:15:00 +000010380 if (isa<CXXMethodDecl>(VarDC) &&
10381 cast<CXXRecordDecl>(VarDC->getParent())->isLambda()) {
10382 S.Diag(loc, diag::err_reference_to_local_var_in_enclosing_lambda)
10383 << var->getIdentifier();
10384 } else if (FunctionDecl *fn = dyn_cast<FunctionDecl>(VarDC)) {
10385 S.Diag(loc, diag::err_reference_to_local_var_in_enclosing_function)
10386 << var->getIdentifier() << fn->getDeclName();
10387 } else if (isa<BlockDecl>(VarDC)) {
10388 S.Diag(loc, diag::err_reference_to_local_var_in_enclosing_block)
10389 << var->getIdentifier();
10390 } else {
10391 // FIXME: Is there any other context where a local variable can be
10392 // declared?
10393 S.Diag(loc, diag::err_reference_to_local_var_in_enclosing_context)
10394 << var->getIdentifier();
10395 }
Eli Friedman9bb33f52012-02-03 02:04:35 +000010396
Eli Friedman9bb33f52012-02-03 02:04:35 +000010397 S.Diag(var->getLocation(), diag::note_local_variable_declared_here)
10398 << var->getIdentifier();
Eli Friedmandd053f62012-02-07 00:15:00 +000010399
10400 // FIXME: Add additional diagnostic info about class etc. which prevents
10401 // capture.
Eli Friedman9bb33f52012-02-03 02:04:35 +000010402}
10403
Douglas Gregor81495f32012-02-12 18:42:33 +000010404/// \brief Capture the given variable in the given lambda expression.
10405static ExprResult captureInLambda(Sema &S, LambdaScopeInfo *LSI,
Douglas Gregorfdf598e2012-02-18 09:37:24 +000010406 VarDecl *Var, QualType FieldType,
10407 QualType DeclRefType,
Douglas Gregora8182f92012-05-16 17:01:33 +000010408 SourceLocation Loc,
10409 bool RefersToEnclosingLocal) {
Douglas Gregor81495f32012-02-12 18:42:33 +000010410 CXXRecordDecl *Lambda = LSI->Lambda;
Douglas Gregor81495f32012-02-12 18:42:33 +000010411
Douglas Gregorabecb9c2012-02-09 01:56:40 +000010412 // Build the non-static data member.
10413 FieldDecl *Field
10414 = FieldDecl::Create(S.Context, Lambda, Loc, Loc, 0, FieldType,
10415 S.Context.getTrivialTypeSourceInfo(FieldType, Loc),
Richard Smith2b013182012-06-10 03:12:00 +000010416 0, false, ICIS_NoInit);
Douglas Gregorabecb9c2012-02-09 01:56:40 +000010417 Field->setImplicit(true);
10418 Field->setAccess(AS_private);
Douglas Gregor3d23f7882012-02-09 02:12:34 +000010419 Lambda->addDecl(Field);
Douglas Gregorabecb9c2012-02-09 01:56:40 +000010420
10421 // C++11 [expr.prim.lambda]p21:
10422 // When the lambda-expression is evaluated, the entities that
10423 // are captured by copy are used to direct-initialize each
10424 // corresponding non-static data member of the resulting closure
10425 // object. (For array members, the array elements are
10426 // direct-initialized in increasing subscript order.) These
10427 // initializations are performed in the (unspecified) order in
10428 // which the non-static data members are declared.
Douglas Gregorabecb9c2012-02-09 01:56:40 +000010429
Douglas Gregor89625492012-02-09 08:14:43 +000010430 // Introduce a new evaluation context for the initialization, so
10431 // that temporaries introduced as part of the capture are retained
10432 // to be re-"exported" from the lambda expression itself.
Douglas Gregorabecb9c2012-02-09 01:56:40 +000010433 S.PushExpressionEvaluationContext(Sema::PotentiallyEvaluated);
10434
Douglas Gregorf02455e2012-02-10 09:26:04 +000010435 // C++ [expr.prim.labda]p12:
10436 // An entity captured by a lambda-expression is odr-used (3.2) in
10437 // the scope containing the lambda-expression.
Douglas Gregora8182f92012-05-16 17:01:33 +000010438 Expr *Ref = new (S.Context) DeclRefExpr(Var, RefersToEnclosingLocal,
10439 DeclRefType, VK_LValue, Loc);
Eli Friedman23b1be92012-03-01 21:32:56 +000010440 Var->setReferenced(true);
Douglas Gregorf02455e2012-02-10 09:26:04 +000010441 Var->setUsed(true);
Douglas Gregor199cec72012-02-09 02:45:47 +000010442
10443 // When the field has array type, create index variables for each
10444 // dimension of the array. We use these index variables to subscript
10445 // the source array, and other clients (e.g., CodeGen) will perform
10446 // the necessary iteration with these index variables.
10447 SmallVector<VarDecl *, 4> IndexVariables;
Douglas Gregor199cec72012-02-09 02:45:47 +000010448 QualType BaseType = FieldType;
10449 QualType SizeType = S.Context.getSizeType();
Douglas Gregor54fcea62012-02-13 16:35:30 +000010450 LSI->ArrayIndexStarts.push_back(LSI->ArrayIndexVars.size());
Douglas Gregor199cec72012-02-09 02:45:47 +000010451 while (const ConstantArrayType *Array
10452 = S.Context.getAsConstantArrayType(BaseType)) {
Douglas Gregor199cec72012-02-09 02:45:47 +000010453 // Create the iteration variable for this array index.
10454 IdentifierInfo *IterationVarName = 0;
10455 {
10456 SmallString<8> Str;
10457 llvm::raw_svector_ostream OS(Str);
10458 OS << "__i" << IndexVariables.size();
10459 IterationVarName = &S.Context.Idents.get(OS.str());
10460 }
10461 VarDecl *IterationVar
10462 = VarDecl::Create(S.Context, S.CurContext, Loc, Loc,
10463 IterationVarName, SizeType,
10464 S.Context.getTrivialTypeSourceInfo(SizeType, Loc),
10465 SC_None, SC_None);
10466 IndexVariables.push_back(IterationVar);
Douglas Gregor54fcea62012-02-13 16:35:30 +000010467 LSI->ArrayIndexVars.push_back(IterationVar);
10468
Douglas Gregor199cec72012-02-09 02:45:47 +000010469 // Create a reference to the iteration variable.
10470 ExprResult IterationVarRef
10471 = S.BuildDeclRefExpr(IterationVar, SizeType, VK_LValue, Loc);
10472 assert(!IterationVarRef.isInvalid() &&
10473 "Reference to invented variable cannot fail!");
10474 IterationVarRef = S.DefaultLvalueConversion(IterationVarRef.take());
10475 assert(!IterationVarRef.isInvalid() &&
10476 "Conversion of invented variable cannot fail!");
10477
10478 // Subscript the array with this iteration variable.
10479 ExprResult Subscript = S.CreateBuiltinArraySubscriptExpr(
10480 Ref, Loc, IterationVarRef.take(), Loc);
10481 if (Subscript.isInvalid()) {
10482 S.CleanupVarDeclMarking();
10483 S.DiscardCleanupsInEvaluationContext();
10484 S.PopExpressionEvaluationContext();
10485 return ExprError();
10486 }
10487
10488 Ref = Subscript.take();
10489 BaseType = Array->getElementType();
10490 }
10491
10492 // Construct the entity that we will be initializing. For an array, this
10493 // will be first element in the array, which may require several levels
10494 // of array-subscript entities.
10495 SmallVector<InitializedEntity, 4> Entities;
10496 Entities.reserve(1 + IndexVariables.size());
Douglas Gregor19666fb2012-02-15 16:57:26 +000010497 Entities.push_back(
10498 InitializedEntity::InitializeLambdaCapture(Var, Field, Loc));
Douglas Gregor199cec72012-02-09 02:45:47 +000010499 for (unsigned I = 0, N = IndexVariables.size(); I != N; ++I)
10500 Entities.push_back(InitializedEntity::InitializeElement(S.Context,
10501 0,
10502 Entities.back()));
10503
Douglas Gregorabecb9c2012-02-09 01:56:40 +000010504 InitializationKind InitKind
10505 = InitializationKind::CreateDirect(Loc, Loc, Loc);
Douglas Gregor199cec72012-02-09 02:45:47 +000010506 InitializationSequence Init(S, Entities.back(), InitKind, &Ref, 1);
Douglas Gregorabecb9c2012-02-09 01:56:40 +000010507 ExprResult Result(true);
Douglas Gregor199cec72012-02-09 02:45:47 +000010508 if (!Init.Diagnose(S, Entities.back(), InitKind, &Ref, 1))
Benjamin Kramercc4c49d2012-08-23 23:38:35 +000010509 Result = Init.Perform(S, Entities.back(), InitKind, Ref);
Douglas Gregorabecb9c2012-02-09 01:56:40 +000010510
10511 // If this initialization requires any cleanups (e.g., due to a
10512 // default argument to a copy constructor), note that for the
10513 // lambda.
10514 if (S.ExprNeedsCleanups)
10515 LSI->ExprNeedsCleanups = true;
10516
10517 // Exit the expression evaluation context used for the capture.
10518 S.CleanupVarDeclMarking();
10519 S.DiscardCleanupsInEvaluationContext();
10520 S.PopExpressionEvaluationContext();
10521 return Result;
Douglas Gregor199cec72012-02-09 02:45:47 +000010522}
Douglas Gregorabecb9c2012-02-09 01:56:40 +000010523
Douglas Gregorfdf598e2012-02-18 09:37:24 +000010524bool Sema::tryCaptureVariable(VarDecl *Var, SourceLocation Loc,
10525 TryCaptureKind Kind, SourceLocation EllipsisLoc,
10526 bool BuildAndDiagnose,
10527 QualType &CaptureType,
10528 QualType &DeclRefType) {
10529 bool Nested = false;
Douglas Gregor81495f32012-02-12 18:42:33 +000010530
Eli Friedman24af8502012-02-03 22:47:37 +000010531 DeclContext *DC = CurContext;
Douglas Gregorfdf598e2012-02-18 09:37:24 +000010532 if (Var->getDeclContext() == DC) return true;
10533 if (!Var->hasLocalStorage()) return true;
Eli Friedman9bb33f52012-02-03 02:04:35 +000010534
Douglas Gregor81495f32012-02-12 18:42:33 +000010535 bool HasBlocksAttr = Var->hasAttr<BlocksAttr>();
Eli Friedman9bb33f52012-02-03 02:04:35 +000010536
Douglas Gregorfdf598e2012-02-18 09:37:24 +000010537 // Walk up the stack to determine whether we can capture the variable,
10538 // performing the "simple" checks that don't depend on type. We stop when
10539 // we've either hit the declared scope of the variable or find an existing
10540 // capture of that variable.
10541 CaptureType = Var->getType();
10542 DeclRefType = CaptureType.getNonReferenceType();
10543 bool Explicit = (Kind != TryCapture_Implicit);
10544 unsigned FunctionScopesIndex = FunctionScopes.size() - 1;
Eli Friedman9bb33f52012-02-03 02:04:35 +000010545 do {
Eli Friedman24af8502012-02-03 22:47:37 +000010546 // Only block literals and lambda expressions can capture; other
Eli Friedman9bb33f52012-02-03 02:04:35 +000010547 // scopes don't work.
Eli Friedman24af8502012-02-03 22:47:37 +000010548 DeclContext *ParentDC;
10549 if (isa<BlockDecl>(DC))
10550 ParentDC = DC->getParent();
10551 else if (isa<CXXMethodDecl>(DC) &&
Douglas Gregor81495f32012-02-12 18:42:33 +000010552 cast<CXXMethodDecl>(DC)->getOverloadedOperator() == OO_Call &&
Eli Friedman24af8502012-02-03 22:47:37 +000010553 cast<CXXRecordDecl>(DC->getParent())->isLambda())
10554 ParentDC = DC->getParent()->getParent();
Douglas Gregor81495f32012-02-12 18:42:33 +000010555 else {
Douglas Gregorfdf598e2012-02-18 09:37:24 +000010556 if (BuildAndDiagnose)
Douglas Gregor81495f32012-02-12 18:42:33 +000010557 diagnoseUncapturableValueReference(*this, Loc, Var, DC);
Douglas Gregorfdf598e2012-02-18 09:37:24 +000010558 return true;
Douglas Gregor81495f32012-02-12 18:42:33 +000010559 }
Eli Friedman9bb33f52012-02-03 02:04:35 +000010560
Eli Friedman24af8502012-02-03 22:47:37 +000010561 CapturingScopeInfo *CSI =
Douglas Gregor81495f32012-02-12 18:42:33 +000010562 cast<CapturingScopeInfo>(FunctionScopes[FunctionScopesIndex]);
Eli Friedman9bb33f52012-02-03 02:04:35 +000010563
Eli Friedman24af8502012-02-03 22:47:37 +000010564 // Check whether we've already captured it.
Douglas Gregor81495f32012-02-12 18:42:33 +000010565 if (CSI->CaptureMap.count(Var)) {
Douglas Gregorfdf598e2012-02-18 09:37:24 +000010566 // If we found a capture, any subcaptures are nested.
Eli Friedman9bb33f52012-02-03 02:04:35 +000010567 Nested = true;
Douglas Gregorfdf598e2012-02-18 09:37:24 +000010568
10569 // Retrieve the capture type for this variable.
10570 CaptureType = CSI->getCapture(Var).getCaptureType();
10571
10572 // Compute the type of an expression that refers to this variable.
10573 DeclRefType = CaptureType.getNonReferenceType();
10574
10575 const CapturingScopeInfo::Capture &Cap = CSI->getCapture(Var);
10576 if (Cap.isCopyCapture() &&
10577 !(isa<LambdaScopeInfo>(CSI) && cast<LambdaScopeInfo>(CSI)->Mutable))
10578 DeclRefType.addConst();
Eli Friedman9bb33f52012-02-03 02:04:35 +000010579 break;
10580 }
10581
Douglas Gregor81495f32012-02-12 18:42:33 +000010582 bool IsBlock = isa<BlockScopeInfo>(CSI);
Douglas Gregorfdf598e2012-02-18 09:37:24 +000010583 bool IsLambda = !IsBlock;
Eli Friedman24af8502012-02-03 22:47:37 +000010584
10585 // Lambdas are not allowed to capture unnamed variables
10586 // (e.g. anonymous unions).
10587 // FIXME: The C++11 rule don't actually state this explicitly, but I'm
10588 // assuming that's the intent.
Douglas Gregor81495f32012-02-12 18:42:33 +000010589 if (IsLambda && !Var->getDeclName()) {
Douglas Gregorfdf598e2012-02-18 09:37:24 +000010590 if (BuildAndDiagnose) {
Douglas Gregor81495f32012-02-12 18:42:33 +000010591 Diag(Loc, diag::err_lambda_capture_anonymous_var);
10592 Diag(Var->getLocation(), diag::note_declared_at);
10593 }
Douglas Gregorfdf598e2012-02-18 09:37:24 +000010594 return true;
Eli Friedman24af8502012-02-03 22:47:37 +000010595 }
10596
10597 // Prohibit variably-modified types; they're difficult to deal with.
Douglas Gregorfdf598e2012-02-18 09:37:24 +000010598 if (Var->getType()->isVariablyModifiedType()) {
10599 if (BuildAndDiagnose) {
Douglas Gregor81495f32012-02-12 18:42:33 +000010600 if (IsBlock)
10601 Diag(Loc, diag::err_ref_vm_type);
10602 else
10603 Diag(Loc, diag::err_lambda_capture_vm_type) << Var->getDeclName();
10604 Diag(Var->getLocation(), diag::note_previous_decl)
10605 << Var->getDeclName();
10606 }
Douglas Gregorfdf598e2012-02-18 09:37:24 +000010607 return true;
Eli Friedman9bb33f52012-02-03 02:04:35 +000010608 }
10609
Eli Friedman24af8502012-02-03 22:47:37 +000010610 // Lambdas are not allowed to capture __block variables; they don't
10611 // support the expected semantics.
Douglas Gregor81495f32012-02-12 18:42:33 +000010612 if (IsLambda && HasBlocksAttr) {
Douglas Gregorfdf598e2012-02-18 09:37:24 +000010613 if (BuildAndDiagnose) {
Douglas Gregor81495f32012-02-12 18:42:33 +000010614 Diag(Loc, diag::err_lambda_capture_block)
10615 << Var->getDeclName();
10616 Diag(Var->getLocation(), diag::note_previous_decl)
10617 << Var->getDeclName();
10618 }
Douglas Gregorfdf598e2012-02-18 09:37:24 +000010619 return true;
Eli Friedman24af8502012-02-03 22:47:37 +000010620 }
10621
Douglas Gregor81495f32012-02-12 18:42:33 +000010622 if (CSI->ImpCaptureStyle == CapturingScopeInfo::ImpCap_None && !Explicit) {
10623 // No capture-default
Douglas Gregorfdf598e2012-02-18 09:37:24 +000010624 if (BuildAndDiagnose) {
Douglas Gregor81495f32012-02-12 18:42:33 +000010625 Diag(Loc, diag::err_lambda_impcap) << Var->getDeclName();
10626 Diag(Var->getLocation(), diag::note_previous_decl)
10627 << Var->getDeclName();
10628 Diag(cast<LambdaScopeInfo>(CSI)->Lambda->getLocStart(),
10629 diag::note_lambda_decl);
10630 }
Douglas Gregorfdf598e2012-02-18 09:37:24 +000010631 return true;
Douglas Gregor81495f32012-02-12 18:42:33 +000010632 }
10633
10634 FunctionScopesIndex--;
10635 DC = ParentDC;
10636 Explicit = false;
10637 } while (!Var->getDeclContext()->Equals(DC));
10638
Douglas Gregorfdf598e2012-02-18 09:37:24 +000010639 // Walk back down the scope stack, computing the type of the capture at
10640 // each step, checking type-specific requirements, and adding captures if
10641 // requested.
10642 for (unsigned I = ++FunctionScopesIndex, N = FunctionScopes.size(); I != N;
10643 ++I) {
10644 CapturingScopeInfo *CSI = cast<CapturingScopeInfo>(FunctionScopes[I]);
Douglas Gregor812d8f62012-02-18 05:51:20 +000010645
Douglas Gregorfdf598e2012-02-18 09:37:24 +000010646 // Compute the type of the capture and of a reference to the capture within
10647 // this scope.
10648 if (isa<BlockScopeInfo>(CSI)) {
10649 Expr *CopyExpr = 0;
10650 bool ByRef = false;
10651
10652 // Blocks are not allowed to capture arrays.
10653 if (CaptureType->isArrayType()) {
10654 if (BuildAndDiagnose) {
10655 Diag(Loc, diag::err_ref_array_type);
10656 Diag(Var->getLocation(), diag::note_previous_decl)
10657 << Var->getDeclName();
10658 }
10659 return true;
10660 }
10661
John McCall67cd5e02012-03-30 05:23:48 +000010662 // Forbid the block-capture of autoreleasing variables.
10663 if (CaptureType.getObjCLifetime() == Qualifiers::OCL_Autoreleasing) {
10664 if (BuildAndDiagnose) {
10665 Diag(Loc, diag::err_arc_autoreleasing_capture)
10666 << /*block*/ 0;
10667 Diag(Var->getLocation(), diag::note_previous_decl)
10668 << Var->getDeclName();
10669 }
10670 return true;
10671 }
10672
Douglas Gregorfdf598e2012-02-18 09:37:24 +000010673 if (HasBlocksAttr || CaptureType->isReferenceType()) {
10674 // Block capture by reference does not change the capture or
10675 // declaration reference types.
10676 ByRef = true;
10677 } else {
10678 // Block capture by copy introduces 'const'.
10679 CaptureType = CaptureType.getNonReferenceType().withConst();
10680 DeclRefType = CaptureType;
10681
David Blaikiebbafb8a2012-03-11 07:00:24 +000010682 if (getLangOpts().CPlusPlus && BuildAndDiagnose) {
Douglas Gregorfdf598e2012-02-18 09:37:24 +000010683 if (const RecordType *Record = DeclRefType->getAs<RecordType>()) {
10684 // The capture logic needs the destructor, so make sure we mark it.
10685 // Usually this is unnecessary because most local variables have
10686 // their destructors marked at declaration time, but parameters are
10687 // an exception because it's technically only the call site that
10688 // actually requires the destructor.
10689 if (isa<ParmVarDecl>(Var))
10690 FinalizeVarWithDestructor(Var, Record);
10691
10692 // According to the blocks spec, the capture of a variable from
10693 // the stack requires a const copy constructor. This is not true
10694 // of the copy/move done to move a __block variable to the heap.
John McCall113bee02012-03-10 09:33:50 +000010695 Expr *DeclRef = new (Context) DeclRefExpr(Var, false,
Douglas Gregorfdf598e2012-02-18 09:37:24 +000010696 DeclRefType.withConst(),
10697 VK_LValue, Loc);
10698 ExprResult Result
10699 = PerformCopyInitialization(
10700 InitializedEntity::InitializeBlock(Var->getLocation(),
10701 CaptureType, false),
10702 Loc, Owned(DeclRef));
10703
10704 // Build a full-expression copy expression if initialization
10705 // succeeded and used a non-trivial constructor. Recover from
10706 // errors by pretending that the copy isn't necessary.
10707 if (!Result.isInvalid() &&
10708 !cast<CXXConstructExpr>(Result.get())->getConstructor()
10709 ->isTrivial()) {
10710 Result = MaybeCreateExprWithCleanups(Result);
10711 CopyExpr = Result.take();
10712 }
10713 }
10714 }
10715 }
10716
10717 // Actually capture the variable.
10718 if (BuildAndDiagnose)
10719 CSI->addCapture(Var, HasBlocksAttr, ByRef, Nested, Loc,
10720 SourceLocation(), CaptureType, CopyExpr);
10721 Nested = true;
10722 continue;
10723 }
Douglas Gregor812d8f62012-02-18 05:51:20 +000010724
Douglas Gregorfdf598e2012-02-18 09:37:24 +000010725 LambdaScopeInfo *LSI = cast<LambdaScopeInfo>(CSI);
10726
10727 // Determine whether we are capturing by reference or by value.
10728 bool ByRef = false;
10729 if (I == N - 1 && Kind != TryCapture_Implicit) {
10730 ByRef = (Kind == TryCapture_ExplicitByRef);
Eli Friedman24af8502012-02-03 22:47:37 +000010731 } else {
Douglas Gregorfdf598e2012-02-18 09:37:24 +000010732 ByRef = (LSI->ImpCaptureStyle == LambdaScopeInfo::ImpCap_LambdaByref);
Eli Friedman24af8502012-02-03 22:47:37 +000010733 }
Douglas Gregorfdf598e2012-02-18 09:37:24 +000010734
10735 // Compute the type of the field that will capture this variable.
10736 if (ByRef) {
10737 // C++11 [expr.prim.lambda]p15:
10738 // An entity is captured by reference if it is implicitly or
10739 // explicitly captured but not captured by copy. It is
10740 // unspecified whether additional unnamed non-static data
10741 // members are declared in the closure type for entities
10742 // captured by reference.
10743 //
10744 // FIXME: It is not clear whether we want to build an lvalue reference
10745 // to the DeclRefType or to CaptureType.getNonReferenceType(). GCC appears
10746 // to do the former, while EDG does the latter. Core issue 1249 will
10747 // clarify, but for now we follow GCC because it's a more permissive and
10748 // easily defensible position.
10749 CaptureType = Context.getLValueReferenceType(DeclRefType);
10750 } else {
10751 // C++11 [expr.prim.lambda]p14:
10752 // For each entity captured by copy, an unnamed non-static
10753 // data member is declared in the closure type. The
10754 // declaration order of these members is unspecified. The type
10755 // of such a data member is the type of the corresponding
10756 // captured entity if the entity is not a reference to an
10757 // object, or the referenced type otherwise. [Note: If the
10758 // captured entity is a reference to a function, the
10759 // corresponding data member is also a reference to a
10760 // function. - end note ]
10761 if (const ReferenceType *RefType = CaptureType->getAs<ReferenceType>()){
10762 if (!RefType->getPointeeType()->isFunctionType())
10763 CaptureType = RefType->getPointeeType();
Eli Friedman9bb33f52012-02-03 02:04:35 +000010764 }
John McCall67cd5e02012-03-30 05:23:48 +000010765
10766 // Forbid the lambda copy-capture of autoreleasing variables.
10767 if (CaptureType.getObjCLifetime() == Qualifiers::OCL_Autoreleasing) {
10768 if (BuildAndDiagnose) {
10769 Diag(Loc, diag::err_arc_autoreleasing_capture) << /*lambda*/ 1;
10770 Diag(Var->getLocation(), diag::note_previous_decl)
10771 << Var->getDeclName();
10772 }
10773 return true;
10774 }
Eli Friedman9bb33f52012-02-03 02:04:35 +000010775 }
10776
Douglas Gregorfdf598e2012-02-18 09:37:24 +000010777 // Capture this variable in the lambda.
10778 Expr *CopyExpr = 0;
10779 if (BuildAndDiagnose) {
10780 ExprResult Result = captureInLambda(*this, LSI, Var, CaptureType,
Douglas Gregora8182f92012-05-16 17:01:33 +000010781 DeclRefType, Loc,
10782 I == N-1);
Douglas Gregorfdf598e2012-02-18 09:37:24 +000010783 if (!Result.isInvalid())
10784 CopyExpr = Result.take();
10785 }
10786
10787 // Compute the type of a reference to this captured variable.
10788 if (ByRef)
10789 DeclRefType = CaptureType.getNonReferenceType();
10790 else {
10791 // C++ [expr.prim.lambda]p5:
10792 // The closure type for a lambda-expression has a public inline
10793 // function call operator [...]. This function call operator is
10794 // declared const (9.3.1) if and only if the lambda-expression’s
10795 // parameter-declaration-clause is not followed by mutable.
10796 DeclRefType = CaptureType.getNonReferenceType();
10797 if (!LSI->Mutable && !CaptureType->isReferenceType())
10798 DeclRefType.addConst();
10799 }
10800
10801 // Add the capture.
10802 if (BuildAndDiagnose)
10803 CSI->addCapture(Var, /*IsBlock=*/false, ByRef, Nested, Loc,
10804 EllipsisLoc, CaptureType, CopyExpr);
Eli Friedman9bb33f52012-02-03 02:04:35 +000010805 Nested = true;
10806 }
Douglas Gregorfdf598e2012-02-18 09:37:24 +000010807
10808 return false;
10809}
10810
10811bool Sema::tryCaptureVariable(VarDecl *Var, SourceLocation Loc,
10812 TryCaptureKind Kind, SourceLocation EllipsisLoc) {
10813 QualType CaptureType;
10814 QualType DeclRefType;
10815 return tryCaptureVariable(Var, Loc, Kind, EllipsisLoc,
10816 /*BuildAndDiagnose=*/true, CaptureType,
10817 DeclRefType);
10818}
10819
10820QualType Sema::getCapturedDeclRefType(VarDecl *Var, SourceLocation Loc) {
10821 QualType CaptureType;
10822 QualType DeclRefType;
10823
10824 // Determine whether we can capture this variable.
10825 if (tryCaptureVariable(Var, Loc, TryCapture_Implicit, SourceLocation(),
10826 /*BuildAndDiagnose=*/false, CaptureType, DeclRefType))
10827 return QualType();
10828
10829 return DeclRefType;
Eli Friedman9bb33f52012-02-03 02:04:35 +000010830}
10831
Eli Friedman3bda6b12012-02-02 23:15:15 +000010832static void MarkVarDeclODRUsed(Sema &SemaRef, VarDecl *Var,
10833 SourceLocation Loc) {
10834 // Keep track of used but undefined variables.
Eli Friedman130bbd02012-02-04 00:54:05 +000010835 // FIXME: We shouldn't suppress this warning for static data members.
Daniel Dunbar9d355812012-03-09 01:51:51 +000010836 if (Var->hasDefinition(SemaRef.Context) == VarDecl::DeclarationOnly &&
Eli Friedman130bbd02012-02-04 00:54:05 +000010837 Var->getLinkage() != ExternalLinkage &&
10838 !(Var->isStaticDataMember() && Var->hasInit())) {
Eli Friedman3bda6b12012-02-02 23:15:15 +000010839 SourceLocation &old = SemaRef.UndefinedInternals[Var->getCanonicalDecl()];
10840 if (old.isInvalid()) old = Loc;
10841 }
10842
Douglas Gregorfdf598e2012-02-18 09:37:24 +000010843 SemaRef.tryCaptureVariable(Var, Loc);
Eli Friedman9bb33f52012-02-03 02:04:35 +000010844
Eli Friedman3bda6b12012-02-02 23:15:15 +000010845 Var->setUsed(true);
10846}
10847
10848void Sema::UpdateMarkingForLValueToRValue(Expr *E) {
10849 // Per C++11 [basic.def.odr], a variable is odr-used "unless it is
10850 // an object that satisfies the requirements for appearing in a
10851 // constant expression (5.19) and the lvalue-to-rvalue conversion (4.1)
10852 // is immediately applied." This function handles the lvalue-to-rvalue
10853 // conversion part.
10854 MaybeODRUseExprs.erase(E->IgnoreParens());
10855}
10856
Eli Friedmanc6237c62012-02-29 03:16:56 +000010857ExprResult Sema::ActOnConstantExpression(ExprResult Res) {
10858 if (!Res.isUsable())
10859 return Res;
10860
10861 // If a constant-expression is a reference to a variable where we delay
10862 // deciding whether it is an odr-use, just assume we will apply the
10863 // lvalue-to-rvalue conversion. In the one case where this doesn't happen
10864 // (a non-type template argument), we have special handling anyway.
10865 UpdateMarkingForLValueToRValue(Res.get());
10866 return Res;
10867}
10868
Eli Friedman3bda6b12012-02-02 23:15:15 +000010869void Sema::CleanupVarDeclMarking() {
10870 for (llvm::SmallPtrSetIterator<Expr*> i = MaybeODRUseExprs.begin(),
10871 e = MaybeODRUseExprs.end();
10872 i != e; ++i) {
10873 VarDecl *Var;
10874 SourceLocation Loc;
John McCall113bee02012-03-10 09:33:50 +000010875 if (DeclRefExpr *DRE = dyn_cast<DeclRefExpr>(*i)) {
Eli Friedman3bda6b12012-02-02 23:15:15 +000010876 Var = cast<VarDecl>(DRE->getDecl());
10877 Loc = DRE->getLocation();
10878 } else if (MemberExpr *ME = dyn_cast<MemberExpr>(*i)) {
10879 Var = cast<VarDecl>(ME->getMemberDecl());
10880 Loc = ME->getMemberLoc();
10881 } else {
10882 llvm_unreachable("Unexpcted expression");
10883 }
10884
10885 MarkVarDeclODRUsed(*this, Var, Loc);
10886 }
10887
10888 MaybeODRUseExprs.clear();
10889}
10890
10891// Mark a VarDecl referenced, and perform the necessary handling to compute
10892// odr-uses.
10893static void DoMarkVarDeclReferenced(Sema &SemaRef, SourceLocation Loc,
10894 VarDecl *Var, Expr *E) {
Eli Friedmanfa0df832012-02-02 03:46:19 +000010895 Var->setReferenced();
10896
Eli Friedman3bda6b12012-02-02 23:15:15 +000010897 if (!IsPotentiallyEvaluatedContext(SemaRef))
Eli Friedmanfa0df832012-02-02 03:46:19 +000010898 return;
10899
10900 // Implicit instantiation of static data members of class templates.
Richard Smithd3cf2382012-02-15 02:42:50 +000010901 if (Var->isStaticDataMember() && Var->getInstantiatedFromStaticDataMember()) {
Eli Friedmanfa0df832012-02-02 03:46:19 +000010902 MemberSpecializationInfo *MSInfo = Var->getMemberSpecializationInfo();
10903 assert(MSInfo && "Missing member specialization information?");
Richard Smithd3cf2382012-02-15 02:42:50 +000010904 bool AlreadyInstantiated = !MSInfo->getPointOfInstantiation().isInvalid();
10905 if (MSInfo->getTemplateSpecializationKind() == TSK_ImplicitInstantiation &&
Daniel Dunbar9d355812012-03-09 01:51:51 +000010906 (!AlreadyInstantiated ||
10907 Var->isUsableInConstantExpressions(SemaRef.Context))) {
Richard Smithd3cf2382012-02-15 02:42:50 +000010908 if (!AlreadyInstantiated) {
10909 // This is a modification of an existing AST node. Notify listeners.
10910 if (ASTMutationListener *L = SemaRef.getASTMutationListener())
10911 L->StaticDataMemberInstantiated(Var);
10912 MSInfo->setPointOfInstantiation(Loc);
10913 }
10914 SourceLocation PointOfInstantiation = MSInfo->getPointOfInstantiation();
Daniel Dunbar9d355812012-03-09 01:51:51 +000010915 if (Var->isUsableInConstantExpressions(SemaRef.Context))
Eli Friedmanfa0df832012-02-02 03:46:19 +000010916 // Do not defer instantiations of variables which could be used in a
10917 // constant expression.
Richard Smithd3cf2382012-02-15 02:42:50 +000010918 SemaRef.InstantiateStaticDataMemberDefinition(PointOfInstantiation,Var);
Eli Friedmanfa0df832012-02-02 03:46:19 +000010919 else
Richard Smithd3cf2382012-02-15 02:42:50 +000010920 SemaRef.PendingInstantiations.push_back(
10921 std::make_pair(Var, PointOfInstantiation));
Eli Friedmanfa0df832012-02-02 03:46:19 +000010922 }
10923 }
10924
Eli Friedman3bda6b12012-02-02 23:15:15 +000010925 // Per C++11 [basic.def.odr], a variable is odr-used "unless it is
10926 // an object that satisfies the requirements for appearing in a
10927 // constant expression (5.19) and the lvalue-to-rvalue conversion (4.1)
10928 // is immediately applied." We check the first part here, and
10929 // Sema::UpdateMarkingForLValueToRValue deals with the second part.
10930 // Note that we use the C++11 definition everywhere because nothing in
Richard Smith35ecb362012-03-02 04:14:40 +000010931 // C++03 depends on whether we get the C++03 version correct. This does not
10932 // apply to references, since they are not objects.
Eli Friedman3bda6b12012-02-02 23:15:15 +000010933 const VarDecl *DefVD;
Richard Smith35ecb362012-03-02 04:14:40 +000010934 if (E && !isa<ParmVarDecl>(Var) && !Var->getType()->isReferenceType() &&
Daniel Dunbar9d355812012-03-09 01:51:51 +000010935 Var->isUsableInConstantExpressions(SemaRef.Context) &&
Eli Friedman3bda6b12012-02-02 23:15:15 +000010936 Var->getAnyInitializer(DefVD) && DefVD->checkInitIsICE())
10937 SemaRef.MaybeODRUseExprs.insert(E);
10938 else
10939 MarkVarDeclODRUsed(SemaRef, Var, Loc);
10940}
Eli Friedmanfa0df832012-02-02 03:46:19 +000010941
Eli Friedman3bda6b12012-02-02 23:15:15 +000010942/// \brief Mark a variable referenced, and check whether it is odr-used
10943/// (C++ [basic.def.odr]p2, C99 6.9p3). Note that this should not be
10944/// used directly for normal expressions referring to VarDecl.
10945void Sema::MarkVariableReferenced(SourceLocation Loc, VarDecl *Var) {
10946 DoMarkVarDeclReferenced(*this, Loc, Var, 0);
Eli Friedmanfa0df832012-02-02 03:46:19 +000010947}
10948
10949static void MarkExprReferenced(Sema &SemaRef, SourceLocation Loc,
10950 Decl *D, Expr *E) {
Eli Friedman3bda6b12012-02-02 23:15:15 +000010951 if (VarDecl *Var = dyn_cast<VarDecl>(D)) {
10952 DoMarkVarDeclReferenced(SemaRef, Loc, Var, E);
10953 return;
10954 }
10955
Eli Friedmanfa0df832012-02-02 03:46:19 +000010956 SemaRef.MarkAnyDeclReferenced(Loc, D);
Rafael Espindola49e860b2012-06-26 17:45:31 +000010957
10958 // If this is a call to a method via a cast, also mark the method in the
10959 // derived class used in case codegen can devirtualize the call.
10960 const MemberExpr *ME = dyn_cast<MemberExpr>(E);
10961 if (!ME)
10962 return;
10963 CXXMethodDecl *MD = dyn_cast<CXXMethodDecl>(ME->getMemberDecl());
10964 if (!MD)
10965 return;
10966 const Expr *Base = ME->getBase();
Rafael Espindolab7f5a9c2012-06-27 18:18:05 +000010967 const CXXRecordDecl *MostDerivedClassDecl = Base->getBestDynamicClassType();
Rafael Espindola49e860b2012-06-26 17:45:31 +000010968 if (!MostDerivedClassDecl)
10969 return;
10970 CXXMethodDecl *DM = MD->getCorrespondingMethodInClass(MostDerivedClassDecl);
Rafael Espindolaa245edc2012-06-27 17:44:39 +000010971 if (!DM)
10972 return;
Rafael Espindola49e860b2012-06-26 17:45:31 +000010973 SemaRef.MarkAnyDeclReferenced(Loc, DM);
Douglas Gregord3b672c2012-02-16 01:06:16 +000010974}
Eli Friedmanfa0df832012-02-02 03:46:19 +000010975
Eli Friedmanfa0df832012-02-02 03:46:19 +000010976/// \brief Perform reference-marking and odr-use handling for a DeclRefExpr.
10977void Sema::MarkDeclRefReferenced(DeclRefExpr *E) {
10978 MarkExprReferenced(*this, E->getLocation(), E->getDecl(), E);
10979}
10980
10981/// \brief Perform reference-marking and odr-use handling for a MemberExpr.
10982void Sema::MarkMemberReferenced(MemberExpr *E) {
10983 MarkExprReferenced(*this, E->getMemberLoc(), E->getMemberDecl(), E);
10984}
10985
Douglas Gregorf02455e2012-02-10 09:26:04 +000010986/// \brief Perform marking for a reference to an arbitrary declaration. It
Eli Friedmanfa0df832012-02-02 03:46:19 +000010987/// marks the declaration referenced, and performs odr-use checking for functions
10988/// and variables. This method should not be used when building an normal
10989/// expression which refers to a variable.
10990void Sema::MarkAnyDeclReferenced(SourceLocation Loc, Decl *D) {
10991 if (VarDecl *VD = dyn_cast<VarDecl>(D))
10992 MarkVariableReferenced(Loc, VD);
10993 else if (FunctionDecl *FD = dyn_cast<FunctionDecl>(D))
10994 MarkFunctionReferenced(Loc, FD);
10995 else
10996 D->setReferenced();
Douglas Gregorc9c02ed2009-06-19 23:52:42 +000010997}
Anders Carlsson7f84ed92009-10-09 23:51:55 +000010998
Douglas Gregor5597ab42010-05-07 23:12:07 +000010999namespace {
Chandler Carruthaf80f662010-06-09 08:17:30 +000011000 // Mark all of the declarations referenced
Douglas Gregor5597ab42010-05-07 23:12:07 +000011001 // FIXME: Not fully implemented yet! We need to have a better understanding
Chandler Carruthaf80f662010-06-09 08:17:30 +000011002 // of when we're entering
Douglas Gregor5597ab42010-05-07 23:12:07 +000011003 class MarkReferencedDecls : public RecursiveASTVisitor<MarkReferencedDecls> {
11004 Sema &S;
11005 SourceLocation Loc;
Chandler Carruthaf80f662010-06-09 08:17:30 +000011006
Douglas Gregor5597ab42010-05-07 23:12:07 +000011007 public:
11008 typedef RecursiveASTVisitor<MarkReferencedDecls> Inherited;
Chandler Carruthaf80f662010-06-09 08:17:30 +000011009
Douglas Gregor5597ab42010-05-07 23:12:07 +000011010 MarkReferencedDecls(Sema &S, SourceLocation Loc) : S(S), Loc(Loc) { }
Chandler Carruthaf80f662010-06-09 08:17:30 +000011011
11012 bool TraverseTemplateArgument(const TemplateArgument &Arg);
11013 bool TraverseRecordType(RecordType *T);
Douglas Gregor5597ab42010-05-07 23:12:07 +000011014 };
11015}
11016
Chandler Carruthaf80f662010-06-09 08:17:30 +000011017bool MarkReferencedDecls::TraverseTemplateArgument(
11018 const TemplateArgument &Arg) {
Douglas Gregor5597ab42010-05-07 23:12:07 +000011019 if (Arg.getKind() == TemplateArgument::Declaration) {
Douglas Gregor31f55dc2012-04-06 22:40:38 +000011020 if (Decl *D = Arg.getAsDecl())
11021 S.MarkAnyDeclReferenced(Loc, D);
Douglas Gregor5597ab42010-05-07 23:12:07 +000011022 }
Chandler Carruthaf80f662010-06-09 08:17:30 +000011023
11024 return Inherited::TraverseTemplateArgument(Arg);
Douglas Gregor5597ab42010-05-07 23:12:07 +000011025}
11026
Chandler Carruthaf80f662010-06-09 08:17:30 +000011027bool MarkReferencedDecls::TraverseRecordType(RecordType *T) {
Douglas Gregor5597ab42010-05-07 23:12:07 +000011028 if (ClassTemplateSpecializationDecl *Spec
11029 = dyn_cast<ClassTemplateSpecializationDecl>(T->getDecl())) {
11030 const TemplateArgumentList &Args = Spec->getTemplateArgs();
Douglas Gregor1ccc8412010-11-07 23:05:16 +000011031 return TraverseTemplateArguments(Args.data(), Args.size());
Douglas Gregor5597ab42010-05-07 23:12:07 +000011032 }
11033
Chandler Carruthc65667c2010-06-10 10:31:57 +000011034 return true;
Douglas Gregor5597ab42010-05-07 23:12:07 +000011035}
11036
11037void Sema::MarkDeclarationsReferencedInType(SourceLocation Loc, QualType T) {
11038 MarkReferencedDecls Marker(*this, Loc);
Chandler Carruthaf80f662010-06-09 08:17:30 +000011039 Marker.TraverseType(Context.getCanonicalType(T));
Douglas Gregor5597ab42010-05-07 23:12:07 +000011040}
11041
Douglas Gregor8a01b2a2010-09-11 20:24:53 +000011042namespace {
11043 /// \brief Helper class that marks all of the declarations referenced by
11044 /// potentially-evaluated subexpressions as "referenced".
11045 class EvaluatedExprMarker : public EvaluatedExprVisitor<EvaluatedExprMarker> {
11046 Sema &S;
Douglas Gregor680e9e02012-02-21 19:11:17 +000011047 bool SkipLocalVariables;
Douglas Gregor8a01b2a2010-09-11 20:24:53 +000011048
11049 public:
11050 typedef EvaluatedExprVisitor<EvaluatedExprMarker> Inherited;
11051
Douglas Gregor680e9e02012-02-21 19:11:17 +000011052 EvaluatedExprMarker(Sema &S, bool SkipLocalVariables)
11053 : Inherited(S.Context), S(S), SkipLocalVariables(SkipLocalVariables) { }
Douglas Gregor8a01b2a2010-09-11 20:24:53 +000011054
11055 void VisitDeclRefExpr(DeclRefExpr *E) {
Douglas Gregor680e9e02012-02-21 19:11:17 +000011056 // If we were asked not to visit local variables, don't.
11057 if (SkipLocalVariables) {
11058 if (VarDecl *VD = dyn_cast<VarDecl>(E->getDecl()))
11059 if (VD->hasLocalStorage())
11060 return;
11061 }
11062
Eli Friedmanfa0df832012-02-02 03:46:19 +000011063 S.MarkDeclRefReferenced(E);
Douglas Gregor8a01b2a2010-09-11 20:24:53 +000011064 }
11065
11066 void VisitMemberExpr(MemberExpr *E) {
Eli Friedmanfa0df832012-02-02 03:46:19 +000011067 S.MarkMemberReferenced(E);
Douglas Gregor32b3de52010-09-11 23:32:50 +000011068 Inherited::VisitMemberExpr(E);
Douglas Gregor8a01b2a2010-09-11 20:24:53 +000011069 }
11070
John McCall28fc7092011-11-10 05:35:25 +000011071 void VisitCXXBindTemporaryExpr(CXXBindTemporaryExpr *E) {
Eli Friedmanfa0df832012-02-02 03:46:19 +000011072 S.MarkFunctionReferenced(E->getLocStart(),
John McCall28fc7092011-11-10 05:35:25 +000011073 const_cast<CXXDestructorDecl*>(E->getTemporary()->getDestructor()));
11074 Visit(E->getSubExpr());
11075 }
11076
Douglas Gregor8a01b2a2010-09-11 20:24:53 +000011077 void VisitCXXNewExpr(CXXNewExpr *E) {
Douglas Gregor8a01b2a2010-09-11 20:24:53 +000011078 if (E->getOperatorNew())
Eli Friedmanfa0df832012-02-02 03:46:19 +000011079 S.MarkFunctionReferenced(E->getLocStart(), E->getOperatorNew());
Douglas Gregor8a01b2a2010-09-11 20:24:53 +000011080 if (E->getOperatorDelete())
Eli Friedmanfa0df832012-02-02 03:46:19 +000011081 S.MarkFunctionReferenced(E->getLocStart(), E->getOperatorDelete());
Douglas Gregor32b3de52010-09-11 23:32:50 +000011082 Inherited::VisitCXXNewExpr(E);
Douglas Gregor8a01b2a2010-09-11 20:24:53 +000011083 }
Sebastian Redl6047f072012-02-16 12:22:20 +000011084
Douglas Gregor8a01b2a2010-09-11 20:24:53 +000011085 void VisitCXXDeleteExpr(CXXDeleteExpr *E) {
11086 if (E->getOperatorDelete())
Eli Friedmanfa0df832012-02-02 03:46:19 +000011087 S.MarkFunctionReferenced(E->getLocStart(), E->getOperatorDelete());
Douglas Gregor6ed2fee2010-09-14 22:55:20 +000011088 QualType Destroyed = S.Context.getBaseElementType(E->getDestroyedType());
11089 if (const RecordType *DestroyedRec = Destroyed->getAs<RecordType>()) {
11090 CXXRecordDecl *Record = cast<CXXRecordDecl>(DestroyedRec->getDecl());
Eli Friedmanfa0df832012-02-02 03:46:19 +000011091 S.MarkFunctionReferenced(E->getLocStart(),
Douglas Gregor6ed2fee2010-09-14 22:55:20 +000011092 S.LookupDestructor(Record));
11093 }
11094
Douglas Gregor32b3de52010-09-11 23:32:50 +000011095 Inherited::VisitCXXDeleteExpr(E);
Douglas Gregor8a01b2a2010-09-11 20:24:53 +000011096 }
11097
11098 void VisitCXXConstructExpr(CXXConstructExpr *E) {
Eli Friedmanfa0df832012-02-02 03:46:19 +000011099 S.MarkFunctionReferenced(E->getLocStart(), E->getConstructor());
Douglas Gregor32b3de52010-09-11 23:32:50 +000011100 Inherited::VisitCXXConstructExpr(E);
Douglas Gregor8a01b2a2010-09-11 20:24:53 +000011101 }
11102
Douglas Gregorf0873f42010-10-19 17:17:35 +000011103 void VisitCXXDefaultArgExpr(CXXDefaultArgExpr *E) {
11104 Visit(E->getExpr());
11105 }
Eli Friedman3bda6b12012-02-02 23:15:15 +000011106
11107 void VisitImplicitCastExpr(ImplicitCastExpr *E) {
11108 Inherited::VisitImplicitCastExpr(E);
11109
11110 if (E->getCastKind() == CK_LValueToRValue)
11111 S.UpdateMarkingForLValueToRValue(E->getSubExpr());
11112 }
Douglas Gregor8a01b2a2010-09-11 20:24:53 +000011113 };
11114}
11115
11116/// \brief Mark any declarations that appear within this expression or any
11117/// potentially-evaluated subexpressions as "referenced".
Douglas Gregor680e9e02012-02-21 19:11:17 +000011118///
11119/// \param SkipLocalVariables If true, don't mark local variables as
11120/// 'referenced'.
11121void Sema::MarkDeclarationsReferencedInExpr(Expr *E,
11122 bool SkipLocalVariables) {
11123 EvaluatedExprMarker(*this, SkipLocalVariables).Visit(E);
Douglas Gregor8a01b2a2010-09-11 20:24:53 +000011124}
11125
Douglas Gregorda8cdbc2009-12-22 01:01:55 +000011126/// \brief Emit a diagnostic that describes an effect on the run-time behavior
11127/// of the program being compiled.
11128///
11129/// This routine emits the given diagnostic when the code currently being
Kovarththanan Rajaratnamba2c6522010-03-13 10:17:05 +000011130/// type-checked is "potentially evaluated", meaning that there is a
Douglas Gregorda8cdbc2009-12-22 01:01:55 +000011131/// possibility that the code will actually be executable. Code in sizeof()
11132/// expressions, code used only during overload resolution, etc., are not
11133/// potentially evaluated. This routine will suppress such diagnostics or,
11134/// in the absolutely nutty case of potentially potentially evaluated
Kovarththanan Rajaratnamba2c6522010-03-13 10:17:05 +000011135/// expressions (C++ typeid), queue the diagnostic to potentially emit it
Douglas Gregorda8cdbc2009-12-22 01:01:55 +000011136/// later.
Kovarththanan Rajaratnamba2c6522010-03-13 10:17:05 +000011137///
Douglas Gregorda8cdbc2009-12-22 01:01:55 +000011138/// This routine should be used for all diagnostics that describe the run-time
11139/// behavior of a program, such as passing a non-POD value through an ellipsis.
11140/// Failure to do so will likely result in spurious diagnostics or failures
11141/// during overload resolution or within sizeof/alignof/typeof/typeid.
Richard Trieuba63ce62011-09-09 01:45:06 +000011142bool Sema::DiagRuntimeBehavior(SourceLocation Loc, const Stmt *Statement,
Douglas Gregorda8cdbc2009-12-22 01:01:55 +000011143 const PartialDiagnostic &PD) {
John McCall31168b02011-06-15 23:02:42 +000011144 switch (ExprEvalContexts.back().Context) {
Douglas Gregorda8cdbc2009-12-22 01:01:55 +000011145 case Unevaluated:
11146 // The argument will never be evaluated, so don't complain.
11147 break;
Kovarththanan Rajaratnamba2c6522010-03-13 10:17:05 +000011148
Richard Smith764d2fe2011-12-20 02:08:33 +000011149 case ConstantEvaluated:
11150 // Relevant diagnostics should be produced by constant evaluation.
11151 break;
11152
Douglas Gregorda8cdbc2009-12-22 01:01:55 +000011153 case PotentiallyEvaluated:
Douglas Gregor8a01b2a2010-09-11 20:24:53 +000011154 case PotentiallyEvaluatedIfUsed:
Richard Trieuba63ce62011-09-09 01:45:06 +000011155 if (Statement && getCurFunctionOrMethodDecl()) {
Ted Kremenek3427fac2011-02-23 01:52:04 +000011156 FunctionScopes.back()->PossiblyUnreachableDiags.
Richard Trieuba63ce62011-09-09 01:45:06 +000011157 push_back(sema::PossiblyUnreachableDiag(PD, Loc, Statement));
Ted Kremenek3427fac2011-02-23 01:52:04 +000011158 }
11159 else
11160 Diag(Loc, PD);
11161
Douglas Gregorda8cdbc2009-12-22 01:01:55 +000011162 return true;
Douglas Gregorda8cdbc2009-12-22 01:01:55 +000011163 }
11164
11165 return false;
11166}
11167
Anders Carlsson7f84ed92009-10-09 23:51:55 +000011168bool Sema::CheckCallReturnType(QualType ReturnType, SourceLocation Loc,
11169 CallExpr *CE, FunctionDecl *FD) {
11170 if (ReturnType->isVoidType() || !ReturnType->isIncompleteType())
11171 return false;
11172
Richard Smithfd555f62012-02-22 02:04:18 +000011173 // If we're inside a decltype's expression, don't check for a valid return
11174 // type or construct temporaries until we know whether this is the last call.
11175 if (ExprEvalContexts.back().IsDecltype) {
11176 ExprEvalContexts.back().DelayedDecltypeCalls.push_back(CE);
11177 return false;
11178 }
11179
Douglas Gregora6c5abb2012-05-04 16:48:41 +000011180 class CallReturnIncompleteDiagnoser : public TypeDiagnoser {
Douglas Gregor7bfb2d02012-05-04 16:32:21 +000011181 FunctionDecl *FD;
11182 CallExpr *CE;
11183
11184 public:
11185 CallReturnIncompleteDiagnoser(FunctionDecl *FD, CallExpr *CE)
11186 : FD(FD), CE(CE) { }
11187
11188 virtual void diagnose(Sema &S, SourceLocation Loc, QualType T) {
11189 if (!FD) {
11190 S.Diag(Loc, diag::err_call_incomplete_return)
11191 << T << CE->getSourceRange();
11192 return;
11193 }
11194
11195 S.Diag(Loc, diag::err_call_function_incomplete_return)
11196 << CE->getSourceRange() << FD->getDeclName() << T;
11197 S.Diag(FD->getLocation(),
11198 diag::note_function_with_incomplete_return_type_declared_here)
11199 << FD->getDeclName();
11200 }
11201 } Diagnoser(FD, CE);
11202
11203 if (RequireCompleteType(Loc, ReturnType, Diagnoser))
Anders Carlsson7f84ed92009-10-09 23:51:55 +000011204 return true;
11205
11206 return false;
11207}
11208
Douglas Gregor2d4f64f2011-01-19 16:50:08 +000011209// Diagnose the s/=/==/ and s/\|=/!=/ typos. Note that adding parentheses
John McCalld5707ab2009-10-12 21:59:07 +000011210// will prevent this condition from triggering, which is what we want.
11211void Sema::DiagnoseAssignmentAsCondition(Expr *E) {
11212 SourceLocation Loc;
11213
John McCall0506e4a2009-11-11 02:41:58 +000011214 unsigned diagnostic = diag::warn_condition_is_assignment;
Douglas Gregor2d4f64f2011-01-19 16:50:08 +000011215 bool IsOrAssign = false;
John McCall0506e4a2009-11-11 02:41:58 +000011216
Chandler Carruthf87d6c02011-08-16 22:30:10 +000011217 if (BinaryOperator *Op = dyn_cast<BinaryOperator>(E)) {
Douglas Gregor2d4f64f2011-01-19 16:50:08 +000011218 if (Op->getOpcode() != BO_Assign && Op->getOpcode() != BO_OrAssign)
John McCalld5707ab2009-10-12 21:59:07 +000011219 return;
11220
Douglas Gregor2d4f64f2011-01-19 16:50:08 +000011221 IsOrAssign = Op->getOpcode() == BO_OrAssign;
11222
John McCallb0e419e2009-11-12 00:06:05 +000011223 // Greylist some idioms by putting them into a warning subcategory.
11224 if (ObjCMessageExpr *ME
11225 = dyn_cast<ObjCMessageExpr>(Op->getRHS()->IgnoreParenCasts())) {
11226 Selector Sel = ME->getSelector();
11227
John McCallb0e419e2009-11-12 00:06:05 +000011228 // self = [<foo> init...]
Douglas Gregor486b74e2011-09-27 16:10:05 +000011229 if (isSelfExpr(Op->getLHS()) && Sel.getNameForSlot(0).startswith("init"))
John McCallb0e419e2009-11-12 00:06:05 +000011230 diagnostic = diag::warn_condition_is_idiomatic_assignment;
11231
11232 // <foo> = [<bar> nextObject]
Douglas Gregoraf2a6ae2011-02-18 22:29:55 +000011233 else if (Sel.isUnarySelector() && Sel.getNameForSlot(0) == "nextObject")
John McCallb0e419e2009-11-12 00:06:05 +000011234 diagnostic = diag::warn_condition_is_idiomatic_assignment;
11235 }
John McCall0506e4a2009-11-11 02:41:58 +000011236
John McCalld5707ab2009-10-12 21:59:07 +000011237 Loc = Op->getOperatorLoc();
Chandler Carruthf87d6c02011-08-16 22:30:10 +000011238 } else if (CXXOperatorCallExpr *Op = dyn_cast<CXXOperatorCallExpr>(E)) {
Douglas Gregor2d4f64f2011-01-19 16:50:08 +000011239 if (Op->getOperator() != OO_Equal && Op->getOperator() != OO_PipeEqual)
John McCalld5707ab2009-10-12 21:59:07 +000011240 return;
11241
Douglas Gregor2d4f64f2011-01-19 16:50:08 +000011242 IsOrAssign = Op->getOperator() == OO_PipeEqual;
John McCalld5707ab2009-10-12 21:59:07 +000011243 Loc = Op->getOperatorLoc();
Fariborz Jahanianf07bcc52012-08-29 17:17:11 +000011244 } else if (PseudoObjectExpr *POE = dyn_cast<PseudoObjectExpr>(E))
11245 return DiagnoseAssignmentAsCondition(POE->getSyntacticForm());
11246 else {
John McCalld5707ab2009-10-12 21:59:07 +000011247 // Not an assignment.
11248 return;
11249 }
11250
Douglas Gregor2bf2d3d2010-04-14 16:09:52 +000011251 Diag(Loc, diagnostic) << E->getSourceRange();
Douglas Gregor2d4f64f2011-01-19 16:50:08 +000011252
Daniel Dunbar62ee6412012-03-09 18:35:03 +000011253 SourceLocation Open = E->getLocStart();
Argyrios Kyrtzidise1b97c42011-04-25 23:01:29 +000011254 SourceLocation Close = PP.getLocForEndOfToken(E->getSourceRange().getEnd());
11255 Diag(Loc, diag::note_condition_assign_silence)
11256 << FixItHint::CreateInsertion(Open, "(")
11257 << FixItHint::CreateInsertion(Close, ")");
11258
Douglas Gregor2d4f64f2011-01-19 16:50:08 +000011259 if (IsOrAssign)
11260 Diag(Loc, diag::note_condition_or_assign_to_comparison)
11261 << FixItHint::CreateReplacement(Loc, "!=");
11262 else
11263 Diag(Loc, diag::note_condition_assign_to_comparison)
11264 << FixItHint::CreateReplacement(Loc, "==");
John McCalld5707ab2009-10-12 21:59:07 +000011265}
11266
Argyrios Kyrtzidis8b6ec682011-02-01 18:24:22 +000011267/// \brief Redundant parentheses over an equality comparison can indicate
11268/// that the user intended an assignment used as condition.
Richard Trieuba63ce62011-09-09 01:45:06 +000011269void Sema::DiagnoseEqualityWithExtraParens(ParenExpr *ParenE) {
Argyrios Kyrtzidisf4f82782011-02-01 22:23:56 +000011270 // Don't warn if the parens came from a macro.
Richard Trieuba63ce62011-09-09 01:45:06 +000011271 SourceLocation parenLoc = ParenE->getLocStart();
Argyrios Kyrtzidisf4f82782011-02-01 22:23:56 +000011272 if (parenLoc.isInvalid() || parenLoc.isMacroID())
11273 return;
Argyrios Kyrtzidisba699d62011-03-28 23:52:04 +000011274 // Don't warn for dependent expressions.
Richard Trieuba63ce62011-09-09 01:45:06 +000011275 if (ParenE->isTypeDependent())
Argyrios Kyrtzidisba699d62011-03-28 23:52:04 +000011276 return;
Argyrios Kyrtzidisf4f82782011-02-01 22:23:56 +000011277
Richard Trieuba63ce62011-09-09 01:45:06 +000011278 Expr *E = ParenE->IgnoreParens();
Argyrios Kyrtzidis8b6ec682011-02-01 18:24:22 +000011279
11280 if (BinaryOperator *opE = dyn_cast<BinaryOperator>(E))
Argyrios Kyrtzidis582dd682011-02-01 19:32:59 +000011281 if (opE->getOpcode() == BO_EQ &&
11282 opE->getLHS()->IgnoreParenImpCasts()->isModifiableLvalue(Context)
11283 == Expr::MLV_Valid) {
Argyrios Kyrtzidis8b6ec682011-02-01 18:24:22 +000011284 SourceLocation Loc = opE->getOperatorLoc();
Ted Kremenekc358d9f2011-02-01 22:36:09 +000011285
Ted Kremenekae022092011-02-02 02:20:30 +000011286 Diag(Loc, diag::warn_equality_with_extra_parens) << E->getSourceRange();
Daniel Dunbar62ee6412012-03-09 18:35:03 +000011287 SourceRange ParenERange = ParenE->getSourceRange();
Ted Kremenekae022092011-02-02 02:20:30 +000011288 Diag(Loc, diag::note_equality_comparison_silence)
Daniel Dunbar62ee6412012-03-09 18:35:03 +000011289 << FixItHint::CreateRemoval(ParenERange.getBegin())
11290 << FixItHint::CreateRemoval(ParenERange.getEnd());
Argyrios Kyrtzidise1b97c42011-04-25 23:01:29 +000011291 Diag(Loc, diag::note_equality_comparison_to_assign)
11292 << FixItHint::CreateReplacement(Loc, "=");
Argyrios Kyrtzidis8b6ec682011-02-01 18:24:22 +000011293 }
11294}
11295
John Wiegley01296292011-04-08 18:41:53 +000011296ExprResult Sema::CheckBooleanCondition(Expr *E, SourceLocation Loc) {
John McCalld5707ab2009-10-12 21:59:07 +000011297 DiagnoseAssignmentAsCondition(E);
Argyrios Kyrtzidis8b6ec682011-02-01 18:24:22 +000011298 if (ParenExpr *parenE = dyn_cast<ParenExpr>(E))
11299 DiagnoseEqualityWithExtraParens(parenE);
John McCalld5707ab2009-10-12 21:59:07 +000011300
John McCall0009fcc2011-04-26 20:42:42 +000011301 ExprResult result = CheckPlaceholderExpr(E);
11302 if (result.isInvalid()) return ExprError();
11303 E = result.take();
Argyrios Kyrtzidisca766292010-11-01 18:49:26 +000011304
John McCall0009fcc2011-04-26 20:42:42 +000011305 if (!E->isTypeDependent()) {
David Blaikiebbafb8a2012-03-11 07:00:24 +000011306 if (getLangOpts().CPlusPlus)
John McCall34376a62010-12-04 03:47:34 +000011307 return CheckCXXBooleanCondition(E); // C++ 6.4p4
11308
John Wiegley01296292011-04-08 18:41:53 +000011309 ExprResult ERes = DefaultFunctionArrayLvalueConversion(E);
11310 if (ERes.isInvalid())
11311 return ExprError();
11312 E = ERes.take();
John McCall29cb2fd2010-12-04 06:09:13 +000011313
11314 QualType T = E->getType();
John Wiegley01296292011-04-08 18:41:53 +000011315 if (!T->isScalarType()) { // C99 6.8.4.1p1
11316 Diag(Loc, diag::err_typecheck_statement_requires_scalar)
11317 << T << E->getSourceRange();
11318 return ExprError();
11319 }
John McCalld5707ab2009-10-12 21:59:07 +000011320 }
11321
John Wiegley01296292011-04-08 18:41:53 +000011322 return Owned(E);
John McCalld5707ab2009-10-12 21:59:07 +000011323}
Douglas Gregore60e41a2010-05-06 17:25:47 +000011324
John McCalldadc5752010-08-24 06:29:42 +000011325ExprResult Sema::ActOnBooleanCondition(Scope *S, SourceLocation Loc,
Richard Trieuba63ce62011-09-09 01:45:06 +000011326 Expr *SubExpr) {
11327 if (!SubExpr)
Douglas Gregore60e41a2010-05-06 17:25:47 +000011328 return ExprError();
John Wiegley01296292011-04-08 18:41:53 +000011329
Richard Trieuba63ce62011-09-09 01:45:06 +000011330 return CheckBooleanCondition(SubExpr, Loc);
Douglas Gregore60e41a2010-05-06 17:25:47 +000011331}
John McCall36e7fe32010-10-12 00:20:44 +000011332
John McCall31996342011-04-07 08:22:57 +000011333namespace {
John McCall2979fe02011-04-12 00:42:48 +000011334 /// A visitor for rebuilding a call to an __unknown_any expression
11335 /// to have an appropriate type.
11336 struct RebuildUnknownAnyFunction
11337 : StmtVisitor<RebuildUnknownAnyFunction, ExprResult> {
11338
11339 Sema &S;
11340
11341 RebuildUnknownAnyFunction(Sema &S) : S(S) {}
11342
11343 ExprResult VisitStmt(Stmt *S) {
11344 llvm_unreachable("unexpected statement!");
John McCall2979fe02011-04-12 00:42:48 +000011345 }
11346
Richard Trieu10162ab2011-09-09 03:59:41 +000011347 ExprResult VisitExpr(Expr *E) {
11348 S.Diag(E->getExprLoc(), diag::err_unsupported_unknown_any_call)
11349 << E->getSourceRange();
John McCall2979fe02011-04-12 00:42:48 +000011350 return ExprError();
11351 }
11352
11353 /// Rebuild an expression which simply semantically wraps another
11354 /// expression which it shares the type and value kind of.
Richard Trieu10162ab2011-09-09 03:59:41 +000011355 template <class T> ExprResult rebuildSugarExpr(T *E) {
11356 ExprResult SubResult = Visit(E->getSubExpr());
11357 if (SubResult.isInvalid()) return ExprError();
John McCall2979fe02011-04-12 00:42:48 +000011358
Richard Trieu10162ab2011-09-09 03:59:41 +000011359 Expr *SubExpr = SubResult.take();
11360 E->setSubExpr(SubExpr);
11361 E->setType(SubExpr->getType());
11362 E->setValueKind(SubExpr->getValueKind());
11363 assert(E->getObjectKind() == OK_Ordinary);
11364 return E;
John McCall2979fe02011-04-12 00:42:48 +000011365 }
11366
Richard Trieu10162ab2011-09-09 03:59:41 +000011367 ExprResult VisitParenExpr(ParenExpr *E) {
11368 return rebuildSugarExpr(E);
John McCall2979fe02011-04-12 00:42:48 +000011369 }
11370
Richard Trieu10162ab2011-09-09 03:59:41 +000011371 ExprResult VisitUnaryExtension(UnaryOperator *E) {
11372 return rebuildSugarExpr(E);
John McCall2979fe02011-04-12 00:42:48 +000011373 }
11374
Richard Trieu10162ab2011-09-09 03:59:41 +000011375 ExprResult VisitUnaryAddrOf(UnaryOperator *E) {
11376 ExprResult SubResult = Visit(E->getSubExpr());
11377 if (SubResult.isInvalid()) return ExprError();
John McCall2979fe02011-04-12 00:42:48 +000011378
Richard Trieu10162ab2011-09-09 03:59:41 +000011379 Expr *SubExpr = SubResult.take();
11380 E->setSubExpr(SubExpr);
11381 E->setType(S.Context.getPointerType(SubExpr->getType()));
11382 assert(E->getValueKind() == VK_RValue);
11383 assert(E->getObjectKind() == OK_Ordinary);
11384 return E;
John McCall2979fe02011-04-12 00:42:48 +000011385 }
11386
Richard Trieu10162ab2011-09-09 03:59:41 +000011387 ExprResult resolveDecl(Expr *E, ValueDecl *VD) {
11388 if (!isa<FunctionDecl>(VD)) return VisitExpr(E);
John McCall2979fe02011-04-12 00:42:48 +000011389
Richard Trieu10162ab2011-09-09 03:59:41 +000011390 E->setType(VD->getType());
John McCall2979fe02011-04-12 00:42:48 +000011391
Richard Trieu10162ab2011-09-09 03:59:41 +000011392 assert(E->getValueKind() == VK_RValue);
David Blaikiebbafb8a2012-03-11 07:00:24 +000011393 if (S.getLangOpts().CPlusPlus &&
Richard Trieu10162ab2011-09-09 03:59:41 +000011394 !(isa<CXXMethodDecl>(VD) &&
11395 cast<CXXMethodDecl>(VD)->isInstance()))
11396 E->setValueKind(VK_LValue);
John McCall2979fe02011-04-12 00:42:48 +000011397
Richard Trieu10162ab2011-09-09 03:59:41 +000011398 return E;
John McCall2979fe02011-04-12 00:42:48 +000011399 }
11400
Richard Trieu10162ab2011-09-09 03:59:41 +000011401 ExprResult VisitMemberExpr(MemberExpr *E) {
11402 return resolveDecl(E, E->getMemberDecl());
John McCall2979fe02011-04-12 00:42:48 +000011403 }
11404
Richard Trieu10162ab2011-09-09 03:59:41 +000011405 ExprResult VisitDeclRefExpr(DeclRefExpr *E) {
11406 return resolveDecl(E, E->getDecl());
John McCall2979fe02011-04-12 00:42:48 +000011407 }
11408 };
11409}
11410
11411/// Given a function expression of unknown-any type, try to rebuild it
11412/// to have a function type.
Richard Trieu10162ab2011-09-09 03:59:41 +000011413static ExprResult rebuildUnknownAnyFunction(Sema &S, Expr *FunctionExpr) {
11414 ExprResult Result = RebuildUnknownAnyFunction(S).Visit(FunctionExpr);
11415 if (Result.isInvalid()) return ExprError();
11416 return S.DefaultFunctionArrayConversion(Result.take());
John McCall2979fe02011-04-12 00:42:48 +000011417}
11418
11419namespace {
John McCall2d2e8702011-04-11 07:02:50 +000011420 /// A visitor for rebuilding an expression of type __unknown_anytype
11421 /// into one which resolves the type directly on the referring
11422 /// expression. Strict preservation of the original source
11423 /// structure is not a goal.
John McCall31996342011-04-07 08:22:57 +000011424 struct RebuildUnknownAnyExpr
John McCall39439732011-04-09 22:50:59 +000011425 : StmtVisitor<RebuildUnknownAnyExpr, ExprResult> {
John McCall31996342011-04-07 08:22:57 +000011426
11427 Sema &S;
11428
11429 /// The current destination type.
11430 QualType DestType;
11431
Richard Trieu10162ab2011-09-09 03:59:41 +000011432 RebuildUnknownAnyExpr(Sema &S, QualType CastType)
11433 : S(S), DestType(CastType) {}
John McCall31996342011-04-07 08:22:57 +000011434
John McCall39439732011-04-09 22:50:59 +000011435 ExprResult VisitStmt(Stmt *S) {
John McCall2d2e8702011-04-11 07:02:50 +000011436 llvm_unreachable("unexpected statement!");
John McCall31996342011-04-07 08:22:57 +000011437 }
11438
Richard Trieu10162ab2011-09-09 03:59:41 +000011439 ExprResult VisitExpr(Expr *E) {
11440 S.Diag(E->getExprLoc(), diag::err_unsupported_unknown_any_expr)
11441 << E->getSourceRange();
John McCall2d2e8702011-04-11 07:02:50 +000011442 return ExprError();
John McCall31996342011-04-07 08:22:57 +000011443 }
11444
Richard Trieu10162ab2011-09-09 03:59:41 +000011445 ExprResult VisitCallExpr(CallExpr *E);
11446 ExprResult VisitObjCMessageExpr(ObjCMessageExpr *E);
John McCall2d2e8702011-04-11 07:02:50 +000011447
John McCall39439732011-04-09 22:50:59 +000011448 /// Rebuild an expression which simply semantically wraps another
11449 /// expression which it shares the type and value kind of.
Richard Trieu10162ab2011-09-09 03:59:41 +000011450 template <class T> ExprResult rebuildSugarExpr(T *E) {
11451 ExprResult SubResult = Visit(E->getSubExpr());
11452 if (SubResult.isInvalid()) return ExprError();
11453 Expr *SubExpr = SubResult.take();
11454 E->setSubExpr(SubExpr);
11455 E->setType(SubExpr->getType());
11456 E->setValueKind(SubExpr->getValueKind());
11457 assert(E->getObjectKind() == OK_Ordinary);
11458 return E;
John McCall39439732011-04-09 22:50:59 +000011459 }
John McCall31996342011-04-07 08:22:57 +000011460
Richard Trieu10162ab2011-09-09 03:59:41 +000011461 ExprResult VisitParenExpr(ParenExpr *E) {
11462 return rebuildSugarExpr(E);
John McCall39439732011-04-09 22:50:59 +000011463 }
11464
Richard Trieu10162ab2011-09-09 03:59:41 +000011465 ExprResult VisitUnaryExtension(UnaryOperator *E) {
11466 return rebuildSugarExpr(E);
John McCall39439732011-04-09 22:50:59 +000011467 }
11468
Richard Trieu10162ab2011-09-09 03:59:41 +000011469 ExprResult VisitUnaryAddrOf(UnaryOperator *E) {
11470 const PointerType *Ptr = DestType->getAs<PointerType>();
11471 if (!Ptr) {
11472 S.Diag(E->getOperatorLoc(), diag::err_unknown_any_addrof)
11473 << E->getSourceRange();
John McCall2979fe02011-04-12 00:42:48 +000011474 return ExprError();
11475 }
Richard Trieu10162ab2011-09-09 03:59:41 +000011476 assert(E->getValueKind() == VK_RValue);
11477 assert(E->getObjectKind() == OK_Ordinary);
11478 E->setType(DestType);
John McCall2979fe02011-04-12 00:42:48 +000011479
11480 // Build the sub-expression as if it were an object of the pointee type.
Richard Trieu10162ab2011-09-09 03:59:41 +000011481 DestType = Ptr->getPointeeType();
11482 ExprResult SubResult = Visit(E->getSubExpr());
11483 if (SubResult.isInvalid()) return ExprError();
11484 E->setSubExpr(SubResult.take());
11485 return E;
John McCall2979fe02011-04-12 00:42:48 +000011486 }
11487
Richard Trieu10162ab2011-09-09 03:59:41 +000011488 ExprResult VisitImplicitCastExpr(ImplicitCastExpr *E);
John McCall39439732011-04-09 22:50:59 +000011489
Richard Trieu10162ab2011-09-09 03:59:41 +000011490 ExprResult resolveDecl(Expr *E, ValueDecl *VD);
John McCall39439732011-04-09 22:50:59 +000011491
Richard Trieu10162ab2011-09-09 03:59:41 +000011492 ExprResult VisitMemberExpr(MemberExpr *E) {
11493 return resolveDecl(E, E->getMemberDecl());
John McCall2979fe02011-04-12 00:42:48 +000011494 }
John McCall39439732011-04-09 22:50:59 +000011495
Richard Trieu10162ab2011-09-09 03:59:41 +000011496 ExprResult VisitDeclRefExpr(DeclRefExpr *E) {
11497 return resolveDecl(E, E->getDecl());
John McCall31996342011-04-07 08:22:57 +000011498 }
11499 };
11500}
11501
John McCall2d2e8702011-04-11 07:02:50 +000011502/// Rebuilds a call expression which yielded __unknown_anytype.
Richard Trieu10162ab2011-09-09 03:59:41 +000011503ExprResult RebuildUnknownAnyExpr::VisitCallExpr(CallExpr *E) {
11504 Expr *CalleeExpr = E->getCallee();
John McCall2d2e8702011-04-11 07:02:50 +000011505
11506 enum FnKind {
John McCall4adb38c2011-04-27 00:36:17 +000011507 FK_MemberFunction,
John McCall2d2e8702011-04-11 07:02:50 +000011508 FK_FunctionPointer,
11509 FK_BlockPointer
11510 };
11511
Richard Trieu10162ab2011-09-09 03:59:41 +000011512 FnKind Kind;
11513 QualType CalleeType = CalleeExpr->getType();
11514 if (CalleeType == S.Context.BoundMemberTy) {
11515 assert(isa<CXXMemberCallExpr>(E) || isa<CXXOperatorCallExpr>(E));
11516 Kind = FK_MemberFunction;
11517 CalleeType = Expr::findBoundMemberType(CalleeExpr);
11518 } else if (const PointerType *Ptr = CalleeType->getAs<PointerType>()) {
11519 CalleeType = Ptr->getPointeeType();
11520 Kind = FK_FunctionPointer;
John McCall2d2e8702011-04-11 07:02:50 +000011521 } else {
Richard Trieu10162ab2011-09-09 03:59:41 +000011522 CalleeType = CalleeType->castAs<BlockPointerType>()->getPointeeType();
11523 Kind = FK_BlockPointer;
John McCall2d2e8702011-04-11 07:02:50 +000011524 }
Richard Trieu10162ab2011-09-09 03:59:41 +000011525 const FunctionType *FnType = CalleeType->castAs<FunctionType>();
John McCall2d2e8702011-04-11 07:02:50 +000011526
11527 // Verify that this is a legal result type of a function.
11528 if (DestType->isArrayType() || DestType->isFunctionType()) {
11529 unsigned diagID = diag::err_func_returning_array_function;
Richard Trieu10162ab2011-09-09 03:59:41 +000011530 if (Kind == FK_BlockPointer)
John McCall2d2e8702011-04-11 07:02:50 +000011531 diagID = diag::err_block_returning_array_function;
11532
Richard Trieu10162ab2011-09-09 03:59:41 +000011533 S.Diag(E->getExprLoc(), diagID)
John McCall2d2e8702011-04-11 07:02:50 +000011534 << DestType->isFunctionType() << DestType;
11535 return ExprError();
11536 }
11537
11538 // Otherwise, go ahead and set DestType as the call's result.
Richard Trieu10162ab2011-09-09 03:59:41 +000011539 E->setType(DestType.getNonLValueExprType(S.Context));
11540 E->setValueKind(Expr::getValueKindForType(DestType));
11541 assert(E->getObjectKind() == OK_Ordinary);
John McCall2d2e8702011-04-11 07:02:50 +000011542
11543 // Rebuild the function type, replacing the result type with DestType.
Richard Trieu10162ab2011-09-09 03:59:41 +000011544 if (const FunctionProtoType *Proto = dyn_cast<FunctionProtoType>(FnType))
John McCall2d2e8702011-04-11 07:02:50 +000011545 DestType = S.Context.getFunctionType(DestType,
Richard Trieu10162ab2011-09-09 03:59:41 +000011546 Proto->arg_type_begin(),
11547 Proto->getNumArgs(),
11548 Proto->getExtProtoInfo());
John McCall2d2e8702011-04-11 07:02:50 +000011549 else
11550 DestType = S.Context.getFunctionNoProtoType(DestType,
Richard Trieu10162ab2011-09-09 03:59:41 +000011551 FnType->getExtInfo());
John McCall2d2e8702011-04-11 07:02:50 +000011552
11553 // Rebuild the appropriate pointer-to-function type.
Richard Trieu10162ab2011-09-09 03:59:41 +000011554 switch (Kind) {
John McCall4adb38c2011-04-27 00:36:17 +000011555 case FK_MemberFunction:
John McCall2d2e8702011-04-11 07:02:50 +000011556 // Nothing to do.
11557 break;
11558
11559 case FK_FunctionPointer:
11560 DestType = S.Context.getPointerType(DestType);
11561 break;
11562
11563 case FK_BlockPointer:
11564 DestType = S.Context.getBlockPointerType(DestType);
11565 break;
11566 }
11567
11568 // Finally, we can recurse.
Richard Trieu10162ab2011-09-09 03:59:41 +000011569 ExprResult CalleeResult = Visit(CalleeExpr);
11570 if (!CalleeResult.isUsable()) return ExprError();
11571 E->setCallee(CalleeResult.take());
John McCall2d2e8702011-04-11 07:02:50 +000011572
11573 // Bind a temporary if necessary.
Richard Trieu10162ab2011-09-09 03:59:41 +000011574 return S.MaybeBindToTemporary(E);
John McCall2d2e8702011-04-11 07:02:50 +000011575}
11576
Richard Trieu10162ab2011-09-09 03:59:41 +000011577ExprResult RebuildUnknownAnyExpr::VisitObjCMessageExpr(ObjCMessageExpr *E) {
John McCall2979fe02011-04-12 00:42:48 +000011578 // Verify that this is a legal result type of a call.
11579 if (DestType->isArrayType() || DestType->isFunctionType()) {
Richard Trieu10162ab2011-09-09 03:59:41 +000011580 S.Diag(E->getExprLoc(), diag::err_func_returning_array_function)
John McCall2979fe02011-04-12 00:42:48 +000011581 << DestType->isFunctionType() << DestType;
11582 return ExprError();
John McCall2d2e8702011-04-11 07:02:50 +000011583 }
11584
John McCall3f4138c2011-07-13 17:56:40 +000011585 // Rewrite the method result type if available.
Richard Trieu10162ab2011-09-09 03:59:41 +000011586 if (ObjCMethodDecl *Method = E->getMethodDecl()) {
11587 assert(Method->getResultType() == S.Context.UnknownAnyTy);
11588 Method->setResultType(DestType);
John McCall3f4138c2011-07-13 17:56:40 +000011589 }
John McCall2979fe02011-04-12 00:42:48 +000011590
John McCall2d2e8702011-04-11 07:02:50 +000011591 // Change the type of the message.
Richard Trieu10162ab2011-09-09 03:59:41 +000011592 E->setType(DestType.getNonReferenceType());
11593 E->setValueKind(Expr::getValueKindForType(DestType));
John McCall2d2e8702011-04-11 07:02:50 +000011594
Richard Trieu10162ab2011-09-09 03:59:41 +000011595 return S.MaybeBindToTemporary(E);
John McCall2d2e8702011-04-11 07:02:50 +000011596}
11597
Richard Trieu10162ab2011-09-09 03:59:41 +000011598ExprResult RebuildUnknownAnyExpr::VisitImplicitCastExpr(ImplicitCastExpr *E) {
John McCall2979fe02011-04-12 00:42:48 +000011599 // The only case we should ever see here is a function-to-pointer decay.
Sean Callanan2db103c2012-03-06 23:12:57 +000011600 if (E->getCastKind() == CK_FunctionToPointerDecay) {
Sean Callanan12495112012-03-06 21:34:12 +000011601 assert(E->getValueKind() == VK_RValue);
11602 assert(E->getObjectKind() == OK_Ordinary);
11603
11604 E->setType(DestType);
11605
11606 // Rebuild the sub-expression as the pointee (function) type.
11607 DestType = DestType->castAs<PointerType>()->getPointeeType();
11608
11609 ExprResult Result = Visit(E->getSubExpr());
11610 if (!Result.isUsable()) return ExprError();
11611
11612 E->setSubExpr(Result.take());
11613 return S.Owned(E);
Sean Callanan2db103c2012-03-06 23:12:57 +000011614 } else if (E->getCastKind() == CK_LValueToRValue) {
Sean Callanan12495112012-03-06 21:34:12 +000011615 assert(E->getValueKind() == VK_RValue);
11616 assert(E->getObjectKind() == OK_Ordinary);
John McCall2d2e8702011-04-11 07:02:50 +000011617
Sean Callanan12495112012-03-06 21:34:12 +000011618 assert(isa<BlockPointerType>(E->getType()));
John McCall2979fe02011-04-12 00:42:48 +000011619
Sean Callanan12495112012-03-06 21:34:12 +000011620 E->setType(DestType);
John McCall2d2e8702011-04-11 07:02:50 +000011621
Sean Callanan12495112012-03-06 21:34:12 +000011622 // The sub-expression has to be a lvalue reference, so rebuild it as such.
11623 DestType = S.Context.getLValueReferenceType(DestType);
John McCall2d2e8702011-04-11 07:02:50 +000011624
Sean Callanan12495112012-03-06 21:34:12 +000011625 ExprResult Result = Visit(E->getSubExpr());
11626 if (!Result.isUsable()) return ExprError();
11627
11628 E->setSubExpr(Result.take());
11629 return S.Owned(E);
Sean Callanan2db103c2012-03-06 23:12:57 +000011630 } else {
Sean Callanan12495112012-03-06 21:34:12 +000011631 llvm_unreachable("Unhandled cast type!");
11632 }
John McCall2d2e8702011-04-11 07:02:50 +000011633}
11634
Richard Trieu10162ab2011-09-09 03:59:41 +000011635ExprResult RebuildUnknownAnyExpr::resolveDecl(Expr *E, ValueDecl *VD) {
11636 ExprValueKind ValueKind = VK_LValue;
11637 QualType Type = DestType;
John McCall2d2e8702011-04-11 07:02:50 +000011638
11639 // We know how to make this work for certain kinds of decls:
11640
11641 // - functions
Richard Trieu10162ab2011-09-09 03:59:41 +000011642 if (FunctionDecl *FD = dyn_cast<FunctionDecl>(VD)) {
11643 if (const PointerType *Ptr = Type->getAs<PointerType>()) {
11644 DestType = Ptr->getPointeeType();
11645 ExprResult Result = resolveDecl(E, VD);
11646 if (Result.isInvalid()) return ExprError();
11647 return S.ImpCastExprToType(Result.take(), Type,
John McCall9a877fe2011-08-10 04:12:23 +000011648 CK_FunctionToPointerDecay, VK_RValue);
11649 }
11650
Richard Trieu10162ab2011-09-09 03:59:41 +000011651 if (!Type->isFunctionType()) {
11652 S.Diag(E->getExprLoc(), diag::err_unknown_any_function)
11653 << VD << E->getSourceRange();
John McCall9a877fe2011-08-10 04:12:23 +000011654 return ExprError();
11655 }
John McCall2d2e8702011-04-11 07:02:50 +000011656
Richard Trieu10162ab2011-09-09 03:59:41 +000011657 if (CXXMethodDecl *MD = dyn_cast<CXXMethodDecl>(FD))
11658 if (MD->isInstance()) {
11659 ValueKind = VK_RValue;
11660 Type = S.Context.BoundMemberTy;
John McCall4adb38c2011-04-27 00:36:17 +000011661 }
11662
John McCall2d2e8702011-04-11 07:02:50 +000011663 // Function references aren't l-values in C.
David Blaikiebbafb8a2012-03-11 07:00:24 +000011664 if (!S.getLangOpts().CPlusPlus)
Richard Trieu10162ab2011-09-09 03:59:41 +000011665 ValueKind = VK_RValue;
John McCall2d2e8702011-04-11 07:02:50 +000011666
11667 // - variables
Richard Trieu10162ab2011-09-09 03:59:41 +000011668 } else if (isa<VarDecl>(VD)) {
11669 if (const ReferenceType *RefTy = Type->getAs<ReferenceType>()) {
11670 Type = RefTy->getPointeeType();
11671 } else if (Type->isFunctionType()) {
11672 S.Diag(E->getExprLoc(), diag::err_unknown_any_var_function_type)
11673 << VD << E->getSourceRange();
John McCall2979fe02011-04-12 00:42:48 +000011674 return ExprError();
John McCall2d2e8702011-04-11 07:02:50 +000011675 }
11676
11677 // - nothing else
11678 } else {
Richard Trieu10162ab2011-09-09 03:59:41 +000011679 S.Diag(E->getExprLoc(), diag::err_unsupported_unknown_any_decl)
11680 << VD << E->getSourceRange();
John McCall2d2e8702011-04-11 07:02:50 +000011681 return ExprError();
11682 }
11683
Richard Trieu10162ab2011-09-09 03:59:41 +000011684 VD->setType(DestType);
11685 E->setType(Type);
11686 E->setValueKind(ValueKind);
11687 return S.Owned(E);
John McCall2d2e8702011-04-11 07:02:50 +000011688}
11689
John McCall31996342011-04-07 08:22:57 +000011690/// Check a cast of an unknown-any type. We intentionally only
11691/// trigger this for C-style casts.
Richard Trieuba63ce62011-09-09 01:45:06 +000011692ExprResult Sema::checkUnknownAnyCast(SourceRange TypeRange, QualType CastType,
11693 Expr *CastExpr, CastKind &CastKind,
11694 ExprValueKind &VK, CXXCastPath &Path) {
John McCall31996342011-04-07 08:22:57 +000011695 // Rewrite the casted expression from scratch.
Richard Trieuba63ce62011-09-09 01:45:06 +000011696 ExprResult result = RebuildUnknownAnyExpr(*this, CastType).Visit(CastExpr);
John McCall39439732011-04-09 22:50:59 +000011697 if (!result.isUsable()) return ExprError();
John McCall31996342011-04-07 08:22:57 +000011698
Richard Trieuba63ce62011-09-09 01:45:06 +000011699 CastExpr = result.take();
11700 VK = CastExpr->getValueKind();
11701 CastKind = CK_NoOp;
John McCall39439732011-04-09 22:50:59 +000011702
Richard Trieuba63ce62011-09-09 01:45:06 +000011703 return CastExpr;
John McCall31996342011-04-07 08:22:57 +000011704}
11705
Douglas Gregord8fb1e32011-12-01 01:37:36 +000011706ExprResult Sema::forceUnknownAnyToType(Expr *E, QualType ToType) {
11707 return RebuildUnknownAnyExpr(*this, ToType).Visit(E);
11708}
11709
Richard Trieuba63ce62011-09-09 01:45:06 +000011710static ExprResult diagnoseUnknownAnyExpr(Sema &S, Expr *E) {
11711 Expr *orig = E;
John McCall2d2e8702011-04-11 07:02:50 +000011712 unsigned diagID = diag::err_uncasted_use_of_unknown_any;
John McCall31996342011-04-07 08:22:57 +000011713 while (true) {
Richard Trieuba63ce62011-09-09 01:45:06 +000011714 E = E->IgnoreParenImpCasts();
11715 if (CallExpr *call = dyn_cast<CallExpr>(E)) {
11716 E = call->getCallee();
John McCall2d2e8702011-04-11 07:02:50 +000011717 diagID = diag::err_uncasted_call_of_unknown_any;
11718 } else {
John McCall31996342011-04-07 08:22:57 +000011719 break;
John McCall2d2e8702011-04-11 07:02:50 +000011720 }
John McCall31996342011-04-07 08:22:57 +000011721 }
11722
John McCall2d2e8702011-04-11 07:02:50 +000011723 SourceLocation loc;
11724 NamedDecl *d;
Richard Trieuba63ce62011-09-09 01:45:06 +000011725 if (DeclRefExpr *ref = dyn_cast<DeclRefExpr>(E)) {
John McCall2d2e8702011-04-11 07:02:50 +000011726 loc = ref->getLocation();
11727 d = ref->getDecl();
Richard Trieuba63ce62011-09-09 01:45:06 +000011728 } else if (MemberExpr *mem = dyn_cast<MemberExpr>(E)) {
John McCall2d2e8702011-04-11 07:02:50 +000011729 loc = mem->getMemberLoc();
11730 d = mem->getMemberDecl();
Richard Trieuba63ce62011-09-09 01:45:06 +000011731 } else if (ObjCMessageExpr *msg = dyn_cast<ObjCMessageExpr>(E)) {
John McCall2d2e8702011-04-11 07:02:50 +000011732 diagID = diag::err_uncasted_call_of_unknown_any;
Argyrios Kyrtzidisa6011e22011-10-03 06:36:51 +000011733 loc = msg->getSelectorStartLoc();
John McCall2d2e8702011-04-11 07:02:50 +000011734 d = msg->getMethodDecl();
John McCallfa6f5d62011-08-31 20:57:36 +000011735 if (!d) {
11736 S.Diag(loc, diag::err_uncasted_send_to_unknown_any_method)
11737 << static_cast<unsigned>(msg->isClassMessage()) << msg->getSelector()
11738 << orig->getSourceRange();
11739 return ExprError();
11740 }
John McCall2d2e8702011-04-11 07:02:50 +000011741 } else {
Richard Trieuba63ce62011-09-09 01:45:06 +000011742 S.Diag(E->getExprLoc(), diag::err_unsupported_unknown_any_expr)
11743 << E->getSourceRange();
John McCall2d2e8702011-04-11 07:02:50 +000011744 return ExprError();
11745 }
11746
11747 S.Diag(loc, diagID) << d << orig->getSourceRange();
John McCall31996342011-04-07 08:22:57 +000011748
11749 // Never recoverable.
11750 return ExprError();
11751}
11752
John McCall36e7fe32010-10-12 00:20:44 +000011753/// Check for operands with placeholder types and complain if found.
11754/// Returns true if there was an error and no recovery was possible.
John McCall3aef3d82011-04-10 19:13:55 +000011755ExprResult Sema::CheckPlaceholderExpr(Expr *E) {
John McCall4124c492011-10-17 18:40:02 +000011756 const BuiltinType *placeholderType = E->getType()->getAsPlaceholderType();
11757 if (!placeholderType) return Owned(E);
11758
11759 switch (placeholderType->getKind()) {
John McCall36e7fe32010-10-12 00:20:44 +000011760
John McCall31996342011-04-07 08:22:57 +000011761 // Overloaded expressions.
John McCall4124c492011-10-17 18:40:02 +000011762 case BuiltinType::Overload: {
John McCall50a2c2c2011-10-11 23:14:30 +000011763 // Try to resolve a single function template specialization.
11764 // This is obligatory.
11765 ExprResult result = Owned(E);
11766 if (ResolveAndFixSingleFunctionTemplateSpecialization(result, false)) {
11767 return result;
11768
11769 // If that failed, try to recover with a call.
11770 } else {
11771 tryToRecoverWithCall(result, PDiag(diag::err_ovl_unresolvable),
11772 /*complain*/ true);
11773 return result;
11774 }
11775 }
John McCall31996342011-04-07 08:22:57 +000011776
John McCall0009fcc2011-04-26 20:42:42 +000011777 // Bound member functions.
John McCall4124c492011-10-17 18:40:02 +000011778 case BuiltinType::BoundMember: {
John McCall50a2c2c2011-10-11 23:14:30 +000011779 ExprResult result = Owned(E);
11780 tryToRecoverWithCall(result, PDiag(diag::err_bound_member_function),
11781 /*complain*/ true);
11782 return result;
John McCall4124c492011-10-17 18:40:02 +000011783 }
11784
11785 // ARC unbridged casts.
11786 case BuiltinType::ARCUnbridgedCast: {
11787 Expr *realCast = stripARCUnbridgedCast(E);
11788 diagnoseARCUnbridgedCast(realCast);
11789 return Owned(realCast);
11790 }
John McCall0009fcc2011-04-26 20:42:42 +000011791
John McCall31996342011-04-07 08:22:57 +000011792 // Expressions of unknown type.
John McCall4124c492011-10-17 18:40:02 +000011793 case BuiltinType::UnknownAny:
John McCall31996342011-04-07 08:22:57 +000011794 return diagnoseUnknownAnyExpr(*this, E);
11795
John McCall526ab472011-10-25 17:37:35 +000011796 // Pseudo-objects.
11797 case BuiltinType::PseudoObject:
11798 return checkPseudoObjectRValue(E);
11799
Eli Friedman34866c72012-08-31 00:14:07 +000011800 case BuiltinType::BuiltinFn:
11801 Diag(E->getLocStart(), diag::err_builtin_fn_use);
11802 return ExprError();
11803
John McCalle314e272011-10-18 21:02:43 +000011804 // Everything else should be impossible.
11805#define BUILTIN_TYPE(Id, SingletonId) \
11806 case BuiltinType::Id:
11807#define PLACEHOLDER_TYPE(Id, SingletonId)
11808#include "clang/AST/BuiltinTypes.def"
John McCall4124c492011-10-17 18:40:02 +000011809 break;
11810 }
11811
11812 llvm_unreachable("invalid placeholder type!");
John McCall36e7fe32010-10-12 00:20:44 +000011813}
Richard Trieu2c850c02011-04-21 21:44:26 +000011814
Richard Trieuba63ce62011-09-09 01:45:06 +000011815bool Sema::CheckCaseExpression(Expr *E) {
11816 if (E->isTypeDependent())
Richard Trieu2c850c02011-04-21 21:44:26 +000011817 return true;
Richard Trieuba63ce62011-09-09 01:45:06 +000011818 if (E->isValueDependent() || E->isIntegerConstantExpr(Context))
11819 return E->getType()->isIntegralOrEnumerationType();
Richard Trieu2c850c02011-04-21 21:44:26 +000011820 return false;
11821}
Ted Kremeneke65b0862012-03-06 20:05:56 +000011822
11823/// ActOnObjCBoolLiteral - Parse {__objc_yes,__objc_no} literals.
11824ExprResult
11825Sema::ActOnObjCBoolLiteral(SourceLocation OpLoc, tok::TokenKind Kind) {
11826 assert((Kind == tok::kw___objc_yes || Kind == tok::kw___objc_no) &&
11827 "Unknown Objective-C Boolean value!");
Fariborz Jahanianf2578572012-08-30 18:49:41 +000011828 QualType BoolT = Context.ObjCBuiltinBoolTy;
11829 if (!Context.getBOOLDecl()) {
11830 LookupResult Result(*this, &Context.Idents.get("BOOL"), SourceLocation(),
11831 Sema::LookupOrdinaryName);
11832 if (LookupName(Result, getCurScope())) {
11833 NamedDecl *ND = Result.getFoundDecl();
11834 if (TypedefDecl *TD = dyn_cast<TypedefDecl>(ND))
11835 Context.setBOOLDecl(TD);
11836 }
11837 }
11838 if (Context.getBOOLDecl())
11839 BoolT = Context.getBOOLType();
Ted Kremeneke65b0862012-03-06 20:05:56 +000011840 return Owned(new (Context) ObjCBoolLiteralExpr(Kind == tok::kw___objc_yes,
Fariborz Jahanianf2578572012-08-30 18:49:41 +000011841 BoolT, OpLoc));
Ted Kremeneke65b0862012-03-06 20:05:56 +000011842}