blob: 57dab09e46d2dc59d659856ccd9fedfe17d569dd [file] [log] [blame]
Reid Spencer5f016e22007-07-11 17:01:13 +00001//===--- SemaExpr.cpp - Semantic Analysis for Expressions -----------------===//
2//
3// The LLVM Compiler Infrastructure
4//
Chris Lattner0bc735f2007-12-29 19:59:25 +00005// This file is distributed under the University of Illinois Open Source
6// License. See LICENSE.TXT for details.
Reid Spencer5f016e22007-07-11 17:01:13 +00007//
8//===----------------------------------------------------------------------===//
9//
10// This file implements semantic analysis for expressions.
11//
12//===----------------------------------------------------------------------===//
13
John McCall2d887082010-08-25 22:03:47 +000014#include "clang/Sema/SemaInternal.h"
Eli Friedman93c878e2012-01-18 01:05:54 +000015#include "clang/Sema/DelayedDiagnostic.h"
Douglas Gregore737f502010-08-12 20:07:10 +000016#include "clang/Sema/Initialization.h"
17#include "clang/Sema/Lookup.h"
Eli Friedman93c878e2012-01-18 01:05:54 +000018#include "clang/Sema/ScopeInfo.h"
Douglas Gregore737f502010-08-12 20:07:10 +000019#include "clang/Sema/AnalysisBasedWarnings.h"
Reid Spencer5f016e22007-07-11 17:01:13 +000020#include "clang/AST/ASTContext.h"
Argyrios Kyrtzidis6d968362012-02-10 20:10:44 +000021#include "clang/AST/ASTConsumer.h"
Sebastian Redlf79a7192011-04-29 08:19:30 +000022#include "clang/AST/ASTMutationListener.h"
Douglas Gregorcc8a5d52010-04-29 00:18:15 +000023#include "clang/AST/CXXInheritance.h"
Daniel Dunbarc4a1dea2008-08-11 05:35:13 +000024#include "clang/AST/DeclObjC.h"
Anders Carlssond497ba72009-08-26 22:59:12 +000025#include "clang/AST/DeclTemplate.h"
Douglas Gregorbe0f7bd2010-09-11 20:24:53 +000026#include "clang/AST/EvaluatedExprVisitor.h"
Douglas Gregor8ecdb652010-04-28 22:16:22 +000027#include "clang/AST/Expr.h"
Chris Lattner04421082008-04-08 04:40:51 +000028#include "clang/AST/ExprCXX.h"
Steve Narofff494b572008-05-29 21:12:08 +000029#include "clang/AST/ExprObjC.h"
Douglas Gregorb4eeaff2010-05-07 23:12:07 +000030#include "clang/AST/RecursiveASTVisitor.h"
Douglas Gregor8ecdb652010-04-28 22:16:22 +000031#include "clang/AST/TypeLoc.h"
Anders Carlssond497ba72009-08-26 22:59:12 +000032#include "clang/Basic/PartialDiagnostic.h"
Reid Spencer5f016e22007-07-11 17:01:13 +000033#include "clang/Basic/SourceManager.h"
Reid Spencer5f016e22007-07-11 17:01:13 +000034#include "clang/Basic/TargetInfo.h"
Anders Carlssond497ba72009-08-26 22:59:12 +000035#include "clang/Lex/LiteralSupport.h"
36#include "clang/Lex/Preprocessor.h"
John McCall19510852010-08-20 18:27:03 +000037#include "clang/Sema/DeclSpec.h"
38#include "clang/Sema/Designator.h"
39#include "clang/Sema/Scope.h"
John McCall781472f2010-08-25 08:40:02 +000040#include "clang/Sema/ScopeInfo.h"
John McCall19510852010-08-20 18:27:03 +000041#include "clang/Sema/ParsedTemplate.h"
Anna Zaks67221552011-07-28 19:51:27 +000042#include "clang/Sema/SemaFixItUtils.h"
John McCall7cd088e2010-08-24 07:21:54 +000043#include "clang/Sema/Template.h"
Eli Friedmanef331b72012-01-20 01:26:23 +000044#include "TreeTransform.h"
Reid Spencer5f016e22007-07-11 17:01:13 +000045using namespace clang;
John McCall781472f2010-08-25 08:40:02 +000046using namespace sema;
Reid Spencer5f016e22007-07-11 17:01:13 +000047
Sebastian Redl14b0c192011-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 Redl28bdb142011-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 Redl14b0c192011-09-24 17:48:00 +000066 return true;
67}
David Chisnall0f436562009-08-17 16:35:33 +000068
Ted Kremenekd6cf9122012-02-10 02:45:47 +000069static AvailabilityResult DiagnoseAvailabilityOfDecl(Sema &S,
Fariborz Jahanian0f32caf2011-09-29 22:45:21 +000070 NamedDecl *D, SourceLocation Loc,
71 const ObjCInterfaceDecl *UnknownObjCClass) {
72 // See if this declaration is unavailable or deprecated.
73 std::string Message;
74 AvailabilityResult Result = D->getAvailability(&Message);
Fariborz Jahanian39b4fc82011-11-28 19:45:58 +000075 if (const EnumConstantDecl *ECD = dyn_cast<EnumConstantDecl>(D))
76 if (Result == AR_Available) {
77 const DeclContext *DC = ECD->getDeclContext();
78 if (const EnumDecl *TheEnumDecl = dyn_cast<EnumDecl>(DC))
79 Result = TheEnumDecl->getAvailability(&Message);
80 }
81
Fariborz Jahanian0f32caf2011-09-29 22:45:21 +000082 switch (Result) {
83 case AR_Available:
84 case AR_NotYetIntroduced:
85 break;
86
87 case AR_Deprecated:
Ted Kremenekd6cf9122012-02-10 02:45:47 +000088 S.EmitDeprecationWarning(D, Message, Loc, UnknownObjCClass);
Fariborz Jahanian0f32caf2011-09-29 22:45:21 +000089 break;
90
91 case AR_Unavailable:
Ted Kremenekd6cf9122012-02-10 02:45:47 +000092 if (S.getCurContextAvailability() != AR_Unavailable) {
Fariborz Jahanian0f32caf2011-09-29 22:45:21 +000093 if (Message.empty()) {
94 if (!UnknownObjCClass)
Ted Kremenekd6cf9122012-02-10 02:45:47 +000095 S.Diag(Loc, diag::err_unavailable) << D->getDeclName();
Fariborz Jahanian0f32caf2011-09-29 22:45:21 +000096 else
Ted Kremenekd6cf9122012-02-10 02:45:47 +000097 S.Diag(Loc, diag::warn_unavailable_fwdclass_message)
Fariborz Jahanian0f32caf2011-09-29 22:45:21 +000098 << D->getDeclName();
99 }
100 else
Ted Kremenekd6cf9122012-02-10 02:45:47 +0000101 S.Diag(Loc, diag::err_unavailable_message)
Fariborz Jahanian0f32caf2011-09-29 22:45:21 +0000102 << D->getDeclName() << Message;
Ted Kremenekd6cf9122012-02-10 02:45:47 +0000103 S.Diag(D->getLocation(), diag::note_unavailable_here)
Fariborz Jahanian0f32caf2011-09-29 22:45:21 +0000104 << isa<FunctionDecl>(D) << false;
105 }
106 break;
107 }
108 return Result;
109}
110
Richard Smith6c4c36c2012-03-30 20:53:28 +0000111/// \brief Emit a note explaining that this function is deleted or unavailable.
112void Sema::NoteDeletedFunction(FunctionDecl *Decl) {
113 CXXMethodDecl *Method = dyn_cast<CXXMethodDecl>(Decl);
114
Richard Smith5bdaac52012-04-02 20:59:25 +0000115 if (Method && Method->isDeleted() && !Method->isDeletedAsWritten()) {
116 // If the method was explicitly defaulted, point at that declaration.
117 if (!Method->isImplicit())
118 Diag(Decl->getLocation(), diag::note_implicitly_deleted);
119
120 // Try to diagnose why this special member function was implicitly
121 // deleted. This might fail, if that reason no longer applies.
Richard Smith6c4c36c2012-03-30 20:53:28 +0000122 CXXSpecialMember CSM = getSpecialMember(Method);
Richard Smith5bdaac52012-04-02 20:59:25 +0000123 if (CSM != CXXInvalid)
124 ShouldDeleteSpecialMember(Method, CSM, /*Diagnose=*/true);
125
126 return;
Richard Smith6c4c36c2012-03-30 20:53:28 +0000127 }
128
129 Diag(Decl->getLocation(), diag::note_unavailable_here)
130 << 1 << Decl->isDeleted();
131}
132
Jordan Rose0eb3f452012-06-18 22:09:19 +0000133/// \brief Determine whether a FunctionDecl was ever declared with an
134/// explicit storage class.
135static bool hasAnyExplicitStorageClass(const FunctionDecl *D) {
136 for (FunctionDecl::redecl_iterator I = D->redecls_begin(),
137 E = D->redecls_end();
138 I != E; ++I) {
139 if (I->getStorageClassAsWritten() != SC_None)
140 return true;
141 }
142 return false;
143}
144
145/// \brief Check whether we're in an extern inline function and referring to a
Jordan Rose33c0f372012-06-20 18:50:06 +0000146/// variable or function with internal linkage (C11 6.7.4p3).
Jordan Rose0eb3f452012-06-18 22:09:19 +0000147///
Jordan Rose0eb3f452012-06-18 22:09:19 +0000148/// This is only a warning because we used to silently accept this code, but
Jordan Rose33c0f372012-06-20 18:50:06 +0000149/// in many cases it will not behave correctly. This is not enabled in C++ mode
150/// because the restriction language is a bit weaker (C++11 [basic.def.odr]p6)
151/// and so while there may still be user mistakes, most of the time we can't
152/// prove that there are errors.
Jordan Rose0eb3f452012-06-18 22:09:19 +0000153static void diagnoseUseOfInternalDeclInInlineFunction(Sema &S,
154 const NamedDecl *D,
155 SourceLocation Loc) {
Jordan Rose33c0f372012-06-20 18:50:06 +0000156 // This is disabled under C++; there are too many ways for this to fire in
157 // contexts where the warning is a false positive, or where it is technically
158 // correct but benign.
159 if (S.getLangOpts().CPlusPlus)
160 return;
Jordan Rose0eb3f452012-06-18 22:09:19 +0000161
162 // Check if this is an inlined function or method.
163 FunctionDecl *Current = S.getCurFunctionDecl();
164 if (!Current)
165 return;
166 if (!Current->isInlined())
167 return;
168 if (Current->getLinkage() != ExternalLinkage)
169 return;
170
171 // Check if the decl has internal linkage.
Jordan Rose33c0f372012-06-20 18:50:06 +0000172 if (D->getLinkage() != InternalLinkage)
Jordan Rose0eb3f452012-06-18 22:09:19 +0000173 return;
Jordan Rose0eb3f452012-06-18 22:09:19 +0000174
Jordan Rose05233272012-06-21 05:54:50 +0000175 // Downgrade from ExtWarn to Extension if
176 // (1) the supposedly external inline function is in the main file,
177 // and probably won't be included anywhere else.
178 // (2) the thing we're referencing is a pure function.
179 // (3) the thing we're referencing is another inline function.
180 // This last can give us false negatives, but it's better than warning on
181 // wrappers for simple C library functions.
182 const FunctionDecl *UsedFn = dyn_cast<FunctionDecl>(D);
183 bool DowngradeWarning = S.getSourceManager().isFromMainFile(Loc);
184 if (!DowngradeWarning && UsedFn)
185 DowngradeWarning = UsedFn->isInlined() || UsedFn->hasAttr<ConstAttr>();
186
187 S.Diag(Loc, DowngradeWarning ? diag::ext_internal_in_extern_inline
188 : diag::warn_internal_in_extern_inline)
189 << /*IsVar=*/!UsedFn << D;
Jordan Rose0eb3f452012-06-18 22:09:19 +0000190
191 // Suggest "static" on the inline function, if possible.
Jordan Rose33c0f372012-06-20 18:50:06 +0000192 if (!hasAnyExplicitStorageClass(Current)) {
Jordan Rose0eb3f452012-06-18 22:09:19 +0000193 const FunctionDecl *FirstDecl = Current->getCanonicalDecl();
194 SourceLocation DeclBegin = FirstDecl->getSourceRange().getBegin();
195 S.Diag(DeclBegin, diag::note_convert_inline_to_static)
196 << Current << FixItHint::CreateInsertion(DeclBegin, "static ");
197 }
198
199 S.Diag(D->getCanonicalDecl()->getLocation(),
200 diag::note_internal_decl_declared_here)
201 << D;
202}
203
Douglas Gregor48f3bb92009-02-18 21:56:37 +0000204/// \brief Determine whether the use of this declaration is valid, and
205/// emit any corresponding diagnostics.
206///
207/// This routine diagnoses various problems with referencing
208/// declarations that can occur when using a declaration. For example,
209/// it might warn if a deprecated or unavailable declaration is being
210/// used, or produce an error (and return true) if a C++0x deleted
211/// function is being used.
212///
213/// \returns true if there was an error (this declaration cannot be
214/// referenced), false otherwise.
Chris Lattner52338262009-10-25 22:31:57 +0000215///
Fariborz Jahanian8e5fc9b2010-12-21 00:44:01 +0000216bool Sema::DiagnoseUseOfDecl(NamedDecl *D, SourceLocation Loc,
Fariborz Jahanian0f32caf2011-09-29 22:45:21 +0000217 const ObjCInterfaceDecl *UnknownObjCClass) {
David Blaikie4e4d0842012-03-11 07:00:24 +0000218 if (getLangOpts().CPlusPlus && isa<FunctionDecl>(D)) {
Douglas Gregor9b623632010-10-12 23:32:35 +0000219 // If there were any diagnostics suppressed by template argument deduction,
220 // emit them now.
Chris Lattner5f9e2722011-07-23 10:55:15 +0000221 llvm::DenseMap<Decl *, SmallVector<PartialDiagnosticAt, 1> >::iterator
Douglas Gregor9b623632010-10-12 23:32:35 +0000222 Pos = SuppressedDiagnostics.find(D->getCanonicalDecl());
223 if (Pos != SuppressedDiagnostics.end()) {
Chris Lattner5f9e2722011-07-23 10:55:15 +0000224 SmallVectorImpl<PartialDiagnosticAt> &Suppressed = Pos->second;
Douglas Gregor9b623632010-10-12 23:32:35 +0000225 for (unsigned I = 0, N = Suppressed.size(); I != N; ++I)
226 Diag(Suppressed[I].first, Suppressed[I].second);
227
228 // Clear out the list of suppressed diagnostics, so that we don't emit
Douglas Gregor0a0d2b12011-03-23 00:50:03 +0000229 // them again for this specialization. However, we don't obsolete this
Douglas Gregor9b623632010-10-12 23:32:35 +0000230 // entry from the table, because we want to avoid ever emitting these
231 // diagnostics again.
232 Suppressed.clear();
233 }
234 }
235
Richard Smith34b41d92011-02-20 03:19:35 +0000236 // See if this is an auto-typed variable whose initializer we are parsing.
Richard Smith483b9f32011-02-21 20:05:19 +0000237 if (ParsingInitForAutoVars.count(D)) {
238 Diag(Loc, diag::err_auto_variable_cannot_appear_in_own_initializer)
239 << D->getDeclName();
240 return true;
Richard Smith34b41d92011-02-20 03:19:35 +0000241 }
242
Douglas Gregor48f3bb92009-02-18 21:56:37 +0000243 // See if this is a deleted function.
Douglas Gregor25d944a2009-02-24 04:26:15 +0000244 if (FunctionDecl *FD = dyn_cast<FunctionDecl>(D)) {
Douglas Gregor48f3bb92009-02-18 21:56:37 +0000245 if (FD->isDeleted()) {
246 Diag(Loc, diag::err_deleted_function_use);
Richard Smith6c4c36c2012-03-30 20:53:28 +0000247 NoteDeletedFunction(FD);
Douglas Gregor48f3bb92009-02-18 21:56:37 +0000248 return true;
249 }
Douglas Gregor25d944a2009-02-24 04:26:15 +0000250 }
Ted Kremenekd6cf9122012-02-10 02:45:47 +0000251 DiagnoseAvailabilityOfDecl(*this, D, Loc, UnknownObjCClass);
Douglas Gregor0a0d2b12011-03-23 00:50:03 +0000252
Anders Carlsson2127ecc2010-10-22 23:37:08 +0000253 // Warn if this is used but marked unused.
Fariborz Jahanian0f32caf2011-09-29 22:45:21 +0000254 if (D->hasAttr<UnusedAttr>())
Anders Carlsson2127ecc2010-10-22 23:37:08 +0000255 Diag(Loc, diag::warn_used_but_marked_unused) << D->getDeclName();
Jordan Rose106af9e2012-06-15 18:19:48 +0000256
Jordan Rose0eb3f452012-06-18 22:09:19 +0000257 diagnoseUseOfInternalDeclInInlineFunction(*this, D, Loc);
Jordan Rose106af9e2012-06-15 18:19:48 +0000258
Douglas Gregor48f3bb92009-02-18 21:56:37 +0000259 return false;
Chris Lattner76a642f2009-02-15 22:43:40 +0000260}
261
Douglas Gregor0a0d2b12011-03-23 00:50:03 +0000262/// \brief Retrieve the message suffix that should be added to a
263/// diagnostic complaining about the given function being deleted or
264/// unavailable.
265std::string Sema::getDeletedOrUnavailableSuffix(const FunctionDecl *FD) {
266 // FIXME: C++0x implicitly-deleted special member functions could be
267 // detected here so that we could improve diagnostics to say, e.g.,
268 // "base class 'A' had a deleted copy constructor".
269 if (FD->isDeleted())
270 return std::string();
271
272 std::string Message;
273 if (FD->getAvailability(&Message))
274 return ": " + Message;
275
276 return std::string();
277}
278
John McCall3323fad2011-09-09 07:56:05 +0000279/// DiagnoseSentinelCalls - This routine checks whether a call or
280/// message-send is to a declaration with the sentinel attribute, and
281/// if so, it checks that the requirements of the sentinel are
282/// satisfied.
Fariborz Jahanian5b530052009-05-13 18:09:35 +0000283void Sema::DiagnoseSentinelCalls(NamedDecl *D, SourceLocation Loc,
John McCall3323fad2011-09-09 07:56:05 +0000284 Expr **args, unsigned numArgs) {
Argyrios Kyrtzidis40b598e2009-06-30 02:34:44 +0000285 const SentinelAttr *attr = D->getAttr<SentinelAttr>();
Mike Stump1eb44332009-09-09 15:08:12 +0000286 if (!attr)
Fariborz Jahanian88f1ba02009-05-13 23:20:50 +0000287 return;
Douglas Gregor92e986e2010-04-22 16:44:27 +0000288
John McCall3323fad2011-09-09 07:56:05 +0000289 // The number of formal parameters of the declaration.
290 unsigned numFormalParams;
Mike Stump1eb44332009-09-09 15:08:12 +0000291
John McCall3323fad2011-09-09 07:56:05 +0000292 // The kind of declaration. This is also an index into a %select in
293 // the diagnostic.
294 enum CalleeType { CT_Function, CT_Method, CT_Block } calleeType;
295
Fariborz Jahanian236673e2009-05-14 18:00:00 +0000296 if (ObjCMethodDecl *MD = dyn_cast<ObjCMethodDecl>(D)) {
John McCall3323fad2011-09-09 07:56:05 +0000297 numFormalParams = MD->param_size();
298 calleeType = CT_Method;
Mike Stumpac5fc7c2009-08-04 21:02:39 +0000299 } else if (FunctionDecl *FD = dyn_cast<FunctionDecl>(D)) {
John McCall3323fad2011-09-09 07:56:05 +0000300 numFormalParams = FD->param_size();
301 calleeType = CT_Function;
302 } else if (isa<VarDecl>(D)) {
303 QualType type = cast<ValueDecl>(D)->getType();
304 const FunctionType *fn = 0;
305 if (const PointerType *ptr = type->getAs<PointerType>()) {
306 fn = ptr->getPointeeType()->getAs<FunctionType>();
307 if (!fn) return;
308 calleeType = CT_Function;
309 } else if (const BlockPointerType *ptr = type->getAs<BlockPointerType>()) {
310 fn = ptr->getPointeeType()->castAs<FunctionType>();
311 calleeType = CT_Block;
312 } else {
Fariborz Jahaniandaf04152009-05-15 20:33:25 +0000313 return;
John McCall3323fad2011-09-09 07:56:05 +0000314 }
Fariborz Jahanian236673e2009-05-14 18:00:00 +0000315
John McCall3323fad2011-09-09 07:56:05 +0000316 if (const FunctionProtoType *proto = dyn_cast<FunctionProtoType>(fn)) {
317 numFormalParams = proto->getNumArgs();
318 } else {
319 numFormalParams = 0;
320 }
321 } else {
Fariborz Jahanian88f1ba02009-05-13 23:20:50 +0000322 return;
323 }
John McCall3323fad2011-09-09 07:56:05 +0000324
325 // "nullPos" is the number of formal parameters at the end which
326 // effectively count as part of the variadic arguments. This is
327 // useful if you would prefer to not have *any* formal parameters,
328 // but the language forces you to have at least one.
329 unsigned nullPos = attr->getNullPos();
330 assert((nullPos == 0 || nullPos == 1) && "invalid null position on sentinel");
331 numFormalParams = (nullPos > numFormalParams ? 0 : numFormalParams - nullPos);
332
333 // The number of arguments which should follow the sentinel.
334 unsigned numArgsAfterSentinel = attr->getSentinel();
335
336 // If there aren't enough arguments for all the formal parameters,
337 // the sentinel, and the args after the sentinel, complain.
338 if (numArgs < numFormalParams + numArgsAfterSentinel + 1) {
Fariborz Jahanian88f1ba02009-05-13 23:20:50 +0000339 Diag(Loc, diag::warn_not_enough_argument) << D->getDeclName();
John McCall3323fad2011-09-09 07:56:05 +0000340 Diag(D->getLocation(), diag::note_sentinel_here) << calleeType;
Fariborz Jahanian88f1ba02009-05-13 23:20:50 +0000341 return;
342 }
John McCall3323fad2011-09-09 07:56:05 +0000343
344 // Otherwise, find the sentinel expression.
345 Expr *sentinelExpr = args[numArgs - numArgsAfterSentinel - 1];
John McCall8eb662e2010-05-06 23:53:00 +0000346 if (!sentinelExpr) return;
John McCall8eb662e2010-05-06 23:53:00 +0000347 if (sentinelExpr->isValueDependent()) return;
Argyrios Kyrtzidis8deabc12012-02-03 05:58:16 +0000348 if (Context.isSentinelNullExpr(sentinelExpr)) return;
John McCall8eb662e2010-05-06 23:53:00 +0000349
John McCall3323fad2011-09-09 07:56:05 +0000350 // Pick a reasonable string to insert. Optimistically use 'nil' or
351 // 'NULL' if those are actually defined in the context. Only use
352 // 'nil' for ObjC methods, where it's much more likely that the
353 // variadic arguments form a list of object pointers.
354 SourceLocation MissingNilLoc
Douglas Gregorf78c4e52011-07-30 08:57:03 +0000355 = PP.getLocForEndOfToken(sentinelExpr->getLocEnd());
356 std::string NullValue;
John McCall3323fad2011-09-09 07:56:05 +0000357 if (calleeType == CT_Method &&
358 PP.getIdentifierInfo("nil")->hasMacroDefinition())
Douglas Gregorf78c4e52011-07-30 08:57:03 +0000359 NullValue = "nil";
360 else if (PP.getIdentifierInfo("NULL")->hasMacroDefinition())
361 NullValue = "NULL";
Douglas Gregorf78c4e52011-07-30 08:57:03 +0000362 else
John McCall3323fad2011-09-09 07:56:05 +0000363 NullValue = "(void*) 0";
Eli Friedman39834ba2011-09-27 23:46:37 +0000364
365 if (MissingNilLoc.isInvalid())
366 Diag(Loc, diag::warn_missing_sentinel) << calleeType;
367 else
368 Diag(MissingNilLoc, diag::warn_missing_sentinel)
369 << calleeType
370 << FixItHint::CreateInsertion(MissingNilLoc, ", " + NullValue);
John McCall3323fad2011-09-09 07:56:05 +0000371 Diag(D->getLocation(), diag::note_sentinel_here) << calleeType;
Fariborz Jahanian5b530052009-05-13 18:09:35 +0000372}
373
Richard Trieuccd891a2011-09-09 01:45:06 +0000374SourceRange Sema::getExprRange(Expr *E) const {
375 return E ? E->getSourceRange() : SourceRange();
Douglas Gregor4b2d3f72009-02-26 21:00:50 +0000376}
377
Chris Lattnere7a2e912008-07-25 21:10:04 +0000378//===----------------------------------------------------------------------===//
379// Standard Promotions and Conversions
380//===----------------------------------------------------------------------===//
381
Chris Lattnere7a2e912008-07-25 21:10:04 +0000382/// DefaultFunctionArrayConversion (C99 6.3.2.1p3, C99 6.3.2.1p4).
John Wiegley429bb272011-04-08 18:41:53 +0000383ExprResult Sema::DefaultFunctionArrayConversion(Expr *E) {
John McCall6dbba4f2011-10-11 23:14:30 +0000384 // Handle any placeholder expressions which made it here.
385 if (E->getType()->isPlaceholderType()) {
386 ExprResult result = CheckPlaceholderExpr(E);
387 if (result.isInvalid()) return ExprError();
388 E = result.take();
389 }
390
Chris Lattnere7a2e912008-07-25 21:10:04 +0000391 QualType Ty = E->getType();
392 assert(!Ty.isNull() && "DefaultFunctionArrayConversion - missing type");
393
Chris Lattnere7a2e912008-07-25 21:10:04 +0000394 if (Ty->isFunctionType())
John Wiegley429bb272011-04-08 18:41:53 +0000395 E = ImpCastExprToType(E, Context.getPointerType(Ty),
396 CK_FunctionToPointerDecay).take();
Chris Lattner67d33d82008-07-25 21:33:13 +0000397 else if (Ty->isArrayType()) {
398 // In C90 mode, arrays only promote to pointers if the array expression is
399 // an lvalue. The relevant legalese is C90 6.2.2.1p3: "an lvalue that has
400 // type 'array of type' is converted to an expression that has type 'pointer
401 // to type'...". In C99 this was changed to: C99 6.3.2.1p3: "an expression
402 // that has type 'array of type' ...". The relevant change is "an lvalue"
403 // (C90) to "an expression" (C99).
Argyrios Kyrtzidisc39a3d72008-09-11 04:25:59 +0000404 //
405 // C++ 4.2p1:
406 // An lvalue or rvalue of type "array of N T" or "array of unknown bound of
407 // T" can be converted to an rvalue of type "pointer to T".
408 //
David Blaikie4e4d0842012-03-11 07:00:24 +0000409 if (getLangOpts().C99 || getLangOpts().CPlusPlus || E->isLValue())
John Wiegley429bb272011-04-08 18:41:53 +0000410 E = ImpCastExprToType(E, Context.getArrayDecayedType(Ty),
411 CK_ArrayToPointerDecay).take();
Chris Lattner67d33d82008-07-25 21:33:13 +0000412 }
John Wiegley429bb272011-04-08 18:41:53 +0000413 return Owned(E);
Chris Lattnere7a2e912008-07-25 21:10:04 +0000414}
415
Argyrios Kyrtzidis8a285ae2011-04-26 17:41:22 +0000416static void CheckForNullPointerDereference(Sema &S, Expr *E) {
417 // Check to see if we are dereferencing a null pointer. If so,
418 // and if not volatile-qualified, this is undefined behavior that the
419 // optimizer will delete, so warn about it. People sometimes try to use this
420 // to get a deterministic trap and are surprised by clang's behavior. This
421 // only handles the pattern "*null", which is a very syntactic check.
422 if (UnaryOperator *UO = dyn_cast<UnaryOperator>(E->IgnoreParenCasts()))
423 if (UO->getOpcode() == UO_Deref &&
424 UO->getSubExpr()->IgnoreParenCasts()->
425 isNullPointerConstant(S.Context, Expr::NPC_ValueDependentIsNotNull) &&
426 !UO->getType().isVolatileQualified()) {
427 S.DiagRuntimeBehavior(UO->getOperatorLoc(), UO,
428 S.PDiag(diag::warn_indirection_through_null)
429 << UO->getSubExpr()->getSourceRange());
430 S.DiagRuntimeBehavior(UO->getOperatorLoc(), UO,
431 S.PDiag(diag::note_indirection_through_null));
432 }
433}
434
John Wiegley429bb272011-04-08 18:41:53 +0000435ExprResult Sema::DefaultLvalueConversion(Expr *E) {
John McCall6dbba4f2011-10-11 23:14:30 +0000436 // Handle any placeholder expressions which made it here.
437 if (E->getType()->isPlaceholderType()) {
438 ExprResult result = CheckPlaceholderExpr(E);
439 if (result.isInvalid()) return ExprError();
440 E = result.take();
441 }
442
John McCall0ae287a2010-12-01 04:43:34 +0000443 // C++ [conv.lval]p1:
444 // A glvalue of a non-function, non-array type T can be
445 // converted to a prvalue.
John Wiegley429bb272011-04-08 18:41:53 +0000446 if (!E->isGLValue()) return Owned(E);
Kaelyn Uhraind6c88652011-08-05 23:18:04 +0000447
John McCall409fa9a2010-12-06 20:48:59 +0000448 QualType T = E->getType();
449 assert(!T.isNull() && "r-value conversion on typeless expression?");
John McCallf6a16482010-12-04 03:47:34 +0000450
John McCall409fa9a2010-12-06 20:48:59 +0000451 // We don't want to throw lvalue-to-rvalue casts on top of
452 // expressions of certain types in C++.
David Blaikie4e4d0842012-03-11 07:00:24 +0000453 if (getLangOpts().CPlusPlus &&
John McCall409fa9a2010-12-06 20:48:59 +0000454 (E->getType() == Context.OverloadTy ||
455 T->isDependentType() ||
456 T->isRecordType()))
John Wiegley429bb272011-04-08 18:41:53 +0000457 return Owned(E);
John McCall409fa9a2010-12-06 20:48:59 +0000458
459 // The C standard is actually really unclear on this point, and
460 // DR106 tells us what the result should be but not why. It's
461 // generally best to say that void types just doesn't undergo
462 // lvalue-to-rvalue at all. Note that expressions of unqualified
463 // 'void' type are never l-values, but qualified void can be.
464 if (T->isVoidType())
John Wiegley429bb272011-04-08 18:41:53 +0000465 return Owned(E);
John McCall409fa9a2010-12-06 20:48:59 +0000466
Argyrios Kyrtzidis8a285ae2011-04-26 17:41:22 +0000467 CheckForNullPointerDereference(*this, E);
468
John McCall409fa9a2010-12-06 20:48:59 +0000469 // C++ [conv.lval]p1:
470 // [...] If T is a non-class type, the type of the prvalue is the
471 // cv-unqualified version of T. Otherwise, the type of the
472 // rvalue is T.
473 //
474 // C99 6.3.2.1p2:
475 // If the lvalue has qualified type, the value has the unqualified
476 // version of the type of the lvalue; otherwise, the value has the
Anton Korobeynikovaa4a99b2011-10-14 23:23:15 +0000477 // type of the lvalue.
John McCall409fa9a2010-12-06 20:48:59 +0000478 if (T.hasQualifiers())
479 T = T.getUnqualifiedType();
Anton Korobeynikovaa4a99b2011-10-14 23:23:15 +0000480
Eli Friedmand2cce132012-02-02 23:15:15 +0000481 UpdateMarkingForLValueToRValue(E);
482
Anton Korobeynikovaa4a99b2011-10-14 23:23:15 +0000483 ExprResult Res = Owned(ImplicitCastExpr::Create(Context, T, CK_LValueToRValue,
484 E, 0, VK_RValue));
485
Douglas Gregorf7ecc302012-04-12 17:51:55 +0000486 // C11 6.3.2.1p2:
487 // ... if the lvalue has atomic type, the value has the non-atomic version
488 // of the type of the lvalue ...
489 if (const AtomicType *Atomic = T->getAs<AtomicType>()) {
490 T = Atomic->getValueType().getUnqualifiedType();
491 Res = Owned(ImplicitCastExpr::Create(Context, T, CK_AtomicToNonAtomic,
492 Res.get(), 0, VK_RValue));
493 }
494
Anton Korobeynikovaa4a99b2011-10-14 23:23:15 +0000495 return Res;
John McCall409fa9a2010-12-06 20:48:59 +0000496}
497
John Wiegley429bb272011-04-08 18:41:53 +0000498ExprResult Sema::DefaultFunctionArrayLvalueConversion(Expr *E) {
499 ExprResult Res = DefaultFunctionArrayConversion(E);
500 if (Res.isInvalid())
501 return ExprError();
502 Res = DefaultLvalueConversion(Res.take());
503 if (Res.isInvalid())
504 return ExprError();
Benjamin Kramer3fe198b2012-08-23 21:35:17 +0000505 return Res;
Douglas Gregora873dfc2010-02-03 00:27:59 +0000506}
507
508
Chris Lattnere7a2e912008-07-25 21:10:04 +0000509/// UsualUnaryConversions - Performs various conversions that are common to most
Mike Stump1eb44332009-09-09 15:08:12 +0000510/// operators (C99 6.3). The conversions of array and function types are
Chris Lattnerfc8f0e12011-04-15 05:22:18 +0000511/// sometimes suppressed. For example, the array->pointer conversion doesn't
Chris Lattnere7a2e912008-07-25 21:10:04 +0000512/// apply if the array is an argument to the sizeof or address (&) operators.
513/// In these instances, this routine should *not* be called.
John Wiegley429bb272011-04-08 18:41:53 +0000514ExprResult Sema::UsualUnaryConversions(Expr *E) {
John McCall0ae287a2010-12-01 04:43:34 +0000515 // First, convert to an r-value.
John Wiegley429bb272011-04-08 18:41:53 +0000516 ExprResult Res = DefaultFunctionArrayLvalueConversion(E);
517 if (Res.isInvalid())
518 return Owned(E);
519 E = Res.take();
Anton Korobeynikovaa4a99b2011-10-14 23:23:15 +0000520
John McCall0ae287a2010-12-01 04:43:34 +0000521 QualType Ty = E->getType();
Chris Lattnere7a2e912008-07-25 21:10:04 +0000522 assert(!Ty.isNull() && "UsualUnaryConversions - missing type");
Anton Korobeynikovaa4a99b2011-10-14 23:23:15 +0000523
524 // Half FP is a bit different: it's a storage-only type, meaning that any
525 // "use" of it should be promoted to float.
526 if (Ty->isHalfType())
527 return ImpCastExprToType(Res.take(), Context.FloatTy, CK_FloatingCast);
528
John McCall0ae287a2010-12-01 04:43:34 +0000529 // Try to perform integral promotions if the object has a theoretically
530 // promotable type.
531 if (Ty->isIntegralOrUnscopedEnumerationType()) {
532 // C99 6.3.1.1p2:
533 //
534 // The following may be used in an expression wherever an int or
535 // unsigned int may be used:
536 // - an object or expression with an integer type whose integer
537 // conversion rank is less than or equal to the rank of int
538 // and unsigned int.
539 // - A bit-field of type _Bool, int, signed int, or unsigned int.
540 //
541 // If an int can represent all values of the original type, the
542 // value is converted to an int; otherwise, it is converted to an
543 // unsigned int. These are called the integer promotions. All
544 // other types are unchanged by the integer promotions.
Anton Korobeynikovaa4a99b2011-10-14 23:23:15 +0000545
John McCall0ae287a2010-12-01 04:43:34 +0000546 QualType PTy = Context.isPromotableBitField(E);
547 if (!PTy.isNull()) {
John Wiegley429bb272011-04-08 18:41:53 +0000548 E = ImpCastExprToType(E, PTy, CK_IntegralCast).take();
549 return Owned(E);
John McCall0ae287a2010-12-01 04:43:34 +0000550 }
551 if (Ty->isPromotableIntegerType()) {
552 QualType PT = Context.getPromotedIntegerType(Ty);
John Wiegley429bb272011-04-08 18:41:53 +0000553 E = ImpCastExprToType(E, PT, CK_IntegralCast).take();
554 return Owned(E);
John McCall0ae287a2010-12-01 04:43:34 +0000555 }
Eli Friedman04e83572009-08-20 04:21:42 +0000556 }
John Wiegley429bb272011-04-08 18:41:53 +0000557 return Owned(E);
Chris Lattnere7a2e912008-07-25 21:10:04 +0000558}
559
Chris Lattner05faf172008-07-25 22:25:12 +0000560/// DefaultArgumentPromotion (C99 6.5.2.2p6). Used for function calls that
Mike Stump1eb44332009-09-09 15:08:12 +0000561/// do not have a prototype. Arguments that have type float are promoted to
Chris Lattner05faf172008-07-25 22:25:12 +0000562/// double. All other argument types are converted by UsualUnaryConversions().
John Wiegley429bb272011-04-08 18:41:53 +0000563ExprResult Sema::DefaultArgumentPromotion(Expr *E) {
564 QualType Ty = E->getType();
Chris Lattner05faf172008-07-25 22:25:12 +0000565 assert(!Ty.isNull() && "DefaultArgumentPromotion - missing type");
Mike Stump1eb44332009-09-09 15:08:12 +0000566
John Wiegley429bb272011-04-08 18:41:53 +0000567 ExprResult Res = UsualUnaryConversions(E);
568 if (Res.isInvalid())
569 return Owned(E);
570 E = Res.take();
John McCall40c29132010-12-06 18:36:11 +0000571
Chris Lattner05faf172008-07-25 22:25:12 +0000572 // If this is a 'float' (CVR qualified or typedef) promote to double.
Chris Lattner40378332010-05-16 04:01:30 +0000573 if (Ty->isSpecificBuiltinType(BuiltinType::Float))
John Wiegley429bb272011-04-08 18:41:53 +0000574 E = ImpCastExprToType(E, Context.DoubleTy, CK_FloatingCast).take();
575
John McCall96a914a2011-08-27 22:06:17 +0000576 // C++ performs lvalue-to-rvalue conversion as a default argument
John McCall709bca82011-08-29 23:55:37 +0000577 // promotion, even on class types, but note:
578 // C++11 [conv.lval]p2:
579 // When an lvalue-to-rvalue conversion occurs in an unevaluated
580 // operand or a subexpression thereof the value contained in the
581 // referenced object is not accessed. Otherwise, if the glvalue
582 // has a class type, the conversion copy-initializes a temporary
583 // of type T from the glvalue and the result of the conversion
584 // is a prvalue for the temporary.
Eli Friedman55693fb2012-01-17 02:13:45 +0000585 // FIXME: add some way to gate this entire thing for correctness in
586 // potentially potentially evaluated contexts.
David Blaikie71f55f72012-08-06 22:47:24 +0000587 if (getLangOpts().CPlusPlus && E->isGLValue() && !isUnevaluatedContext()) {
Eli Friedman55693fb2012-01-17 02:13:45 +0000588 ExprResult Temp = PerformCopyInitialization(
589 InitializedEntity::InitializeTemporary(E->getType()),
590 E->getExprLoc(),
591 Owned(E));
592 if (Temp.isInvalid())
593 return ExprError();
594 E = Temp.get();
John McCall5f8d6042011-08-27 01:09:30 +0000595 }
596
John Wiegley429bb272011-04-08 18:41:53 +0000597 return Owned(E);
Chris Lattner05faf172008-07-25 22:25:12 +0000598}
599
Richard Smith831421f2012-06-25 20:30:08 +0000600/// Determine the degree of POD-ness for an expression.
601/// Incomplete types are considered POD, since this check can be performed
602/// when we're in an unevaluated context.
603Sema::VarArgKind Sema::isValidVarArgType(const QualType &Ty) {
Jordan Roseddcfbc92012-07-19 18:10:23 +0000604 if (Ty->isIncompleteType()) {
605 if (Ty->isObjCObjectType())
606 return VAK_Invalid;
Richard Smith831421f2012-06-25 20:30:08 +0000607 return VAK_Valid;
Jordan Roseddcfbc92012-07-19 18:10:23 +0000608 }
609
610 if (Ty.isCXX98PODType(Context))
611 return VAK_Valid;
612
Richard Smith831421f2012-06-25 20:30:08 +0000613 // C++0x [expr.call]p7:
614 // Passing a potentially-evaluated argument of class type (Clause 9)
615 // having a non-trivial copy constructor, a non-trivial move constructor,
616 // or a non-trivial destructor, with no corresponding parameter,
617 // is conditionally-supported with implementation-defined semantics.
Richard Smith831421f2012-06-25 20:30:08 +0000618 if (getLangOpts().CPlusPlus0x && !Ty->isDependentType())
619 if (CXXRecordDecl *Record = Ty->getAsCXXRecordDecl())
620 if (Record->hasTrivialCopyConstructor() &&
621 Record->hasTrivialMoveConstructor() &&
622 Record->hasTrivialDestructor())
623 return VAK_ValidInCXX11;
624
625 if (getLangOpts().ObjCAutoRefCount && Ty->isObjCLifetimeType())
626 return VAK_Valid;
627 return VAK_Invalid;
628}
629
630bool Sema::variadicArgumentPODCheck(const Expr *E, VariadicCallType CT) {
631 // Don't allow one to pass an Objective-C interface to a vararg.
632 const QualType & Ty = E->getType();
633
634 // Complain about passing non-POD types through varargs.
635 switch (isValidVarArgType(Ty)) {
636 case VAK_Valid:
637 break;
638 case VAK_ValidInCXX11:
639 DiagRuntimeBehavior(E->getLocStart(), 0,
640 PDiag(diag::warn_cxx98_compat_pass_non_pod_arg_to_vararg)
641 << E->getType() << CT);
642 break;
Jordan Roseddcfbc92012-07-19 18:10:23 +0000643 case VAK_Invalid: {
644 if (Ty->isObjCObjectType())
645 return DiagRuntimeBehavior(E->getLocStart(), 0,
646 PDiag(diag::err_cannot_pass_objc_interface_to_vararg)
647 << Ty << CT);
648
Richard Smith831421f2012-06-25 20:30:08 +0000649 return DiagRuntimeBehavior(E->getLocStart(), 0,
650 PDiag(diag::warn_cannot_pass_non_pod_arg_to_vararg)
651 << getLangOpts().CPlusPlus0x << Ty << CT);
652 }
Jordan Roseddcfbc92012-07-19 18:10:23 +0000653 }
Richard Smith831421f2012-06-25 20:30:08 +0000654 // c++ rules are enforced elsewhere.
655 return false;
656}
657
Chris Lattner312531a2009-04-12 08:11:20 +0000658/// DefaultVariadicArgumentPromotion - Like DefaultArgumentPromotion, but
Jordan Roseddcfbc92012-07-19 18:10:23 +0000659/// will create a trap if the resulting type is not a POD type.
John Wiegley429bb272011-04-08 18:41:53 +0000660ExprResult Sema::DefaultVariadicArgumentPromotion(Expr *E, VariadicCallType CT,
John McCallf85e1932011-06-15 23:02:42 +0000661 FunctionDecl *FDecl) {
Richard Smithe1971a12012-06-27 20:29:39 +0000662 if (const BuiltinType *PlaceholderTy = E->getType()->getAsPlaceholderType()) {
John McCall5acb0c92011-10-17 18:40:02 +0000663 // Strip the unbridged-cast placeholder expression off, if applicable.
664 if (PlaceholderTy->getKind() == BuiltinType::ARCUnbridgedCast &&
665 (CT == VariadicMethod ||
666 (FDecl && FDecl->hasAttr<CFAuditedTransferAttr>()))) {
667 E = stripARCUnbridgedCast(E);
668
669 // Otherwise, do normal placeholder checking.
670 } else {
671 ExprResult ExprRes = CheckPlaceholderExpr(E);
672 if (ExprRes.isInvalid())
673 return ExprError();
674 E = ExprRes.take();
675 }
676 }
Douglas Gregor8d5e18c2011-06-17 00:15:10 +0000677
John McCall5acb0c92011-10-17 18:40:02 +0000678 ExprResult ExprRes = DefaultArgumentPromotion(E);
John Wiegley429bb272011-04-08 18:41:53 +0000679 if (ExprRes.isInvalid())
680 return ExprError();
681 E = ExprRes.take();
Mike Stump1eb44332009-09-09 15:08:12 +0000682
Richard Smith831421f2012-06-25 20:30:08 +0000683 // Diagnostics regarding non-POD argument types are
684 // emitted along with format string checking in Sema::CheckFunctionCall().
Richard Smith83ea5302012-06-27 20:23:58 +0000685 if (isValidVarArgType(E->getType()) == VAK_Invalid) {
Richard Smith831421f2012-06-25 20:30:08 +0000686 // Turn this into a trap.
687 CXXScopeSpec SS;
688 SourceLocation TemplateKWLoc;
689 UnqualifiedId Name;
690 Name.setIdentifier(PP.getIdentifierInfo("__builtin_trap"),
691 E->getLocStart());
692 ExprResult TrapFn = ActOnIdExpression(TUScope, SS, TemplateKWLoc,
693 Name, true, false);
694 if (TrapFn.isInvalid())
695 return ExprError();
John McCallf85e1932011-06-15 23:02:42 +0000696
Richard Smith831421f2012-06-25 20:30:08 +0000697 ExprResult Call = ActOnCallExpr(TUScope, TrapFn.get(),
698 E->getLocStart(), MultiExprArg(),
699 E->getLocEnd());
700 if (Call.isInvalid())
701 return ExprError();
Douglas Gregor930a9ab2011-05-21 19:26:31 +0000702
Richard Smith831421f2012-06-25 20:30:08 +0000703 ExprResult Comma = ActOnBinOp(TUScope, E->getLocStart(), tok::comma,
704 Call.get(), E);
705 if (Comma.isInvalid())
706 return ExprError();
707 return Comma.get();
Douglas Gregor0fd228d2011-05-21 16:27:21 +0000708 }
Richard Smith831421f2012-06-25 20:30:08 +0000709
David Blaikie4e4d0842012-03-11 07:00:24 +0000710 if (!getLangOpts().CPlusPlus &&
Fariborz Jahaniane853bb32012-03-01 23:42:00 +0000711 RequireCompleteType(E->getExprLoc(), E->getType(),
Fariborz Jahaniana0e005b2012-03-02 17:05:03 +0000712 diag::err_call_incomplete_argument))
Fariborz Jahaniane853bb32012-03-01 23:42:00 +0000713 return ExprError();
Richard Smith831421f2012-06-25 20:30:08 +0000714
John Wiegley429bb272011-04-08 18:41:53 +0000715 return Owned(E);
Anders Carlssondce5e2c2009-01-16 16:48:51 +0000716}
717
Richard Trieu8289f492011-09-02 20:58:51 +0000718/// \brief Converts an integer to complex float type. Helper function of
719/// UsualArithmeticConversions()
720///
721/// \return false if the integer expression is an integer type and is
722/// successfully converted to the complex type.
Richard Trieuccd891a2011-09-09 01:45:06 +0000723static bool handleIntegerToComplexFloatConversion(Sema &S, ExprResult &IntExpr,
724 ExprResult &ComplexExpr,
725 QualType IntTy,
726 QualType ComplexTy,
727 bool SkipCast) {
728 if (IntTy->isComplexType() || IntTy->isRealFloatingType()) return true;
729 if (SkipCast) return false;
730 if (IntTy->isIntegerType()) {
731 QualType fpTy = cast<ComplexType>(ComplexTy)->getElementType();
732 IntExpr = S.ImpCastExprToType(IntExpr.take(), fpTy, CK_IntegralToFloating);
733 IntExpr = S.ImpCastExprToType(IntExpr.take(), ComplexTy,
Richard Trieu8289f492011-09-02 20:58:51 +0000734 CK_FloatingRealToComplex);
735 } else {
Richard Trieuccd891a2011-09-09 01:45:06 +0000736 assert(IntTy->isComplexIntegerType());
737 IntExpr = S.ImpCastExprToType(IntExpr.take(), ComplexTy,
Richard Trieu8289f492011-09-02 20:58:51 +0000738 CK_IntegralComplexToFloatingComplex);
739 }
740 return false;
741}
742
743/// \brief Takes two complex float types and converts them to the same type.
744/// Helper function of UsualArithmeticConversions()
745static QualType
Richard Trieucafd30b2011-09-06 18:25:09 +0000746handleComplexFloatToComplexFloatConverstion(Sema &S, ExprResult &LHS,
747 ExprResult &RHS, QualType LHSType,
748 QualType RHSType,
Richard Trieuccd891a2011-09-09 01:45:06 +0000749 bool IsCompAssign) {
Richard Trieucafd30b2011-09-06 18:25:09 +0000750 int order = S.Context.getFloatingTypeOrder(LHSType, RHSType);
Richard Trieu8289f492011-09-02 20:58:51 +0000751
752 if (order < 0) {
753 // _Complex float -> _Complex double
Richard Trieuccd891a2011-09-09 01:45:06 +0000754 if (!IsCompAssign)
Richard Trieucafd30b2011-09-06 18:25:09 +0000755 LHS = S.ImpCastExprToType(LHS.take(), RHSType, CK_FloatingComplexCast);
756 return RHSType;
Richard Trieu8289f492011-09-02 20:58:51 +0000757 }
758 if (order > 0)
759 // _Complex float -> _Complex double
Richard Trieucafd30b2011-09-06 18:25:09 +0000760 RHS = S.ImpCastExprToType(RHS.take(), LHSType, CK_FloatingComplexCast);
761 return LHSType;
Richard Trieu8289f492011-09-02 20:58:51 +0000762}
763
764/// \brief Converts otherExpr to complex float and promotes complexExpr if
765/// necessary. Helper function of UsualArithmeticConversions()
766static QualType handleOtherComplexFloatConversion(Sema &S,
Richard Trieuccd891a2011-09-09 01:45:06 +0000767 ExprResult &ComplexExpr,
768 ExprResult &OtherExpr,
769 QualType ComplexTy,
770 QualType OtherTy,
771 bool ConvertComplexExpr,
772 bool ConvertOtherExpr) {
773 int order = S.Context.getFloatingTypeOrder(ComplexTy, OtherTy);
Richard Trieu8289f492011-09-02 20:58:51 +0000774
775 // If just the complexExpr is complex, the otherExpr needs to be converted,
776 // and the complexExpr might need to be promoted.
777 if (order > 0) { // complexExpr is wider
778 // float -> _Complex double
Richard Trieuccd891a2011-09-09 01:45:06 +0000779 if (ConvertOtherExpr) {
780 QualType fp = cast<ComplexType>(ComplexTy)->getElementType();
781 OtherExpr = S.ImpCastExprToType(OtherExpr.take(), fp, CK_FloatingCast);
782 OtherExpr = S.ImpCastExprToType(OtherExpr.take(), ComplexTy,
Richard Trieu8289f492011-09-02 20:58:51 +0000783 CK_FloatingRealToComplex);
784 }
Richard Trieuccd891a2011-09-09 01:45:06 +0000785 return ComplexTy;
Richard Trieu8289f492011-09-02 20:58:51 +0000786 }
787
788 // otherTy is at least as wide. Find its corresponding complex type.
Richard Trieuccd891a2011-09-09 01:45:06 +0000789 QualType result = (order == 0 ? ComplexTy :
790 S.Context.getComplexType(OtherTy));
Richard Trieu8289f492011-09-02 20:58:51 +0000791
792 // double -> _Complex double
Richard Trieuccd891a2011-09-09 01:45:06 +0000793 if (ConvertOtherExpr)
794 OtherExpr = S.ImpCastExprToType(OtherExpr.take(), result,
Richard Trieu8289f492011-09-02 20:58:51 +0000795 CK_FloatingRealToComplex);
796
797 // _Complex float -> _Complex double
Richard Trieuccd891a2011-09-09 01:45:06 +0000798 if (ConvertComplexExpr && order < 0)
799 ComplexExpr = S.ImpCastExprToType(ComplexExpr.take(), result,
Richard Trieu8289f492011-09-02 20:58:51 +0000800 CK_FloatingComplexCast);
801
802 return result;
803}
804
805/// \brief Handle arithmetic conversion with complex types. Helper function of
806/// UsualArithmeticConversions()
Richard Trieucafd30b2011-09-06 18:25:09 +0000807static QualType handleComplexFloatConversion(Sema &S, ExprResult &LHS,
808 ExprResult &RHS, QualType LHSType,
809 QualType RHSType,
Richard Trieuccd891a2011-09-09 01:45:06 +0000810 bool IsCompAssign) {
Richard Trieu8289f492011-09-02 20:58:51 +0000811 // if we have an integer operand, the result is the complex type.
Richard Trieucafd30b2011-09-06 18:25:09 +0000812 if (!handleIntegerToComplexFloatConversion(S, RHS, LHS, RHSType, LHSType,
Richard Trieu8289f492011-09-02 20:58:51 +0000813 /*skipCast*/false))
Richard Trieucafd30b2011-09-06 18:25:09 +0000814 return LHSType;
815 if (!handleIntegerToComplexFloatConversion(S, LHS, RHS, LHSType, RHSType,
Richard Trieuccd891a2011-09-09 01:45:06 +0000816 /*skipCast*/IsCompAssign))
Richard Trieucafd30b2011-09-06 18:25:09 +0000817 return RHSType;
Richard Trieu8289f492011-09-02 20:58:51 +0000818
819 // This handles complex/complex, complex/float, or float/complex.
820 // When both operands are complex, the shorter operand is converted to the
821 // type of the longer, and that is the type of the result. This corresponds
822 // to what is done when combining two real floating-point operands.
823 // The fun begins when size promotion occur across type domains.
824 // From H&S 6.3.4: When one operand is complex and the other is a real
825 // floating-point type, the less precise type is converted, within it's
826 // real or complex domain, to the precision of the other type. For example,
827 // when combining a "long double" with a "double _Complex", the
828 // "double _Complex" is promoted to "long double _Complex".
829
Richard Trieucafd30b2011-09-06 18:25:09 +0000830 bool LHSComplexFloat = LHSType->isComplexType();
831 bool RHSComplexFloat = RHSType->isComplexType();
Richard Trieu8289f492011-09-02 20:58:51 +0000832
833 // If both are complex, just cast to the more precise type.
834 if (LHSComplexFloat && RHSComplexFloat)
Richard Trieucafd30b2011-09-06 18:25:09 +0000835 return handleComplexFloatToComplexFloatConverstion(S, LHS, RHS,
836 LHSType, RHSType,
Richard Trieuccd891a2011-09-09 01:45:06 +0000837 IsCompAssign);
Richard Trieu8289f492011-09-02 20:58:51 +0000838
839 // If only one operand is complex, promote it if necessary and convert the
840 // other operand to complex.
841 if (LHSComplexFloat)
842 return handleOtherComplexFloatConversion(
Richard Trieuccd891a2011-09-09 01:45:06 +0000843 S, LHS, RHS, LHSType, RHSType, /*convertComplexExpr*/!IsCompAssign,
Richard Trieu8289f492011-09-02 20:58:51 +0000844 /*convertOtherExpr*/ true);
845
846 assert(RHSComplexFloat);
847 return handleOtherComplexFloatConversion(
Richard Trieucafd30b2011-09-06 18:25:09 +0000848 S, RHS, LHS, RHSType, LHSType, /*convertComplexExpr*/true,
Richard Trieuccd891a2011-09-09 01:45:06 +0000849 /*convertOtherExpr*/ !IsCompAssign);
Richard Trieu8289f492011-09-02 20:58:51 +0000850}
851
852/// \brief Hande arithmetic conversion from integer to float. Helper function
853/// of UsualArithmeticConversions()
Richard Trieuccd891a2011-09-09 01:45:06 +0000854static QualType handleIntToFloatConversion(Sema &S, ExprResult &FloatExpr,
855 ExprResult &IntExpr,
856 QualType FloatTy, QualType IntTy,
857 bool ConvertFloat, bool ConvertInt) {
858 if (IntTy->isIntegerType()) {
859 if (ConvertInt)
Richard Trieu8289f492011-09-02 20:58:51 +0000860 // Convert intExpr to the lhs floating point type.
Richard Trieuccd891a2011-09-09 01:45:06 +0000861 IntExpr = S.ImpCastExprToType(IntExpr.take(), FloatTy,
Richard Trieu8289f492011-09-02 20:58:51 +0000862 CK_IntegralToFloating);
Richard Trieuccd891a2011-09-09 01:45:06 +0000863 return FloatTy;
Richard Trieu8289f492011-09-02 20:58:51 +0000864 }
865
866 // Convert both sides to the appropriate complex float.
Richard Trieuccd891a2011-09-09 01:45:06 +0000867 assert(IntTy->isComplexIntegerType());
868 QualType result = S.Context.getComplexType(FloatTy);
Richard Trieu8289f492011-09-02 20:58:51 +0000869
870 // _Complex int -> _Complex float
Richard Trieuccd891a2011-09-09 01:45:06 +0000871 if (ConvertInt)
872 IntExpr = S.ImpCastExprToType(IntExpr.take(), result,
Richard Trieu8289f492011-09-02 20:58:51 +0000873 CK_IntegralComplexToFloatingComplex);
874
875 // float -> _Complex float
Richard Trieuccd891a2011-09-09 01:45:06 +0000876 if (ConvertFloat)
877 FloatExpr = S.ImpCastExprToType(FloatExpr.take(), result,
Richard Trieu8289f492011-09-02 20:58:51 +0000878 CK_FloatingRealToComplex);
879
880 return result;
881}
882
883/// \brief Handle arithmethic conversion with floating point types. Helper
884/// function of UsualArithmeticConversions()
Richard Trieu8ef5c8e2011-09-06 18:38:41 +0000885static QualType handleFloatConversion(Sema &S, ExprResult &LHS,
886 ExprResult &RHS, QualType LHSType,
Richard Trieuccd891a2011-09-09 01:45:06 +0000887 QualType RHSType, bool IsCompAssign) {
Richard Trieu8ef5c8e2011-09-06 18:38:41 +0000888 bool LHSFloat = LHSType->isRealFloatingType();
889 bool RHSFloat = RHSType->isRealFloatingType();
Richard Trieu8289f492011-09-02 20:58:51 +0000890
891 // If we have two real floating types, convert the smaller operand
892 // to the bigger result.
893 if (LHSFloat && RHSFloat) {
Richard Trieu8ef5c8e2011-09-06 18:38:41 +0000894 int order = S.Context.getFloatingTypeOrder(LHSType, RHSType);
Richard Trieu8289f492011-09-02 20:58:51 +0000895 if (order > 0) {
Richard Trieu8ef5c8e2011-09-06 18:38:41 +0000896 RHS = S.ImpCastExprToType(RHS.take(), LHSType, CK_FloatingCast);
897 return LHSType;
Richard Trieu8289f492011-09-02 20:58:51 +0000898 }
899
900 assert(order < 0 && "illegal float comparison");
Richard Trieuccd891a2011-09-09 01:45:06 +0000901 if (!IsCompAssign)
Richard Trieu8ef5c8e2011-09-06 18:38:41 +0000902 LHS = S.ImpCastExprToType(LHS.take(), RHSType, CK_FloatingCast);
903 return RHSType;
Richard Trieu8289f492011-09-02 20:58:51 +0000904 }
905
906 if (LHSFloat)
Richard Trieu8ef5c8e2011-09-06 18:38:41 +0000907 return handleIntToFloatConversion(S, LHS, RHS, LHSType, RHSType,
Richard Trieuccd891a2011-09-09 01:45:06 +0000908 /*convertFloat=*/!IsCompAssign,
Richard Trieu8289f492011-09-02 20:58:51 +0000909 /*convertInt=*/ true);
910 assert(RHSFloat);
Richard Trieu8ef5c8e2011-09-06 18:38:41 +0000911 return handleIntToFloatConversion(S, RHS, LHS, RHSType, LHSType,
Richard Trieu8289f492011-09-02 20:58:51 +0000912 /*convertInt=*/ true,
Richard Trieuccd891a2011-09-09 01:45:06 +0000913 /*convertFloat=*/!IsCompAssign);
Richard Trieu8289f492011-09-02 20:58:51 +0000914}
915
916/// \brief Handle conversions with GCC complex int extension. Helper function
Benjamin Kramer5cc86802011-09-06 19:57:14 +0000917/// of UsualArithmeticConversions()
Richard Trieu8289f492011-09-02 20:58:51 +0000918// FIXME: if the operands are (int, _Complex long), we currently
919// don't promote the complex. Also, signedness?
Benjamin Kramer5cc86802011-09-06 19:57:14 +0000920static QualType handleComplexIntConversion(Sema &S, ExprResult &LHS,
921 ExprResult &RHS, QualType LHSType,
922 QualType RHSType,
Richard Trieuccd891a2011-09-09 01:45:06 +0000923 bool IsCompAssign) {
Richard Trieu8ef5c8e2011-09-06 18:38:41 +0000924 const ComplexType *LHSComplexInt = LHSType->getAsComplexIntegerType();
925 const ComplexType *RHSComplexInt = RHSType->getAsComplexIntegerType();
Richard Trieu8289f492011-09-02 20:58:51 +0000926
Richard Trieu8ef5c8e2011-09-06 18:38:41 +0000927 if (LHSComplexInt && RHSComplexInt) {
928 int order = S.Context.getIntegerTypeOrder(LHSComplexInt->getElementType(),
929 RHSComplexInt->getElementType());
Richard Trieu8289f492011-09-02 20:58:51 +0000930 assert(order && "inequal types with equal element ordering");
931 if (order > 0) {
932 // _Complex int -> _Complex long
Richard Trieu8ef5c8e2011-09-06 18:38:41 +0000933 RHS = S.ImpCastExprToType(RHS.take(), LHSType, CK_IntegralComplexCast);
934 return LHSType;
Richard Trieu8289f492011-09-02 20:58:51 +0000935 }
936
Richard Trieuccd891a2011-09-09 01:45:06 +0000937 if (!IsCompAssign)
Richard Trieu8ef5c8e2011-09-06 18:38:41 +0000938 LHS = S.ImpCastExprToType(LHS.take(), RHSType, CK_IntegralComplexCast);
939 return RHSType;
Richard Trieu8289f492011-09-02 20:58:51 +0000940 }
941
Richard Trieu8ef5c8e2011-09-06 18:38:41 +0000942 if (LHSComplexInt) {
Richard Trieu8289f492011-09-02 20:58:51 +0000943 // int -> _Complex int
Eli Friedmanddadaa42011-11-12 03:56:23 +0000944 // FIXME: This needs to take integer ranks into account
945 RHS = S.ImpCastExprToType(RHS.take(), LHSComplexInt->getElementType(),
946 CK_IntegralCast);
Richard Trieu8ef5c8e2011-09-06 18:38:41 +0000947 RHS = S.ImpCastExprToType(RHS.take(), LHSType, CK_IntegralRealToComplex);
948 return LHSType;
Richard Trieu8289f492011-09-02 20:58:51 +0000949 }
950
Richard Trieu8ef5c8e2011-09-06 18:38:41 +0000951 assert(RHSComplexInt);
Richard Trieu8289f492011-09-02 20:58:51 +0000952 // int -> _Complex int
Eli Friedmanddadaa42011-11-12 03:56:23 +0000953 // FIXME: This needs to take integer ranks into account
954 if (!IsCompAssign) {
955 LHS = S.ImpCastExprToType(LHS.take(), RHSComplexInt->getElementType(),
956 CK_IntegralCast);
Richard Trieu8ef5c8e2011-09-06 18:38:41 +0000957 LHS = S.ImpCastExprToType(LHS.take(), RHSType, CK_IntegralRealToComplex);
Eli Friedmanddadaa42011-11-12 03:56:23 +0000958 }
Richard Trieu8ef5c8e2011-09-06 18:38:41 +0000959 return RHSType;
Richard Trieu8289f492011-09-02 20:58:51 +0000960}
961
962/// \brief Handle integer arithmetic conversions. Helper function of
963/// UsualArithmeticConversions()
Richard Trieu2e8a95d2011-09-06 19:52:52 +0000964static QualType handleIntegerConversion(Sema &S, ExprResult &LHS,
965 ExprResult &RHS, QualType LHSType,
Richard Trieuccd891a2011-09-09 01:45:06 +0000966 QualType RHSType, bool IsCompAssign) {
Richard Trieu8289f492011-09-02 20:58:51 +0000967 // The rules for this case are in C99 6.3.1.8
Richard Trieu2e8a95d2011-09-06 19:52:52 +0000968 int order = S.Context.getIntegerTypeOrder(LHSType, RHSType);
969 bool LHSSigned = LHSType->hasSignedIntegerRepresentation();
970 bool RHSSigned = RHSType->hasSignedIntegerRepresentation();
971 if (LHSSigned == RHSSigned) {
Richard Trieu8289f492011-09-02 20:58:51 +0000972 // Same signedness; use the higher-ranked type
973 if (order >= 0) {
Richard Trieu2e8a95d2011-09-06 19:52:52 +0000974 RHS = S.ImpCastExprToType(RHS.take(), LHSType, CK_IntegralCast);
975 return LHSType;
Richard Trieuccd891a2011-09-09 01:45:06 +0000976 } else if (!IsCompAssign)
Richard Trieu2e8a95d2011-09-06 19:52:52 +0000977 LHS = S.ImpCastExprToType(LHS.take(), RHSType, CK_IntegralCast);
978 return RHSType;
979 } else if (order != (LHSSigned ? 1 : -1)) {
Richard Trieu8289f492011-09-02 20:58:51 +0000980 // The unsigned type has greater than or equal rank to the
981 // signed type, so use the unsigned type
Richard Trieu2e8a95d2011-09-06 19:52:52 +0000982 if (RHSSigned) {
983 RHS = S.ImpCastExprToType(RHS.take(), LHSType, CK_IntegralCast);
984 return LHSType;
Richard Trieuccd891a2011-09-09 01:45:06 +0000985 } else if (!IsCompAssign)
Richard Trieu2e8a95d2011-09-06 19:52:52 +0000986 LHS = S.ImpCastExprToType(LHS.take(), RHSType, CK_IntegralCast);
987 return RHSType;
988 } else if (S.Context.getIntWidth(LHSType) != S.Context.getIntWidth(RHSType)) {
Richard Trieu8289f492011-09-02 20:58:51 +0000989 // The two types are different widths; if we are here, that
990 // means the signed type is larger than the unsigned type, so
991 // use the signed type.
Richard Trieu2e8a95d2011-09-06 19:52:52 +0000992 if (LHSSigned) {
993 RHS = S.ImpCastExprToType(RHS.take(), LHSType, CK_IntegralCast);
994 return LHSType;
Richard Trieuccd891a2011-09-09 01:45:06 +0000995 } else if (!IsCompAssign)
Richard Trieu2e8a95d2011-09-06 19:52:52 +0000996 LHS = S.ImpCastExprToType(LHS.take(), RHSType, CK_IntegralCast);
997 return RHSType;
Richard Trieu8289f492011-09-02 20:58:51 +0000998 } else {
999 // The signed type is higher-ranked than the unsigned type,
1000 // but isn't actually any bigger (like unsigned int and long
1001 // on most 32-bit systems). Use the unsigned type corresponding
1002 // to the signed type.
1003 QualType result =
Richard Trieu2e8a95d2011-09-06 19:52:52 +00001004 S.Context.getCorrespondingUnsignedType(LHSSigned ? LHSType : RHSType);
1005 RHS = S.ImpCastExprToType(RHS.take(), result, CK_IntegralCast);
Richard Trieuccd891a2011-09-09 01:45:06 +00001006 if (!IsCompAssign)
Richard Trieu2e8a95d2011-09-06 19:52:52 +00001007 LHS = S.ImpCastExprToType(LHS.take(), result, CK_IntegralCast);
Richard Trieu8289f492011-09-02 20:58:51 +00001008 return result;
1009 }
1010}
1011
Chris Lattnere7a2e912008-07-25 21:10:04 +00001012/// UsualArithmeticConversions - Performs various conversions that are common to
1013/// binary operators (C99 6.3.1.8). If both operands aren't arithmetic, this
Mike Stump1eb44332009-09-09 15:08:12 +00001014/// routine returns the first non-arithmetic type found. The client is
Chris Lattnere7a2e912008-07-25 21:10:04 +00001015/// responsible for emitting appropriate error diagnostics.
1016/// FIXME: verify the conversion rules for "complex int" are consistent with
1017/// GCC.
Richard Trieu2e8a95d2011-09-06 19:52:52 +00001018QualType Sema::UsualArithmeticConversions(ExprResult &LHS, ExprResult &RHS,
Richard Trieuccd891a2011-09-09 01:45:06 +00001019 bool IsCompAssign) {
1020 if (!IsCompAssign) {
Richard Trieu2e8a95d2011-09-06 19:52:52 +00001021 LHS = UsualUnaryConversions(LHS.take());
1022 if (LHS.isInvalid())
John Wiegley429bb272011-04-08 18:41:53 +00001023 return QualType();
1024 }
Eli Friedmanab3a8522009-03-28 01:22:36 +00001025
Richard Trieu2e8a95d2011-09-06 19:52:52 +00001026 RHS = UsualUnaryConversions(RHS.take());
1027 if (RHS.isInvalid())
John Wiegley429bb272011-04-08 18:41:53 +00001028 return QualType();
Douglas Gregoreb8f3062008-11-12 17:17:38 +00001029
Mike Stump1eb44332009-09-09 15:08:12 +00001030 // For conversion purposes, we ignore any qualifiers.
Chris Lattnere7a2e912008-07-25 21:10:04 +00001031 // For example, "const float" and "float" are equivalent.
Richard Trieu2e8a95d2011-09-06 19:52:52 +00001032 QualType LHSType =
1033 Context.getCanonicalType(LHS.get()->getType()).getUnqualifiedType();
1034 QualType RHSType =
1035 Context.getCanonicalType(RHS.get()->getType()).getUnqualifiedType();
Douglas Gregoreb8f3062008-11-12 17:17:38 +00001036
Eli Friedman860a3192012-06-16 02:19:17 +00001037 // For conversion purposes, we ignore any atomic qualifier on the LHS.
1038 if (const AtomicType *AtomicLHS = LHSType->getAs<AtomicType>())
1039 LHSType = AtomicLHS->getValueType();
1040
Douglas Gregoreb8f3062008-11-12 17:17:38 +00001041 // If both types are identical, no conversion is needed.
Richard Trieu2e8a95d2011-09-06 19:52:52 +00001042 if (LHSType == RHSType)
1043 return LHSType;
Douglas Gregoreb8f3062008-11-12 17:17:38 +00001044
1045 // If either side is a non-arithmetic type (e.g. a pointer), we are done.
1046 // The caller can deal with this (e.g. pointer + int).
Richard Trieu2e8a95d2011-09-06 19:52:52 +00001047 if (!LHSType->isArithmeticType() || !RHSType->isArithmeticType())
Eli Friedman860a3192012-06-16 02:19:17 +00001048 return QualType();
Douglas Gregoreb8f3062008-11-12 17:17:38 +00001049
John McCallcf33b242010-11-13 08:17:45 +00001050 // Apply unary and bitfield promotions to the LHS's type.
Richard Trieu2e8a95d2011-09-06 19:52:52 +00001051 QualType LHSUnpromotedType = LHSType;
1052 if (LHSType->isPromotableIntegerType())
1053 LHSType = Context.getPromotedIntegerType(LHSType);
1054 QualType LHSBitfieldPromoteTy = Context.isPromotableBitField(LHS.get());
Douglas Gregor2d833e32009-05-02 00:36:19 +00001055 if (!LHSBitfieldPromoteTy.isNull())
Richard Trieu2e8a95d2011-09-06 19:52:52 +00001056 LHSType = LHSBitfieldPromoteTy;
Richard Trieuccd891a2011-09-09 01:45:06 +00001057 if (LHSType != LHSUnpromotedType && !IsCompAssign)
Richard Trieu2e8a95d2011-09-06 19:52:52 +00001058 LHS = ImpCastExprToType(LHS.take(), LHSType, CK_IntegralCast);
Douglas Gregor2d833e32009-05-02 00:36:19 +00001059
John McCallcf33b242010-11-13 08:17:45 +00001060 // If both types are identical, no conversion is needed.
Richard Trieu2e8a95d2011-09-06 19:52:52 +00001061 if (LHSType == RHSType)
1062 return LHSType;
John McCallcf33b242010-11-13 08:17:45 +00001063
1064 // At this point, we have two different arithmetic types.
1065
1066 // Handle complex types first (C99 6.3.1.8p1).
Richard Trieu2e8a95d2011-09-06 19:52:52 +00001067 if (LHSType->isComplexType() || RHSType->isComplexType())
1068 return handleComplexFloatConversion(*this, LHS, RHS, LHSType, RHSType,
Richard Trieuccd891a2011-09-09 01:45:06 +00001069 IsCompAssign);
John McCallcf33b242010-11-13 08:17:45 +00001070
1071 // Now handle "real" floating types (i.e. float, double, long double).
Richard Trieu2e8a95d2011-09-06 19:52:52 +00001072 if (LHSType->isRealFloatingType() || RHSType->isRealFloatingType())
1073 return handleFloatConversion(*this, LHS, RHS, LHSType, RHSType,
Richard Trieuccd891a2011-09-09 01:45:06 +00001074 IsCompAssign);
John McCallcf33b242010-11-13 08:17:45 +00001075
1076 // Handle GCC complex int extension.
Richard Trieu2e8a95d2011-09-06 19:52:52 +00001077 if (LHSType->isComplexIntegerType() || RHSType->isComplexIntegerType())
Benjamin Kramer5cc86802011-09-06 19:57:14 +00001078 return handleComplexIntConversion(*this, LHS, RHS, LHSType, RHSType,
Richard Trieuccd891a2011-09-09 01:45:06 +00001079 IsCompAssign);
John McCallcf33b242010-11-13 08:17:45 +00001080
1081 // Finally, we have two differing integer types.
Richard Trieu2e8a95d2011-09-06 19:52:52 +00001082 return handleIntegerConversion(*this, LHS, RHS, LHSType, RHSType,
Richard Trieuccd891a2011-09-09 01:45:06 +00001083 IsCompAssign);
Douglas Gregoreb8f3062008-11-12 17:17:38 +00001084}
1085
Chris Lattnere7a2e912008-07-25 21:10:04 +00001086//===----------------------------------------------------------------------===//
1087// Semantic Analysis for various Expression Types
1088//===----------------------------------------------------------------------===//
1089
1090
Peter Collingbournef111d932011-04-15 00:35:48 +00001091ExprResult
1092Sema::ActOnGenericSelectionExpr(SourceLocation KeyLoc,
1093 SourceLocation DefaultLoc,
1094 SourceLocation RParenLoc,
1095 Expr *ControllingExpr,
Richard Trieuccd891a2011-09-09 01:45:06 +00001096 MultiTypeArg ArgTypes,
1097 MultiExprArg ArgExprs) {
1098 unsigned NumAssocs = ArgTypes.size();
1099 assert(NumAssocs == ArgExprs.size());
Peter Collingbournef111d932011-04-15 00:35:48 +00001100
Benjamin Kramer5354e772012-08-23 23:38:35 +00001101 ParsedType *ParsedTypes = ArgTypes.data();
1102 Expr **Exprs = ArgExprs.data();
Peter Collingbournef111d932011-04-15 00:35:48 +00001103
1104 TypeSourceInfo **Types = new TypeSourceInfo*[NumAssocs];
1105 for (unsigned i = 0; i < NumAssocs; ++i) {
1106 if (ParsedTypes[i])
1107 (void) GetTypeFromParser(ParsedTypes[i], &Types[i]);
1108 else
1109 Types[i] = 0;
1110 }
1111
1112 ExprResult ER = CreateGenericSelectionExpr(KeyLoc, DefaultLoc, RParenLoc,
1113 ControllingExpr, Types, Exprs,
1114 NumAssocs);
Benjamin Kramer5bf47f72011-04-15 11:21:57 +00001115 delete [] Types;
Peter Collingbournef111d932011-04-15 00:35:48 +00001116 return ER;
1117}
1118
1119ExprResult
1120Sema::CreateGenericSelectionExpr(SourceLocation KeyLoc,
1121 SourceLocation DefaultLoc,
1122 SourceLocation RParenLoc,
1123 Expr *ControllingExpr,
1124 TypeSourceInfo **Types,
1125 Expr **Exprs,
1126 unsigned NumAssocs) {
1127 bool TypeErrorFound = false,
1128 IsResultDependent = ControllingExpr->isTypeDependent(),
1129 ContainsUnexpandedParameterPack
1130 = ControllingExpr->containsUnexpandedParameterPack();
1131
1132 for (unsigned i = 0; i < NumAssocs; ++i) {
1133 if (Exprs[i]->containsUnexpandedParameterPack())
1134 ContainsUnexpandedParameterPack = true;
1135
1136 if (Types[i]) {
1137 if (Types[i]->getType()->containsUnexpandedParameterPack())
1138 ContainsUnexpandedParameterPack = true;
1139
1140 if (Types[i]->getType()->isDependentType()) {
1141 IsResultDependent = true;
1142 } else {
Benjamin Kramerffbe9b92011-12-23 17:00:35 +00001143 // C11 6.5.1.1p2 "The type name in a generic association shall specify a
Peter Collingbournef111d932011-04-15 00:35:48 +00001144 // complete object type other than a variably modified type."
1145 unsigned D = 0;
1146 if (Types[i]->getType()->isIncompleteType())
1147 D = diag::err_assoc_type_incomplete;
1148 else if (!Types[i]->getType()->isObjectType())
1149 D = diag::err_assoc_type_nonobject;
1150 else if (Types[i]->getType()->isVariablyModifiedType())
1151 D = diag::err_assoc_type_variably_modified;
1152
1153 if (D != 0) {
1154 Diag(Types[i]->getTypeLoc().getBeginLoc(), D)
1155 << Types[i]->getTypeLoc().getSourceRange()
1156 << Types[i]->getType();
1157 TypeErrorFound = true;
1158 }
1159
Benjamin Kramerffbe9b92011-12-23 17:00:35 +00001160 // C11 6.5.1.1p2 "No two generic associations in the same generic
Peter Collingbournef111d932011-04-15 00:35:48 +00001161 // selection shall specify compatible types."
1162 for (unsigned j = i+1; j < NumAssocs; ++j)
1163 if (Types[j] && !Types[j]->getType()->isDependentType() &&
1164 Context.typesAreCompatible(Types[i]->getType(),
1165 Types[j]->getType())) {
1166 Diag(Types[j]->getTypeLoc().getBeginLoc(),
1167 diag::err_assoc_compatible_types)
1168 << Types[j]->getTypeLoc().getSourceRange()
1169 << Types[j]->getType()
1170 << Types[i]->getType();
1171 Diag(Types[i]->getTypeLoc().getBeginLoc(),
1172 diag::note_compat_assoc)
1173 << Types[i]->getTypeLoc().getSourceRange()
1174 << Types[i]->getType();
1175 TypeErrorFound = true;
1176 }
1177 }
1178 }
1179 }
1180 if (TypeErrorFound)
1181 return ExprError();
1182
1183 // If we determined that the generic selection is result-dependent, don't
1184 // try to compute the result expression.
1185 if (IsResultDependent)
1186 return Owned(new (Context) GenericSelectionExpr(
1187 Context, KeyLoc, ControllingExpr,
Benjamin Kramer3b6bef92012-08-24 11:54:20 +00001188 llvm::makeArrayRef(Types, NumAssocs),
1189 llvm::makeArrayRef(Exprs, NumAssocs),
1190 DefaultLoc, RParenLoc, ContainsUnexpandedParameterPack));
Peter Collingbournef111d932011-04-15 00:35:48 +00001191
Chris Lattner5f9e2722011-07-23 10:55:15 +00001192 SmallVector<unsigned, 1> CompatIndices;
Peter Collingbournef111d932011-04-15 00:35:48 +00001193 unsigned DefaultIndex = -1U;
1194 for (unsigned i = 0; i < NumAssocs; ++i) {
1195 if (!Types[i])
1196 DefaultIndex = i;
1197 else if (Context.typesAreCompatible(ControllingExpr->getType(),
1198 Types[i]->getType()))
1199 CompatIndices.push_back(i);
1200 }
1201
Benjamin Kramerffbe9b92011-12-23 17:00:35 +00001202 // C11 6.5.1.1p2 "The controlling expression of a generic selection shall have
Peter Collingbournef111d932011-04-15 00:35:48 +00001203 // type compatible with at most one of the types named in its generic
1204 // association list."
1205 if (CompatIndices.size() > 1) {
1206 // We strip parens here because the controlling expression is typically
1207 // parenthesized in macro definitions.
1208 ControllingExpr = ControllingExpr->IgnoreParens();
1209 Diag(ControllingExpr->getLocStart(), diag::err_generic_sel_multi_match)
1210 << ControllingExpr->getSourceRange() << ControllingExpr->getType()
1211 << (unsigned) CompatIndices.size();
Chris Lattner5f9e2722011-07-23 10:55:15 +00001212 for (SmallVector<unsigned, 1>::iterator I = CompatIndices.begin(),
Peter Collingbournef111d932011-04-15 00:35:48 +00001213 E = CompatIndices.end(); I != E; ++I) {
1214 Diag(Types[*I]->getTypeLoc().getBeginLoc(),
1215 diag::note_compat_assoc)
1216 << Types[*I]->getTypeLoc().getSourceRange()
1217 << Types[*I]->getType();
1218 }
1219 return ExprError();
1220 }
1221
Benjamin Kramerffbe9b92011-12-23 17:00:35 +00001222 // C11 6.5.1.1p2 "If a generic selection has no default generic association,
Peter Collingbournef111d932011-04-15 00:35:48 +00001223 // its controlling expression shall have type compatible with exactly one of
1224 // the types named in its generic association list."
1225 if (DefaultIndex == -1U && CompatIndices.size() == 0) {
1226 // We strip parens here because the controlling expression is typically
1227 // parenthesized in macro definitions.
1228 ControllingExpr = ControllingExpr->IgnoreParens();
1229 Diag(ControllingExpr->getLocStart(), diag::err_generic_sel_no_match)
1230 << ControllingExpr->getSourceRange() << ControllingExpr->getType();
1231 return ExprError();
1232 }
1233
Benjamin Kramerffbe9b92011-12-23 17:00:35 +00001234 // C11 6.5.1.1p3 "If a generic selection has a generic association with a
Peter Collingbournef111d932011-04-15 00:35:48 +00001235 // type name that is compatible with the type of the controlling expression,
1236 // then the result expression of the generic selection is the expression
1237 // in that generic association. Otherwise, the result expression of the
1238 // generic selection is the expression in the default generic association."
1239 unsigned ResultIndex =
1240 CompatIndices.size() ? CompatIndices[0] : DefaultIndex;
1241
1242 return Owned(new (Context) GenericSelectionExpr(
1243 Context, KeyLoc, ControllingExpr,
Benjamin Kramer3b6bef92012-08-24 11:54:20 +00001244 llvm::makeArrayRef(Types, NumAssocs),
1245 llvm::makeArrayRef(Exprs, NumAssocs),
1246 DefaultLoc, RParenLoc, ContainsUnexpandedParameterPack,
Peter Collingbournef111d932011-04-15 00:35:48 +00001247 ResultIndex));
1248}
1249
Richard Smithdd66be72012-03-08 01:34:56 +00001250/// getUDSuffixLoc - Create a SourceLocation for a ud-suffix, given the
1251/// location of the token and the offset of the ud-suffix within it.
1252static SourceLocation getUDSuffixLoc(Sema &S, SourceLocation TokLoc,
1253 unsigned Offset) {
1254 return Lexer::AdvanceToTokenCharacter(TokLoc, Offset, S.getSourceManager(),
David Blaikie4e4d0842012-03-11 07:00:24 +00001255 S.getLangOpts());
Richard Smithdd66be72012-03-08 01:34:56 +00001256}
1257
Richard Smith36f5cfe2012-03-09 08:00:36 +00001258/// BuildCookedLiteralOperatorCall - A user-defined literal was found. Look up
1259/// the corresponding cooked (non-raw) literal operator, and build a call to it.
1260static ExprResult BuildCookedLiteralOperatorCall(Sema &S, Scope *Scope,
1261 IdentifierInfo *UDSuffix,
1262 SourceLocation UDSuffixLoc,
1263 ArrayRef<Expr*> Args,
1264 SourceLocation LitEndLoc) {
1265 assert(Args.size() <= 2 && "too many arguments for literal operator");
1266
1267 QualType ArgTy[2];
1268 for (unsigned ArgIdx = 0; ArgIdx != Args.size(); ++ArgIdx) {
1269 ArgTy[ArgIdx] = Args[ArgIdx]->getType();
1270 if (ArgTy[ArgIdx]->isArrayType())
1271 ArgTy[ArgIdx] = S.Context.getArrayDecayedType(ArgTy[ArgIdx]);
1272 }
1273
1274 DeclarationName OpName =
1275 S.Context.DeclarationNames.getCXXLiteralOperatorName(UDSuffix);
1276 DeclarationNameInfo OpNameInfo(OpName, UDSuffixLoc);
1277 OpNameInfo.setCXXLiteralOperatorNameLoc(UDSuffixLoc);
1278
1279 LookupResult R(S, OpName, UDSuffixLoc, Sema::LookupOrdinaryName);
1280 if (S.LookupLiteralOperator(Scope, R, llvm::makeArrayRef(ArgTy, Args.size()),
1281 /*AllowRawAndTemplate*/false) == Sema::LOLR_Error)
1282 return ExprError();
1283
1284 return S.BuildLiteralOperatorCall(R, OpNameInfo, Args, LitEndLoc);
1285}
1286
Steve Narofff69936d2007-09-16 03:34:24 +00001287/// ActOnStringLiteral - The specified tokens were lexed as pasted string
Reid Spencer5f016e22007-07-11 17:01:13 +00001288/// fragments (e.g. "foo" "bar" L"baz"). The result string has to handle string
1289/// concatenation ([C99 5.1.1.2, translation phase #6]), so it may come from
1290/// multiple tokens. However, the common case is that StringToks points to one
1291/// string.
Sebastian Redlcd965b92009-01-18 18:53:16 +00001292///
John McCall60d7b3a2010-08-24 06:29:42 +00001293ExprResult
Richard Smith36f5cfe2012-03-09 08:00:36 +00001294Sema::ActOnStringLiteral(const Token *StringToks, unsigned NumStringToks,
1295 Scope *UDLScope) {
Reid Spencer5f016e22007-07-11 17:01:13 +00001296 assert(NumStringToks && "Must have at least one string!");
1297
Chris Lattnerbbee00b2009-01-16 18:51:42 +00001298 StringLiteralParser Literal(StringToks, NumStringToks, PP);
Reid Spencer5f016e22007-07-11 17:01:13 +00001299 if (Literal.hadError)
Sebastian Redlcd965b92009-01-18 18:53:16 +00001300 return ExprError();
Reid Spencer5f016e22007-07-11 17:01:13 +00001301
Chris Lattner5f9e2722011-07-23 10:55:15 +00001302 SmallVector<SourceLocation, 4> StringTokLocs;
Reid Spencer5f016e22007-07-11 17:01:13 +00001303 for (unsigned i = 0; i != NumStringToks; ++i)
1304 StringTokLocs.push_back(StringToks[i].getLocation());
Chris Lattnera7ad98f2008-02-11 00:02:17 +00001305
Chris Lattnera7ad98f2008-02-11 00:02:17 +00001306 QualType StrTy = Context.CharTy;
Douglas Gregor5cee1192011-07-27 05:40:30 +00001307 if (Literal.isWide())
Anders Carlsson96b4adc2011-04-06 18:42:48 +00001308 StrTy = Context.getWCharType();
Douglas Gregor5cee1192011-07-27 05:40:30 +00001309 else if (Literal.isUTF16())
1310 StrTy = Context.Char16Ty;
1311 else if (Literal.isUTF32())
1312 StrTy = Context.Char32Ty;
Eli Friedman64f45a22011-11-01 02:23:42 +00001313 else if (Literal.isPascal())
Anders Carlsson96b4adc2011-04-06 18:42:48 +00001314 StrTy = Context.UnsignedCharTy;
Douglas Gregor77a52232008-09-12 00:47:35 +00001315
Douglas Gregor5cee1192011-07-27 05:40:30 +00001316 StringLiteral::StringKind Kind = StringLiteral::Ascii;
1317 if (Literal.isWide())
1318 Kind = StringLiteral::Wide;
1319 else if (Literal.isUTF8())
1320 Kind = StringLiteral::UTF8;
1321 else if (Literal.isUTF16())
1322 Kind = StringLiteral::UTF16;
1323 else if (Literal.isUTF32())
1324 Kind = StringLiteral::UTF32;
1325
Douglas Gregor77a52232008-09-12 00:47:35 +00001326 // A C++ string literal has a const-qualified element type (C++ 2.13.4p1).
David Blaikie4e4d0842012-03-11 07:00:24 +00001327 if (getLangOpts().CPlusPlus || getLangOpts().ConstStrings)
Douglas Gregor77a52232008-09-12 00:47:35 +00001328 StrTy.addConst();
Sebastian Redlcd965b92009-01-18 18:53:16 +00001329
Chris Lattnera7ad98f2008-02-11 00:02:17 +00001330 // Get an array type for the string, according to C99 6.4.5. This includes
1331 // the nul terminator character as well as the string length for pascal
1332 // strings.
1333 StrTy = Context.getConstantArrayType(StrTy,
Chris Lattnerdbb1ecc2009-02-26 23:01:51 +00001334 llvm::APInt(32, Literal.GetNumStringChars()+1),
Chris Lattnera7ad98f2008-02-11 00:02:17 +00001335 ArrayType::Normal, 0);
Mike Stump1eb44332009-09-09 15:08:12 +00001336
Reid Spencer5f016e22007-07-11 17:01:13 +00001337 // Pass &StringTokLocs[0], StringTokLocs.size() to factory!
Richard Smith9fcce652012-03-07 08:35:16 +00001338 StringLiteral *Lit = StringLiteral::Create(Context, Literal.GetString(),
1339 Kind, Literal.Pascal, StrTy,
1340 &StringTokLocs[0],
1341 StringTokLocs.size());
1342 if (Literal.getUDSuffix().empty())
1343 return Owned(Lit);
1344
1345 // We're building a user-defined literal.
1346 IdentifierInfo *UDSuffix = &Context.Idents.get(Literal.getUDSuffix());
Richard Smithdd66be72012-03-08 01:34:56 +00001347 SourceLocation UDSuffixLoc =
1348 getUDSuffixLoc(*this, StringTokLocs[Literal.getUDSuffixToken()],
1349 Literal.getUDSuffixOffset());
Richard Smith9fcce652012-03-07 08:35:16 +00001350
Richard Smith36f5cfe2012-03-09 08:00:36 +00001351 // Make sure we're allowed user-defined literals here.
1352 if (!UDLScope)
1353 return ExprError(Diag(UDSuffixLoc, diag::err_invalid_string_udl));
1354
Richard Smith9fcce652012-03-07 08:35:16 +00001355 // C++11 [lex.ext]p5: The literal L is treated as a call of the form
1356 // operator "" X (str, len)
1357 QualType SizeType = Context.getSizeType();
1358 llvm::APInt Len(Context.getIntWidth(SizeType), Literal.GetNumStringChars());
1359 IntegerLiteral *LenArg = IntegerLiteral::Create(Context, Len, SizeType,
1360 StringTokLocs[0]);
1361 Expr *Args[] = { Lit, LenArg };
Richard Smith36f5cfe2012-03-09 08:00:36 +00001362 return BuildCookedLiteralOperatorCall(*this, UDLScope, UDSuffix, UDSuffixLoc,
1363 Args, StringTokLocs.back());
Reid Spencer5f016e22007-07-11 17:01:13 +00001364}
1365
John McCall60d7b3a2010-08-24 06:29:42 +00001366ExprResult
John McCallf89e55a2010-11-18 06:31:45 +00001367Sema::BuildDeclRefExpr(ValueDecl *D, QualType Ty, ExprValueKind VK,
John McCall76a40212011-02-09 01:13:10 +00001368 SourceLocation Loc,
1369 const CXXScopeSpec *SS) {
Abramo Bagnara25777432010-08-11 22:01:17 +00001370 DeclarationNameInfo NameInfo(D->getDeclName(), Loc);
John McCallf89e55a2010-11-18 06:31:45 +00001371 return BuildDeclRefExpr(D, Ty, VK, NameInfo, SS);
Abramo Bagnara25777432010-08-11 22:01:17 +00001372}
1373
John McCall76a40212011-02-09 01:13:10 +00001374/// BuildDeclRefExpr - Build an expression that references a
1375/// declaration that does not require a closure capture.
John McCall60d7b3a2010-08-24 06:29:42 +00001376ExprResult
John McCall76a40212011-02-09 01:13:10 +00001377Sema::BuildDeclRefExpr(ValueDecl *D, QualType Ty, ExprValueKind VK,
Abramo Bagnara25777432010-08-11 22:01:17 +00001378 const DeclarationNameInfo &NameInfo,
1379 const CXXScopeSpec *SS) {
David Blaikie4e4d0842012-03-11 07:00:24 +00001380 if (getLangOpts().CUDA)
Peter Collingbourne78dd67e2011-10-02 23:49:40 +00001381 if (const FunctionDecl *Caller = dyn_cast<FunctionDecl>(CurContext))
1382 if (const FunctionDecl *Callee = dyn_cast<FunctionDecl>(D)) {
1383 CUDAFunctionTarget CallerTarget = IdentifyCUDATarget(Caller),
1384 CalleeTarget = IdentifyCUDATarget(Callee);
1385 if (CheckCUDATarget(CallerTarget, CalleeTarget)) {
1386 Diag(NameInfo.getLoc(), diag::err_ref_bad_target)
1387 << CalleeTarget << D->getIdentifier() << CallerTarget;
1388 Diag(D->getLocation(), diag::note_previous_decl)
1389 << D->getIdentifier();
1390 return ExprError();
1391 }
1392 }
1393
John McCallf4b88a42012-03-10 09:33:50 +00001394 bool refersToEnclosingScope =
1395 (CurContext != D->getDeclContext() &&
1396 D->getDeclContext()->isFunctionOrMethod());
1397
Eli Friedman5f2987c2012-02-02 03:46:19 +00001398 DeclRefExpr *E = DeclRefExpr::Create(Context,
1399 SS ? SS->getWithLocInContext(Context)
1400 : NestedNameSpecifierLoc(),
John McCallf4b88a42012-03-10 09:33:50 +00001401 SourceLocation(),
1402 D, refersToEnclosingScope,
1403 NameInfo, Ty, VK);
Mike Stump1eb44332009-09-09 15:08:12 +00001404
Eli Friedman5f2987c2012-02-02 03:46:19 +00001405 MarkDeclRefReferenced(E);
John McCall7eb0a9e2010-11-24 05:12:34 +00001406
1407 // Just in case we're building an illegal pointer-to-member.
Richard Smitha6b8b2c2011-10-10 18:28:20 +00001408 FieldDecl *FD = dyn_cast<FieldDecl>(D);
1409 if (FD && FD->isBitField())
John McCall7eb0a9e2010-11-24 05:12:34 +00001410 E->setObjectKind(OK_BitField);
1411
1412 return Owned(E);
Douglas Gregor1a49af92009-01-06 05:10:23 +00001413}
1414
Abramo Bagnara25777432010-08-11 22:01:17 +00001415/// Decomposes the given name into a DeclarationNameInfo, its location, and
John McCall129e2df2009-11-30 22:42:35 +00001416/// possibly a list of template arguments.
1417///
1418/// If this produces template arguments, it is permitted to call
1419/// DecomposeTemplateName.
1420///
1421/// This actually loses a lot of source location information for
1422/// non-standard name kinds; we should consider preserving that in
1423/// some way.
Richard Trieu67e29332011-08-02 04:35:43 +00001424void
1425Sema::DecomposeUnqualifiedId(const UnqualifiedId &Id,
1426 TemplateArgumentListInfo &Buffer,
1427 DeclarationNameInfo &NameInfo,
1428 const TemplateArgumentListInfo *&TemplateArgs) {
John McCall129e2df2009-11-30 22:42:35 +00001429 if (Id.getKind() == UnqualifiedId::IK_TemplateId) {
1430 Buffer.setLAngleLoc(Id.TemplateId->LAngleLoc);
1431 Buffer.setRAngleLoc(Id.TemplateId->RAngleLoc);
1432
Benjamin Kramer5354e772012-08-23 23:38:35 +00001433 ASTTemplateArgsPtr TemplateArgsPtr(Id.TemplateId->getTemplateArgs(),
John McCall129e2df2009-11-30 22:42:35 +00001434 Id.TemplateId->NumArgs);
Douglas Gregor2b1ad8b2011-06-23 00:49:38 +00001435 translateTemplateArguments(TemplateArgsPtr, Buffer);
John McCall129e2df2009-11-30 22:42:35 +00001436
John McCall2b5289b2010-08-23 07:28:44 +00001437 TemplateName TName = Id.TemplateId->Template.get();
Abramo Bagnara25777432010-08-11 22:01:17 +00001438 SourceLocation TNameLoc = Id.TemplateId->TemplateNameLoc;
Douglas Gregor2b1ad8b2011-06-23 00:49:38 +00001439 NameInfo = Context.getNameForTemplate(TName, TNameLoc);
John McCall129e2df2009-11-30 22:42:35 +00001440 TemplateArgs = &Buffer;
1441 } else {
Douglas Gregor2b1ad8b2011-06-23 00:49:38 +00001442 NameInfo = GetNameFromUnqualifiedId(Id);
John McCall129e2df2009-11-30 22:42:35 +00001443 TemplateArgs = 0;
1444 }
1445}
1446
John McCall578b69b2009-12-16 08:11:27 +00001447/// Diagnose an empty lookup.
1448///
1449/// \return false if new lookup candidates were found
Nick Lewycky03d98c52010-07-06 19:51:49 +00001450bool Sema::DiagnoseEmptyLookup(Scope *S, CXXScopeSpec &SS, LookupResult &R,
Kaelyn Uhrain4798f8d2012-01-18 05:58:54 +00001451 CorrectionCandidateCallback &CCC,
Kaelyn Uhrainace5e762011-08-05 00:09:52 +00001452 TemplateArgumentListInfo *ExplicitTemplateArgs,
Ahmed Charles13a140c2012-02-25 11:00:22 +00001453 llvm::ArrayRef<Expr *> Args) {
John McCall578b69b2009-12-16 08:11:27 +00001454 DeclarationName Name = R.getLookupName();
1455
John McCall578b69b2009-12-16 08:11:27 +00001456 unsigned diagnostic = diag::err_undeclared_var_use;
Douglas Gregorbb092ba2009-12-31 05:20:13 +00001457 unsigned diagnostic_suggest = diag::err_undeclared_var_use_suggest;
John McCall578b69b2009-12-16 08:11:27 +00001458 if (Name.getNameKind() == DeclarationName::CXXOperatorName ||
1459 Name.getNameKind() == DeclarationName::CXXLiteralOperatorName ||
Douglas Gregorbb092ba2009-12-31 05:20:13 +00001460 Name.getNameKind() == DeclarationName::CXXConversionFunctionName) {
John McCall578b69b2009-12-16 08:11:27 +00001461 diagnostic = diag::err_undeclared_use;
Douglas Gregorbb092ba2009-12-31 05:20:13 +00001462 diagnostic_suggest = diag::err_undeclared_use_suggest;
1463 }
John McCall578b69b2009-12-16 08:11:27 +00001464
Douglas Gregorbb092ba2009-12-31 05:20:13 +00001465 // If the original lookup was an unqualified lookup, fake an
1466 // unqualified lookup. This is useful when (for example) the
1467 // original lookup would not have found something because it was a
1468 // dependent name.
David Blaikie4872e102012-05-28 01:26:45 +00001469 DeclContext *DC = (SS.isEmpty() && !CallsUndergoingInstantiation.empty())
1470 ? CurContext : 0;
Francois Pichetc8ff9152011-11-25 01:10:54 +00001471 while (DC) {
John McCall578b69b2009-12-16 08:11:27 +00001472 if (isa<CXXRecordDecl>(DC)) {
1473 LookupQualifiedName(R, DC);
1474
1475 if (!R.empty()) {
1476 // Don't give errors about ambiguities in this lookup.
1477 R.suppressDiagnostics();
1478
Francois Pichete6226ae2011-11-17 03:44:24 +00001479 // During a default argument instantiation the CurContext points
1480 // to a CXXMethodDecl; but we can't apply a this-> fixit inside a
1481 // function parameter list, hence add an explicit check.
1482 bool isDefaultArgument = !ActiveTemplateInstantiations.empty() &&
1483 ActiveTemplateInstantiations.back().Kind ==
1484 ActiveTemplateInstantiation::DefaultFunctionArgumentInstantiation;
John McCall578b69b2009-12-16 08:11:27 +00001485 CXXMethodDecl *CurMethod = dyn_cast<CXXMethodDecl>(CurContext);
1486 bool isInstance = CurMethod &&
1487 CurMethod->isInstance() &&
Francois Pichete6226ae2011-11-17 03:44:24 +00001488 DC == CurMethod->getParent() && !isDefaultArgument;
1489
John McCall578b69b2009-12-16 08:11:27 +00001490
1491 // Give a code modification hint to insert 'this->'.
1492 // TODO: fixit for inserting 'Base<T>::' in the other cases.
1493 // Actually quite difficult!
Nico Weber4b554f42012-06-20 20:21:42 +00001494 if (getLangOpts().MicrosoftMode)
1495 diagnostic = diag::warn_found_via_dependent_bases_lookup;
Nick Lewycky03d98c52010-07-06 19:51:49 +00001496 if (isInstance) {
Nico Weber94c4d612012-06-22 16:39:39 +00001497 Diag(R.getNameLoc(), diagnostic) << Name
1498 << FixItHint::CreateInsertion(R.getNameLoc(), "this->");
Nick Lewycky03d98c52010-07-06 19:51:49 +00001499 UnresolvedLookupExpr *ULE = cast<UnresolvedLookupExpr>(
1500 CallsUndergoingInstantiation.back()->getCallee());
Nico Weber94c4d612012-06-22 16:39:39 +00001501
1502
1503 CXXMethodDecl *DepMethod;
1504 if (CurMethod->getTemplatedKind() ==
1505 FunctionDecl::TK_FunctionTemplateSpecialization)
1506 DepMethod = cast<CXXMethodDecl>(CurMethod->getPrimaryTemplate()->
1507 getInstantiatedFromMemberTemplate()->getTemplatedDecl());
1508 else
1509 DepMethod = cast<CXXMethodDecl>(
1510 CurMethod->getInstantiatedFromMemberFunction());
1511 assert(DepMethod && "No template pattern found");
1512
1513 QualType DepThisType = DepMethod->getThisType(Context);
1514 CheckCXXThisCapture(R.getNameLoc());
1515 CXXThisExpr *DepThis = new (Context) CXXThisExpr(
1516 R.getNameLoc(), DepThisType, false);
1517 TemplateArgumentListInfo TList;
1518 if (ULE->hasExplicitTemplateArgs())
1519 ULE->copyTemplateArgumentsInto(TList);
1520
1521 CXXScopeSpec SS;
1522 SS.Adopt(ULE->getQualifierLoc());
1523 CXXDependentScopeMemberExpr *DepExpr =
1524 CXXDependentScopeMemberExpr::Create(
1525 Context, DepThis, DepThisType, true, SourceLocation(),
1526 SS.getWithLocInContext(Context),
1527 ULE->getTemplateKeywordLoc(), 0,
1528 R.getLookupNameInfo(),
1529 ULE->hasExplicitTemplateArgs() ? &TList : 0);
1530 CallsUndergoingInstantiation.back()->setCallee(DepExpr);
Nick Lewycky03d98c52010-07-06 19:51:49 +00001531 } else {
John McCall578b69b2009-12-16 08:11:27 +00001532 Diag(R.getNameLoc(), diagnostic) << Name;
Nick Lewycky03d98c52010-07-06 19:51:49 +00001533 }
John McCall578b69b2009-12-16 08:11:27 +00001534
1535 // Do we really want to note all of these?
1536 for (LookupResult::iterator I = R.begin(), E = R.end(); I != E; ++I)
1537 Diag((*I)->getLocation(), diag::note_dependent_var_use);
1538
Francois Pichete6226ae2011-11-17 03:44:24 +00001539 // Return true if we are inside a default argument instantiation
1540 // and the found name refers to an instance member function, otherwise
1541 // the function calling DiagnoseEmptyLookup will try to create an
1542 // implicit member call and this is wrong for default argument.
1543 if (isDefaultArgument && ((*R.begin())->isCXXInstanceMember())) {
1544 Diag(R.getNameLoc(), diag::err_member_call_without_object);
1545 return true;
1546 }
1547
John McCall578b69b2009-12-16 08:11:27 +00001548 // Tell the callee to try to recover.
1549 return false;
1550 }
Douglas Gregore26f0432010-08-09 22:38:14 +00001551
1552 R.clear();
John McCall578b69b2009-12-16 08:11:27 +00001553 }
Francois Pichetc8ff9152011-11-25 01:10:54 +00001554
1555 // In Microsoft mode, if we are performing lookup from within a friend
1556 // function definition declared at class scope then we must set
1557 // DC to the lexical parent to be able to search into the parent
1558 // class.
David Blaikie4e4d0842012-03-11 07:00:24 +00001559 if (getLangOpts().MicrosoftMode && isa<FunctionDecl>(DC) &&
Francois Pichetc8ff9152011-11-25 01:10:54 +00001560 cast<FunctionDecl>(DC)->getFriendObjectKind() &&
1561 DC->getLexicalParent()->isRecord())
1562 DC = DC->getLexicalParent();
1563 else
1564 DC = DC->getParent();
John McCall578b69b2009-12-16 08:11:27 +00001565 }
1566
Douglas Gregorbb092ba2009-12-31 05:20:13 +00001567 // We didn't find anything, so try to correct for a typo.
Douglas Gregord8bba9c2011-06-28 16:20:02 +00001568 TypoCorrection Corrected;
1569 if (S && (Corrected = CorrectTypo(R.getLookupNameInfo(), R.getLookupKind(),
Kaelyn Uhrain16e46dd2012-01-31 23:49:25 +00001570 S, &SS, CCC))) {
David Blaikie4e4d0842012-03-11 07:00:24 +00001571 std::string CorrectedStr(Corrected.getAsString(getLangOpts()));
1572 std::string CorrectedQuotedStr(Corrected.getQuoted(getLangOpts()));
Douglas Gregord8bba9c2011-06-28 16:20:02 +00001573 R.setLookupName(Corrected.getCorrection());
1574
Hans Wennborg701d1e72011-07-12 08:45:31 +00001575 if (NamedDecl *ND = Corrected.getCorrectionDecl()) {
Kaelyn Uhrainf0c1d8f2011-08-03 20:36:05 +00001576 if (Corrected.isOverloaded()) {
1577 OverloadCandidateSet OCS(R.getNameLoc());
1578 OverloadCandidateSet::iterator Best;
1579 for (TypoCorrection::decl_iterator CD = Corrected.begin(),
1580 CDEnd = Corrected.end();
1581 CD != CDEnd; ++CD) {
Kaelyn Uhrainadc7a732011-08-08 17:35:31 +00001582 if (FunctionTemplateDecl *FTD =
Kaelyn Uhrainace5e762011-08-05 00:09:52 +00001583 dyn_cast<FunctionTemplateDecl>(*CD))
1584 AddTemplateOverloadCandidate(
1585 FTD, DeclAccessPair::make(FTD, AS_none), ExplicitTemplateArgs,
Ahmed Charles13a140c2012-02-25 11:00:22 +00001586 Args, OCS);
Kaelyn Uhrainadc7a732011-08-08 17:35:31 +00001587 else if (FunctionDecl *FD = dyn_cast<FunctionDecl>(*CD))
1588 if (!ExplicitTemplateArgs || ExplicitTemplateArgs->size() == 0)
1589 AddOverloadCandidate(FD, DeclAccessPair::make(FD, AS_none),
Ahmed Charles13a140c2012-02-25 11:00:22 +00001590 Args, OCS);
Kaelyn Uhrainf0c1d8f2011-08-03 20:36:05 +00001591 }
1592 switch (OCS.BestViableFunction(*this, R.getNameLoc(), Best)) {
1593 case OR_Success:
1594 ND = Best->Function;
1595 break;
1596 default:
Kaelyn Uhrain844d5722011-08-04 23:30:54 +00001597 break;
Kaelyn Uhrainf0c1d8f2011-08-03 20:36:05 +00001598 }
1599 }
Douglas Gregord8bba9c2011-06-28 16:20:02 +00001600 R.addDecl(ND);
1601 if (isa<ValueDecl>(ND) || isa<FunctionTemplateDecl>(ND)) {
Douglas Gregoraaf87162010-04-14 20:04:41 +00001602 if (SS.isEmpty())
Douglas Gregord8bba9c2011-06-28 16:20:02 +00001603 Diag(R.getNameLoc(), diagnostic_suggest) << Name << CorrectedQuotedStr
1604 << FixItHint::CreateReplacement(R.getNameLoc(), CorrectedStr);
Douglas Gregoraaf87162010-04-14 20:04:41 +00001605 else
1606 Diag(R.getNameLoc(), diag::err_no_member_suggest)
Douglas Gregord8bba9c2011-06-28 16:20:02 +00001607 << Name << computeDeclContext(SS, false) << CorrectedQuotedStr
Douglas Gregoraaf87162010-04-14 20:04:41 +00001608 << SS.getRange()
Douglas Gregord8bba9c2011-06-28 16:20:02 +00001609 << FixItHint::CreateReplacement(R.getNameLoc(), CorrectedStr);
1610 if (ND)
Douglas Gregoraaf87162010-04-14 20:04:41 +00001611 Diag(ND->getLocation(), diag::note_previous_decl)
Douglas Gregord8bba9c2011-06-28 16:20:02 +00001612 << CorrectedQuotedStr;
Douglas Gregoraaf87162010-04-14 20:04:41 +00001613
1614 // Tell the callee to try to recover.
1615 return false;
1616 }
Sean Hunt1e3f5ba2010-04-28 23:02:27 +00001617
Douglas Gregord8bba9c2011-06-28 16:20:02 +00001618 if (isa<TypeDecl>(ND) || isa<ObjCInterfaceDecl>(ND)) {
Douglas Gregoraaf87162010-04-14 20:04:41 +00001619 // FIXME: If we ended up with a typo for a type name or
1620 // Objective-C class name, we're in trouble because the parser
1621 // is in the wrong place to recover. Suggest the typo
1622 // correction, but don't make it a fix-it since we're not going
1623 // to recover well anyway.
1624 if (SS.isEmpty())
Richard Trieu67e29332011-08-02 04:35:43 +00001625 Diag(R.getNameLoc(), diagnostic_suggest)
1626 << Name << CorrectedQuotedStr;
Douglas Gregoraaf87162010-04-14 20:04:41 +00001627 else
1628 Diag(R.getNameLoc(), diag::err_no_member_suggest)
Douglas Gregord8bba9c2011-06-28 16:20:02 +00001629 << Name << computeDeclContext(SS, false) << CorrectedQuotedStr
Douglas Gregoraaf87162010-04-14 20:04:41 +00001630 << SS.getRange();
1631
1632 // Don't try to recover; it won't work.
1633 return true;
1634 }
1635 } else {
Sean Hunt1e3f5ba2010-04-28 23:02:27 +00001636 // FIXME: We found a keyword. Suggest it, but don't provide a fix-it
Douglas Gregoraaf87162010-04-14 20:04:41 +00001637 // because we aren't able to recover.
Douglas Gregord203a162010-01-01 00:15:04 +00001638 if (SS.isEmpty())
Douglas Gregord8bba9c2011-06-28 16:20:02 +00001639 Diag(R.getNameLoc(), diagnostic_suggest) << Name << CorrectedQuotedStr;
Kovarththanan Rajaratnam19357542010-03-13 10:17:05 +00001640 else
Douglas Gregord203a162010-01-01 00:15:04 +00001641 Diag(R.getNameLoc(), diag::err_no_member_suggest)
Douglas Gregord8bba9c2011-06-28 16:20:02 +00001642 << Name << computeDeclContext(SS, false) << CorrectedQuotedStr
Douglas Gregoraaf87162010-04-14 20:04:41 +00001643 << SS.getRange();
Douglas Gregord203a162010-01-01 00:15:04 +00001644 return true;
1645 }
Douglas Gregorbb092ba2009-12-31 05:20:13 +00001646 }
Douglas Gregord8bba9c2011-06-28 16:20:02 +00001647 R.clear();
Douglas Gregorbb092ba2009-12-31 05:20:13 +00001648
1649 // Emit a special diagnostic for failed member lookups.
1650 // FIXME: computing the declaration context might fail here (?)
1651 if (!SS.isEmpty()) {
1652 Diag(R.getNameLoc(), diag::err_no_member)
1653 << Name << computeDeclContext(SS, false)
1654 << SS.getRange();
1655 return true;
1656 }
1657
John McCall578b69b2009-12-16 08:11:27 +00001658 // Give up, we can't recover.
1659 Diag(R.getNameLoc(), diagnostic) << Name;
1660 return true;
1661}
1662
John McCall60d7b3a2010-08-24 06:29:42 +00001663ExprResult Sema::ActOnIdExpression(Scope *S,
John McCallfb97e752010-08-24 22:52:39 +00001664 CXXScopeSpec &SS,
Abramo Bagnarae4b92762012-01-27 09:46:47 +00001665 SourceLocation TemplateKWLoc,
John McCallfb97e752010-08-24 22:52:39 +00001666 UnqualifiedId &Id,
1667 bool HasTrailingLParen,
Kaelyn Uhraincd78e612012-01-25 20:49:08 +00001668 bool IsAddressOfOperand,
1669 CorrectionCandidateCallback *CCC) {
Richard Trieuccd891a2011-09-09 01:45:06 +00001670 assert(!(IsAddressOfOperand && HasTrailingLParen) &&
John McCallf7a1a742009-11-24 19:00:30 +00001671 "cannot be direct & operand and have a trailing lparen");
1672
1673 if (SS.isInvalid())
Douglas Gregor4c921ae2009-01-30 01:04:22 +00001674 return ExprError();
Douglas Gregor5953d8b2009-03-19 17:26:29 +00001675
John McCall129e2df2009-11-30 22:42:35 +00001676 TemplateArgumentListInfo TemplateArgsBuffer;
John McCallf7a1a742009-11-24 19:00:30 +00001677
1678 // Decompose the UnqualifiedId into the following data.
Abramo Bagnara25777432010-08-11 22:01:17 +00001679 DeclarationNameInfo NameInfo;
John McCallf7a1a742009-11-24 19:00:30 +00001680 const TemplateArgumentListInfo *TemplateArgs;
Douglas Gregor2b1ad8b2011-06-23 00:49:38 +00001681 DecomposeUnqualifiedId(Id, TemplateArgsBuffer, NameInfo, TemplateArgs);
Douglas Gregor5953d8b2009-03-19 17:26:29 +00001682
Abramo Bagnara25777432010-08-11 22:01:17 +00001683 DeclarationName Name = NameInfo.getName();
Douglas Gregor10c42622008-11-18 15:03:34 +00001684 IdentifierInfo *II = Name.getAsIdentifierInfo();
Abramo Bagnara25777432010-08-11 22:01:17 +00001685 SourceLocation NameLoc = NameInfo.getLoc();
John McCallba135432009-11-21 08:51:07 +00001686
John McCallf7a1a742009-11-24 19:00:30 +00001687 // C++ [temp.dep.expr]p3:
1688 // An id-expression is type-dependent if it contains:
Douglas Gregor48026d22010-01-11 18:40:55 +00001689 // -- an identifier that was declared with a dependent type,
1690 // (note: handled after lookup)
1691 // -- a template-id that is dependent,
1692 // (note: handled in BuildTemplateIdExpr)
1693 // -- a conversion-function-id that specifies a dependent type,
John McCallf7a1a742009-11-24 19:00:30 +00001694 // -- a nested-name-specifier that contains a class-name that
1695 // names a dependent type.
1696 // Determine whether this is a member of an unknown specialization;
1697 // we need to handle these differently.
Eli Friedman647c8b32010-08-06 23:41:47 +00001698 bool DependentID = false;
1699 if (Name.getNameKind() == DeclarationName::CXXConversionFunctionName &&
1700 Name.getCXXNameType()->isDependentType()) {
1701 DependentID = true;
1702 } else if (SS.isSet()) {
Chris Lattner337e5502011-02-18 01:27:55 +00001703 if (DeclContext *DC = computeDeclContext(SS, false)) {
Eli Friedman647c8b32010-08-06 23:41:47 +00001704 if (RequireCompleteDeclContext(SS, DC))
1705 return ExprError();
Eli Friedman647c8b32010-08-06 23:41:47 +00001706 } else {
1707 DependentID = true;
1708 }
1709 }
1710
Chris Lattner337e5502011-02-18 01:27:55 +00001711 if (DependentID)
Abramo Bagnarae4b92762012-01-27 09:46:47 +00001712 return ActOnDependentIdExpression(SS, TemplateKWLoc, NameInfo,
1713 IsAddressOfOperand, TemplateArgs);
Chris Lattner337e5502011-02-18 01:27:55 +00001714
John McCallf7a1a742009-11-24 19:00:30 +00001715 // Perform the required lookup.
Fariborz Jahanian98a54032011-07-12 17:16:56 +00001716 LookupResult R(*this, NameInfo,
1717 (Id.getKind() == UnqualifiedId::IK_ImplicitSelfParam)
1718 ? LookupObjCImplicitSelfParam : LookupOrdinaryName);
John McCallf7a1a742009-11-24 19:00:30 +00001719 if (TemplateArgs) {
Douglas Gregord2235f62010-05-20 20:58:56 +00001720 // Lookup the template name again to correctly establish the context in
1721 // which it was found. This is really unfortunate as we already did the
1722 // lookup to determine that it was a template name in the first place. If
1723 // this becomes a performance hit, we can work harder to preserve those
1724 // results until we get here but it's likely not worth it.
Douglas Gregor1fd6d442010-05-21 23:18:07 +00001725 bool MemberOfUnknownSpecialization;
1726 LookupTemplateName(R, S, SS, QualType(), /*EnteringContext=*/false,
1727 MemberOfUnknownSpecialization);
Douglas Gregor2f9f89c2011-02-04 13:35:07 +00001728
1729 if (MemberOfUnknownSpecialization ||
1730 (R.getResultKind() == LookupResult::NotFoundInCurrentInstantiation))
Abramo Bagnarae4b92762012-01-27 09:46:47 +00001731 return ActOnDependentIdExpression(SS, TemplateKWLoc, NameInfo,
1732 IsAddressOfOperand, TemplateArgs);
John McCallf7a1a742009-11-24 19:00:30 +00001733 } else {
Benjamin Kramerb7ff74a2012-01-20 14:57:34 +00001734 bool IvarLookupFollowUp = II && !SS.isSet() && getCurMethodDecl();
Fariborz Jahanian48c2d562010-01-12 23:58:59 +00001735 LookupParsedName(R, S, &SS, !IvarLookupFollowUp);
Mike Stump1eb44332009-09-09 15:08:12 +00001736
Douglas Gregor2f9f89c2011-02-04 13:35:07 +00001737 // If the result might be in a dependent base class, this is a dependent
1738 // id-expression.
1739 if (R.getResultKind() == LookupResult::NotFoundInCurrentInstantiation)
Abramo Bagnarae4b92762012-01-27 09:46:47 +00001740 return ActOnDependentIdExpression(SS, TemplateKWLoc, NameInfo,
1741 IsAddressOfOperand, TemplateArgs);
1742
John McCallf7a1a742009-11-24 19:00:30 +00001743 // If this reference is in an Objective-C method, then we need to do
1744 // some special Objective-C lookup, too.
Fariborz Jahanian48c2d562010-01-12 23:58:59 +00001745 if (IvarLookupFollowUp) {
John McCall60d7b3a2010-08-24 06:29:42 +00001746 ExprResult E(LookupInObjCMethod(R, S, II, true));
John McCallf7a1a742009-11-24 19:00:30 +00001747 if (E.isInvalid())
1748 return ExprError();
Mike Stump1eb44332009-09-09 15:08:12 +00001749
Chris Lattner337e5502011-02-18 01:27:55 +00001750 if (Expr *Ex = E.takeAs<Expr>())
1751 return Owned(Ex);
Steve Naroffe3e9add2008-06-02 23:03:37 +00001752 }
Chris Lattner8a934232008-03-31 00:36:02 +00001753 }
Douglas Gregorc71e28c2009-02-16 19:28:42 +00001754
John McCallf7a1a742009-11-24 19:00:30 +00001755 if (R.isAmbiguous())
1756 return ExprError();
1757
Douglas Gregor48f3bb92009-02-18 21:56:37 +00001758 // Determine whether this name might be a candidate for
1759 // argument-dependent lookup.
John McCallf7a1a742009-11-24 19:00:30 +00001760 bool ADL = UseArgumentDependentLookup(SS, R, HasTrailingLParen);
Douglas Gregor48f3bb92009-02-18 21:56:37 +00001761
John McCallf7a1a742009-11-24 19:00:30 +00001762 if (R.empty() && !ADL) {
Reid Spencer5f016e22007-07-11 17:01:13 +00001763 // Otherwise, this could be an implicitly declared function reference (legal
John McCallf7a1a742009-11-24 19:00:30 +00001764 // in C90, extension in C99, forbidden in C++).
David Blaikie4e4d0842012-03-11 07:00:24 +00001765 if (HasTrailingLParen && II && !getLangOpts().CPlusPlus) {
John McCallf7a1a742009-11-24 19:00:30 +00001766 NamedDecl *D = ImplicitlyDefineFunction(NameLoc, *II, S);
1767 if (D) R.addDecl(D);
1768 }
1769
1770 // If this name wasn't predeclared and if this is not a function
1771 // call, diagnose the problem.
1772 if (R.empty()) {
Francois Pichetfce1a3a2011-09-24 10:38:05 +00001773
1774 // In Microsoft mode, if we are inside a template class member function
1775 // and we can't resolve an identifier then assume the identifier is type
1776 // dependent. The goal is to postpone name lookup to instantiation time
1777 // to be able to search into type dependent base classes.
David Blaikie4e4d0842012-03-11 07:00:24 +00001778 if (getLangOpts().MicrosoftMode && CurContext->isDependentContext() &&
Francois Pichetfce1a3a2011-09-24 10:38:05 +00001779 isa<CXXMethodDecl>(CurContext))
Abramo Bagnarae4b92762012-01-27 09:46:47 +00001780 return ActOnDependentIdExpression(SS, TemplateKWLoc, NameInfo,
1781 IsAddressOfOperand, TemplateArgs);
Francois Pichetfce1a3a2011-09-24 10:38:05 +00001782
Kaelyn Uhrain4798f8d2012-01-18 05:58:54 +00001783 CorrectionCandidateCallback DefaultValidator;
Kaelyn Uhraincd78e612012-01-25 20:49:08 +00001784 if (DiagnoseEmptyLookup(S, SS, R, CCC ? *CCC : DefaultValidator))
John McCall578b69b2009-12-16 08:11:27 +00001785 return ExprError();
1786
1787 assert(!R.empty() &&
1788 "DiagnoseEmptyLookup returned false but added no results");
Douglas Gregorf06cdae2010-01-03 18:01:57 +00001789
1790 // If we found an Objective-C instance variable, let
1791 // LookupInObjCMethod build the appropriate expression to
Kovarththanan Rajaratnam19357542010-03-13 10:17:05 +00001792 // reference the ivar.
Douglas Gregorf06cdae2010-01-03 18:01:57 +00001793 if (ObjCIvarDecl *Ivar = R.getAsSingle<ObjCIvarDecl>()) {
1794 R.clear();
John McCall60d7b3a2010-08-24 06:29:42 +00001795 ExprResult E(LookupInObjCMethod(R, S, Ivar->getIdentifier()));
Fariborz Jahanianbc2b91a2011-09-23 23:11:38 +00001796 // In a hopelessly buggy code, Objective-C instance variable
1797 // lookup fails and no expression will be built to reference it.
1798 if (!E.isInvalid() && !E.get())
1799 return ExprError();
Benjamin Kramer3fe198b2012-08-23 21:35:17 +00001800 return E;
Douglas Gregorf06cdae2010-01-03 18:01:57 +00001801 }
Reid Spencer5f016e22007-07-11 17:01:13 +00001802 }
1803 }
Mike Stump1eb44332009-09-09 15:08:12 +00001804
John McCallf7a1a742009-11-24 19:00:30 +00001805 // This is guaranteed from this point on.
1806 assert(!R.empty() || ADL);
1807
John McCallaa81e162009-12-01 22:10:20 +00001808 // Check whether this might be a C++ implicit instance member access.
John McCallfb97e752010-08-24 22:52:39 +00001809 // C++ [class.mfct.non-static]p3:
1810 // When an id-expression that is not part of a class member access
1811 // syntax and not used to form a pointer to member is used in the
1812 // body of a non-static member function of class X, if name lookup
1813 // resolves the name in the id-expression to a non-static non-type
1814 // member of some class C, the id-expression is transformed into a
1815 // class member access expression using (*this) as the
1816 // postfix-expression to the left of the . operator.
John McCall9c72c602010-08-27 09:08:28 +00001817 //
1818 // But we don't actually need to do this for '&' operands if R
1819 // resolved to a function or overloaded function set, because the
1820 // expression is ill-formed if it actually works out to be a
1821 // non-static member function:
1822 //
1823 // C++ [expr.ref]p4:
1824 // Otherwise, if E1.E2 refers to a non-static member function. . .
1825 // [t]he expression can be used only as the left-hand operand of a
1826 // member function call.
1827 //
1828 // There are other safeguards against such uses, but it's important
1829 // to get this right here so that we don't end up making a
1830 // spuriously dependent expression if we're inside a dependent
1831 // instance method.
John McCall3b4294e2009-12-16 12:17:52 +00001832 if (!R.empty() && (*R.begin())->isCXXClassMember()) {
John McCall9c72c602010-08-27 09:08:28 +00001833 bool MightBeImplicitMember;
Richard Trieuccd891a2011-09-09 01:45:06 +00001834 if (!IsAddressOfOperand)
John McCall9c72c602010-08-27 09:08:28 +00001835 MightBeImplicitMember = true;
1836 else if (!SS.isEmpty())
1837 MightBeImplicitMember = false;
1838 else if (R.isOverloadedResult())
1839 MightBeImplicitMember = false;
Douglas Gregore2248be2010-08-30 16:00:47 +00001840 else if (R.isUnresolvableResult())
1841 MightBeImplicitMember = true;
John McCall9c72c602010-08-27 09:08:28 +00001842 else
Francois Pichet87c2e122010-11-21 06:08:52 +00001843 MightBeImplicitMember = isa<FieldDecl>(R.getFoundDecl()) ||
1844 isa<IndirectFieldDecl>(R.getFoundDecl());
John McCall9c72c602010-08-27 09:08:28 +00001845
1846 if (MightBeImplicitMember)
Abramo Bagnarae4b92762012-01-27 09:46:47 +00001847 return BuildPossibleImplicitMemberExpr(SS, TemplateKWLoc,
1848 R, TemplateArgs);
John McCall5b3f9132009-11-22 01:44:31 +00001849 }
1850
Abramo Bagnara9d9922a2012-02-06 14:31:00 +00001851 if (TemplateArgs || TemplateKWLoc.isValid())
1852 return BuildTemplateIdExpr(SS, TemplateKWLoc, R, ADL, TemplateArgs);
John McCall5b3f9132009-11-22 01:44:31 +00001853
John McCallf7a1a742009-11-24 19:00:30 +00001854 return BuildDeclarationNameExpr(SS, R, ADL);
1855}
1856
John McCall129e2df2009-11-30 22:42:35 +00001857/// BuildQualifiedDeclarationNameExpr - Build a C++ qualified
1858/// declaration name, generally during template instantiation.
1859/// There's a large number of things which don't need to be done along
1860/// this path.
John McCall60d7b3a2010-08-24 06:29:42 +00001861ExprResult
Jeffrey Yasskin9ab14542010-04-08 16:38:48 +00001862Sema::BuildQualifiedDeclarationNameExpr(CXXScopeSpec &SS,
Abramo Bagnara25777432010-08-11 22:01:17 +00001863 const DeclarationNameInfo &NameInfo) {
John McCallf7a1a742009-11-24 19:00:30 +00001864 DeclContext *DC;
Douglas Gregore6ec5c42010-04-28 07:04:26 +00001865 if (!(DC = computeDeclContext(SS, false)) || DC->isDependentContext())
Abramo Bagnara9d9922a2012-02-06 14:31:00 +00001866 return BuildDependentDeclRefExpr(SS, /*TemplateKWLoc=*/SourceLocation(),
1867 NameInfo, /*TemplateArgs=*/0);
John McCallf7a1a742009-11-24 19:00:30 +00001868
John McCall77bb1aa2010-05-01 00:40:08 +00001869 if (RequireCompleteDeclContext(SS, DC))
Douglas Gregore6ec5c42010-04-28 07:04:26 +00001870 return ExprError();
1871
Abramo Bagnara25777432010-08-11 22:01:17 +00001872 LookupResult R(*this, NameInfo, LookupOrdinaryName);
John McCallf7a1a742009-11-24 19:00:30 +00001873 LookupQualifiedName(R, DC);
1874
1875 if (R.isAmbiguous())
1876 return ExprError();
1877
1878 if (R.empty()) {
Abramo Bagnara25777432010-08-11 22:01:17 +00001879 Diag(NameInfo.getLoc(), diag::err_no_member)
1880 << NameInfo.getName() << DC << SS.getRange();
John McCallf7a1a742009-11-24 19:00:30 +00001881 return ExprError();
1882 }
1883
1884 return BuildDeclarationNameExpr(SS, R, /*ADL*/ false);
1885}
1886
1887/// LookupInObjCMethod - The parser has read a name in, and Sema has
1888/// detected that we're currently inside an ObjC method. Perform some
1889/// additional lookup.
1890///
1891/// Ideally, most of this would be done by lookup, but there's
1892/// actually quite a lot of extra work involved.
1893///
1894/// Returns a null sentinel to indicate trivial success.
John McCall60d7b3a2010-08-24 06:29:42 +00001895ExprResult
John McCallf7a1a742009-11-24 19:00:30 +00001896Sema::LookupInObjCMethod(LookupResult &Lookup, Scope *S,
Chris Lattnereb483eb2010-04-11 08:28:14 +00001897 IdentifierInfo *II, bool AllowBuiltinCreation) {
John McCallf7a1a742009-11-24 19:00:30 +00001898 SourceLocation Loc = Lookup.getNameLoc();
Chris Lattneraec43db2010-04-12 05:10:17 +00001899 ObjCMethodDecl *CurMethod = getCurMethodDecl();
Sean Hunt1e3f5ba2010-04-28 23:02:27 +00001900
John McCallf7a1a742009-11-24 19:00:30 +00001901 // There are two cases to handle here. 1) scoped lookup could have failed,
1902 // in which case we should look for an ivar. 2) scoped lookup could have
1903 // found a decl, but that decl is outside the current instance method (i.e.
1904 // a global variable). In these two cases, we do a lookup for an ivar with
1905 // this name, if the lookup sucedes, we replace it our current decl.
1906
1907 // If we're in a class method, we don't normally want to look for
1908 // ivars. But if we don't find anything else, and there's an
1909 // ivar, that's an error.
Chris Lattneraec43db2010-04-12 05:10:17 +00001910 bool IsClassMethod = CurMethod->isClassMethod();
John McCallf7a1a742009-11-24 19:00:30 +00001911
1912 bool LookForIvars;
1913 if (Lookup.empty())
1914 LookForIvars = true;
1915 else if (IsClassMethod)
1916 LookForIvars = false;
1917 else
1918 LookForIvars = (Lookup.isSingleResult() &&
1919 Lookup.getFoundDecl()->isDefinedOutsideFunctionOrMethod());
Fariborz Jahanian412e7982010-02-09 19:31:38 +00001920 ObjCInterfaceDecl *IFace = 0;
John McCallf7a1a742009-11-24 19:00:30 +00001921 if (LookForIvars) {
Chris Lattneraec43db2010-04-12 05:10:17 +00001922 IFace = CurMethod->getClassInterface();
John McCallf7a1a742009-11-24 19:00:30 +00001923 ObjCInterfaceDecl *ClassDeclared;
Argyrios Kyrtzidis7c81c2a2011-10-19 02:25:16 +00001924 ObjCIvarDecl *IV = 0;
1925 if (IFace && (IV = IFace->lookupInstanceVariable(II, ClassDeclared))) {
John McCallf7a1a742009-11-24 19:00:30 +00001926 // Diagnose using an ivar in a class method.
1927 if (IsClassMethod)
1928 return ExprError(Diag(Loc, diag::error_ivar_use_in_class_method)
1929 << IV->getDeclName());
1930
1931 // If we're referencing an invalid decl, just return this as a silent
1932 // error node. The error diagnostic was already emitted on the decl.
1933 if (IV->isInvalidDecl())
1934 return ExprError();
1935
1936 // Check if referencing a field with __attribute__((deprecated)).
1937 if (DiagnoseUseOfDecl(IV, Loc))
1938 return ExprError();
1939
1940 // Diagnose the use of an ivar outside of the declaring class.
1941 if (IV->getAccessControl() == ObjCIvarDecl::Private &&
Fariborz Jahanian458a7fb2012-03-07 00:58:41 +00001942 !declaresSameEntity(ClassDeclared, IFace) &&
David Blaikie4e4d0842012-03-11 07:00:24 +00001943 !getLangOpts().DebuggerSupport)
John McCallf7a1a742009-11-24 19:00:30 +00001944 Diag(Loc, diag::error_private_ivar_access) << IV->getDeclName();
1945
1946 // FIXME: This should use a new expr for a direct reference, don't
1947 // turn this into Self->ivar, just return a BareIVarExpr or something.
1948 IdentifierInfo &II = Context.Idents.get("self");
1949 UnqualifiedId SelfName;
Kovarththanan Rajaratnam19357542010-03-13 10:17:05 +00001950 SelfName.setIdentifier(&II, SourceLocation());
Fariborz Jahanian98a54032011-07-12 17:16:56 +00001951 SelfName.setKind(UnqualifiedId::IK_ImplicitSelfParam);
John McCallf7a1a742009-11-24 19:00:30 +00001952 CXXScopeSpec SelfScopeSpec;
Abramo Bagnarae4b92762012-01-27 09:46:47 +00001953 SourceLocation TemplateKWLoc;
1954 ExprResult SelfExpr = ActOnIdExpression(S, SelfScopeSpec, TemplateKWLoc,
Douglas Gregore45bb6a2010-09-22 16:33:13 +00001955 SelfName, false, false);
1956 if (SelfExpr.isInvalid())
1957 return ExprError();
1958
John Wiegley429bb272011-04-08 18:41:53 +00001959 SelfExpr = DefaultLvalueConversion(SelfExpr.take());
1960 if (SelfExpr.isInvalid())
1961 return ExprError();
John McCall409fa9a2010-12-06 20:48:59 +00001962
Eli Friedman5f2987c2012-02-02 03:46:19 +00001963 MarkAnyDeclReferenced(Loc, IV);
Fariborz Jahanianed6662d2012-08-08 16:41:04 +00001964
1965 ObjCMethodFamily MF = CurMethod->getMethodFamily();
1966 if (MF != OMF_init && MF != OMF_dealloc && MF != OMF_finalize)
1967 Diag(Loc, diag::warn_direct_ivar_access) << IV->getDeclName();
John McCallf7a1a742009-11-24 19:00:30 +00001968 return Owned(new (Context)
1969 ObjCIvarRefExpr(IV, IV->getType(), Loc,
John Wiegley429bb272011-04-08 18:41:53 +00001970 SelfExpr.take(), true, true));
John McCallf7a1a742009-11-24 19:00:30 +00001971 }
Chris Lattneraec43db2010-04-12 05:10:17 +00001972 } else if (CurMethod->isInstanceMethod()) {
John McCallf7a1a742009-11-24 19:00:30 +00001973 // We should warn if a local variable hides an ivar.
Fariborz Jahanian90f7b622011-11-08 22:51:27 +00001974 if (ObjCInterfaceDecl *IFace = CurMethod->getClassInterface()) {
1975 ObjCInterfaceDecl *ClassDeclared;
1976 if (ObjCIvarDecl *IV = IFace->lookupInstanceVariable(II, ClassDeclared)) {
1977 if (IV->getAccessControl() != ObjCIvarDecl::Private ||
Douglas Gregor60ef3082011-12-15 00:29:59 +00001978 declaresSameEntity(IFace, ClassDeclared))
Fariborz Jahanian90f7b622011-11-08 22:51:27 +00001979 Diag(Loc, diag::warn_ivar_use_hidden) << IV->getDeclName();
1980 }
John McCallf7a1a742009-11-24 19:00:30 +00001981 }
Fariborz Jahanianb5ea9db2011-12-20 22:21:08 +00001982 } else if (Lookup.isSingleResult() &&
1983 Lookup.getFoundDecl()->isDefinedOutsideFunctionOrMethod()) {
1984 // If accessing a stand-alone ivar in a class method, this is an error.
1985 if (const ObjCIvarDecl *IV = dyn_cast<ObjCIvarDecl>(Lookup.getFoundDecl()))
1986 return ExprError(Diag(Loc, diag::error_ivar_use_in_class_method)
1987 << IV->getDeclName());
John McCallf7a1a742009-11-24 19:00:30 +00001988 }
1989
Fariborz Jahanian48c2d562010-01-12 23:58:59 +00001990 if (Lookup.empty() && II && AllowBuiltinCreation) {
1991 // FIXME. Consolidate this with similar code in LookupName.
1992 if (unsigned BuiltinID = II->getBuiltinID()) {
David Blaikie4e4d0842012-03-11 07:00:24 +00001993 if (!(getLangOpts().CPlusPlus &&
Fariborz Jahanian48c2d562010-01-12 23:58:59 +00001994 Context.BuiltinInfo.isPredefinedLibFunction(BuiltinID))) {
1995 NamedDecl *D = LazilyCreateBuiltin((IdentifierInfo *)II, BuiltinID,
1996 S, Lookup.isForRedeclaration(),
1997 Lookup.getNameLoc());
1998 if (D) Lookup.addDecl(D);
1999 }
2000 }
2001 }
John McCallf7a1a742009-11-24 19:00:30 +00002002 // Sentinel value saying that we didn't do anything special.
2003 return Owned((Expr*) 0);
Douglas Gregor751f9a42009-06-30 15:47:41 +00002004}
John McCallba135432009-11-21 08:51:07 +00002005
John McCall6bb80172010-03-30 21:47:33 +00002006/// \brief Cast a base object to a member's actual type.
2007///
2008/// Logically this happens in three phases:
2009///
2010/// * First we cast from the base type to the naming class.
2011/// The naming class is the class into which we were looking
2012/// when we found the member; it's the qualifier type if a
2013/// qualifier was provided, and otherwise it's the base type.
2014///
2015/// * Next we cast from the naming class to the declaring class.
2016/// If the member we found was brought into a class's scope by
2017/// a using declaration, this is that class; otherwise it's
2018/// the class declaring the member.
2019///
2020/// * Finally we cast from the declaring class to the "true"
2021/// declaring class of the member. This conversion does not
2022/// obey access control.
John Wiegley429bb272011-04-08 18:41:53 +00002023ExprResult
2024Sema::PerformObjectMemberConversion(Expr *From,
Douglas Gregor5fccd362010-03-03 23:55:11 +00002025 NestedNameSpecifier *Qualifier,
John McCall6bb80172010-03-30 21:47:33 +00002026 NamedDecl *FoundDecl,
Douglas Gregor5fccd362010-03-03 23:55:11 +00002027 NamedDecl *Member) {
2028 CXXRecordDecl *RD = dyn_cast<CXXRecordDecl>(Member->getDeclContext());
2029 if (!RD)
John Wiegley429bb272011-04-08 18:41:53 +00002030 return Owned(From);
Kovarththanan Rajaratnam19357542010-03-13 10:17:05 +00002031
Douglas Gregor5fccd362010-03-03 23:55:11 +00002032 QualType DestRecordType;
2033 QualType DestType;
2034 QualType FromRecordType;
2035 QualType FromType = From->getType();
2036 bool PointerConversions = false;
2037 if (isa<FieldDecl>(Member)) {
2038 DestRecordType = Context.getCanonicalType(Context.getTypeDeclType(RD));
Kovarththanan Rajaratnam19357542010-03-13 10:17:05 +00002039
Douglas Gregor5fccd362010-03-03 23:55:11 +00002040 if (FromType->getAs<PointerType>()) {
2041 DestType = Context.getPointerType(DestRecordType);
2042 FromRecordType = FromType->getPointeeType();
2043 PointerConversions = true;
2044 } else {
2045 DestType = DestRecordType;
2046 FromRecordType = FromType;
Fariborz Jahanian98a541e2009-07-29 18:40:24 +00002047 }
Douglas Gregor5fccd362010-03-03 23:55:11 +00002048 } else if (CXXMethodDecl *Method = dyn_cast<CXXMethodDecl>(Member)) {
2049 if (Method->isStatic())
John Wiegley429bb272011-04-08 18:41:53 +00002050 return Owned(From);
Kovarththanan Rajaratnam19357542010-03-13 10:17:05 +00002051
Douglas Gregor5fccd362010-03-03 23:55:11 +00002052 DestType = Method->getThisType(Context);
2053 DestRecordType = DestType->getPointeeType();
Kovarththanan Rajaratnam19357542010-03-13 10:17:05 +00002054
Douglas Gregor5fccd362010-03-03 23:55:11 +00002055 if (FromType->getAs<PointerType>()) {
2056 FromRecordType = FromType->getPointeeType();
2057 PointerConversions = true;
2058 } else {
2059 FromRecordType = FromType;
2060 DestType = DestRecordType;
2061 }
2062 } else {
2063 // No conversion necessary.
John Wiegley429bb272011-04-08 18:41:53 +00002064 return Owned(From);
Douglas Gregor5fccd362010-03-03 23:55:11 +00002065 }
Kovarththanan Rajaratnam19357542010-03-13 10:17:05 +00002066
Douglas Gregor5fccd362010-03-03 23:55:11 +00002067 if (DestType->isDependentType() || FromType->isDependentType())
John Wiegley429bb272011-04-08 18:41:53 +00002068 return Owned(From);
Kovarththanan Rajaratnam19357542010-03-13 10:17:05 +00002069
Douglas Gregor5fccd362010-03-03 23:55:11 +00002070 // If the unqualified types are the same, no conversion is necessary.
2071 if (Context.hasSameUnqualifiedType(FromRecordType, DestRecordType))
John Wiegley429bb272011-04-08 18:41:53 +00002072 return Owned(From);
Kovarththanan Rajaratnam19357542010-03-13 10:17:05 +00002073
John McCall6bb80172010-03-30 21:47:33 +00002074 SourceRange FromRange = From->getSourceRange();
2075 SourceLocation FromLoc = FromRange.getBegin();
2076
Eli Friedmanc1c0dfb2011-09-27 21:58:52 +00002077 ExprValueKind VK = From->getValueKind();
Sebastian Redl906082e2010-07-20 04:20:21 +00002078
Douglas Gregor5fccd362010-03-03 23:55:11 +00002079 // C++ [class.member.lookup]p8:
Kovarththanan Rajaratnam19357542010-03-13 10:17:05 +00002080 // [...] Ambiguities can often be resolved by qualifying a name with its
Douglas Gregor5fccd362010-03-03 23:55:11 +00002081 // class name.
2082 //
2083 // If the member was a qualified name and the qualified referred to a
2084 // specific base subobject type, we'll cast to that intermediate type
2085 // first and then to the object in which the member is declared. That allows
2086 // one to resolve ambiguities in, e.g., a diamond-shaped hierarchy such as:
2087 //
2088 // class Base { public: int x; };
2089 // class Derived1 : public Base { };
2090 // class Derived2 : public Base { };
2091 // class VeryDerived : public Derived1, public Derived2 { void f(); };
2092 //
2093 // void VeryDerived::f() {
2094 // x = 17; // error: ambiguous base subobjects
2095 // Derived1::x = 17; // okay, pick the Base subobject of Derived1
2096 // }
Douglas Gregor5fccd362010-03-03 23:55:11 +00002097 if (Qualifier) {
John McCall6bb80172010-03-30 21:47:33 +00002098 QualType QType = QualType(Qualifier->getAsType(), 0);
2099 assert(!QType.isNull() && "lookup done with dependent qualifier?");
2100 assert(QType->isRecordType() && "lookup done with non-record type");
2101
2102 QualType QRecordType = QualType(QType->getAs<RecordType>(), 0);
2103
2104 // In C++98, the qualifier type doesn't actually have to be a base
2105 // type of the object type, in which case we just ignore it.
2106 // Otherwise build the appropriate casts.
2107 if (IsDerivedFrom(FromRecordType, QRecordType)) {
John McCallf871d0c2010-08-07 06:22:56 +00002108 CXXCastPath BasePath;
John McCall6bb80172010-03-30 21:47:33 +00002109 if (CheckDerivedToBaseConversion(FromRecordType, QRecordType,
Anders Carlssoncee22422010-04-24 19:22:20 +00002110 FromLoc, FromRange, &BasePath))
John Wiegley429bb272011-04-08 18:41:53 +00002111 return ExprError();
John McCall6bb80172010-03-30 21:47:33 +00002112
Douglas Gregor5fccd362010-03-03 23:55:11 +00002113 if (PointerConversions)
John McCall6bb80172010-03-30 21:47:33 +00002114 QType = Context.getPointerType(QType);
John Wiegley429bb272011-04-08 18:41:53 +00002115 From = ImpCastExprToType(From, QType, CK_UncheckedDerivedToBase,
2116 VK, &BasePath).take();
John McCall6bb80172010-03-30 21:47:33 +00002117
2118 FromType = QType;
2119 FromRecordType = QRecordType;
2120
2121 // If the qualifier type was the same as the destination type,
2122 // we're done.
2123 if (Context.hasSameUnqualifiedType(FromRecordType, DestRecordType))
John Wiegley429bb272011-04-08 18:41:53 +00002124 return Owned(From);
Douglas Gregor5fccd362010-03-03 23:55:11 +00002125 }
2126 }
Kovarththanan Rajaratnam19357542010-03-13 10:17:05 +00002127
John McCall6bb80172010-03-30 21:47:33 +00002128 bool IgnoreAccess = false;
Douglas Gregor5fccd362010-03-03 23:55:11 +00002129
John McCall6bb80172010-03-30 21:47:33 +00002130 // If we actually found the member through a using declaration, cast
2131 // down to the using declaration's type.
2132 //
2133 // Pointer equality is fine here because only one declaration of a
2134 // class ever has member declarations.
2135 if (FoundDecl->getDeclContext() != Member->getDeclContext()) {
2136 assert(isa<UsingShadowDecl>(FoundDecl));
2137 QualType URecordType = Context.getTypeDeclType(
2138 cast<CXXRecordDecl>(FoundDecl->getDeclContext()));
2139
2140 // We only need to do this if the naming-class to declaring-class
2141 // conversion is non-trivial.
2142 if (!Context.hasSameUnqualifiedType(FromRecordType, URecordType)) {
2143 assert(IsDerivedFrom(FromRecordType, URecordType));
John McCallf871d0c2010-08-07 06:22:56 +00002144 CXXCastPath BasePath;
John McCall6bb80172010-03-30 21:47:33 +00002145 if (CheckDerivedToBaseConversion(FromRecordType, URecordType,
Anders Carlssoncee22422010-04-24 19:22:20 +00002146 FromLoc, FromRange, &BasePath))
John Wiegley429bb272011-04-08 18:41:53 +00002147 return ExprError();
Sean Hunt1e3f5ba2010-04-28 23:02:27 +00002148
John McCall6bb80172010-03-30 21:47:33 +00002149 QualType UType = URecordType;
2150 if (PointerConversions)
2151 UType = Context.getPointerType(UType);
John Wiegley429bb272011-04-08 18:41:53 +00002152 From = ImpCastExprToType(From, UType, CK_UncheckedDerivedToBase,
2153 VK, &BasePath).take();
John McCall6bb80172010-03-30 21:47:33 +00002154 FromType = UType;
2155 FromRecordType = URecordType;
2156 }
2157
2158 // We don't do access control for the conversion from the
2159 // declaring class to the true declaring class.
2160 IgnoreAccess = true;
Douglas Gregor5fccd362010-03-03 23:55:11 +00002161 }
Kovarththanan Rajaratnam19357542010-03-13 10:17:05 +00002162
John McCallf871d0c2010-08-07 06:22:56 +00002163 CXXCastPath BasePath;
Anders Carlssoncee22422010-04-24 19:22:20 +00002164 if (CheckDerivedToBaseConversion(FromRecordType, DestRecordType,
2165 FromLoc, FromRange, &BasePath,
John McCall6bb80172010-03-30 21:47:33 +00002166 IgnoreAccess))
John Wiegley429bb272011-04-08 18:41:53 +00002167 return ExprError();
Kovarththanan Rajaratnam19357542010-03-13 10:17:05 +00002168
John Wiegley429bb272011-04-08 18:41:53 +00002169 return ImpCastExprToType(From, DestType, CK_UncheckedDerivedToBase,
2170 VK, &BasePath);
Fariborz Jahanian98a541e2009-07-29 18:40:24 +00002171}
Douglas Gregor751f9a42009-06-30 15:47:41 +00002172
John McCallf7a1a742009-11-24 19:00:30 +00002173bool Sema::UseArgumentDependentLookup(const CXXScopeSpec &SS,
John McCall5b3f9132009-11-22 01:44:31 +00002174 const LookupResult &R,
2175 bool HasTrailingLParen) {
John McCallba135432009-11-21 08:51:07 +00002176 // Only when used directly as the postfix-expression of a call.
2177 if (!HasTrailingLParen)
2178 return false;
2179
2180 // Never if a scope specifier was provided.
John McCallf7a1a742009-11-24 19:00:30 +00002181 if (SS.isSet())
John McCallba135432009-11-21 08:51:07 +00002182 return false;
2183
2184 // Only in C++ or ObjC++.
David Blaikie4e4d0842012-03-11 07:00:24 +00002185 if (!getLangOpts().CPlusPlus)
John McCallba135432009-11-21 08:51:07 +00002186 return false;
2187
2188 // Turn off ADL when we find certain kinds of declarations during
2189 // normal lookup:
2190 for (LookupResult::iterator I = R.begin(), E = R.end(); I != E; ++I) {
2191 NamedDecl *D = *I;
2192
2193 // C++0x [basic.lookup.argdep]p3:
2194 // -- a declaration of a class member
2195 // Since using decls preserve this property, we check this on the
2196 // original decl.
John McCall3b4294e2009-12-16 12:17:52 +00002197 if (D->isCXXClassMember())
John McCallba135432009-11-21 08:51:07 +00002198 return false;
2199
2200 // C++0x [basic.lookup.argdep]p3:
2201 // -- a block-scope function declaration that is not a
2202 // using-declaration
2203 // NOTE: we also trigger this for function templates (in fact, we
2204 // don't check the decl type at all, since all other decl types
2205 // turn off ADL anyway).
2206 if (isa<UsingShadowDecl>(D))
2207 D = cast<UsingShadowDecl>(D)->getTargetDecl();
2208 else if (D->getDeclContext()->isFunctionOrMethod())
2209 return false;
2210
2211 // C++0x [basic.lookup.argdep]p3:
2212 // -- a declaration that is neither a function or a function
2213 // template
2214 // And also for builtin functions.
2215 if (isa<FunctionDecl>(D)) {
2216 FunctionDecl *FDecl = cast<FunctionDecl>(D);
2217
2218 // But also builtin functions.
2219 if (FDecl->getBuiltinID() && FDecl->isImplicit())
2220 return false;
2221 } else if (!isa<FunctionTemplateDecl>(D))
2222 return false;
2223 }
2224
2225 return true;
2226}
2227
2228
John McCallba135432009-11-21 08:51:07 +00002229/// Diagnoses obvious problems with the use of the given declaration
2230/// as an expression. This is only actually called for lookups that
2231/// were not overloaded, and it doesn't promise that the declaration
2232/// will in fact be used.
2233static bool CheckDeclInExpr(Sema &S, SourceLocation Loc, NamedDecl *D) {
Richard Smith162e1c12011-04-15 14:24:37 +00002234 if (isa<TypedefNameDecl>(D)) {
John McCallba135432009-11-21 08:51:07 +00002235 S.Diag(Loc, diag::err_unexpected_typedef) << D->getDeclName();
2236 return true;
2237 }
2238
2239 if (isa<ObjCInterfaceDecl>(D)) {
2240 S.Diag(Loc, diag::err_unexpected_interface) << D->getDeclName();
2241 return true;
2242 }
2243
2244 if (isa<NamespaceDecl>(D)) {
2245 S.Diag(Loc, diag::err_unexpected_namespace) << D->getDeclName();
2246 return true;
2247 }
2248
2249 return false;
2250}
2251
John McCall60d7b3a2010-08-24 06:29:42 +00002252ExprResult
John McCallf7a1a742009-11-24 19:00:30 +00002253Sema::BuildDeclarationNameExpr(const CXXScopeSpec &SS,
John McCall5b3f9132009-11-22 01:44:31 +00002254 LookupResult &R,
2255 bool NeedsADL) {
John McCallfead20c2009-12-08 22:45:53 +00002256 // If this is a single, fully-resolved result and we don't need ADL,
2257 // just build an ordinary singleton decl ref.
Douglas Gregor86b8e092010-01-29 17:15:43 +00002258 if (!NeedsADL && R.isSingleResult() && !R.getAsSingle<FunctionTemplateDecl>())
Abramo Bagnara25777432010-08-11 22:01:17 +00002259 return BuildDeclarationNameExpr(SS, R.getLookupNameInfo(),
2260 R.getFoundDecl());
John McCallba135432009-11-21 08:51:07 +00002261
2262 // We only need to check the declaration if there's exactly one
2263 // result, because in the overloaded case the results can only be
2264 // functions and function templates.
John McCall5b3f9132009-11-22 01:44:31 +00002265 if (R.isSingleResult() &&
2266 CheckDeclInExpr(*this, R.getNameLoc(), R.getFoundDecl()))
John McCallba135432009-11-21 08:51:07 +00002267 return ExprError();
2268
John McCallc373d482010-01-27 01:50:18 +00002269 // Otherwise, just build an unresolved lookup expression. Suppress
2270 // any lookup-related diagnostics; we'll hash these out later, when
2271 // we've picked a target.
2272 R.suppressDiagnostics();
2273
John McCallba135432009-11-21 08:51:07 +00002274 UnresolvedLookupExpr *ULE
Douglas Gregorbebbe0d2010-12-15 01:34:56 +00002275 = UnresolvedLookupExpr::Create(Context, R.getNamingClass(),
Douglas Gregor4c9be892011-02-28 20:01:57 +00002276 SS.getWithLocInContext(Context),
2277 R.getLookupNameInfo(),
Douglas Gregor5a84dec2010-05-23 18:57:34 +00002278 NeedsADL, R.isOverloadedResult(),
2279 R.begin(), R.end());
John McCallba135432009-11-21 08:51:07 +00002280
2281 return Owned(ULE);
2282}
Kovarththanan Rajaratnam19357542010-03-13 10:17:05 +00002283
John McCallba135432009-11-21 08:51:07 +00002284/// \brief Complete semantic analysis for a reference to the given declaration.
John McCall60d7b3a2010-08-24 06:29:42 +00002285ExprResult
John McCallf7a1a742009-11-24 19:00:30 +00002286Sema::BuildDeclarationNameExpr(const CXXScopeSpec &SS,
Abramo Bagnara25777432010-08-11 22:01:17 +00002287 const DeclarationNameInfo &NameInfo,
2288 NamedDecl *D) {
John McCallba135432009-11-21 08:51:07 +00002289 assert(D && "Cannot refer to a NULL declaration");
John McCall7453ed42009-11-22 00:44:51 +00002290 assert(!isa<FunctionTemplateDecl>(D) &&
2291 "Cannot refer unambiguously to a function template");
John McCallba135432009-11-21 08:51:07 +00002292
Abramo Bagnara25777432010-08-11 22:01:17 +00002293 SourceLocation Loc = NameInfo.getLoc();
John McCallba135432009-11-21 08:51:07 +00002294 if (CheckDeclInExpr(*this, Loc, D))
2295 return ExprError();
Reid Spencer5f016e22007-07-11 17:01:13 +00002296
Douglas Gregor9af2f522009-12-01 16:58:18 +00002297 if (TemplateDecl *Template = dyn_cast<TemplateDecl>(D)) {
2298 // Specifically diagnose references to class templates that are missing
2299 // a template argument list.
2300 Diag(Loc, diag::err_template_decl_ref)
2301 << Template << SS.getRange();
2302 Diag(Template->getLocation(), diag::note_template_decl_here);
2303 return ExprError();
2304 }
2305
2306 // Make sure that we're referring to a value.
2307 ValueDecl *VD = dyn_cast<ValueDecl>(D);
2308 if (!VD) {
Kovarththanan Rajaratnam19357542010-03-13 10:17:05 +00002309 Diag(Loc, diag::err_ref_non_value)
Douglas Gregor9af2f522009-12-01 16:58:18 +00002310 << D << SS.getRange();
John McCall87cf6702009-12-18 18:35:10 +00002311 Diag(D->getLocation(), diag::note_declared_at);
Douglas Gregor9af2f522009-12-01 16:58:18 +00002312 return ExprError();
2313 }
Sebastian Redlcd965b92009-01-18 18:53:16 +00002314
Douglas Gregor48f3bb92009-02-18 21:56:37 +00002315 // Check whether this declaration can be used. Note that we suppress
2316 // this check when we're going to perform argument-dependent lookup
2317 // on this function name, because this might not be the function
2318 // that overload resolution actually selects.
John McCallba135432009-11-21 08:51:07 +00002319 if (DiagnoseUseOfDecl(VD, Loc))
Douglas Gregor48f3bb92009-02-18 21:56:37 +00002320 return ExprError();
2321
Steve Naroffdd972f22008-09-05 22:11:13 +00002322 // Only create DeclRefExpr's for valid Decl's.
2323 if (VD->isInvalidDecl())
Sebastian Redlcd965b92009-01-18 18:53:16 +00002324 return ExprError();
2325
John McCall5808ce42011-02-03 08:15:49 +00002326 // Handle members of anonymous structs and unions. If we got here,
2327 // and the reference is to a class member indirect field, then this
2328 // must be the subject of a pointer-to-member expression.
2329 if (IndirectFieldDecl *indirectField = dyn_cast<IndirectFieldDecl>(VD))
2330 if (!indirectField->isCXXClassMember())
2331 return BuildAnonymousStructUnionMemberReference(SS, NameInfo.getLoc(),
2332 indirectField);
Francois Pichet87c2e122010-11-21 06:08:52 +00002333
Eli Friedman3c0e80e2012-02-03 02:04:35 +00002334 {
John McCall76a40212011-02-09 01:13:10 +00002335 QualType type = VD->getType();
Daniel Dunbarb20de812011-02-10 18:29:28 +00002336 ExprValueKind valueKind = VK_RValue;
John McCall76a40212011-02-09 01:13:10 +00002337
2338 switch (D->getKind()) {
2339 // Ignore all the non-ValueDecl kinds.
2340#define ABSTRACT_DECL(kind)
2341#define VALUE(type, base)
2342#define DECL(type, base) \
2343 case Decl::type:
2344#include "clang/AST/DeclNodes.inc"
2345 llvm_unreachable("invalid value decl kind");
John McCall76a40212011-02-09 01:13:10 +00002346
2347 // These shouldn't make it here.
2348 case Decl::ObjCAtDefsField:
2349 case Decl::ObjCIvar:
2350 llvm_unreachable("forming non-member reference to ivar?");
John McCall76a40212011-02-09 01:13:10 +00002351
2352 // Enum constants are always r-values and never references.
2353 // Unresolved using declarations are dependent.
2354 case Decl::EnumConstant:
2355 case Decl::UnresolvedUsingValue:
2356 valueKind = VK_RValue;
2357 break;
2358
2359 // Fields and indirect fields that got here must be for
2360 // pointer-to-member expressions; we just call them l-values for
2361 // internal consistency, because this subexpression doesn't really
2362 // exist in the high-level semantics.
2363 case Decl::Field:
2364 case Decl::IndirectField:
David Blaikie4e4d0842012-03-11 07:00:24 +00002365 assert(getLangOpts().CPlusPlus &&
John McCall76a40212011-02-09 01:13:10 +00002366 "building reference to field in C?");
2367
2368 // These can't have reference type in well-formed programs, but
2369 // for internal consistency we do this anyway.
2370 type = type.getNonReferenceType();
2371 valueKind = VK_LValue;
2372 break;
2373
2374 // Non-type template parameters are either l-values or r-values
2375 // depending on the type.
2376 case Decl::NonTypeTemplateParm: {
2377 if (const ReferenceType *reftype = type->getAs<ReferenceType>()) {
2378 type = reftype->getPointeeType();
2379 valueKind = VK_LValue; // even if the parameter is an r-value reference
2380 break;
2381 }
2382
2383 // For non-references, we need to strip qualifiers just in case
2384 // the template parameter was declared as 'const int' or whatever.
2385 valueKind = VK_RValue;
2386 type = type.getUnqualifiedType();
2387 break;
2388 }
2389
2390 case Decl::Var:
2391 // In C, "extern void blah;" is valid and is an r-value.
David Blaikie4e4d0842012-03-11 07:00:24 +00002392 if (!getLangOpts().CPlusPlus &&
John McCall76a40212011-02-09 01:13:10 +00002393 !type.hasQualifiers() &&
2394 type->isVoidType()) {
2395 valueKind = VK_RValue;
2396 break;
2397 }
2398 // fallthrough
2399
2400 case Decl::ImplicitParam:
Douglas Gregor68932842012-02-18 05:51:20 +00002401 case Decl::ParmVar: {
John McCall76a40212011-02-09 01:13:10 +00002402 // These are always l-values.
2403 valueKind = VK_LValue;
2404 type = type.getNonReferenceType();
Eli Friedman3c0e80e2012-02-03 02:04:35 +00002405
Douglas Gregor68932842012-02-18 05:51:20 +00002406 // FIXME: Does the addition of const really only apply in
2407 // potentially-evaluated contexts? Since the variable isn't actually
2408 // captured in an unevaluated context, it seems that the answer is no.
David Blaikie71f55f72012-08-06 22:47:24 +00002409 if (!isUnevaluatedContext()) {
Douglas Gregor68932842012-02-18 05:51:20 +00002410 QualType CapturedType = getCapturedDeclRefType(cast<VarDecl>(VD), Loc);
2411 if (!CapturedType.isNull())
2412 type = CapturedType;
2413 }
2414
John McCall76a40212011-02-09 01:13:10 +00002415 break;
Douglas Gregor68932842012-02-18 05:51:20 +00002416 }
2417
John McCall76a40212011-02-09 01:13:10 +00002418 case Decl::Function: {
Eli Friedmana6c66ce2012-08-31 00:14:07 +00002419 if (unsigned BID = cast<FunctionDecl>(VD)->getBuiltinID()) {
2420 if (!Context.BuiltinInfo.isPredefinedLibFunction(BID)) {
2421 type = Context.BuiltinFnTy;
2422 valueKind = VK_RValue;
2423 break;
2424 }
2425 }
2426
John McCall755d8492011-04-12 00:42:48 +00002427 const FunctionType *fty = type->castAs<FunctionType>();
2428
2429 // If we're referring to a function with an __unknown_anytype
2430 // result type, make the entire expression __unknown_anytype.
2431 if (fty->getResultType() == Context.UnknownAnyTy) {
2432 type = Context.UnknownAnyTy;
2433 valueKind = VK_RValue;
2434 break;
2435 }
2436
John McCall76a40212011-02-09 01:13:10 +00002437 // Functions are l-values in C++.
David Blaikie4e4d0842012-03-11 07:00:24 +00002438 if (getLangOpts().CPlusPlus) {
John McCall76a40212011-02-09 01:13:10 +00002439 valueKind = VK_LValue;
2440 break;
2441 }
2442
2443 // C99 DR 316 says that, if a function type comes from a
2444 // function definition (without a prototype), that type is only
2445 // used for checking compatibility. Therefore, when referencing
2446 // the function, we pretend that we don't have the full function
2447 // type.
John McCall755d8492011-04-12 00:42:48 +00002448 if (!cast<FunctionDecl>(VD)->hasPrototype() &&
2449 isa<FunctionProtoType>(fty))
2450 type = Context.getFunctionNoProtoType(fty->getResultType(),
2451 fty->getExtInfo());
John McCall76a40212011-02-09 01:13:10 +00002452
2453 // Functions are r-values in C.
2454 valueKind = VK_RValue;
2455 break;
2456 }
2457
2458 case Decl::CXXMethod:
John McCall755d8492011-04-12 00:42:48 +00002459 // If we're referring to a method with an __unknown_anytype
2460 // result type, make the entire expression __unknown_anytype.
2461 // This should only be possible with a type written directly.
Richard Trieu67e29332011-08-02 04:35:43 +00002462 if (const FunctionProtoType *proto
2463 = dyn_cast<FunctionProtoType>(VD->getType()))
John McCall755d8492011-04-12 00:42:48 +00002464 if (proto->getResultType() == Context.UnknownAnyTy) {
2465 type = Context.UnknownAnyTy;
2466 valueKind = VK_RValue;
2467 break;
2468 }
2469
John McCall76a40212011-02-09 01:13:10 +00002470 // C++ methods are l-values if static, r-values if non-static.
2471 if (cast<CXXMethodDecl>(VD)->isStatic()) {
2472 valueKind = VK_LValue;
2473 break;
2474 }
2475 // fallthrough
2476
2477 case Decl::CXXConversion:
2478 case Decl::CXXDestructor:
2479 case Decl::CXXConstructor:
2480 valueKind = VK_RValue;
2481 break;
2482 }
2483
2484 return BuildDeclRefExpr(VD, type, valueKind, NameInfo, &SS);
2485 }
Reid Spencer5f016e22007-07-11 17:01:13 +00002486}
2487
John McCall755d8492011-04-12 00:42:48 +00002488ExprResult Sema::ActOnPredefinedExpr(SourceLocation Loc, tok::TokenKind Kind) {
Chris Lattnerd9f69102008-08-10 01:53:14 +00002489 PredefinedExpr::IdentType IT;
Sebastian Redlcd965b92009-01-18 18:53:16 +00002490
Reid Spencer5f016e22007-07-11 17:01:13 +00002491 switch (Kind) {
David Blaikieb219cfc2011-09-23 05:06:16 +00002492 default: llvm_unreachable("Unknown simple primary expr!");
Chris Lattnerd9f69102008-08-10 01:53:14 +00002493 case tok::kw___func__: IT = PredefinedExpr::Func; break; // [C99 6.4.2.2]
2494 case tok::kw___FUNCTION__: IT = PredefinedExpr::Function; break;
Nico Weber28ad0632012-06-23 02:07:59 +00002495 case tok::kw_L__FUNCTION__: IT = PredefinedExpr::LFunction; break;
Chris Lattnerd9f69102008-08-10 01:53:14 +00002496 case tok::kw___PRETTY_FUNCTION__: IT = PredefinedExpr::PrettyFunction; break;
Reid Spencer5f016e22007-07-11 17:01:13 +00002497 }
Chris Lattner1423ea42008-01-12 18:39:25 +00002498
Chris Lattnerfa28b302008-01-12 08:14:25 +00002499 // Pre-defined identifiers are of type char[x], where x is the length of the
2500 // string.
Mike Stump1eb44332009-09-09 15:08:12 +00002501
Anders Carlsson3a082d82009-09-08 18:24:21 +00002502 Decl *currentDecl = getCurFunctionOrMethodDecl();
Fariborz Jahanianeb024ac2010-07-23 21:53:24 +00002503 if (!currentDecl && getCurBlock())
2504 currentDecl = getCurBlock()->TheDecl;
Anders Carlsson3a082d82009-09-08 18:24:21 +00002505 if (!currentDecl) {
Chris Lattnerb0da9232008-12-12 05:05:20 +00002506 Diag(Loc, diag::ext_predef_outside_function);
Anders Carlsson3a082d82009-09-08 18:24:21 +00002507 currentDecl = Context.getTranslationUnitDecl();
Chris Lattnerb0da9232008-12-12 05:05:20 +00002508 }
Sebastian Redlcd965b92009-01-18 18:53:16 +00002509
Anders Carlsson773f3972009-09-11 01:22:35 +00002510 QualType ResTy;
2511 if (cast<DeclContext>(currentDecl)->isDependentContext()) {
2512 ResTy = Context.DependentTy;
2513 } else {
Anders Carlsson848fa642010-02-11 18:20:28 +00002514 unsigned Length = PredefinedExpr::ComputeName(IT, currentDecl).length();
Sebastian Redlcd965b92009-01-18 18:53:16 +00002515
Anders Carlsson773f3972009-09-11 01:22:35 +00002516 llvm::APInt LengthI(32, Length + 1);
Nico Weberd68615f2012-06-29 16:39:58 +00002517 if (IT == PredefinedExpr::LFunction)
Nico Weber28ad0632012-06-23 02:07:59 +00002518 ResTy = Context.WCharTy.withConst();
2519 else
2520 ResTy = Context.CharTy.withConst();
Anders Carlsson773f3972009-09-11 01:22:35 +00002521 ResTy = Context.getConstantArrayType(ResTy, LengthI, ArrayType::Normal, 0);
2522 }
Steve Naroff6ece14c2009-01-21 00:14:39 +00002523 return Owned(new (Context) PredefinedExpr(Loc, ResTy, IT));
Reid Spencer5f016e22007-07-11 17:01:13 +00002524}
2525
Richard Smith36f5cfe2012-03-09 08:00:36 +00002526ExprResult Sema::ActOnCharacterConstant(const Token &Tok, Scope *UDLScope) {
Dylan Noblesmithf7ccbad2012-02-05 02:13:05 +00002527 SmallString<16> CharBuffer;
Douglas Gregor453091c2010-03-16 22:30:13 +00002528 bool Invalid = false;
Chris Lattner5f9e2722011-07-23 10:55:15 +00002529 StringRef ThisTok = PP.getSpelling(Tok, CharBuffer, &Invalid);
Douglas Gregor453091c2010-03-16 22:30:13 +00002530 if (Invalid)
2531 return ExprError();
Sebastian Redlcd965b92009-01-18 18:53:16 +00002532
Benjamin Kramerddeea562010-02-27 13:44:12 +00002533 CharLiteralParser Literal(ThisTok.begin(), ThisTok.end(), Tok.getLocation(),
Douglas Gregor5cee1192011-07-27 05:40:30 +00002534 PP, Tok.getKind());
Reid Spencer5f016e22007-07-11 17:01:13 +00002535 if (Literal.hadError())
Sebastian Redlcd965b92009-01-18 18:53:16 +00002536 return ExprError();
Chris Lattnerfc62bfd2008-03-01 08:32:21 +00002537
Chris Lattnere8337df2009-12-30 21:19:39 +00002538 QualType Ty;
Seth Cantrell79f0a822012-01-18 12:27:06 +00002539 if (Literal.isWide())
2540 Ty = Context.WCharTy; // L'x' -> wchar_t in C and C++.
Douglas Gregor5cee1192011-07-27 05:40:30 +00002541 else if (Literal.isUTF16())
Seth Cantrell79f0a822012-01-18 12:27:06 +00002542 Ty = Context.Char16Ty; // u'x' -> char16_t in C11 and C++11.
Douglas Gregor5cee1192011-07-27 05:40:30 +00002543 else if (Literal.isUTF32())
Seth Cantrell79f0a822012-01-18 12:27:06 +00002544 Ty = Context.Char32Ty; // U'x' -> char32_t in C11 and C++11.
David Blaikie4e4d0842012-03-11 07:00:24 +00002545 else if (!getLangOpts().CPlusPlus || Literal.isMultiChar())
Seth Cantrell79f0a822012-01-18 12:27:06 +00002546 Ty = Context.IntTy; // 'x' -> int in C, 'wxyz' -> int in C++.
Chris Lattnere8337df2009-12-30 21:19:39 +00002547 else
2548 Ty = Context.CharTy; // 'x' -> char in C++
Chris Lattnerfc62bfd2008-03-01 08:32:21 +00002549
Douglas Gregor5cee1192011-07-27 05:40:30 +00002550 CharacterLiteral::CharacterKind Kind = CharacterLiteral::Ascii;
2551 if (Literal.isWide())
2552 Kind = CharacterLiteral::Wide;
2553 else if (Literal.isUTF16())
2554 Kind = CharacterLiteral::UTF16;
2555 else if (Literal.isUTF32())
2556 Kind = CharacterLiteral::UTF32;
2557
Richard Smithdd66be72012-03-08 01:34:56 +00002558 Expr *Lit = new (Context) CharacterLiteral(Literal.getValue(), Kind, Ty,
2559 Tok.getLocation());
2560
2561 if (Literal.getUDSuffix().empty())
2562 return Owned(Lit);
2563
2564 // We're building a user-defined literal.
2565 IdentifierInfo *UDSuffix = &Context.Idents.get(Literal.getUDSuffix());
2566 SourceLocation UDSuffixLoc =
2567 getUDSuffixLoc(*this, Tok.getLocation(), Literal.getUDSuffixOffset());
2568
Richard Smith36f5cfe2012-03-09 08:00:36 +00002569 // Make sure we're allowed user-defined literals here.
2570 if (!UDLScope)
2571 return ExprError(Diag(UDSuffixLoc, diag::err_invalid_character_udl));
2572
Richard Smithdd66be72012-03-08 01:34:56 +00002573 // C++11 [lex.ext]p6: The literal L is treated as a call of the form
2574 // operator "" X (ch)
Richard Smith36f5cfe2012-03-09 08:00:36 +00002575 return BuildCookedLiteralOperatorCall(*this, UDLScope, UDSuffix, UDSuffixLoc,
2576 llvm::makeArrayRef(&Lit, 1),
2577 Tok.getLocation());
Reid Spencer5f016e22007-07-11 17:01:13 +00002578}
2579
Ted Kremenekebcb57a2012-03-06 20:05:56 +00002580ExprResult Sema::ActOnIntegerConstant(SourceLocation Loc, uint64_t Val) {
2581 unsigned IntSize = Context.getTargetInfo().getIntWidth();
2582 return Owned(IntegerLiteral::Create(Context, llvm::APInt(IntSize, Val),
2583 Context.IntTy, Loc));
2584}
2585
Richard Smithb453ad32012-03-08 08:45:32 +00002586static Expr *BuildFloatingLiteral(Sema &S, NumericLiteralParser &Literal,
2587 QualType Ty, SourceLocation Loc) {
2588 const llvm::fltSemantics &Format = S.Context.getFloatTypeSemantics(Ty);
2589
2590 using llvm::APFloat;
2591 APFloat Val(Format);
2592
2593 APFloat::opStatus result = Literal.GetFloatValue(Val);
2594
2595 // Overflow is always an error, but underflow is only an error if
2596 // we underflowed to zero (APFloat reports denormals as underflow).
2597 if ((result & APFloat::opOverflow) ||
2598 ((result & APFloat::opUnderflow) && Val.isZero())) {
2599 unsigned diagnostic;
2600 SmallString<20> buffer;
2601 if (result & APFloat::opOverflow) {
2602 diagnostic = diag::warn_float_overflow;
2603 APFloat::getLargest(Format).toString(buffer);
2604 } else {
2605 diagnostic = diag::warn_float_underflow;
2606 APFloat::getSmallest(Format).toString(buffer);
2607 }
2608
2609 S.Diag(Loc, diagnostic)
2610 << Ty
2611 << StringRef(buffer.data(), buffer.size());
2612 }
2613
2614 bool isExact = (result == APFloat::opOK);
2615 return FloatingLiteral::Create(S.Context, Val, isExact, Ty, Loc);
2616}
2617
Richard Smith36f5cfe2012-03-09 08:00:36 +00002618ExprResult Sema::ActOnNumericConstant(const Token &Tok, Scope *UDLScope) {
Sebastian Redlcd965b92009-01-18 18:53:16 +00002619 // Fast path for a single digit (which is quite common). A single digit
Richard Smith36f5cfe2012-03-09 08:00:36 +00002620 // cannot have a trigraph, escaped newline, radix prefix, or suffix.
Reid Spencer5f016e22007-07-11 17:01:13 +00002621 if (Tok.getLength() == 1) {
Chris Lattner7216dc92009-01-26 22:36:52 +00002622 const char Val = PP.getSpellingOfSingleCharacterNumericConstant(Tok);
Ted Kremenekebcb57a2012-03-06 20:05:56 +00002623 return ActOnIntegerConstant(Tok.getLocation(), Val-'0');
Reid Spencer5f016e22007-07-11 17:01:13 +00002624 }
Ted Kremenek28396602009-01-13 23:19:12 +00002625
Dylan Noblesmithf7ccbad2012-02-05 02:13:05 +00002626 SmallString<512> IntegerBuffer;
Chris Lattner2a299042008-09-30 20:53:45 +00002627 // Add padding so that NumericLiteralParser can overread by one character.
2628 IntegerBuffer.resize(Tok.getLength()+1);
Reid Spencer5f016e22007-07-11 17:01:13 +00002629 const char *ThisTokBegin = &IntegerBuffer[0];
Sebastian Redlcd965b92009-01-18 18:53:16 +00002630
Reid Spencer5f016e22007-07-11 17:01:13 +00002631 // Get the spelling of the token, which eliminates trigraphs, etc.
Douglas Gregor453091c2010-03-16 22:30:13 +00002632 bool Invalid = false;
2633 unsigned ActualLength = PP.getSpelling(Tok, ThisTokBegin, &Invalid);
2634 if (Invalid)
2635 return ExprError();
Sebastian Redlcd965b92009-01-18 18:53:16 +00002636
Mike Stump1eb44332009-09-09 15:08:12 +00002637 NumericLiteralParser Literal(ThisTokBegin, ThisTokBegin+ActualLength,
Reid Spencer5f016e22007-07-11 17:01:13 +00002638 Tok.getLocation(), PP);
2639 if (Literal.hadError)
Sebastian Redlcd965b92009-01-18 18:53:16 +00002640 return ExprError();
2641
Richard Smithb453ad32012-03-08 08:45:32 +00002642 if (Literal.hasUDSuffix()) {
2643 // We're building a user-defined literal.
2644 IdentifierInfo *UDSuffix = &Context.Idents.get(Literal.getUDSuffix());
2645 SourceLocation UDSuffixLoc =
2646 getUDSuffixLoc(*this, Tok.getLocation(), Literal.getUDSuffixOffset());
2647
Richard Smith36f5cfe2012-03-09 08:00:36 +00002648 // Make sure we're allowed user-defined literals here.
2649 if (!UDLScope)
2650 return ExprError(Diag(UDSuffixLoc, diag::err_invalid_numeric_udl));
Richard Smithb453ad32012-03-08 08:45:32 +00002651
Richard Smith36f5cfe2012-03-09 08:00:36 +00002652 QualType CookedTy;
Richard Smithb453ad32012-03-08 08:45:32 +00002653 if (Literal.isFloatingLiteral()) {
2654 // C++11 [lex.ext]p4: If S contains a literal operator with parameter type
2655 // long double, the literal is treated as a call of the form
2656 // operator "" X (f L)
Richard Smith36f5cfe2012-03-09 08:00:36 +00002657 CookedTy = Context.LongDoubleTy;
Richard Smithb453ad32012-03-08 08:45:32 +00002658 } else {
2659 // C++11 [lex.ext]p3: If S contains a literal operator with parameter type
2660 // unsigned long long, the literal is treated as a call of the form
2661 // operator "" X (n ULL)
Richard Smith36f5cfe2012-03-09 08:00:36 +00002662 CookedTy = Context.UnsignedLongLongTy;
Richard Smithb453ad32012-03-08 08:45:32 +00002663 }
2664
Richard Smith36f5cfe2012-03-09 08:00:36 +00002665 DeclarationName OpName =
2666 Context.DeclarationNames.getCXXLiteralOperatorName(UDSuffix);
2667 DeclarationNameInfo OpNameInfo(OpName, UDSuffixLoc);
2668 OpNameInfo.setCXXLiteralOperatorNameLoc(UDSuffixLoc);
2669
2670 // Perform literal operator lookup to determine if we're building a raw
2671 // literal or a cooked one.
2672 LookupResult R(*this, OpName, UDSuffixLoc, LookupOrdinaryName);
2673 switch (LookupLiteralOperator(UDLScope, R, llvm::makeArrayRef(&CookedTy, 1),
2674 /*AllowRawAndTemplate*/true)) {
2675 case LOLR_Error:
2676 return ExprError();
2677
2678 case LOLR_Cooked: {
2679 Expr *Lit;
2680 if (Literal.isFloatingLiteral()) {
2681 Lit = BuildFloatingLiteral(*this, Literal, CookedTy, Tok.getLocation());
2682 } else {
2683 llvm::APInt ResultVal(Context.getTargetInfo().getLongLongWidth(), 0);
2684 if (Literal.GetIntegerValue(ResultVal))
2685 Diag(Tok.getLocation(), diag::warn_integer_too_large);
2686 Lit = IntegerLiteral::Create(Context, ResultVal, CookedTy,
2687 Tok.getLocation());
2688 }
2689 return BuildLiteralOperatorCall(R, OpNameInfo,
2690 llvm::makeArrayRef(&Lit, 1),
2691 Tok.getLocation());
2692 }
2693
2694 case LOLR_Raw: {
2695 // C++11 [lit.ext]p3, p4: If S contains a raw literal operator, the
2696 // literal is treated as a call of the form
2697 // operator "" X ("n")
2698 SourceLocation TokLoc = Tok.getLocation();
2699 unsigned Length = Literal.getUDSuffixOffset();
2700 QualType StrTy = Context.getConstantArrayType(
2701 Context.CharTy, llvm::APInt(32, Length + 1),
2702 ArrayType::Normal, 0);
2703 Expr *Lit = StringLiteral::Create(
2704 Context, StringRef(ThisTokBegin, Length), StringLiteral::Ascii,
2705 /*Pascal*/false, StrTy, &TokLoc, 1);
2706 return BuildLiteralOperatorCall(R, OpNameInfo,
2707 llvm::makeArrayRef(&Lit, 1), TokLoc);
2708 }
2709
2710 case LOLR_Template:
2711 // C++11 [lit.ext]p3, p4: Otherwise (S contains a literal operator
2712 // template), L is treated as a call fo the form
2713 // operator "" X <'c1', 'c2', ... 'ck'>()
2714 // where n is the source character sequence c1 c2 ... ck.
2715 TemplateArgumentListInfo ExplicitArgs;
2716 unsigned CharBits = Context.getIntWidth(Context.CharTy);
2717 bool CharIsUnsigned = Context.CharTy->isUnsignedIntegerType();
2718 llvm::APSInt Value(CharBits, CharIsUnsigned);
2719 for (unsigned I = 0, N = Literal.getUDSuffixOffset(); I != N; ++I) {
2720 Value = ThisTokBegin[I];
Benjamin Kramer85524372012-06-07 15:09:51 +00002721 TemplateArgument Arg(Context, Value, Context.CharTy);
Richard Smith36f5cfe2012-03-09 08:00:36 +00002722 TemplateArgumentLocInfo ArgInfo;
2723 ExplicitArgs.addArgument(TemplateArgumentLoc(Arg, ArgInfo));
2724 }
2725 return BuildLiteralOperatorCall(R, OpNameInfo, ArrayRef<Expr*>(),
2726 Tok.getLocation(), &ExplicitArgs);
2727 }
2728
2729 llvm_unreachable("unexpected literal operator lookup result");
Richard Smithb453ad32012-03-08 08:45:32 +00002730 }
2731
Chris Lattner5d661452007-08-26 03:42:43 +00002732 Expr *Res;
Sebastian Redlcd965b92009-01-18 18:53:16 +00002733
Chris Lattner5d661452007-08-26 03:42:43 +00002734 if (Literal.isFloatingLiteral()) {
Chris Lattner525a0502007-09-22 18:29:59 +00002735 QualType Ty;
Chris Lattnerb7cfe882008-06-30 18:32:54 +00002736 if (Literal.isFloat)
Chris Lattner525a0502007-09-22 18:29:59 +00002737 Ty = Context.FloatTy;
Chris Lattnerb7cfe882008-06-30 18:32:54 +00002738 else if (!Literal.isLong)
Chris Lattner525a0502007-09-22 18:29:59 +00002739 Ty = Context.DoubleTy;
Chris Lattnerb7cfe882008-06-30 18:32:54 +00002740 else
Chris Lattner9e9b6dc2008-03-08 08:52:55 +00002741 Ty = Context.LongDoubleTy;
Chris Lattnerb7cfe882008-06-30 18:32:54 +00002742
Richard Smithb453ad32012-03-08 08:45:32 +00002743 Res = BuildFloatingLiteral(*this, Literal, Ty, Tok.getLocation());
Sebastian Redlcd965b92009-01-18 18:53:16 +00002744
Peter Collingbournef4f7cb82011-03-11 19:24:59 +00002745 if (Ty == Context.DoubleTy) {
David Blaikie4e4d0842012-03-11 07:00:24 +00002746 if (getLangOpts().SinglePrecisionConstants) {
John Wiegley429bb272011-04-08 18:41:53 +00002747 Res = ImpCastExprToType(Res, Context.FloatTy, CK_FloatingCast).take();
David Blaikie4e4d0842012-03-11 07:00:24 +00002748 } else if (getLangOpts().OpenCL && !getOpenCLOptions().cl_khr_fp64) {
Peter Collingbournef4f7cb82011-03-11 19:24:59 +00002749 Diag(Tok.getLocation(), diag::warn_double_const_requires_fp64);
John Wiegley429bb272011-04-08 18:41:53 +00002750 Res = ImpCastExprToType(Res, Context.FloatTy, CK_FloatingCast).take();
Peter Collingbournef4f7cb82011-03-11 19:24:59 +00002751 }
2752 }
Chris Lattner5d661452007-08-26 03:42:43 +00002753 } else if (!Literal.isIntegerLiteral()) {
Sebastian Redlcd965b92009-01-18 18:53:16 +00002754 return ExprError();
Chris Lattner5d661452007-08-26 03:42:43 +00002755 } else {
Chris Lattnerf0467b32008-04-02 04:24:33 +00002756 QualType Ty;
Reid Spencer5f016e22007-07-11 17:01:13 +00002757
Neil Boothb9449512007-08-29 22:00:19 +00002758 // long long is a C99 feature.
David Blaikie4e4d0842012-03-11 07:00:24 +00002759 if (!getLangOpts().C99 && Literal.isLongLong)
Richard Smithebaf0e62011-10-18 20:49:44 +00002760 Diag(Tok.getLocation(),
David Blaikie4e4d0842012-03-11 07:00:24 +00002761 getLangOpts().CPlusPlus0x ?
Richard Smithebaf0e62011-10-18 20:49:44 +00002762 diag::warn_cxx98_compat_longlong : diag::ext_longlong);
Neil Boothb9449512007-08-29 22:00:19 +00002763
Reid Spencer5f016e22007-07-11 17:01:13 +00002764 // Get the value in the widest-possible width.
Stephen Canonb9e05f12012-05-03 22:49:43 +00002765 unsigned MaxWidth = Context.getTargetInfo().getIntMaxTWidth();
2766 // The microsoft literal suffix extensions support 128-bit literals, which
2767 // may be wider than [u]intmax_t.
2768 if (Literal.isMicrosoftInteger && MaxWidth < 128)
2769 MaxWidth = 128;
2770 llvm::APInt ResultVal(MaxWidth, 0);
Sebastian Redlcd965b92009-01-18 18:53:16 +00002771
Reid Spencer5f016e22007-07-11 17:01:13 +00002772 if (Literal.GetIntegerValue(ResultVal)) {
2773 // If this value didn't fit into uintmax_t, warn and force to ull.
2774 Diag(Tok.getLocation(), diag::warn_integer_too_large);
Chris Lattnerf0467b32008-04-02 04:24:33 +00002775 Ty = Context.UnsignedLongLongTy;
2776 assert(Context.getTypeSize(Ty) == ResultVal.getBitWidth() &&
Chris Lattner98be4942008-03-05 18:54:05 +00002777 "long long is not intmax_t?");
Reid Spencer5f016e22007-07-11 17:01:13 +00002778 } else {
2779 // If this value fits into a ULL, try to figure out what else it fits into
2780 // according to the rules of C99 6.4.4.1p5.
Sebastian Redlcd965b92009-01-18 18:53:16 +00002781
Reid Spencer5f016e22007-07-11 17:01:13 +00002782 // Octal, Hexadecimal, and integers with a U suffix are allowed to
2783 // be an unsigned int.
2784 bool AllowUnsigned = Literal.isUnsigned || Literal.getRadix() != 10;
2785
2786 // Check from smallest to largest, picking the smallest type we can.
Chris Lattner8cbcb0e2008-05-09 05:59:00 +00002787 unsigned Width = 0;
Chris Lattner97c51562007-08-23 21:58:08 +00002788 if (!Literal.isLong && !Literal.isLongLong) {
2789 // Are int/unsigned possibilities?
Douglas Gregorbcfd1f52011-09-02 00:18:52 +00002790 unsigned IntSize = Context.getTargetInfo().getIntWidth();
Sebastian Redlcd965b92009-01-18 18:53:16 +00002791
Reid Spencer5f016e22007-07-11 17:01:13 +00002792 // Does it fit in a unsigned int?
2793 if (ResultVal.isIntN(IntSize)) {
2794 // Does it fit in a signed int?
2795 if (!Literal.isUnsigned && ResultVal[IntSize-1] == 0)
Chris Lattnerf0467b32008-04-02 04:24:33 +00002796 Ty = Context.IntTy;
Reid Spencer5f016e22007-07-11 17:01:13 +00002797 else if (AllowUnsigned)
Chris Lattnerf0467b32008-04-02 04:24:33 +00002798 Ty = Context.UnsignedIntTy;
Chris Lattner8cbcb0e2008-05-09 05:59:00 +00002799 Width = IntSize;
Reid Spencer5f016e22007-07-11 17:01:13 +00002800 }
Reid Spencer5f016e22007-07-11 17:01:13 +00002801 }
Sebastian Redlcd965b92009-01-18 18:53:16 +00002802
Reid Spencer5f016e22007-07-11 17:01:13 +00002803 // Are long/unsigned long possibilities?
Chris Lattnerf0467b32008-04-02 04:24:33 +00002804 if (Ty.isNull() && !Literal.isLongLong) {
Douglas Gregorbcfd1f52011-09-02 00:18:52 +00002805 unsigned LongSize = Context.getTargetInfo().getLongWidth();
Sebastian Redlcd965b92009-01-18 18:53:16 +00002806
Reid Spencer5f016e22007-07-11 17:01:13 +00002807 // Does it fit in a unsigned long?
2808 if (ResultVal.isIntN(LongSize)) {
2809 // Does it fit in a signed long?
2810 if (!Literal.isUnsigned && ResultVal[LongSize-1] == 0)
Chris Lattnerf0467b32008-04-02 04:24:33 +00002811 Ty = Context.LongTy;
Reid Spencer5f016e22007-07-11 17:01:13 +00002812 else if (AllowUnsigned)
Chris Lattnerf0467b32008-04-02 04:24:33 +00002813 Ty = Context.UnsignedLongTy;
Chris Lattner8cbcb0e2008-05-09 05:59:00 +00002814 Width = LongSize;
Reid Spencer5f016e22007-07-11 17:01:13 +00002815 }
Sebastian Redlcd965b92009-01-18 18:53:16 +00002816 }
2817
Stephen Canonb9e05f12012-05-03 22:49:43 +00002818 // Check long long if needed.
Chris Lattnerf0467b32008-04-02 04:24:33 +00002819 if (Ty.isNull()) {
Douglas Gregorbcfd1f52011-09-02 00:18:52 +00002820 unsigned LongLongSize = Context.getTargetInfo().getLongLongWidth();
Sebastian Redlcd965b92009-01-18 18:53:16 +00002821
Reid Spencer5f016e22007-07-11 17:01:13 +00002822 // Does it fit in a unsigned long long?
2823 if (ResultVal.isIntN(LongLongSize)) {
2824 // Does it fit in a signed long long?
Francois Pichet24323202011-01-11 23:38:13 +00002825 // To be compatible with MSVC, hex integer literals ending with the
2826 // LL or i64 suffix are always signed in Microsoft mode.
Francois Picheta15a5ee2011-01-11 12:23:00 +00002827 if (!Literal.isUnsigned && (ResultVal[LongLongSize-1] == 0 ||
David Blaikie4e4d0842012-03-11 07:00:24 +00002828 (getLangOpts().MicrosoftExt && Literal.isLongLong)))
Chris Lattnerf0467b32008-04-02 04:24:33 +00002829 Ty = Context.LongLongTy;
Reid Spencer5f016e22007-07-11 17:01:13 +00002830 else if (AllowUnsigned)
Chris Lattnerf0467b32008-04-02 04:24:33 +00002831 Ty = Context.UnsignedLongLongTy;
Chris Lattner8cbcb0e2008-05-09 05:59:00 +00002832 Width = LongLongSize;
Reid Spencer5f016e22007-07-11 17:01:13 +00002833 }
2834 }
Stephen Canonb9e05f12012-05-03 22:49:43 +00002835
2836 // If it doesn't fit in unsigned long long, and we're using Microsoft
2837 // extensions, then its a 128-bit integer literal.
2838 if (Ty.isNull() && Literal.isMicrosoftInteger) {
2839 if (Literal.isUnsigned)
2840 Ty = Context.UnsignedInt128Ty;
2841 else
2842 Ty = Context.Int128Ty;
2843 Width = 128;
2844 }
Sebastian Redlcd965b92009-01-18 18:53:16 +00002845
Reid Spencer5f016e22007-07-11 17:01:13 +00002846 // If we still couldn't decide a type, we probably have something that
2847 // does not fit in a signed long long, but has no U suffix.
Chris Lattnerf0467b32008-04-02 04:24:33 +00002848 if (Ty.isNull()) {
Reid Spencer5f016e22007-07-11 17:01:13 +00002849 Diag(Tok.getLocation(), diag::warn_integer_too_large_for_signed);
Chris Lattnerf0467b32008-04-02 04:24:33 +00002850 Ty = Context.UnsignedLongLongTy;
Douglas Gregorbcfd1f52011-09-02 00:18:52 +00002851 Width = Context.getTargetInfo().getLongLongWidth();
Reid Spencer5f016e22007-07-11 17:01:13 +00002852 }
Sebastian Redlcd965b92009-01-18 18:53:16 +00002853
Chris Lattner8cbcb0e2008-05-09 05:59:00 +00002854 if (ResultVal.getBitWidth() != Width)
Jay Foad9f71a8f2010-12-07 08:25:34 +00002855 ResultVal = ResultVal.trunc(Width);
Reid Spencer5f016e22007-07-11 17:01:13 +00002856 }
Argyrios Kyrtzidis9996a7f2010-08-28 09:06:06 +00002857 Res = IntegerLiteral::Create(Context, ResultVal, Ty, Tok.getLocation());
Reid Spencer5f016e22007-07-11 17:01:13 +00002858 }
Sebastian Redlcd965b92009-01-18 18:53:16 +00002859
Chris Lattner5d661452007-08-26 03:42:43 +00002860 // If this is an imaginary literal, create the ImaginaryLiteral wrapper.
2861 if (Literal.isImaginary)
Mike Stump1eb44332009-09-09 15:08:12 +00002862 Res = new (Context) ImaginaryLiteral(Res,
Steve Naroff6ece14c2009-01-21 00:14:39 +00002863 Context.getComplexType(Res->getType()));
Sebastian Redlcd965b92009-01-18 18:53:16 +00002864
2865 return Owned(Res);
Reid Spencer5f016e22007-07-11 17:01:13 +00002866}
2867
Richard Trieuccd891a2011-09-09 01:45:06 +00002868ExprResult Sema::ActOnParenExpr(SourceLocation L, SourceLocation R, Expr *E) {
Chris Lattnerf0467b32008-04-02 04:24:33 +00002869 assert((E != 0) && "ActOnParenExpr() missing expr");
Steve Naroff6ece14c2009-01-21 00:14:39 +00002870 return Owned(new (Context) ParenExpr(L, R, E));
Reid Spencer5f016e22007-07-11 17:01:13 +00002871}
2872
Chandler Carruthdf1f3772011-05-26 08:53:12 +00002873static bool CheckVecStepTraitOperandType(Sema &S, QualType T,
2874 SourceLocation Loc,
2875 SourceRange ArgRange) {
2876 // [OpenCL 1.1 6.11.12] "The vec_step built-in function takes a built-in
2877 // scalar or vector data type argument..."
2878 // Every built-in scalar type (OpenCL 1.1 6.1.1) is either an arithmetic
2879 // type (C99 6.2.5p18) or void.
2880 if (!(T->isArithmeticType() || T->isVoidType() || T->isVectorType())) {
2881 S.Diag(Loc, diag::err_vecstep_non_scalar_vector_type)
2882 << T << ArgRange;
2883 return true;
2884 }
2885
2886 assert((T->isVoidType() || !T->isIncompleteType()) &&
2887 "Scalar types should always be complete");
2888 return false;
2889}
2890
Chandler Carruth42ec65d2011-05-26 08:53:16 +00002891static bool CheckExtensionTraitOperandType(Sema &S, QualType T,
2892 SourceLocation Loc,
2893 SourceRange ArgRange,
2894 UnaryExprOrTypeTrait TraitKind) {
2895 // C99 6.5.3.4p1:
2896 if (T->isFunctionType()) {
2897 // alignof(function) is allowed as an extension.
2898 if (TraitKind == UETT_SizeOf)
2899 S.Diag(Loc, diag::ext_sizeof_function_type) << ArgRange;
2900 return false;
2901 }
2902
2903 // Allow sizeof(void)/alignof(void) as an extension.
2904 if (T->isVoidType()) {
2905 S.Diag(Loc, diag::ext_sizeof_void_type) << TraitKind << ArgRange;
2906 return false;
2907 }
2908
2909 return true;
2910}
2911
2912static bool CheckObjCTraitOperandConstraints(Sema &S, QualType T,
2913 SourceLocation Loc,
2914 SourceRange ArgRange,
2915 UnaryExprOrTypeTrait TraitKind) {
John McCall1503f0d2012-07-31 05:14:30 +00002916 // Reject sizeof(interface) and sizeof(interface<proto>) if the
2917 // runtime doesn't allow it.
2918 if (!S.LangOpts.ObjCRuntime.allowsSizeofAlignof() && T->isObjCObjectType()) {
Chandler Carruth42ec65d2011-05-26 08:53:16 +00002919 S.Diag(Loc, diag::err_sizeof_nonfragile_interface)
2920 << T << (TraitKind == UETT_SizeOf)
2921 << ArgRange;
2922 return true;
2923 }
2924
2925 return false;
2926}
2927
Chandler Carruth9d342d02011-05-26 08:53:10 +00002928/// \brief Check the constrains on expression operands to unary type expression
2929/// and type traits.
2930///
Chandler Carruthe4d645c2011-05-27 01:33:31 +00002931/// Completes any types necessary and validates the constraints on the operand
2932/// expression. The logic mostly mirrors the type-based overload, but may modify
2933/// the expression as it completes the type for that expression through template
2934/// instantiation, etc.
Richard Trieuccd891a2011-09-09 01:45:06 +00002935bool Sema::CheckUnaryExprOrTypeTraitOperand(Expr *E,
Chandler Carruth9d342d02011-05-26 08:53:10 +00002936 UnaryExprOrTypeTrait ExprKind) {
Richard Trieuccd891a2011-09-09 01:45:06 +00002937 QualType ExprTy = E->getType();
Chandler Carruthe4d645c2011-05-27 01:33:31 +00002938
2939 // C++ [expr.sizeof]p2: "When applied to a reference or a reference type,
2940 // the result is the size of the referenced type."
2941 // C++ [expr.alignof]p3: "When alignof is applied to a reference type, the
2942 // result shall be the alignment of the referenced type."
2943 if (const ReferenceType *Ref = ExprTy->getAs<ReferenceType>())
2944 ExprTy = Ref->getPointeeType();
2945
2946 if (ExprKind == UETT_VecStep)
Richard Trieuccd891a2011-09-09 01:45:06 +00002947 return CheckVecStepTraitOperandType(*this, ExprTy, E->getExprLoc(),
2948 E->getSourceRange());
Chandler Carruthe4d645c2011-05-27 01:33:31 +00002949
2950 // Whitelist some types as extensions
Richard Trieuccd891a2011-09-09 01:45:06 +00002951 if (!CheckExtensionTraitOperandType(*this, ExprTy, E->getExprLoc(),
2952 E->getSourceRange(), ExprKind))
Chandler Carruthe4d645c2011-05-27 01:33:31 +00002953 return false;
2954
Richard Trieuccd891a2011-09-09 01:45:06 +00002955 if (RequireCompleteExprType(E,
Douglas Gregord10099e2012-05-04 16:32:21 +00002956 diag::err_sizeof_alignof_incomplete_type,
2957 ExprKind, E->getSourceRange()))
Chandler Carruthe4d645c2011-05-27 01:33:31 +00002958 return true;
2959
2960 // Completeing the expression's type may have changed it.
Richard Trieuccd891a2011-09-09 01:45:06 +00002961 ExprTy = E->getType();
Chandler Carruthe4d645c2011-05-27 01:33:31 +00002962 if (const ReferenceType *Ref = ExprTy->getAs<ReferenceType>())
2963 ExprTy = Ref->getPointeeType();
2964
Richard Trieuccd891a2011-09-09 01:45:06 +00002965 if (CheckObjCTraitOperandConstraints(*this, ExprTy, E->getExprLoc(),
2966 E->getSourceRange(), ExprKind))
Chandler Carruthe4d645c2011-05-27 01:33:31 +00002967 return true;
2968
Nico Webercf739922011-06-15 02:47:03 +00002969 if (ExprKind == UETT_SizeOf) {
Richard Trieuccd891a2011-09-09 01:45:06 +00002970 if (DeclRefExpr *DeclRef = dyn_cast<DeclRefExpr>(E->IgnoreParens())) {
Nico Webercf739922011-06-15 02:47:03 +00002971 if (ParmVarDecl *PVD = dyn_cast<ParmVarDecl>(DeclRef->getFoundDecl())) {
2972 QualType OType = PVD->getOriginalType();
2973 QualType Type = PVD->getType();
2974 if (Type->isPointerType() && OType->isArrayType()) {
Richard Trieuccd891a2011-09-09 01:45:06 +00002975 Diag(E->getExprLoc(), diag::warn_sizeof_array_param)
Nico Webercf739922011-06-15 02:47:03 +00002976 << Type << OType;
2977 Diag(PVD->getLocation(), diag::note_declared_at);
2978 }
2979 }
2980 }
2981 }
2982
Chandler Carruthe4d645c2011-05-27 01:33:31 +00002983 return false;
Chandler Carruth9d342d02011-05-26 08:53:10 +00002984}
2985
2986/// \brief Check the constraints on operands to unary expression and type
2987/// traits.
2988///
2989/// This will complete any types necessary, and validate the various constraints
2990/// on those operands.
2991///
Reid Spencer5f016e22007-07-11 17:01:13 +00002992/// The UsualUnaryConversions() function is *not* called by this routine.
Chandler Carruth9d342d02011-05-26 08:53:10 +00002993/// C99 6.3.2.1p[2-4] all state:
2994/// Except when it is the operand of the sizeof operator ...
2995///
2996/// C++ [expr.sizeof]p4
2997/// The lvalue-to-rvalue, array-to-pointer, and function-to-pointer
2998/// standard conversions are not applied to the operand of sizeof.
2999///
3000/// This policy is followed for all of the unary trait expressions.
Richard Trieuccd891a2011-09-09 01:45:06 +00003001bool Sema::CheckUnaryExprOrTypeTraitOperand(QualType ExprType,
Peter Collingbournef4e3cfb2011-03-11 19:24:49 +00003002 SourceLocation OpLoc,
3003 SourceRange ExprRange,
3004 UnaryExprOrTypeTrait ExprKind) {
Richard Trieuccd891a2011-09-09 01:45:06 +00003005 if (ExprType->isDependentType())
Sebastian Redl28507842009-02-26 14:39:58 +00003006 return false;
3007
Sebastian Redl5d484e82009-11-23 17:18:46 +00003008 // C++ [expr.sizeof]p2: "When applied to a reference or a reference type,
3009 // the result is the size of the referenced type."
3010 // C++ [expr.alignof]p3: "When alignof is applied to a reference type, the
3011 // result shall be the alignment of the referenced type."
Richard Trieuccd891a2011-09-09 01:45:06 +00003012 if (const ReferenceType *Ref = ExprType->getAs<ReferenceType>())
3013 ExprType = Ref->getPointeeType();
Sebastian Redl5d484e82009-11-23 17:18:46 +00003014
Chandler Carruthdf1f3772011-05-26 08:53:12 +00003015 if (ExprKind == UETT_VecStep)
Richard Trieuccd891a2011-09-09 01:45:06 +00003016 return CheckVecStepTraitOperandType(*this, ExprType, OpLoc, ExprRange);
Peter Collingbournef4e3cfb2011-03-11 19:24:49 +00003017
Chandler Carruth42ec65d2011-05-26 08:53:16 +00003018 // Whitelist some types as extensions
Richard Trieuccd891a2011-09-09 01:45:06 +00003019 if (!CheckExtensionTraitOperandType(*this, ExprType, OpLoc, ExprRange,
Chandler Carruth42ec65d2011-05-26 08:53:16 +00003020 ExprKind))
Chris Lattner01072922009-01-24 19:46:37 +00003021 return false;
Mike Stump1eb44332009-09-09 15:08:12 +00003022
Richard Trieuccd891a2011-09-09 01:45:06 +00003023 if (RequireCompleteType(OpLoc, ExprType,
Douglas Gregord10099e2012-05-04 16:32:21 +00003024 diag::err_sizeof_alignof_incomplete_type,
3025 ExprKind, ExprRange))
Chris Lattner1efaa952009-04-24 00:30:45 +00003026 return true;
Mike Stump1eb44332009-09-09 15:08:12 +00003027
Richard Trieuccd891a2011-09-09 01:45:06 +00003028 if (CheckObjCTraitOperandConstraints(*this, ExprType, OpLoc, ExprRange,
Chandler Carruth42ec65d2011-05-26 08:53:16 +00003029 ExprKind))
Chris Lattner5cb10d32009-04-24 22:30:50 +00003030 return true;
Mike Stump1eb44332009-09-09 15:08:12 +00003031
Chris Lattner1efaa952009-04-24 00:30:45 +00003032 return false;
Reid Spencer5f016e22007-07-11 17:01:13 +00003033}
3034
Chandler Carruth9d342d02011-05-26 08:53:10 +00003035static bool CheckAlignOfExpr(Sema &S, Expr *E) {
Chris Lattner31e21e02009-01-24 20:17:12 +00003036 E = E->IgnoreParens();
Sebastian Redl28507842009-02-26 14:39:58 +00003037
Mike Stump1eb44332009-09-09 15:08:12 +00003038 // alignof decl is always ok.
Chris Lattner31e21e02009-01-24 20:17:12 +00003039 if (isa<DeclRefExpr>(E))
3040 return false;
Sebastian Redl28507842009-02-26 14:39:58 +00003041
3042 // Cannot know anything else if the expression is dependent.
3043 if (E->isTypeDependent())
3044 return false;
3045
Douglas Gregor33bbbc52009-05-02 02:18:30 +00003046 if (E->getBitField()) {
Chandler Carruth9d342d02011-05-26 08:53:10 +00003047 S.Diag(E->getExprLoc(), diag::err_sizeof_alignof_bitfield)
3048 << 1 << E->getSourceRange();
Douglas Gregor33bbbc52009-05-02 02:18:30 +00003049 return true;
Chris Lattner31e21e02009-01-24 20:17:12 +00003050 }
Douglas Gregor33bbbc52009-05-02 02:18:30 +00003051
3052 // Alignment of a field access is always okay, so long as it isn't a
3053 // bit-field.
3054 if (MemberExpr *ME = dyn_cast<MemberExpr>(E))
Mike Stump8e1fab22009-07-22 18:58:19 +00003055 if (isa<FieldDecl>(ME->getMemberDecl()))
Douglas Gregor33bbbc52009-05-02 02:18:30 +00003056 return false;
3057
Chandler Carruth9d342d02011-05-26 08:53:10 +00003058 return S.CheckUnaryExprOrTypeTraitOperand(E, UETT_AlignOf);
Peter Collingbournef4e3cfb2011-03-11 19:24:49 +00003059}
3060
Chandler Carruth9d342d02011-05-26 08:53:10 +00003061bool Sema::CheckVecStepExpr(Expr *E) {
Peter Collingbournef4e3cfb2011-03-11 19:24:49 +00003062 E = E->IgnoreParens();
3063
3064 // Cannot know anything else if the expression is dependent.
3065 if (E->isTypeDependent())
3066 return false;
3067
Chandler Carruth9d342d02011-05-26 08:53:10 +00003068 return CheckUnaryExprOrTypeTraitOperand(E, UETT_VecStep);
Chris Lattner31e21e02009-01-24 20:17:12 +00003069}
3070
Douglas Gregorba498172009-03-13 21:01:28 +00003071/// \brief Build a sizeof or alignof expression given a type operand.
John McCall60d7b3a2010-08-24 06:29:42 +00003072ExprResult
Peter Collingbournef4e3cfb2011-03-11 19:24:49 +00003073Sema::CreateUnaryExprOrTypeTraitExpr(TypeSourceInfo *TInfo,
3074 SourceLocation OpLoc,
3075 UnaryExprOrTypeTrait ExprKind,
3076 SourceRange R) {
John McCalla93c9342009-12-07 02:54:59 +00003077 if (!TInfo)
Douglas Gregorba498172009-03-13 21:01:28 +00003078 return ExprError();
3079
John McCalla93c9342009-12-07 02:54:59 +00003080 QualType T = TInfo->getType();
John McCall5ab75172009-11-04 07:28:41 +00003081
Douglas Gregorba498172009-03-13 21:01:28 +00003082 if (!T->isDependentType() &&
Peter Collingbournef4e3cfb2011-03-11 19:24:49 +00003083 CheckUnaryExprOrTypeTraitOperand(T, OpLoc, R, ExprKind))
Douglas Gregorba498172009-03-13 21:01:28 +00003084 return ExprError();
3085
3086 // C99 6.5.3.4p4: the type (an unsigned integer type) is size_t.
Peter Collingbournef4e3cfb2011-03-11 19:24:49 +00003087 return Owned(new (Context) UnaryExprOrTypeTraitExpr(ExprKind, TInfo,
3088 Context.getSizeType(),
3089 OpLoc, R.getEnd()));
Douglas Gregorba498172009-03-13 21:01:28 +00003090}
3091
3092/// \brief Build a sizeof or alignof expression given an expression
3093/// operand.
John McCall60d7b3a2010-08-24 06:29:42 +00003094ExprResult
Chandler Carruthe72c55b2011-05-29 07:32:14 +00003095Sema::CreateUnaryExprOrTypeTraitExpr(Expr *E, SourceLocation OpLoc,
3096 UnaryExprOrTypeTrait ExprKind) {
Douglas Gregor4f0845e2011-06-22 23:21:00 +00003097 ExprResult PE = CheckPlaceholderExpr(E);
3098 if (PE.isInvalid())
3099 return ExprError();
3100
3101 E = PE.get();
3102
Douglas Gregorba498172009-03-13 21:01:28 +00003103 // Verify that the operand is valid.
3104 bool isInvalid = false;
3105 if (E->isTypeDependent()) {
3106 // Delay type-checking for type-dependent expressions.
Peter Collingbournef4e3cfb2011-03-11 19:24:49 +00003107 } else if (ExprKind == UETT_AlignOf) {
Chandler Carruth9d342d02011-05-26 08:53:10 +00003108 isInvalid = CheckAlignOfExpr(*this, E);
Peter Collingbournef4e3cfb2011-03-11 19:24:49 +00003109 } else if (ExprKind == UETT_VecStep) {
Chandler Carruth9d342d02011-05-26 08:53:10 +00003110 isInvalid = CheckVecStepExpr(E);
Douglas Gregor33bbbc52009-05-02 02:18:30 +00003111 } else if (E->getBitField()) { // C99 6.5.3.4p1.
Chandler Carruth9d342d02011-05-26 08:53:10 +00003112 Diag(E->getExprLoc(), diag::err_sizeof_alignof_bitfield) << 0;
Douglas Gregorba498172009-03-13 21:01:28 +00003113 isInvalid = true;
3114 } else {
Chandler Carruth9d342d02011-05-26 08:53:10 +00003115 isInvalid = CheckUnaryExprOrTypeTraitOperand(E, UETT_SizeOf);
Douglas Gregorba498172009-03-13 21:01:28 +00003116 }
3117
3118 if (isInvalid)
3119 return ExprError();
3120
Eli Friedman71b8fb52012-01-21 01:01:51 +00003121 if (ExprKind == UETT_SizeOf && E->getType()->isVariableArrayType()) {
3122 PE = TranformToPotentiallyEvaluated(E);
3123 if (PE.isInvalid()) return ExprError();
3124 E = PE.take();
3125 }
3126
Douglas Gregorba498172009-03-13 21:01:28 +00003127 // C99 6.5.3.4p4: the type (an unsigned integer type) is size_t.
Chandler Carruth9d342d02011-05-26 08:53:10 +00003128 return Owned(new (Context) UnaryExprOrTypeTraitExpr(
Chandler Carruthe72c55b2011-05-29 07:32:14 +00003129 ExprKind, E, Context.getSizeType(), OpLoc,
Chandler Carruth9d342d02011-05-26 08:53:10 +00003130 E->getSourceRange().getEnd()));
Douglas Gregorba498172009-03-13 21:01:28 +00003131}
3132
Peter Collingbournef4e3cfb2011-03-11 19:24:49 +00003133/// ActOnUnaryExprOrTypeTraitExpr - Handle @c sizeof(type) and @c sizeof @c
3134/// expr and the same for @c alignof and @c __alignof
Sebastian Redl05189992008-11-11 17:56:53 +00003135/// Note that the ArgRange is invalid if isType is false.
John McCall60d7b3a2010-08-24 06:29:42 +00003136ExprResult
Peter Collingbournef4e3cfb2011-03-11 19:24:49 +00003137Sema::ActOnUnaryExprOrTypeTraitExpr(SourceLocation OpLoc,
Richard Trieuccd891a2011-09-09 01:45:06 +00003138 UnaryExprOrTypeTrait ExprKind, bool IsType,
Peter Collingbournef4e3cfb2011-03-11 19:24:49 +00003139 void *TyOrEx, const SourceRange &ArgRange) {
Reid Spencer5f016e22007-07-11 17:01:13 +00003140 // If error parsing type, ignore.
Sebastian Redl0eb23302009-01-19 00:08:26 +00003141 if (TyOrEx == 0) return ExprError();
Reid Spencer5f016e22007-07-11 17:01:13 +00003142
Richard Trieuccd891a2011-09-09 01:45:06 +00003143 if (IsType) {
John McCalla93c9342009-12-07 02:54:59 +00003144 TypeSourceInfo *TInfo;
John McCallb3d87482010-08-24 05:47:05 +00003145 (void) GetTypeFromParser(ParsedType::getFromOpaquePtr(TyOrEx), &TInfo);
Peter Collingbournef4e3cfb2011-03-11 19:24:49 +00003146 return CreateUnaryExprOrTypeTraitExpr(TInfo, OpLoc, ExprKind, ArgRange);
Mike Stump1eb44332009-09-09 15:08:12 +00003147 }
Sebastian Redl05189992008-11-11 17:56:53 +00003148
Douglas Gregorba498172009-03-13 21:01:28 +00003149 Expr *ArgEx = (Expr *)TyOrEx;
Chandler Carruthe72c55b2011-05-29 07:32:14 +00003150 ExprResult Result = CreateUnaryExprOrTypeTraitExpr(ArgEx, OpLoc, ExprKind);
Benjamin Kramer3fe198b2012-08-23 21:35:17 +00003151 return Result;
Reid Spencer5f016e22007-07-11 17:01:13 +00003152}
3153
John Wiegley429bb272011-04-08 18:41:53 +00003154static QualType CheckRealImagOperand(Sema &S, ExprResult &V, SourceLocation Loc,
Richard Trieuccd891a2011-09-09 01:45:06 +00003155 bool IsReal) {
John Wiegley429bb272011-04-08 18:41:53 +00003156 if (V.get()->isTypeDependent())
John McCall09431682010-11-18 19:01:18 +00003157 return S.Context.DependentTy;
Mike Stump1eb44332009-09-09 15:08:12 +00003158
John McCallf6a16482010-12-04 03:47:34 +00003159 // _Real and _Imag are only l-values for normal l-values.
John Wiegley429bb272011-04-08 18:41:53 +00003160 if (V.get()->getObjectKind() != OK_Ordinary) {
3161 V = S.DefaultLvalueConversion(V.take());
3162 if (V.isInvalid())
3163 return QualType();
3164 }
John McCallf6a16482010-12-04 03:47:34 +00003165
Chris Lattnercc26ed72007-08-26 05:39:26 +00003166 // These operators return the element type of a complex type.
John Wiegley429bb272011-04-08 18:41:53 +00003167 if (const ComplexType *CT = V.get()->getType()->getAs<ComplexType>())
Chris Lattnerdbb36972007-08-24 21:16:53 +00003168 return CT->getElementType();
Mike Stump1eb44332009-09-09 15:08:12 +00003169
Chris Lattnercc26ed72007-08-26 05:39:26 +00003170 // Otherwise they pass through real integer and floating point types here.
John Wiegley429bb272011-04-08 18:41:53 +00003171 if (V.get()->getType()->isArithmeticType())
3172 return V.get()->getType();
Mike Stump1eb44332009-09-09 15:08:12 +00003173
John McCall2cd11fe2010-10-12 02:09:17 +00003174 // Test for placeholders.
John McCallfb8721c2011-04-10 19:13:55 +00003175 ExprResult PR = S.CheckPlaceholderExpr(V.get());
John McCall2cd11fe2010-10-12 02:09:17 +00003176 if (PR.isInvalid()) return QualType();
John Wiegley429bb272011-04-08 18:41:53 +00003177 if (PR.get() != V.get()) {
Benjamin Kramer3fe198b2012-08-23 21:35:17 +00003178 V = PR;
Richard Trieuccd891a2011-09-09 01:45:06 +00003179 return CheckRealImagOperand(S, V, Loc, IsReal);
John McCall2cd11fe2010-10-12 02:09:17 +00003180 }
3181
Chris Lattnercc26ed72007-08-26 05:39:26 +00003182 // Reject anything else.
John Wiegley429bb272011-04-08 18:41:53 +00003183 S.Diag(Loc, diag::err_realimag_invalid_type) << V.get()->getType()
Richard Trieuccd891a2011-09-09 01:45:06 +00003184 << (IsReal ? "__real" : "__imag");
Chris Lattnercc26ed72007-08-26 05:39:26 +00003185 return QualType();
Chris Lattnerdbb36972007-08-24 21:16:53 +00003186}
3187
3188
Reid Spencer5f016e22007-07-11 17:01:13 +00003189
John McCall60d7b3a2010-08-24 06:29:42 +00003190ExprResult
Sebastian Redl0eb23302009-01-19 00:08:26 +00003191Sema::ActOnPostfixUnaryOp(Scope *S, SourceLocation OpLoc,
John McCall9ae2f072010-08-23 23:25:46 +00003192 tok::TokenKind Kind, Expr *Input) {
John McCall2de56d12010-08-25 11:45:40 +00003193 UnaryOperatorKind Opc;
Reid Spencer5f016e22007-07-11 17:01:13 +00003194 switch (Kind) {
David Blaikieb219cfc2011-09-23 05:06:16 +00003195 default: llvm_unreachable("Unknown unary op!");
John McCall2de56d12010-08-25 11:45:40 +00003196 case tok::plusplus: Opc = UO_PostInc; break;
3197 case tok::minusminus: Opc = UO_PostDec; break;
Reid Spencer5f016e22007-07-11 17:01:13 +00003198 }
Sebastian Redl0eb23302009-01-19 00:08:26 +00003199
Sebastian Redl5b9cc5d2012-02-11 23:51:47 +00003200 // Since this might is a postfix expression, get rid of ParenListExprs.
3201 ExprResult Result = MaybeConvertParenListExprToParenExpr(S, Input);
3202 if (Result.isInvalid()) return ExprError();
3203 Input = Result.take();
3204
John McCall9ae2f072010-08-23 23:25:46 +00003205 return BuildUnaryOp(S, OpLoc, Opc, Input);
Reid Spencer5f016e22007-07-11 17:01:13 +00003206}
3207
John McCall1503f0d2012-07-31 05:14:30 +00003208/// \brief Diagnose if arithmetic on the given ObjC pointer is illegal.
3209///
3210/// \return true on error
3211static bool checkArithmeticOnObjCPointer(Sema &S,
3212 SourceLocation opLoc,
3213 Expr *op) {
3214 assert(op->getType()->isObjCObjectPointerType());
3215 if (S.LangOpts.ObjCRuntime.allowsPointerArithmetic())
3216 return false;
3217
3218 S.Diag(opLoc, diag::err_arithmetic_nonfragile_interface)
3219 << op->getType()->castAs<ObjCObjectPointerType>()->getPointeeType()
3220 << op->getSourceRange();
3221 return true;
3222}
3223
John McCall60d7b3a2010-08-24 06:29:42 +00003224ExprResult
John McCall9ae2f072010-08-23 23:25:46 +00003225Sema::ActOnArraySubscriptExpr(Scope *S, Expr *Base, SourceLocation LLoc,
3226 Expr *Idx, SourceLocation RLoc) {
Nate Begeman2ef13e52009-08-10 23:49:36 +00003227 // Since this might be a postfix expression, get rid of ParenListExprs.
John McCall60d7b3a2010-08-24 06:29:42 +00003228 ExprResult Result = MaybeConvertParenListExprToParenExpr(S, Base);
John McCall9ae2f072010-08-23 23:25:46 +00003229 if (Result.isInvalid()) return ExprError();
3230 Base = Result.take();
Nate Begeman2ef13e52009-08-10 23:49:36 +00003231
John McCall9ae2f072010-08-23 23:25:46 +00003232 Expr *LHSExp = Base, *RHSExp = Idx;
Mike Stump1eb44332009-09-09 15:08:12 +00003233
David Blaikie4e4d0842012-03-11 07:00:24 +00003234 if (getLangOpts().CPlusPlus &&
Douglas Gregor3384c9c2009-05-19 00:01:19 +00003235 (LHSExp->isTypeDependent() || RHSExp->isTypeDependent())) {
Douglas Gregor3384c9c2009-05-19 00:01:19 +00003236 return Owned(new (Context) ArraySubscriptExpr(LHSExp, RHSExp,
John McCallf89e55a2010-11-18 06:31:45 +00003237 Context.DependentTy,
3238 VK_LValue, OK_Ordinary,
3239 RLoc));
Douglas Gregor3384c9c2009-05-19 00:01:19 +00003240 }
3241
David Blaikie4e4d0842012-03-11 07:00:24 +00003242 if (getLangOpts().CPlusPlus &&
Sebastian Redl0eb23302009-01-19 00:08:26 +00003243 (LHSExp->getType()->isRecordType() ||
Eli Friedman03f332a2008-12-15 22:34:21 +00003244 LHSExp->getType()->isEnumeralType() ||
3245 RHSExp->getType()->isRecordType() ||
Ted Kremenekebcb57a2012-03-06 20:05:56 +00003246 RHSExp->getType()->isEnumeralType()) &&
3247 !LHSExp->getType()->isObjCObjectPointerType()) {
John McCall9ae2f072010-08-23 23:25:46 +00003248 return CreateOverloadedArraySubscriptExpr(LLoc, RLoc, Base, Idx);
Douglas Gregor337c6b92008-11-19 17:17:41 +00003249 }
3250
John McCall9ae2f072010-08-23 23:25:46 +00003251 return CreateBuiltinArraySubscriptExpr(Base, LLoc, Idx, RLoc);
Sebastian Redlf322ed62009-10-29 20:17:01 +00003252}
3253
John McCall60d7b3a2010-08-24 06:29:42 +00003254ExprResult
John McCall9ae2f072010-08-23 23:25:46 +00003255Sema::CreateBuiltinArraySubscriptExpr(Expr *Base, SourceLocation LLoc,
Richard Trieuccd891a2011-09-09 01:45:06 +00003256 Expr *Idx, SourceLocation RLoc) {
John McCall9ae2f072010-08-23 23:25:46 +00003257 Expr *LHSExp = Base;
3258 Expr *RHSExp = Idx;
Sebastian Redlf322ed62009-10-29 20:17:01 +00003259
Chris Lattner12d9ff62007-07-16 00:14:47 +00003260 // Perform default conversions.
John Wiegley429bb272011-04-08 18:41:53 +00003261 if (!LHSExp->getType()->getAs<VectorType>()) {
3262 ExprResult Result = DefaultFunctionArrayLvalueConversion(LHSExp);
3263 if (Result.isInvalid())
3264 return ExprError();
3265 LHSExp = Result.take();
3266 }
3267 ExprResult Result = DefaultFunctionArrayLvalueConversion(RHSExp);
3268 if (Result.isInvalid())
3269 return ExprError();
3270 RHSExp = Result.take();
Sebastian Redl0eb23302009-01-19 00:08:26 +00003271
Chris Lattner12d9ff62007-07-16 00:14:47 +00003272 QualType LHSTy = LHSExp->getType(), RHSTy = RHSExp->getType();
John McCallf89e55a2010-11-18 06:31:45 +00003273 ExprValueKind VK = VK_LValue;
3274 ExprObjectKind OK = OK_Ordinary;
Reid Spencer5f016e22007-07-11 17:01:13 +00003275
Reid Spencer5f016e22007-07-11 17:01:13 +00003276 // C99 6.5.2.1p2: the expression e1[e2] is by definition precisely equivalent
Chris Lattner73d0d4f2007-08-30 17:45:32 +00003277 // to the expression *((e1)+(e2)). This means the array "Base" may actually be
Mike Stumpeed9cac2009-02-19 03:04:26 +00003278 // in the subscript position. As a result, we need to derive the array base
Reid Spencer5f016e22007-07-11 17:01:13 +00003279 // and index from the expression types.
Chris Lattner12d9ff62007-07-16 00:14:47 +00003280 Expr *BaseExpr, *IndexExpr;
3281 QualType ResultType;
Sebastian Redl28507842009-02-26 14:39:58 +00003282 if (LHSTy->isDependentType() || RHSTy->isDependentType()) {
3283 BaseExpr = LHSExp;
3284 IndexExpr = RHSExp;
3285 ResultType = Context.DependentTy;
Ted Kremenek6217b802009-07-29 21:53:49 +00003286 } else if (const PointerType *PTy = LHSTy->getAs<PointerType>()) {
Chris Lattner12d9ff62007-07-16 00:14:47 +00003287 BaseExpr = LHSExp;
3288 IndexExpr = RHSExp;
Chris Lattner12d9ff62007-07-16 00:14:47 +00003289 ResultType = PTy->getPointeeType();
Mike Stump1eb44332009-09-09 15:08:12 +00003290 } else if (const ObjCObjectPointerType *PTy =
John McCall1503f0d2012-07-31 05:14:30 +00003291 LHSTy->getAs<ObjCObjectPointerType>()) {
Steve Naroff14108da2009-07-10 23:34:53 +00003292 BaseExpr = LHSExp;
3293 IndexExpr = RHSExp;
John McCall1503f0d2012-07-31 05:14:30 +00003294
3295 // Use custom logic if this should be the pseudo-object subscript
3296 // expression.
3297 if (!LangOpts.ObjCRuntime.isSubscriptPointerArithmetic())
3298 return BuildObjCSubscriptExpression(RLoc, BaseExpr, IndexExpr, 0, 0);
3299
Steve Naroff14108da2009-07-10 23:34:53 +00003300 ResultType = PTy->getPointeeType();
John McCall1503f0d2012-07-31 05:14:30 +00003301 if (!LangOpts.ObjCRuntime.allowsPointerArithmetic()) {
3302 Diag(LLoc, diag::err_subscript_nonfragile_interface)
3303 << ResultType << BaseExpr->getSourceRange();
3304 return ExprError();
3305 }
Fariborz Jahaniana78eca22012-03-28 17:56:49 +00003306 } else if (const PointerType *PTy = RHSTy->getAs<PointerType>()) {
3307 // Handle the uncommon case of "123[Ptr]".
3308 BaseExpr = RHSExp;
3309 IndexExpr = LHSExp;
3310 ResultType = PTy->getPointeeType();
Mike Stump1eb44332009-09-09 15:08:12 +00003311 } else if (const ObjCObjectPointerType *PTy =
John McCall183700f2009-09-21 23:43:11 +00003312 RHSTy->getAs<ObjCObjectPointerType>()) {
Steve Naroff14108da2009-07-10 23:34:53 +00003313 // Handle the uncommon case of "123[Ptr]".
3314 BaseExpr = RHSExp;
3315 IndexExpr = LHSExp;
3316 ResultType = PTy->getPointeeType();
John McCall1503f0d2012-07-31 05:14:30 +00003317 if (!LangOpts.ObjCRuntime.allowsPointerArithmetic()) {
3318 Diag(LLoc, diag::err_subscript_nonfragile_interface)
3319 << ResultType << BaseExpr->getSourceRange();
3320 return ExprError();
3321 }
John McCall183700f2009-09-21 23:43:11 +00003322 } else if (const VectorType *VTy = LHSTy->getAs<VectorType>()) {
Chris Lattnerc8629632007-07-31 19:29:30 +00003323 BaseExpr = LHSExp; // vectors: V[123]
Chris Lattner12d9ff62007-07-16 00:14:47 +00003324 IndexExpr = RHSExp;
John McCallf89e55a2010-11-18 06:31:45 +00003325 VK = LHSExp->getValueKind();
3326 if (VK != VK_RValue)
3327 OK = OK_VectorComponent;
Nate Begeman334a8022009-01-18 00:45:31 +00003328
Chris Lattner12d9ff62007-07-16 00:14:47 +00003329 // FIXME: need to deal with const...
3330 ResultType = VTy->getElementType();
Eli Friedman7c32f8e2009-04-25 23:46:54 +00003331 } else if (LHSTy->isArrayType()) {
3332 // If we see an array that wasn't promoted by
Douglas Gregora873dfc2010-02-03 00:27:59 +00003333 // DefaultFunctionArrayLvalueConversion, it must be an array that
Eli Friedman7c32f8e2009-04-25 23:46:54 +00003334 // wasn't promoted because of the C90 rule that doesn't
3335 // allow promoting non-lvalue arrays. Warn, then
3336 // force the promotion here.
3337 Diag(LHSExp->getLocStart(), diag::ext_subscript_non_lvalue) <<
3338 LHSExp->getSourceRange();
John Wiegley429bb272011-04-08 18:41:53 +00003339 LHSExp = ImpCastExprToType(LHSExp, Context.getArrayDecayedType(LHSTy),
3340 CK_ArrayToPointerDecay).take();
Eli Friedman7c32f8e2009-04-25 23:46:54 +00003341 LHSTy = LHSExp->getType();
3342
3343 BaseExpr = LHSExp;
3344 IndexExpr = RHSExp;
Ted Kremenek6217b802009-07-29 21:53:49 +00003345 ResultType = LHSTy->getAs<PointerType>()->getPointeeType();
Eli Friedman7c32f8e2009-04-25 23:46:54 +00003346 } else if (RHSTy->isArrayType()) {
3347 // Same as previous, except for 123[f().a] case
3348 Diag(RHSExp->getLocStart(), diag::ext_subscript_non_lvalue) <<
3349 RHSExp->getSourceRange();
John Wiegley429bb272011-04-08 18:41:53 +00003350 RHSExp = ImpCastExprToType(RHSExp, Context.getArrayDecayedType(RHSTy),
3351 CK_ArrayToPointerDecay).take();
Eli Friedman7c32f8e2009-04-25 23:46:54 +00003352 RHSTy = RHSExp->getType();
3353
3354 BaseExpr = RHSExp;
3355 IndexExpr = LHSExp;
Ted Kremenek6217b802009-07-29 21:53:49 +00003356 ResultType = RHSTy->getAs<PointerType>()->getPointeeType();
Reid Spencer5f016e22007-07-11 17:01:13 +00003357 } else {
Chris Lattner338395d2009-04-25 22:50:55 +00003358 return ExprError(Diag(LLoc, diag::err_typecheck_subscript_value)
3359 << LHSExp->getSourceRange() << RHSExp->getSourceRange());
Sebastian Redl0eb23302009-01-19 00:08:26 +00003360 }
Reid Spencer5f016e22007-07-11 17:01:13 +00003361 // C99 6.5.2.1p1
Douglas Gregorf6094622010-07-23 15:58:24 +00003362 if (!IndexExpr->getType()->isIntegerType() && !IndexExpr->isTypeDependent())
Chris Lattner338395d2009-04-25 22:50:55 +00003363 return ExprError(Diag(LLoc, diag::err_typecheck_subscript_not_integer)
3364 << IndexExpr->getSourceRange());
Reid Spencer5f016e22007-07-11 17:01:13 +00003365
Daniel Dunbar7e88a602009-09-17 06:31:17 +00003366 if ((IndexExpr->getType()->isSpecificBuiltinType(BuiltinType::Char_S) ||
Sam Weinig0f9a5b52009-09-14 20:14:57 +00003367 IndexExpr->getType()->isSpecificBuiltinType(BuiltinType::Char_U))
3368 && !IndexExpr->isTypeDependent())
Sam Weinig76e2b712009-09-14 01:58:58 +00003369 Diag(LLoc, diag::warn_subscript_is_char) << IndexExpr->getSourceRange();
3370
Douglas Gregore7450f52009-03-24 19:52:54 +00003371 // C99 6.5.2.1p1: "shall have type "pointer to *object* type". Similarly,
Mike Stump1eb44332009-09-09 15:08:12 +00003372 // C++ [expr.sub]p1: The type "T" shall be a completely-defined object
3373 // type. Note that Functions are not objects, and that (in C99 parlance)
Douglas Gregore7450f52009-03-24 19:52:54 +00003374 // incomplete types are not object types.
3375 if (ResultType->isFunctionType()) {
3376 Diag(BaseExpr->getLocStart(), diag::err_subscript_function_type)
3377 << ResultType << BaseExpr->getSourceRange();
3378 return ExprError();
3379 }
Mike Stump1eb44332009-09-09 15:08:12 +00003380
David Blaikie4e4d0842012-03-11 07:00:24 +00003381 if (ResultType->isVoidType() && !getLangOpts().CPlusPlus) {
Abramo Bagnara46358452010-09-13 06:50:07 +00003382 // GNU extension: subscripting on pointer to void
Chandler Carruth66289692011-06-27 16:32:27 +00003383 Diag(LLoc, diag::ext_gnu_subscript_void_type)
3384 << BaseExpr->getSourceRange();
John McCall09431682010-11-18 19:01:18 +00003385
3386 // C forbids expressions of unqualified void type from being l-values.
3387 // See IsCForbiddenLValueType.
3388 if (!ResultType.hasQualifiers()) VK = VK_RValue;
Abramo Bagnara46358452010-09-13 06:50:07 +00003389 } else if (!ResultType->isDependentType() &&
Mike Stump1eb44332009-09-09 15:08:12 +00003390 RequireCompleteType(LLoc, ResultType,
Douglas Gregord10099e2012-05-04 16:32:21 +00003391 diag::err_subscript_incomplete_type, BaseExpr))
Douglas Gregore7450f52009-03-24 19:52:54 +00003392 return ExprError();
Mike Stump1eb44332009-09-09 15:08:12 +00003393
John McCall09431682010-11-18 19:01:18 +00003394 assert(VK == VK_RValue || LangOpts.CPlusPlus ||
Douglas Gregor2b1ad8b2011-06-23 00:49:38 +00003395 !ResultType.isCForbiddenLValueType());
John McCall09431682010-11-18 19:01:18 +00003396
Mike Stumpeed9cac2009-02-19 03:04:26 +00003397 return Owned(new (Context) ArraySubscriptExpr(LHSExp, RHSExp,
John McCallf89e55a2010-11-18 06:31:45 +00003398 ResultType, VK, OK, RLoc));
Reid Spencer5f016e22007-07-11 17:01:13 +00003399}
3400
John McCall60d7b3a2010-08-24 06:29:42 +00003401ExprResult Sema::BuildCXXDefaultArgExpr(SourceLocation CallLoc,
Nico Weber08e41a62010-11-29 18:19:25 +00003402 FunctionDecl *FD,
3403 ParmVarDecl *Param) {
Anders Carlsson56c5e332009-08-25 03:49:14 +00003404 if (Param->hasUnparsedDefaultArg()) {
Douglas Gregorbe0f7bd2010-09-11 20:24:53 +00003405 Diag(CallLoc,
Nico Weber15d5c832010-11-30 04:44:33 +00003406 diag::err_use_of_default_argument_to_function_declared_later) <<
Anders Carlsson56c5e332009-08-25 03:49:14 +00003407 FD << cast<CXXRecordDecl>(FD->getDeclContext())->getDeclName();
Mike Stump1eb44332009-09-09 15:08:12 +00003408 Diag(UnparsedDefaultArgLocs[Param],
Nico Weber15d5c832010-11-30 04:44:33 +00003409 diag::note_default_argument_declared_here);
Douglas Gregorbe0f7bd2010-09-11 20:24:53 +00003410 return ExprError();
3411 }
3412
3413 if (Param->hasUninstantiatedDefaultArg()) {
3414 Expr *UninstExpr = Param->getUninstantiatedDefaultArg();
Anders Carlsson56c5e332009-08-25 03:49:14 +00003415
Richard Smithadb1d4c2012-07-22 23:45:10 +00003416 EnterExpressionEvaluationContext EvalContext(*this, PotentiallyEvaluated,
3417 Param);
3418
Douglas Gregorbe0f7bd2010-09-11 20:24:53 +00003419 // Instantiate the expression.
3420 MultiLevelTemplateArgumentList ArgList
3421 = getTemplateInstantiationArgs(FD, 0, /*RelativeToPrimary=*/true);
Anders Carlsson25cae7f2009-09-05 05:14:19 +00003422
Nico Weber08e41a62010-11-29 18:19:25 +00003423 std::pair<const TemplateArgument *, unsigned> Innermost
Douglas Gregorbe0f7bd2010-09-11 20:24:53 +00003424 = ArgList.getInnermost();
Richard Smith7e54fb52012-07-16 01:09:10 +00003425 InstantiatingTemplate Inst(*this, CallLoc, Param,
3426 ArrayRef<TemplateArgument>(Innermost.first,
3427 Innermost.second));
Richard Smithab91ef12012-07-08 02:38:24 +00003428 if (Inst)
3429 return ExprError();
Anders Carlsson56c5e332009-08-25 03:49:14 +00003430
Nico Weber08e41a62010-11-29 18:19:25 +00003431 ExprResult Result;
3432 {
3433 // C++ [dcl.fct.default]p5:
3434 // The names in the [default argument] expression are bound, and
3435 // the semantic constraints are checked, at the point where the
3436 // default argument expression appears.
Nico Weber15d5c832010-11-30 04:44:33 +00003437 ContextRAII SavedContext(*this, FD);
Douglas Gregor7bdc1522012-02-16 21:36:18 +00003438 LocalInstantiationScope Local(*this);
Nico Weber08e41a62010-11-29 18:19:25 +00003439 Result = SubstExpr(UninstExpr, ArgList);
3440 }
Douglas Gregorbe0f7bd2010-09-11 20:24:53 +00003441 if (Result.isInvalid())
3442 return ExprError();
Mike Stump1eb44332009-09-09 15:08:12 +00003443
Douglas Gregorbe0f7bd2010-09-11 20:24:53 +00003444 // Check the expression as an initializer for the parameter.
3445 InitializedEntity Entity
Fariborz Jahanian745da3a2010-09-24 17:30:16 +00003446 = InitializedEntity::InitializeParameter(Context, Param);
Douglas Gregorbe0f7bd2010-09-11 20:24:53 +00003447 InitializationKind Kind
3448 = InitializationKind::CreateCopy(Param->getLocation(),
Daniel Dunbar96a00142012-03-09 18:35:03 +00003449 /*FIXME:EqualLoc*/UninstExpr->getLocStart());
Douglas Gregorbe0f7bd2010-09-11 20:24:53 +00003450 Expr *ResultE = Result.takeAs<Expr>();
Douglas Gregor65222e82009-12-23 18:19:08 +00003451
Douglas Gregorbe0f7bd2010-09-11 20:24:53 +00003452 InitializationSequence InitSeq(*this, Entity, Kind, &ResultE, 1);
Benjamin Kramer5354e772012-08-23 23:38:35 +00003453 Result = InitSeq.Perform(*this, Entity, Kind, ResultE);
Douglas Gregorbe0f7bd2010-09-11 20:24:53 +00003454 if (Result.isInvalid())
3455 return ExprError();
Kovarththanan Rajaratnam19357542010-03-13 10:17:05 +00003456
David Blaikiec1c07252012-04-30 18:21:31 +00003457 Expr *Arg = Result.takeAs<Expr>();
David Blaikie9fb1ac52012-05-15 21:57:38 +00003458 CheckImplicitConversions(Arg, Param->getOuterLocStart());
Douglas Gregorbe0f7bd2010-09-11 20:24:53 +00003459 // Build the default argument expression.
David Blaikiec1c07252012-04-30 18:21:31 +00003460 return Owned(CXXDefaultArgExpr::Create(Context, CallLoc, Param, Arg));
Anders Carlsson56c5e332009-08-25 03:49:14 +00003461 }
3462
Douglas Gregorbe0f7bd2010-09-11 20:24:53 +00003463 // If the default expression creates temporaries, we need to
3464 // push them to the current stack of expression temporaries so they'll
3465 // be properly destroyed.
3466 // FIXME: We should really be rebuilding the default argument with new
3467 // bound temporaries; see the comment in PR5810.
John McCall80ee6e82011-11-10 05:35:25 +00003468 // We don't need to do that with block decls, though, because
3469 // blocks in default argument expression can never capture anything.
3470 if (isa<ExprWithCleanups>(Param->getInit())) {
3471 // Set the "needs cleanups" bit regardless of whether there are
3472 // any explicit objects.
John McCallf85e1932011-06-15 23:02:42 +00003473 ExprNeedsCleanups = true;
John McCall80ee6e82011-11-10 05:35:25 +00003474
3475 // Append all the objects to the cleanup list. Right now, this
3476 // should always be a no-op, because blocks in default argument
3477 // expressions should never be able to capture anything.
3478 assert(!cast<ExprWithCleanups>(Param->getInit())->getNumObjects() &&
3479 "default argument expression has capturing blocks?");
Douglas Gregor5833b0b2010-09-14 22:55:20 +00003480 }
Douglas Gregorbe0f7bd2010-09-11 20:24:53 +00003481
3482 // We already type-checked the argument, so we know it works.
Douglas Gregor4fcf5b22010-09-11 23:32:50 +00003483 // Just mark all of the declarations in this potentially-evaluated expression
3484 // as being "referenced".
Douglas Gregorf4b7de12012-02-21 19:11:17 +00003485 MarkDeclarationsReferencedInExpr(Param->getDefaultArg(),
3486 /*SkipLocalVariables=*/true);
Douglas Gregor036aed12009-12-23 23:03:06 +00003487 return Owned(CXXDefaultArgExpr::Create(Context, CallLoc, Param));
Anders Carlsson56c5e332009-08-25 03:49:14 +00003488}
3489
Richard Smith831421f2012-06-25 20:30:08 +00003490
3491Sema::VariadicCallType
3492Sema::getVariadicCallType(FunctionDecl *FDecl, const FunctionProtoType *Proto,
3493 Expr *Fn) {
3494 if (Proto && Proto->isVariadic()) {
3495 if (dyn_cast_or_null<CXXConstructorDecl>(FDecl))
3496 return VariadicConstructor;
3497 else if (Fn && Fn->getType()->isBlockPointerType())
3498 return VariadicBlock;
3499 else if (FDecl) {
3500 if (CXXMethodDecl *Method = dyn_cast_or_null<CXXMethodDecl>(FDecl))
3501 if (Method->isInstance())
3502 return VariadicMethod;
3503 }
3504 return VariadicFunction;
3505 }
3506 return VariadicDoesNotApply;
3507}
3508
Douglas Gregor88a35142008-12-22 05:46:06 +00003509/// ConvertArgumentsForCall - Converts the arguments specified in
3510/// Args/NumArgs to the parameter types of the function FDecl with
3511/// function prototype Proto. Call is the call expression itself, and
3512/// Fn is the function expression. For a C++ member function, this
3513/// routine does not attempt to convert the object argument. Returns
3514/// true if the call is ill-formed.
Mike Stumpeed9cac2009-02-19 03:04:26 +00003515bool
3516Sema::ConvertArgumentsForCall(CallExpr *Call, Expr *Fn,
Douglas Gregor88a35142008-12-22 05:46:06 +00003517 FunctionDecl *FDecl,
Douglas Gregor72564e72009-02-26 23:50:07 +00003518 const FunctionProtoType *Proto,
Douglas Gregor88a35142008-12-22 05:46:06 +00003519 Expr **Args, unsigned NumArgs,
Peter Collingbourne1f240762011-10-02 23:49:29 +00003520 SourceLocation RParenLoc,
3521 bool IsExecConfig) {
John McCall8e10f3b2011-02-26 05:39:39 +00003522 // Bail out early if calling a builtin with custom typechecking.
3523 // We don't need to do this in the
3524 if (FDecl)
3525 if (unsigned ID = FDecl->getBuiltinID())
3526 if (Context.BuiltinInfo.hasCustomTypechecking(ID))
3527 return false;
3528
Mike Stumpeed9cac2009-02-19 03:04:26 +00003529 // C99 6.5.2.2p7 - the arguments are implicitly converted, as if by
Douglas Gregor88a35142008-12-22 05:46:06 +00003530 // assignment, to the types of the corresponding parameter, ...
3531 unsigned NumArgsInProto = Proto->getNumArgs();
Douglas Gregor3fd56d72009-01-23 21:30:56 +00003532 bool Invalid = false;
Peter Collingbourneaf15b4d2011-10-02 23:49:20 +00003533 unsigned MinArgs = FDecl ? FDecl->getMinRequiredArguments() : NumArgsInProto;
Peter Collingbourne1f240762011-10-02 23:49:29 +00003534 unsigned FnKind = Fn->getType()->isBlockPointerType()
3535 ? 1 /* block */
3536 : (IsExecConfig ? 3 /* kernel function (exec config) */
3537 : 0 /* function */);
Kovarththanan Rajaratnam19357542010-03-13 10:17:05 +00003538
Douglas Gregor88a35142008-12-22 05:46:06 +00003539 // If too few arguments are available (and we don't have default
3540 // arguments for the remaining parameters), don't make the call.
3541 if (NumArgs < NumArgsInProto) {
Peter Collingbourneaf15b4d2011-10-02 23:49:20 +00003542 if (NumArgs < MinArgs) {
Richard Smithf7b80562012-05-11 05:16:41 +00003543 if (MinArgs == 1 && FDecl && FDecl->getParamDecl(0)->getDeclName())
3544 Diag(RParenLoc, MinArgs == NumArgsInProto && !Proto->isVariadic()
3545 ? diag::err_typecheck_call_too_few_args_one
3546 : diag::err_typecheck_call_too_few_args_at_least_one)
3547 << FnKind
3548 << FDecl->getParamDecl(0) << Fn->getSourceRange();
3549 else
3550 Diag(RParenLoc, MinArgs == NumArgsInProto && !Proto->isVariadic()
3551 ? diag::err_typecheck_call_too_few_args
3552 : diag::err_typecheck_call_too_few_args_at_least)
3553 << FnKind
3554 << MinArgs << NumArgs << Fn->getSourceRange();
Peter Collingbourne9aab1482011-07-29 00:24:42 +00003555
3556 // Emit the location of the prototype.
Peter Collingbourne1f240762011-10-02 23:49:29 +00003557 if (FDecl && !FDecl->getBuiltinID() && !IsExecConfig)
Peter Collingbourne9aab1482011-07-29 00:24:42 +00003558 Diag(FDecl->getLocStart(), diag::note_callee_decl)
3559 << FDecl;
3560
3561 return true;
3562 }
Ted Kremenek8189cde2009-02-07 01:47:29 +00003563 Call->setNumArgs(Context, NumArgsInProto);
Douglas Gregor88a35142008-12-22 05:46:06 +00003564 }
3565
3566 // If too many are passed and not variadic, error on the extras and drop
3567 // them.
3568 if (NumArgs > NumArgsInProto) {
3569 if (!Proto->isVariadic()) {
Richard Smithc608c3c2012-05-15 06:21:54 +00003570 if (NumArgsInProto == 1 && FDecl && FDecl->getParamDecl(0)->getDeclName())
3571 Diag(Args[NumArgsInProto]->getLocStart(),
3572 MinArgs == NumArgsInProto
3573 ? diag::err_typecheck_call_too_many_args_one
3574 : diag::err_typecheck_call_too_many_args_at_most_one)
3575 << FnKind
3576 << FDecl->getParamDecl(0) << NumArgs << Fn->getSourceRange()
3577 << SourceRange(Args[NumArgsInProto]->getLocStart(),
3578 Args[NumArgs-1]->getLocEnd());
3579 else
3580 Diag(Args[NumArgsInProto]->getLocStart(),
3581 MinArgs == NumArgsInProto
3582 ? diag::err_typecheck_call_too_many_args
3583 : diag::err_typecheck_call_too_many_args_at_most)
3584 << FnKind
3585 << NumArgsInProto << NumArgs << Fn->getSourceRange()
3586 << SourceRange(Args[NumArgsInProto]->getLocStart(),
3587 Args[NumArgs-1]->getLocEnd());
Ted Kremenek5862f0e2011-04-04 17:22:27 +00003588
3589 // Emit the location of the prototype.
Peter Collingbourne1f240762011-10-02 23:49:29 +00003590 if (FDecl && !FDecl->getBuiltinID() && !IsExecConfig)
Peter Collingbourne9aab1482011-07-29 00:24:42 +00003591 Diag(FDecl->getLocStart(), diag::note_callee_decl)
3592 << FDecl;
Ted Kremenek5862f0e2011-04-04 17:22:27 +00003593
Douglas Gregor88a35142008-12-22 05:46:06 +00003594 // This deletes the extra arguments.
Ted Kremenek8189cde2009-02-07 01:47:29 +00003595 Call->setNumArgs(Context, NumArgsInProto);
Fariborz Jahanian048f52a2009-11-24 18:29:37 +00003596 return true;
Douglas Gregor88a35142008-12-22 05:46:06 +00003597 }
Douglas Gregor88a35142008-12-22 05:46:06 +00003598 }
Chris Lattner5f9e2722011-07-23 10:55:15 +00003599 SmallVector<Expr *, 8> AllArgs;
Richard Smith831421f2012-06-25 20:30:08 +00003600 VariadicCallType CallType = getVariadicCallType(FDecl, Proto, Fn);
3601
Daniel Dunbar96a00142012-03-09 18:35:03 +00003602 Invalid = GatherArgumentsForCall(Call->getLocStart(), FDecl,
Fariborz Jahanian2fe168f2009-11-24 21:37:28 +00003603 Proto, 0, Args, NumArgs, AllArgs, CallType);
Fariborz Jahanian048f52a2009-11-24 18:29:37 +00003604 if (Invalid)
3605 return true;
3606 unsigned TotalNumArgs = AllArgs.size();
3607 for (unsigned i = 0; i < TotalNumArgs; ++i)
3608 Call->setArg(i, AllArgs[i]);
Kovarththanan Rajaratnam19357542010-03-13 10:17:05 +00003609
Fariborz Jahanian048f52a2009-11-24 18:29:37 +00003610 return false;
3611}
Mike Stumpeed9cac2009-02-19 03:04:26 +00003612
Fariborz Jahanian048f52a2009-11-24 18:29:37 +00003613bool Sema::GatherArgumentsForCall(SourceLocation CallLoc,
3614 FunctionDecl *FDecl,
3615 const FunctionProtoType *Proto,
3616 unsigned FirstProtoArg,
3617 Expr **Args, unsigned NumArgs,
Chris Lattner5f9e2722011-07-23 10:55:15 +00003618 SmallVector<Expr *, 8> &AllArgs,
Douglas Gregored878af2012-02-24 23:56:31 +00003619 VariadicCallType CallType,
3620 bool AllowExplicit) {
Fariborz Jahanian048f52a2009-11-24 18:29:37 +00003621 unsigned NumArgsInProto = Proto->getNumArgs();
3622 unsigned NumArgsToCheck = NumArgs;
3623 bool Invalid = false;
3624 if (NumArgs != NumArgsInProto)
3625 // Use default arguments for missing arguments
3626 NumArgsToCheck = NumArgsInProto;
3627 unsigned ArgIx = 0;
Douglas Gregor88a35142008-12-22 05:46:06 +00003628 // Continue to check argument types (even if we have too few/many args).
Fariborz Jahanian048f52a2009-11-24 18:29:37 +00003629 for (unsigned i = FirstProtoArg; i != NumArgsToCheck; i++) {
Douglas Gregor88a35142008-12-22 05:46:06 +00003630 QualType ProtoArgType = Proto->getArgType(i);
Kovarththanan Rajaratnam19357542010-03-13 10:17:05 +00003631
Douglas Gregor88a35142008-12-22 05:46:06 +00003632 Expr *Arg;
Peter Collingbourne013e5ce2011-10-19 00:16:45 +00003633 ParmVarDecl *Param;
Fariborz Jahanian048f52a2009-11-24 18:29:37 +00003634 if (ArgIx < NumArgs) {
3635 Arg = Args[ArgIx++];
Kovarththanan Rajaratnam19357542010-03-13 10:17:05 +00003636
Daniel Dunbar96a00142012-03-09 18:35:03 +00003637 if (RequireCompleteType(Arg->getLocStart(),
Eli Friedmane7c6f7a2009-03-22 22:00:50 +00003638 ProtoArgType,
Douglas Gregord10099e2012-05-04 16:32:21 +00003639 diag::err_call_incomplete_argument, Arg))
Eli Friedmane7c6f7a2009-03-22 22:00:50 +00003640 return true;
Kovarththanan Rajaratnam19357542010-03-13 10:17:05 +00003641
Douglas Gregora188ff22009-12-22 16:09:06 +00003642 // Pass the argument
Peter Collingbourne013e5ce2011-10-19 00:16:45 +00003643 Param = 0;
Douglas Gregora188ff22009-12-22 16:09:06 +00003644 if (FDecl && i < FDecl->getNumParams())
3645 Param = FDecl->getParamDecl(i);
Douglas Gregoraa037312009-12-22 07:24:36 +00003646
John McCall5acb0c92011-10-17 18:40:02 +00003647 // Strip the unbridged-cast placeholder expression off, if applicable.
3648 if (Arg->getType() == Context.ARCUnbridgedCastTy &&
3649 FDecl && FDecl->hasAttr<CFAuditedTransferAttr>() &&
3650 (!Param || !Param->hasAttr<CFConsumedAttr>()))
3651 Arg = stripARCUnbridgedCast(Arg);
3652
Douglas Gregora188ff22009-12-22 16:09:06 +00003653 InitializedEntity Entity =
Fariborz Jahanian745da3a2010-09-24 17:30:16 +00003654 Param? InitializedEntity::InitializeParameter(Context, Param)
John McCallf85e1932011-06-15 23:02:42 +00003655 : InitializedEntity::InitializeParameter(Context, ProtoArgType,
3656 Proto->isArgConsumed(i));
John McCall60d7b3a2010-08-24 06:29:42 +00003657 ExprResult ArgE = PerformCopyInitialization(Entity,
John McCallf6a16482010-12-04 03:47:34 +00003658 SourceLocation(),
Douglas Gregored878af2012-02-24 23:56:31 +00003659 Owned(Arg),
3660 /*TopLevelOfInitList=*/false,
3661 AllowExplicit);
Douglas Gregora188ff22009-12-22 16:09:06 +00003662 if (ArgE.isInvalid())
3663 return true;
3664
3665 Arg = ArgE.takeAs<Expr>();
Anders Carlsson5e300d12009-06-12 16:51:40 +00003666 } else {
Peter Collingbourne013e5ce2011-10-19 00:16:45 +00003667 Param = FDecl->getParamDecl(i);
Kovarththanan Rajaratnam19357542010-03-13 10:17:05 +00003668
John McCall60d7b3a2010-08-24 06:29:42 +00003669 ExprResult ArgExpr =
Fariborz Jahanian048f52a2009-11-24 18:29:37 +00003670 BuildCXXDefaultArgExpr(CallLoc, FDecl, Param);
Anders Carlsson56c5e332009-08-25 03:49:14 +00003671 if (ArgExpr.isInvalid())
3672 return true;
Kovarththanan Rajaratnam19357542010-03-13 10:17:05 +00003673
Anders Carlsson56c5e332009-08-25 03:49:14 +00003674 Arg = ArgExpr.takeAs<Expr>();
Anders Carlsson5e300d12009-06-12 16:51:40 +00003675 }
Kaelyn Uhraind6c88652011-08-05 23:18:04 +00003676
3677 // Check for array bounds violations for each argument to the call. This
3678 // check only triggers warnings when the argument isn't a more complex Expr
3679 // with its own checking, such as a BinaryOperator.
3680 CheckArrayAccess(Arg);
3681
Peter Collingbourne013e5ce2011-10-19 00:16:45 +00003682 // Check for violations of C99 static array rules (C99 6.7.5.3p7).
3683 CheckStaticArrayArgument(CallLoc, Param, Arg);
3684
Fariborz Jahanian048f52a2009-11-24 18:29:37 +00003685 AllArgs.push_back(Arg);
Douglas Gregor88a35142008-12-22 05:46:06 +00003686 }
Kovarththanan Rajaratnam19357542010-03-13 10:17:05 +00003687
Douglas Gregor88a35142008-12-22 05:46:06 +00003688 // If this is a variadic call, handle args passed through "...".
Fariborz Jahanian4cd1c702009-11-24 19:27:49 +00003689 if (CallType != VariadicDoesNotApply) {
John McCall755d8492011-04-12 00:42:48 +00003690 // Assume that extern "C" functions with variadic arguments that
3691 // return __unknown_anytype aren't *really* variadic.
3692 if (Proto->getResultType() == Context.UnknownAnyTy &&
3693 FDecl && FDecl->isExternC()) {
3694 for (unsigned i = ArgIx; i != NumArgs; ++i) {
3695 ExprResult arg;
3696 if (isa<ExplicitCastExpr>(Args[i]->IgnoreParens()))
3697 arg = DefaultFunctionArrayLvalueConversion(Args[i]);
3698 else
3699 arg = DefaultVariadicArgumentPromotion(Args[i], CallType, FDecl);
3700 Invalid |= arg.isInvalid();
3701 AllArgs.push_back(arg.take());
3702 }
3703
3704 // Otherwise do argument promotion, (C99 6.5.2.2p7).
3705 } else {
3706 for (unsigned i = ArgIx; i != NumArgs; ++i) {
Richard Trieu67e29332011-08-02 04:35:43 +00003707 ExprResult Arg = DefaultVariadicArgumentPromotion(Args[i], CallType,
3708 FDecl);
John McCall755d8492011-04-12 00:42:48 +00003709 Invalid |= Arg.isInvalid();
3710 AllArgs.push_back(Arg.take());
3711 }
Douglas Gregor88a35142008-12-22 05:46:06 +00003712 }
Ted Kremenek615eb7c2011-09-26 23:36:13 +00003713
3714 // Check for array bounds violations.
3715 for (unsigned i = ArgIx; i != NumArgs; ++i)
3716 CheckArrayAccess(Args[i]);
Douglas Gregor88a35142008-12-22 05:46:06 +00003717 }
Douglas Gregor3fd56d72009-01-23 21:30:56 +00003718 return Invalid;
Douglas Gregor88a35142008-12-22 05:46:06 +00003719}
3720
Peter Collingbourne013e5ce2011-10-19 00:16:45 +00003721static void DiagnoseCalleeStaticArrayParam(Sema &S, ParmVarDecl *PVD) {
3722 TypeLoc TL = PVD->getTypeSourceInfo()->getTypeLoc();
3723 if (ArrayTypeLoc *ATL = dyn_cast<ArrayTypeLoc>(&TL))
3724 S.Diag(PVD->getLocation(), diag::note_callee_static_array)
3725 << ATL->getLocalSourceRange();
3726}
3727
3728/// CheckStaticArrayArgument - If the given argument corresponds to a static
3729/// array parameter, check that it is non-null, and that if it is formed by
3730/// array-to-pointer decay, the underlying array is sufficiently large.
3731///
3732/// C99 6.7.5.3p7: If the keyword static also appears within the [ and ] of the
3733/// array type derivation, then for each call to the function, the value of the
3734/// corresponding actual argument shall provide access to the first element of
3735/// an array with at least as many elements as specified by the size expression.
3736void
3737Sema::CheckStaticArrayArgument(SourceLocation CallLoc,
3738 ParmVarDecl *Param,
3739 const Expr *ArgExpr) {
3740 // Static array parameters are not supported in C++.
David Blaikie4e4d0842012-03-11 07:00:24 +00003741 if (!Param || getLangOpts().CPlusPlus)
Peter Collingbourne013e5ce2011-10-19 00:16:45 +00003742 return;
3743
3744 QualType OrigTy = Param->getOriginalType();
3745
3746 const ArrayType *AT = Context.getAsArrayType(OrigTy);
3747 if (!AT || AT->getSizeModifier() != ArrayType::Static)
3748 return;
3749
3750 if (ArgExpr->isNullPointerConstant(Context,
3751 Expr::NPC_NeverValueDependent)) {
3752 Diag(CallLoc, diag::warn_null_arg) << ArgExpr->getSourceRange();
3753 DiagnoseCalleeStaticArrayParam(*this, Param);
3754 return;
3755 }
3756
3757 const ConstantArrayType *CAT = dyn_cast<ConstantArrayType>(AT);
3758 if (!CAT)
3759 return;
3760
3761 const ConstantArrayType *ArgCAT =
3762 Context.getAsConstantArrayType(ArgExpr->IgnoreParenImpCasts()->getType());
3763 if (!ArgCAT)
3764 return;
3765
3766 if (ArgCAT->getSize().ult(CAT->getSize())) {
3767 Diag(CallLoc, diag::warn_static_array_too_small)
3768 << ArgExpr->getSourceRange()
3769 << (unsigned) ArgCAT->getSize().getZExtValue()
3770 << (unsigned) CAT->getSize().getZExtValue();
3771 DiagnoseCalleeStaticArrayParam(*this, Param);
3772 }
3773}
3774
John McCall755d8492011-04-12 00:42:48 +00003775/// Given a function expression of unknown-any type, try to rebuild it
3776/// to have a function type.
3777static ExprResult rebuildUnknownAnyFunction(Sema &S, Expr *fn);
3778
Steve Narofff69936d2007-09-16 03:34:24 +00003779/// ActOnCallExpr - Handle a call to Fn with the specified array of arguments.
Reid Spencer5f016e22007-07-11 17:01:13 +00003780/// This provides the location of the left/right parens and a list of comma
3781/// locations.
John McCall60d7b3a2010-08-24 06:29:42 +00003782ExprResult
John McCall9ae2f072010-08-23 23:25:46 +00003783Sema::ActOnCallExpr(Scope *S, Expr *Fn, SourceLocation LParenLoc,
Richard Trieuccd891a2011-09-09 01:45:06 +00003784 MultiExprArg ArgExprs, SourceLocation RParenLoc,
Peter Collingbourne1f240762011-10-02 23:49:29 +00003785 Expr *ExecConfig, bool IsExecConfig) {
Nate Begeman2ef13e52009-08-10 23:49:36 +00003786 // Since this might be a postfix expression, get rid of ParenListExprs.
John McCall60d7b3a2010-08-24 06:29:42 +00003787 ExprResult Result = MaybeConvertParenListExprToParenExpr(S, Fn);
John McCall9ae2f072010-08-23 23:25:46 +00003788 if (Result.isInvalid()) return ExprError();
3789 Fn = Result.take();
Mike Stump1eb44332009-09-09 15:08:12 +00003790
David Blaikie4e4d0842012-03-11 07:00:24 +00003791 if (getLangOpts().CPlusPlus) {
Douglas Gregora71d8192009-09-04 17:36:40 +00003792 // If this is a pseudo-destructor expression, build the call immediately.
3793 if (isa<CXXPseudoDestructorExpr>(Fn)) {
Benjamin Kramer3b6bef92012-08-24 11:54:20 +00003794 if (!ArgExprs.empty()) {
Douglas Gregora71d8192009-09-04 17:36:40 +00003795 // Pseudo-destructor calls should not have any arguments.
3796 Diag(Fn->getLocStart(), diag::err_pseudo_dtor_call_with_args)
Douglas Gregor849b2432010-03-31 17:46:05 +00003797 << FixItHint::CreateRemoval(
Benjamin Kramer3b6bef92012-08-24 11:54:20 +00003798 SourceRange(ArgExprs[0]->getLocStart(),
3799 ArgExprs.back()->getLocEnd()));
Douglas Gregora71d8192009-09-04 17:36:40 +00003800 }
Mike Stump1eb44332009-09-09 15:08:12 +00003801
Benjamin Kramer3b6bef92012-08-24 11:54:20 +00003802 return Owned(new (Context) CallExpr(Context, Fn, MultiExprArg(),
3803 Context.VoidTy, VK_RValue,
3804 RParenLoc));
Douglas Gregora71d8192009-09-04 17:36:40 +00003805 }
Mike Stump1eb44332009-09-09 15:08:12 +00003806
Douglas Gregor17330012009-02-04 15:01:18 +00003807 // Determine whether this is a dependent call inside a C++ template,
Mike Stumpeed9cac2009-02-19 03:04:26 +00003808 // in which case we won't do any semantic analysis now.
Mike Stump390b4cc2009-05-16 07:39:55 +00003809 // FIXME: Will need to cache the results of name lookup (including ADL) in
3810 // Fn.
Douglas Gregor17330012009-02-04 15:01:18 +00003811 bool Dependent = false;
3812 if (Fn->isTypeDependent())
3813 Dependent = true;
Benjamin Kramer3b6bef92012-08-24 11:54:20 +00003814 else if (Expr::hasAnyTypeDependentArguments(ArgExprs))
Douglas Gregor17330012009-02-04 15:01:18 +00003815 Dependent = true;
3816
Peter Collingbournee08ce652011-02-09 21:07:24 +00003817 if (Dependent) {
3818 if (ExecConfig) {
3819 return Owned(new (Context) CUDAKernelCallExpr(
Benjamin Kramer3b6bef92012-08-24 11:54:20 +00003820 Context, Fn, cast<CallExpr>(ExecConfig), ArgExprs,
Peter Collingbournee08ce652011-02-09 21:07:24 +00003821 Context.DependentTy, VK_RValue, RParenLoc));
3822 } else {
Benjamin Kramer3b6bef92012-08-24 11:54:20 +00003823 return Owned(new (Context) CallExpr(Context, Fn, ArgExprs,
Peter Collingbournee08ce652011-02-09 21:07:24 +00003824 Context.DependentTy, VK_RValue,
3825 RParenLoc));
3826 }
3827 }
Douglas Gregor17330012009-02-04 15:01:18 +00003828
3829 // Determine whether this is a call to an object (C++ [over.call.object]).
3830 if (Fn->getType()->isRecordType())
Benjamin Kramer3b6bef92012-08-24 11:54:20 +00003831 return Owned(BuildCallToObjectOfClassType(S, Fn, LParenLoc,
3832 ArgExprs.data(),
3833 ArgExprs.size(), RParenLoc));
Douglas Gregor17330012009-02-04 15:01:18 +00003834
John McCall755d8492011-04-12 00:42:48 +00003835 if (Fn->getType() == Context.UnknownAnyTy) {
3836 ExprResult result = rebuildUnknownAnyFunction(*this, Fn);
3837 if (result.isInvalid()) return ExprError();
3838 Fn = result.take();
3839 }
3840
John McCall864c0412011-04-26 20:42:42 +00003841 if (Fn->getType() == Context.BoundMemberTy) {
Benjamin Kramer3b6bef92012-08-24 11:54:20 +00003842 return BuildCallToMemberFunction(S, Fn, LParenLoc, ArgExprs.data(),
3843 ArgExprs.size(), RParenLoc);
John McCall129e2df2009-11-30 22:42:35 +00003844 }
John McCall864c0412011-04-26 20:42:42 +00003845 }
John McCall129e2df2009-11-30 22:42:35 +00003846
John McCall864c0412011-04-26 20:42:42 +00003847 // Check for overloaded calls. This can happen even in C due to extensions.
3848 if (Fn->getType() == Context.OverloadTy) {
3849 OverloadExpr::FindResult find = OverloadExpr::find(Fn);
3850
Douglas Gregoree697e62011-10-13 18:10:35 +00003851 // We aren't supposed to apply this logic for if there's an '&' involved.
Douglas Gregor64a371f2011-10-13 18:26:27 +00003852 if (!find.HasFormOfMemberPointer) {
John McCall864c0412011-04-26 20:42:42 +00003853 OverloadExpr *ovl = find.Expression;
3854 if (isa<UnresolvedLookupExpr>(ovl)) {
3855 UnresolvedLookupExpr *ULE = cast<UnresolvedLookupExpr>(ovl);
Benjamin Kramer3b6bef92012-08-24 11:54:20 +00003856 return BuildOverloadedCallExpr(S, Fn, ULE, LParenLoc, ArgExprs.data(),
3857 ArgExprs.size(), RParenLoc, ExecConfig);
John McCall864c0412011-04-26 20:42:42 +00003858 } else {
Benjamin Kramer3b6bef92012-08-24 11:54:20 +00003859 return BuildCallToMemberFunction(S, Fn, LParenLoc, ArgExprs.data(),
3860 ArgExprs.size(), RParenLoc);
Anders Carlsson83ccfc32009-10-03 17:40:22 +00003861 }
3862 }
Douglas Gregor88a35142008-12-22 05:46:06 +00003863 }
3864
Douglas Gregorfa047642009-02-04 00:32:51 +00003865 // If we're directly calling a function, get the appropriate declaration.
Douglas Gregorf1d1ca52011-12-01 01:37:36 +00003866 if (Fn->getType() == Context.UnknownAnyTy) {
3867 ExprResult result = rebuildUnknownAnyFunction(*this, Fn);
3868 if (result.isInvalid()) return ExprError();
3869 Fn = result.take();
3870 }
Mike Stumpeed9cac2009-02-19 03:04:26 +00003871
Eli Friedmanefa42f72009-12-26 03:35:45 +00003872 Expr *NakedFn = Fn->IgnoreParens();
Douglas Gregoref9b1492010-11-09 20:03:54 +00003873
John McCall3b4294e2009-12-16 12:17:52 +00003874 NamedDecl *NDecl = 0;
Douglas Gregord8f0ade2010-10-25 20:48:33 +00003875 if (UnaryOperator *UnOp = dyn_cast<UnaryOperator>(NakedFn))
3876 if (UnOp->getOpcode() == UO_AddrOf)
3877 NakedFn = UnOp->getSubExpr()->IgnoreParens();
3878
John McCall3b4294e2009-12-16 12:17:52 +00003879 if (isa<DeclRefExpr>(NakedFn))
3880 NDecl = cast<DeclRefExpr>(NakedFn)->getDecl();
John McCall864c0412011-04-26 20:42:42 +00003881 else if (isa<MemberExpr>(NakedFn))
3882 NDecl = cast<MemberExpr>(NakedFn)->getMemberDecl();
John McCall3b4294e2009-12-16 12:17:52 +00003883
Benjamin Kramer3b6bef92012-08-24 11:54:20 +00003884 return BuildResolvedCallExpr(Fn, NDecl, LParenLoc, ArgExprs.data(),
3885 ArgExprs.size(), RParenLoc, ExecConfig,
3886 IsExecConfig);
Peter Collingbournee08ce652011-02-09 21:07:24 +00003887}
3888
3889ExprResult
3890Sema::ActOnCUDAExecConfigExpr(Scope *S, SourceLocation LLLLoc,
Richard Trieuccd891a2011-09-09 01:45:06 +00003891 MultiExprArg ExecConfig, SourceLocation GGGLoc) {
Peter Collingbournee08ce652011-02-09 21:07:24 +00003892 FunctionDecl *ConfigDecl = Context.getcudaConfigureCallDecl();
3893 if (!ConfigDecl)
3894 return ExprError(Diag(LLLLoc, diag::err_undeclared_var_use)
3895 << "cudaConfigureCall");
3896 QualType ConfigQTy = ConfigDecl->getType();
3897
3898 DeclRefExpr *ConfigDR = new (Context) DeclRefExpr(
John McCallf4b88a42012-03-10 09:33:50 +00003899 ConfigDecl, false, ConfigQTy, VK_LValue, LLLLoc);
Eli Friedman5f2987c2012-02-02 03:46:19 +00003900 MarkFunctionReferenced(LLLLoc, ConfigDecl);
Peter Collingbournee08ce652011-02-09 21:07:24 +00003901
Peter Collingbourne1f240762011-10-02 23:49:29 +00003902 return ActOnCallExpr(S, ConfigDR, LLLLoc, ExecConfig, GGGLoc, 0,
3903 /*IsExecConfig=*/true);
John McCallaa81e162009-12-01 22:10:20 +00003904}
3905
Tanya Lattner61eee0c2011-06-04 00:47:47 +00003906/// ActOnAsTypeExpr - create a new asType (bitcast) from the arguments.
3907///
3908/// __builtin_astype( value, dst type )
3909///
Richard Trieuccd891a2011-09-09 01:45:06 +00003910ExprResult Sema::ActOnAsTypeExpr(Expr *E, ParsedType ParsedDestTy,
Tanya Lattner61eee0c2011-06-04 00:47:47 +00003911 SourceLocation BuiltinLoc,
3912 SourceLocation RParenLoc) {
3913 ExprValueKind VK = VK_RValue;
3914 ExprObjectKind OK = OK_Ordinary;
Richard Trieuccd891a2011-09-09 01:45:06 +00003915 QualType DstTy = GetTypeFromParser(ParsedDestTy);
3916 QualType SrcTy = E->getType();
Tanya Lattner61eee0c2011-06-04 00:47:47 +00003917 if (Context.getTypeSize(DstTy) != Context.getTypeSize(SrcTy))
3918 return ExprError(Diag(BuiltinLoc,
3919 diag::err_invalid_astype_of_different_size)
Peter Collingbourneaf9cddf2011-06-08 15:15:17 +00003920 << DstTy
3921 << SrcTy
Richard Trieuccd891a2011-09-09 01:45:06 +00003922 << E->getSourceRange());
3923 return Owned(new (Context) AsTypeExpr(E, DstTy, VK, OK, BuiltinLoc,
Richard Trieu67e29332011-08-02 04:35:43 +00003924 RParenLoc));
Tanya Lattner61eee0c2011-06-04 00:47:47 +00003925}
3926
John McCall3b4294e2009-12-16 12:17:52 +00003927/// BuildResolvedCallExpr - Build a call to a resolved expression,
3928/// i.e. an expression not of \p OverloadTy. The expression should
John McCallaa81e162009-12-01 22:10:20 +00003929/// unary-convert to an expression of function-pointer or
3930/// block-pointer type.
3931///
3932/// \param NDecl the declaration being called, if available
John McCall60d7b3a2010-08-24 06:29:42 +00003933ExprResult
John McCallaa81e162009-12-01 22:10:20 +00003934Sema::BuildResolvedCallExpr(Expr *Fn, NamedDecl *NDecl,
3935 SourceLocation LParenLoc,
3936 Expr **Args, unsigned NumArgs,
Peter Collingbournee08ce652011-02-09 21:07:24 +00003937 SourceLocation RParenLoc,
Peter Collingbourne1f240762011-10-02 23:49:29 +00003938 Expr *Config, bool IsExecConfig) {
John McCallaa81e162009-12-01 22:10:20 +00003939 FunctionDecl *FDecl = dyn_cast_or_null<FunctionDecl>(NDecl);
Eli Friedmana6c66ce2012-08-31 00:14:07 +00003940 unsigned BuiltinID = (FDecl ? FDecl->getBuiltinID() : 0);
John McCallaa81e162009-12-01 22:10:20 +00003941
Chris Lattner04421082008-04-08 04:40:51 +00003942 // Promote the function operand.
Eli Friedmana6c66ce2012-08-31 00:14:07 +00003943 // We special-case function promotion here because we only allow promoting
3944 // builtin functions to function pointers in the callee of a call.
3945 ExprResult Result;
3946 if (BuiltinID &&
3947 Fn->getType()->isSpecificBuiltinType(BuiltinType::BuiltinFn)) {
3948 Result = ImpCastExprToType(Fn, Context.getPointerType(FDecl->getType()),
3949 CK_BuiltinFnToFnPtr).take();
3950 } else {
3951 Result = UsualUnaryConversions(Fn);
3952 }
John Wiegley429bb272011-04-08 18:41:53 +00003953 if (Result.isInvalid())
3954 return ExprError();
3955 Fn = Result.take();
Chris Lattner04421082008-04-08 04:40:51 +00003956
Chris Lattner925e60d2007-12-28 05:29:59 +00003957 // Make the call expr early, before semantic checks. This guarantees cleanup
3958 // of arguments and function on error.
Peter Collingbournee08ce652011-02-09 21:07:24 +00003959 CallExpr *TheCall;
Eric Christophera27cb252012-05-30 01:14:28 +00003960 if (Config)
Peter Collingbournee08ce652011-02-09 21:07:24 +00003961 TheCall = new (Context) CUDAKernelCallExpr(Context, Fn,
3962 cast<CallExpr>(Config),
Benjamin Kramer3b6bef92012-08-24 11:54:20 +00003963 llvm::makeArrayRef(Args,NumArgs),
Peter Collingbournee08ce652011-02-09 21:07:24 +00003964 Context.BoolTy,
3965 VK_RValue,
3966 RParenLoc);
Eric Christophera27cb252012-05-30 01:14:28 +00003967 else
Peter Collingbournee08ce652011-02-09 21:07:24 +00003968 TheCall = new (Context) CallExpr(Context, Fn,
Benjamin Kramer3b6bef92012-08-24 11:54:20 +00003969 llvm::makeArrayRef(Args, NumArgs),
Peter Collingbournee08ce652011-02-09 21:07:24 +00003970 Context.BoolTy,
3971 VK_RValue,
3972 RParenLoc);
Sebastian Redl0eb23302009-01-19 00:08:26 +00003973
John McCall8e10f3b2011-02-26 05:39:39 +00003974 // Bail out early if calling a builtin with custom typechecking.
3975 if (BuiltinID && Context.BuiltinInfo.hasCustomTypechecking(BuiltinID))
3976 return CheckBuiltinFunctionCall(BuiltinID, TheCall);
3977
John McCall1de4d4e2011-04-07 08:22:57 +00003978 retry:
Steve Naroffdd972f22008-09-05 22:11:13 +00003979 const FunctionType *FuncT;
John McCall8e10f3b2011-02-26 05:39:39 +00003980 if (const PointerType *PT = Fn->getType()->getAs<PointerType>()) {
Steve Naroffdd972f22008-09-05 22:11:13 +00003981 // C99 6.5.2.2p1 - "The expression that denotes the called function shall
3982 // have type pointer to function".
John McCall183700f2009-09-21 23:43:11 +00003983 FuncT = PT->getPointeeType()->getAs<FunctionType>();
John McCall8e10f3b2011-02-26 05:39:39 +00003984 if (FuncT == 0)
3985 return ExprError(Diag(LParenLoc, diag::err_typecheck_call_not_function)
3986 << Fn->getType() << Fn->getSourceRange());
3987 } else if (const BlockPointerType *BPT =
3988 Fn->getType()->getAs<BlockPointerType>()) {
3989 FuncT = BPT->getPointeeType()->castAs<FunctionType>();
3990 } else {
John McCall1de4d4e2011-04-07 08:22:57 +00003991 // Handle calls to expressions of unknown-any type.
3992 if (Fn->getType() == Context.UnknownAnyTy) {
John McCall755d8492011-04-12 00:42:48 +00003993 ExprResult rewrite = rebuildUnknownAnyFunction(*this, Fn);
John McCall1de4d4e2011-04-07 08:22:57 +00003994 if (rewrite.isInvalid()) return ExprError();
3995 Fn = rewrite.take();
John McCalla5fc4722011-04-09 22:50:59 +00003996 TheCall->setCallee(Fn);
John McCall1de4d4e2011-04-07 08:22:57 +00003997 goto retry;
3998 }
3999
Sebastian Redl0eb23302009-01-19 00:08:26 +00004000 return ExprError(Diag(LParenLoc, diag::err_typecheck_call_not_function)
4001 << Fn->getType() << Fn->getSourceRange());
John McCall8e10f3b2011-02-26 05:39:39 +00004002 }
Sebastian Redl0eb23302009-01-19 00:08:26 +00004003
David Blaikie4e4d0842012-03-11 07:00:24 +00004004 if (getLangOpts().CUDA) {
Peter Collingbourne0423fc62011-02-23 01:53:29 +00004005 if (Config) {
4006 // CUDA: Kernel calls must be to global functions
4007 if (FDecl && !FDecl->hasAttr<CUDAGlobalAttr>())
4008 return ExprError(Diag(LParenLoc,diag::err_kern_call_not_global_function)
4009 << FDecl->getName() << Fn->getSourceRange());
4010
4011 // CUDA: Kernel function must have 'void' return type
4012 if (!FuncT->getResultType()->isVoidType())
4013 return ExprError(Diag(LParenLoc, diag::err_kern_type_not_void_return)
4014 << Fn->getType() << Fn->getSourceRange());
Peter Collingbourne8591a7f2011-10-02 23:49:15 +00004015 } else {
4016 // CUDA: Calls to global functions must be configured
4017 if (FDecl && FDecl->hasAttr<CUDAGlobalAttr>())
4018 return ExprError(Diag(LParenLoc, diag::err_global_call_not_config)
4019 << FDecl->getName() << Fn->getSourceRange());
Peter Collingbourne0423fc62011-02-23 01:53:29 +00004020 }
4021 }
4022
Eli Friedmane7c6f7a2009-03-22 22:00:50 +00004023 // Check for a valid return type
Kovarththanan Rajaratnam19357542010-03-13 10:17:05 +00004024 if (CheckCallReturnType(FuncT->getResultType(),
Daniel Dunbar96a00142012-03-09 18:35:03 +00004025 Fn->getLocStart(), TheCall,
Anders Carlsson8c8d9192009-10-09 23:51:55 +00004026 FDecl))
Eli Friedmane7c6f7a2009-03-22 22:00:50 +00004027 return ExprError();
4028
Chris Lattner925e60d2007-12-28 05:29:59 +00004029 // We know the result type of the call, set it.
Douglas Gregor5291c3c2010-07-13 08:18:22 +00004030 TheCall->setType(FuncT->getCallResultType(Context));
John McCallf89e55a2010-11-18 06:31:45 +00004031 TheCall->setValueKind(Expr::getValueKindForType(FuncT->getResultType()));
Sebastian Redl0eb23302009-01-19 00:08:26 +00004032
Richard Smith831421f2012-06-25 20:30:08 +00004033 const FunctionProtoType *Proto = dyn_cast<FunctionProtoType>(FuncT);
4034 if (Proto) {
John McCall9ae2f072010-08-23 23:25:46 +00004035 if (ConvertArgumentsForCall(TheCall, Fn, FDecl, Proto, Args, NumArgs,
Peter Collingbourne1f240762011-10-02 23:49:29 +00004036 RParenLoc, IsExecConfig))
Sebastian Redl0eb23302009-01-19 00:08:26 +00004037 return ExprError();
Chris Lattner925e60d2007-12-28 05:29:59 +00004038 } else {
Douglas Gregor72564e72009-02-26 23:50:07 +00004039 assert(isa<FunctionNoProtoType>(FuncT) && "Unknown FunctionType!");
Sebastian Redl0eb23302009-01-19 00:08:26 +00004040
Douglas Gregor74734d52009-04-02 15:37:10 +00004041 if (FDecl) {
4042 // Check if we have too few/too many template arguments, based
4043 // on our knowledge of the function definition.
4044 const FunctionDecl *Def = 0;
Argyrios Kyrtzidis06a54a32010-07-07 11:31:19 +00004045 if (FDecl->hasBody(Def) && NumArgs != Def->param_size()) {
Richard Smith831421f2012-06-25 20:30:08 +00004046 Proto = Def->getType()->getAs<FunctionProtoType>();
Douglas Gregor46542412010-10-25 20:39:23 +00004047 if (!Proto || !(Proto->isVariadic() && NumArgs >= Def->param_size()))
Eli Friedmanbc4e29f2009-06-01 09:24:59 +00004048 Diag(RParenLoc, diag::warn_call_wrong_number_of_arguments)
4049 << (NumArgs > Def->param_size()) << FDecl << Fn->getSourceRange();
Eli Friedmanbc4e29f2009-06-01 09:24:59 +00004050 }
Douglas Gregor46542412010-10-25 20:39:23 +00004051
4052 // If the function we're calling isn't a function prototype, but we have
4053 // a function prototype from a prior declaratiom, use that prototype.
4054 if (!FDecl->hasPrototype())
4055 Proto = FDecl->getType()->getAs<FunctionProtoType>();
Douglas Gregor74734d52009-04-02 15:37:10 +00004056 }
4057
Steve Naroffb291ab62007-08-28 23:30:39 +00004058 // Promote the arguments (C99 6.5.2.2p6).
Chris Lattner925e60d2007-12-28 05:29:59 +00004059 for (unsigned i = 0; i != NumArgs; i++) {
4060 Expr *Arg = Args[i];
Douglas Gregor46542412010-10-25 20:39:23 +00004061
4062 if (Proto && i < Proto->getNumArgs()) {
Douglas Gregor46542412010-10-25 20:39:23 +00004063 InitializedEntity Entity
4064 = InitializedEntity::InitializeParameter(Context,
John McCallf85e1932011-06-15 23:02:42 +00004065 Proto->getArgType(i),
4066 Proto->isArgConsumed(i));
Douglas Gregor46542412010-10-25 20:39:23 +00004067 ExprResult ArgE = PerformCopyInitialization(Entity,
4068 SourceLocation(),
4069 Owned(Arg));
4070 if (ArgE.isInvalid())
4071 return true;
4072
4073 Arg = ArgE.takeAs<Expr>();
4074
4075 } else {
John Wiegley429bb272011-04-08 18:41:53 +00004076 ExprResult ArgE = DefaultArgumentPromotion(Arg);
4077
4078 if (ArgE.isInvalid())
4079 return true;
4080
4081 Arg = ArgE.takeAs<Expr>();
Douglas Gregor46542412010-10-25 20:39:23 +00004082 }
4083
Daniel Dunbar96a00142012-03-09 18:35:03 +00004084 if (RequireCompleteType(Arg->getLocStart(),
Douglas Gregor0700bbf2010-10-26 05:45:40 +00004085 Arg->getType(),
Douglas Gregord10099e2012-05-04 16:32:21 +00004086 diag::err_call_incomplete_argument, Arg))
Douglas Gregor0700bbf2010-10-26 05:45:40 +00004087 return ExprError();
4088
Chris Lattner925e60d2007-12-28 05:29:59 +00004089 TheCall->setArg(i, Arg);
Steve Naroffb291ab62007-08-28 23:30:39 +00004090 }
Reid Spencer5f016e22007-07-11 17:01:13 +00004091 }
Chris Lattner925e60d2007-12-28 05:29:59 +00004092
Douglas Gregor88a35142008-12-22 05:46:06 +00004093 if (CXXMethodDecl *Method = dyn_cast_or_null<CXXMethodDecl>(FDecl))
4094 if (!Method->isStatic())
Sebastian Redl0eb23302009-01-19 00:08:26 +00004095 return ExprError(Diag(LParenLoc, diag::err_member_call_without_object)
4096 << Fn->getSourceRange());
Douglas Gregor88a35142008-12-22 05:46:06 +00004097
Fariborz Jahaniandaf04152009-05-15 20:33:25 +00004098 // Check for sentinels
4099 if (NDecl)
4100 DiagnoseSentinelCalls(NDecl, LParenLoc, Args, NumArgs);
Mike Stump1eb44332009-09-09 15:08:12 +00004101
Chris Lattner59907c42007-08-10 20:18:51 +00004102 // Do special checking on direct calls to functions.
Anders Carlssond406bf02009-08-16 01:56:34 +00004103 if (FDecl) {
Richard Smith831421f2012-06-25 20:30:08 +00004104 if (CheckFunctionCall(FDecl, TheCall, Proto))
Anders Carlssond406bf02009-08-16 01:56:34 +00004105 return ExprError();
Mike Stump1eb44332009-09-09 15:08:12 +00004106
John McCall8e10f3b2011-02-26 05:39:39 +00004107 if (BuiltinID)
Fariborz Jahanian67aba812010-11-30 17:35:24 +00004108 return CheckBuiltinFunctionCall(BuiltinID, TheCall);
Anders Carlssond406bf02009-08-16 01:56:34 +00004109 } else if (NDecl) {
Richard Smith831421f2012-06-25 20:30:08 +00004110 if (CheckBlockCall(NDecl, TheCall, Proto))
Anders Carlssond406bf02009-08-16 01:56:34 +00004111 return ExprError();
4112 }
Chris Lattner59907c42007-08-10 20:18:51 +00004113
John McCall9ae2f072010-08-23 23:25:46 +00004114 return MaybeBindToTemporary(TheCall);
Reid Spencer5f016e22007-07-11 17:01:13 +00004115}
4116
John McCall60d7b3a2010-08-24 06:29:42 +00004117ExprResult
John McCallb3d87482010-08-24 05:47:05 +00004118Sema::ActOnCompoundLiteral(SourceLocation LParenLoc, ParsedType Ty,
John McCall9ae2f072010-08-23 23:25:46 +00004119 SourceLocation RParenLoc, Expr *InitExpr) {
Steve Narofff69936d2007-09-16 03:34:24 +00004120 assert((Ty != 0) && "ActOnCompoundLiteral(): missing type");
Steve Naroffaff1edd2007-07-19 21:32:11 +00004121 // FIXME: put back this assert when initializers are worked out.
Steve Narofff69936d2007-09-16 03:34:24 +00004122 //assert((InitExpr != 0) && "ActOnCompoundLiteral(): missing expression");
John McCall42f56b52010-01-18 19:35:47 +00004123
4124 TypeSourceInfo *TInfo;
4125 QualType literalType = GetTypeFromParser(Ty, &TInfo);
4126 if (!TInfo)
4127 TInfo = Context.getTrivialTypeSourceInfo(literalType);
4128
John McCall9ae2f072010-08-23 23:25:46 +00004129 return BuildCompoundLiteralExpr(LParenLoc, TInfo, RParenLoc, InitExpr);
John McCall42f56b52010-01-18 19:35:47 +00004130}
4131
John McCall60d7b3a2010-08-24 06:29:42 +00004132ExprResult
John McCall42f56b52010-01-18 19:35:47 +00004133Sema::BuildCompoundLiteralExpr(SourceLocation LParenLoc, TypeSourceInfo *TInfo,
Richard Trieuccd891a2011-09-09 01:45:06 +00004134 SourceLocation RParenLoc, Expr *LiteralExpr) {
John McCall42f56b52010-01-18 19:35:47 +00004135 QualType literalType = TInfo->getType();
Anders Carlssond35c8322007-12-05 07:24:19 +00004136
Eli Friedman6223c222008-05-20 05:22:08 +00004137 if (literalType->isArrayType()) {
Argyrios Kyrtzidise6fe9a22010-11-08 19:14:19 +00004138 if (RequireCompleteType(LParenLoc, Context.getBaseElementType(literalType),
Douglas Gregord10099e2012-05-04 16:32:21 +00004139 diag::err_illegal_decl_array_incomplete_type,
4140 SourceRange(LParenLoc,
4141 LiteralExpr->getSourceRange().getEnd())))
Argyrios Kyrtzidise6fe9a22010-11-08 19:14:19 +00004142 return ExprError();
Chris Lattnerc63a1f22008-08-04 07:31:14 +00004143 if (literalType->isVariableArrayType())
Sebastian Redlb8a6aca2009-01-19 22:31:54 +00004144 return ExprError(Diag(LParenLoc, diag::err_variable_object_no_init)
Richard Trieuccd891a2011-09-09 01:45:06 +00004145 << SourceRange(LParenLoc, LiteralExpr->getSourceRange().getEnd()));
Douglas Gregor690dc7f2009-05-21 23:48:18 +00004146 } else if (!literalType->isDependentType() &&
4147 RequireCompleteType(LParenLoc, literalType,
Douglas Gregord10099e2012-05-04 16:32:21 +00004148 diag::err_typecheck_decl_incomplete_type,
4149 SourceRange(LParenLoc, LiteralExpr->getSourceRange().getEnd())))
Sebastian Redlb8a6aca2009-01-19 22:31:54 +00004150 return ExprError();
Eli Friedman6223c222008-05-20 05:22:08 +00004151
Douglas Gregor99a2e602009-12-16 01:38:02 +00004152 InitializedEntity Entity
Douglas Gregord6542d82009-12-22 15:35:07 +00004153 = InitializedEntity::InitializeTemporary(literalType);
Douglas Gregor99a2e602009-12-16 01:38:02 +00004154 InitializationKind Kind
John McCallf85e1932011-06-15 23:02:42 +00004155 = InitializationKind::CreateCStyleCast(LParenLoc,
Sebastian Redl3a45c0e2012-02-12 16:37:36 +00004156 SourceRange(LParenLoc, RParenLoc),
4157 /*InitList=*/true);
Richard Trieuccd891a2011-09-09 01:45:06 +00004158 InitializationSequence InitSeq(*this, Entity, Kind, &LiteralExpr, 1);
Benjamin Kramer5354e772012-08-23 23:38:35 +00004159 ExprResult Result = InitSeq.Perform(*this, Entity, Kind, LiteralExpr,
4160 &literalType);
Eli Friedman08544622009-12-22 02:35:53 +00004161 if (Result.isInvalid())
Sebastian Redlb8a6aca2009-01-19 22:31:54 +00004162 return ExprError();
Richard Trieuccd891a2011-09-09 01:45:06 +00004163 LiteralExpr = Result.get();
Steve Naroffe9b12192008-01-14 18:19:28 +00004164
Chris Lattner371f2582008-12-04 23:50:19 +00004165 bool isFileScope = getCurFunctionOrMethodDecl() == 0;
Steve Naroffe9b12192008-01-14 18:19:28 +00004166 if (isFileScope) { // 6.5.2.5p3
Richard Trieuccd891a2011-09-09 01:45:06 +00004167 if (CheckForConstantInitializer(LiteralExpr, literalType))
Sebastian Redlb8a6aca2009-01-19 22:31:54 +00004168 return ExprError();
Steve Naroffd0091aa2008-01-10 22:15:12 +00004169 }
Eli Friedman08544622009-12-22 02:35:53 +00004170
John McCallf89e55a2010-11-18 06:31:45 +00004171 // In C, compound literals are l-values for some reason.
David Blaikie4e4d0842012-03-11 07:00:24 +00004172 ExprValueKind VK = getLangOpts().CPlusPlus ? VK_RValue : VK_LValue;
John McCallf89e55a2010-11-18 06:31:45 +00004173
Douglas Gregor751ec9b2011-06-17 04:59:12 +00004174 return MaybeBindToTemporary(
4175 new (Context) CompoundLiteralExpr(LParenLoc, TInfo, literalType,
Richard Trieuccd891a2011-09-09 01:45:06 +00004176 VK, LiteralExpr, isFileScope));
Steve Naroff4aa88f82007-07-19 01:06:55 +00004177}
4178
John McCall60d7b3a2010-08-24 06:29:42 +00004179ExprResult
Richard Trieuccd891a2011-09-09 01:45:06 +00004180Sema::ActOnInitList(SourceLocation LBraceLoc, MultiExprArg InitArgList,
Sebastian Redlb8a6aca2009-01-19 22:31:54 +00004181 SourceLocation RBraceLoc) {
John McCall3c3b7f92011-10-25 17:37:35 +00004182 // Immediately handle non-overload placeholders. Overloads can be
4183 // resolved contextually, but everything else here can't.
Benjamin Kramer3b6bef92012-08-24 11:54:20 +00004184 for (unsigned I = 0, E = InitArgList.size(); I != E; ++I) {
4185 if (InitArgList[I]->getType()->isNonOverloadPlaceholderType()) {
4186 ExprResult result = CheckPlaceholderExpr(InitArgList[I]);
John McCall3c3b7f92011-10-25 17:37:35 +00004187
4188 // Ignore failures; dropping the entire initializer list because
4189 // of one failure would be terrible for indexing/etc.
4190 if (result.isInvalid()) continue;
4191
Benjamin Kramer3b6bef92012-08-24 11:54:20 +00004192 InitArgList[I] = result.take();
John McCall3c3b7f92011-10-25 17:37:35 +00004193 }
4194 }
4195
Steve Naroff08d92e42007-09-15 18:49:24 +00004196 // Semantic analysis for initializers is done by ActOnDeclarator() and
Mike Stumpeed9cac2009-02-19 03:04:26 +00004197 // CheckInitializer() - it requires knowledge of the object being intialized.
Sebastian Redlb8a6aca2009-01-19 22:31:54 +00004198
Benjamin Kramer3b6bef92012-08-24 11:54:20 +00004199 InitListExpr *E = new (Context) InitListExpr(Context, LBraceLoc, InitArgList,
4200 RBraceLoc);
Chris Lattnerf0467b32008-04-02 04:24:33 +00004201 E->setType(Context.VoidTy); // FIXME: just a place holder for now.
Sebastian Redlb8a6aca2009-01-19 22:31:54 +00004202 return Owned(E);
Steve Naroff4aa88f82007-07-19 01:06:55 +00004203}
4204
John McCalldc05b112011-09-10 01:16:55 +00004205/// Do an explicit extend of the given block pointer if we're in ARC.
4206static void maybeExtendBlockObject(Sema &S, ExprResult &E) {
4207 assert(E.get()->getType()->isBlockPointerType());
4208 assert(E.get()->isRValue());
4209
4210 // Only do this in an r-value context.
David Blaikie4e4d0842012-03-11 07:00:24 +00004211 if (!S.getLangOpts().ObjCAutoRefCount) return;
John McCalldc05b112011-09-10 01:16:55 +00004212
4213 E = ImplicitCastExpr::Create(S.Context, E.get()->getType(),
John McCall33e56f32011-09-10 06:18:15 +00004214 CK_ARCExtendBlockObject, E.get(),
John McCalldc05b112011-09-10 01:16:55 +00004215 /*base path*/ 0, VK_RValue);
4216 S.ExprNeedsCleanups = true;
4217}
4218
4219/// Prepare a conversion of the given expression to an ObjC object
4220/// pointer type.
4221CastKind Sema::PrepareCastToObjCObjectPointer(ExprResult &E) {
4222 QualType type = E.get()->getType();
4223 if (type->isObjCObjectPointerType()) {
4224 return CK_BitCast;
4225 } else if (type->isBlockPointerType()) {
4226 maybeExtendBlockObject(*this, E);
4227 return CK_BlockPointerToObjCPointerCast;
4228 } else {
4229 assert(type->isPointerType());
4230 return CK_CPointerToObjCPointerCast;
4231 }
4232}
4233
John McCallf3ea8cf2010-11-14 08:17:51 +00004234/// Prepares for a scalar cast, performing all the necessary stages
4235/// except the final cast and returning the kind required.
John McCalla180f042011-10-06 23:25:11 +00004236CastKind Sema::PrepareScalarCast(ExprResult &Src, QualType DestTy) {
John McCallf3ea8cf2010-11-14 08:17:51 +00004237 // Both Src and Dest are scalar types, i.e. arithmetic or pointer.
4238 // Also, callers should have filtered out the invalid cases with
4239 // pointers. Everything else should be possible.
4240
John Wiegley429bb272011-04-08 18:41:53 +00004241 QualType SrcTy = Src.get()->getType();
John McCalla180f042011-10-06 23:25:11 +00004242 if (Context.hasSameUnqualifiedType(SrcTy, DestTy))
John McCall2de56d12010-08-25 11:45:40 +00004243 return CK_NoOp;
Anders Carlsson82debc72009-10-18 18:12:03 +00004244
John McCall1d9b3b22011-09-09 05:25:32 +00004245 switch (Type::ScalarTypeKind SrcKind = SrcTy->getScalarTypeKind()) {
John McCalldaa8e4e2010-11-15 09:13:47 +00004246 case Type::STK_MemberPointer:
4247 llvm_unreachable("member pointer type in C");
Abramo Bagnarabb03f5d2011-01-04 09:50:03 +00004248
John McCall1d9b3b22011-09-09 05:25:32 +00004249 case Type::STK_CPointer:
4250 case Type::STK_BlockPointer:
4251 case Type::STK_ObjCObjectPointer:
John McCalldaa8e4e2010-11-15 09:13:47 +00004252 switch (DestTy->getScalarTypeKind()) {
John McCall1d9b3b22011-09-09 05:25:32 +00004253 case Type::STK_CPointer:
4254 return CK_BitCast;
4255 case Type::STK_BlockPointer:
4256 return (SrcKind == Type::STK_BlockPointer
4257 ? CK_BitCast : CK_AnyPointerToBlockPointerCast);
4258 case Type::STK_ObjCObjectPointer:
4259 if (SrcKind == Type::STK_ObjCObjectPointer)
4260 return CK_BitCast;
David Blaikie7530c032012-01-17 06:56:22 +00004261 if (SrcKind == Type::STK_CPointer)
John McCall1d9b3b22011-09-09 05:25:32 +00004262 return CK_CPointerToObjCPointerCast;
David Blaikie7530c032012-01-17 06:56:22 +00004263 maybeExtendBlockObject(*this, Src);
4264 return CK_BlockPointerToObjCPointerCast;
John McCalldaa8e4e2010-11-15 09:13:47 +00004265 case Type::STK_Bool:
4266 return CK_PointerToBoolean;
4267 case Type::STK_Integral:
4268 return CK_PointerToIntegral;
4269 case Type::STK_Floating:
4270 case Type::STK_FloatingComplex:
4271 case Type::STK_IntegralComplex:
4272 case Type::STK_MemberPointer:
4273 llvm_unreachable("illegal cast from pointer");
4274 }
David Blaikie7530c032012-01-17 06:56:22 +00004275 llvm_unreachable("Should have returned before this");
Kovarththanan Rajaratnam19357542010-03-13 10:17:05 +00004276
John McCalldaa8e4e2010-11-15 09:13:47 +00004277 case Type::STK_Bool: // casting from bool is like casting from an integer
4278 case Type::STK_Integral:
4279 switch (DestTy->getScalarTypeKind()) {
John McCall1d9b3b22011-09-09 05:25:32 +00004280 case Type::STK_CPointer:
4281 case Type::STK_ObjCObjectPointer:
4282 case Type::STK_BlockPointer:
John McCalla180f042011-10-06 23:25:11 +00004283 if (Src.get()->isNullPointerConstant(Context,
Richard Trieu67e29332011-08-02 04:35:43 +00004284 Expr::NPC_ValueDependentIsNull))
John McCall404cd162010-11-13 01:35:44 +00004285 return CK_NullToPointer;
John McCall2de56d12010-08-25 11:45:40 +00004286 return CK_IntegralToPointer;
John McCalldaa8e4e2010-11-15 09:13:47 +00004287 case Type::STK_Bool:
4288 return CK_IntegralToBoolean;
4289 case Type::STK_Integral:
John McCallf3ea8cf2010-11-14 08:17:51 +00004290 return CK_IntegralCast;
John McCalldaa8e4e2010-11-15 09:13:47 +00004291 case Type::STK_Floating:
John McCall2de56d12010-08-25 11:45:40 +00004292 return CK_IntegralToFloating;
John McCalldaa8e4e2010-11-15 09:13:47 +00004293 case Type::STK_IntegralComplex:
John McCalla180f042011-10-06 23:25:11 +00004294 Src = ImpCastExprToType(Src.take(),
4295 DestTy->castAs<ComplexType>()->getElementType(),
4296 CK_IntegralCast);
John McCallf3ea8cf2010-11-14 08:17:51 +00004297 return CK_IntegralRealToComplex;
John McCalldaa8e4e2010-11-15 09:13:47 +00004298 case Type::STK_FloatingComplex:
John McCalla180f042011-10-06 23:25:11 +00004299 Src = ImpCastExprToType(Src.take(),
4300 DestTy->castAs<ComplexType>()->getElementType(),
4301 CK_IntegralToFloating);
John McCallf3ea8cf2010-11-14 08:17:51 +00004302 return CK_FloatingRealToComplex;
John McCalldaa8e4e2010-11-15 09:13:47 +00004303 case Type::STK_MemberPointer:
4304 llvm_unreachable("member pointer type in C");
John McCallf3ea8cf2010-11-14 08:17:51 +00004305 }
David Blaikie7530c032012-01-17 06:56:22 +00004306 llvm_unreachable("Should have returned before this");
Kovarththanan Rajaratnam19357542010-03-13 10:17:05 +00004307
John McCalldaa8e4e2010-11-15 09:13:47 +00004308 case Type::STK_Floating:
4309 switch (DestTy->getScalarTypeKind()) {
4310 case Type::STK_Floating:
John McCall2de56d12010-08-25 11:45:40 +00004311 return CK_FloatingCast;
John McCalldaa8e4e2010-11-15 09:13:47 +00004312 case Type::STK_Bool:
4313 return CK_FloatingToBoolean;
4314 case Type::STK_Integral:
John McCall2de56d12010-08-25 11:45:40 +00004315 return CK_FloatingToIntegral;
John McCalldaa8e4e2010-11-15 09:13:47 +00004316 case Type::STK_FloatingComplex:
John McCalla180f042011-10-06 23:25:11 +00004317 Src = ImpCastExprToType(Src.take(),
4318 DestTy->castAs<ComplexType>()->getElementType(),
4319 CK_FloatingCast);
John McCallf3ea8cf2010-11-14 08:17:51 +00004320 return CK_FloatingRealToComplex;
John McCalldaa8e4e2010-11-15 09:13:47 +00004321 case Type::STK_IntegralComplex:
John McCalla180f042011-10-06 23:25:11 +00004322 Src = ImpCastExprToType(Src.take(),
4323 DestTy->castAs<ComplexType>()->getElementType(),
4324 CK_FloatingToIntegral);
John McCallf3ea8cf2010-11-14 08:17:51 +00004325 return CK_IntegralRealToComplex;
John McCall1d9b3b22011-09-09 05:25:32 +00004326 case Type::STK_CPointer:
4327 case Type::STK_ObjCObjectPointer:
4328 case Type::STK_BlockPointer:
John McCalldaa8e4e2010-11-15 09:13:47 +00004329 llvm_unreachable("valid float->pointer cast?");
4330 case Type::STK_MemberPointer:
4331 llvm_unreachable("member pointer type in C");
John McCallf3ea8cf2010-11-14 08:17:51 +00004332 }
David Blaikie7530c032012-01-17 06:56:22 +00004333 llvm_unreachable("Should have returned before this");
John McCallf3ea8cf2010-11-14 08:17:51 +00004334
John McCalldaa8e4e2010-11-15 09:13:47 +00004335 case Type::STK_FloatingComplex:
4336 switch (DestTy->getScalarTypeKind()) {
4337 case Type::STK_FloatingComplex:
John McCallf3ea8cf2010-11-14 08:17:51 +00004338 return CK_FloatingComplexCast;
John McCalldaa8e4e2010-11-15 09:13:47 +00004339 case Type::STK_IntegralComplex:
John McCallf3ea8cf2010-11-14 08:17:51 +00004340 return CK_FloatingComplexToIntegralComplex;
John McCall8786da72010-12-14 17:51:41 +00004341 case Type::STK_Floating: {
John McCalla180f042011-10-06 23:25:11 +00004342 QualType ET = SrcTy->castAs<ComplexType>()->getElementType();
4343 if (Context.hasSameType(ET, DestTy))
John McCall8786da72010-12-14 17:51:41 +00004344 return CK_FloatingComplexToReal;
John McCalla180f042011-10-06 23:25:11 +00004345 Src = ImpCastExprToType(Src.take(), ET, CK_FloatingComplexToReal);
John McCall8786da72010-12-14 17:51:41 +00004346 return CK_FloatingCast;
4347 }
John McCalldaa8e4e2010-11-15 09:13:47 +00004348 case Type::STK_Bool:
John McCallf3ea8cf2010-11-14 08:17:51 +00004349 return CK_FloatingComplexToBoolean;
John McCalldaa8e4e2010-11-15 09:13:47 +00004350 case Type::STK_Integral:
John McCalla180f042011-10-06 23:25:11 +00004351 Src = ImpCastExprToType(Src.take(),
4352 SrcTy->castAs<ComplexType>()->getElementType(),
4353 CK_FloatingComplexToReal);
John McCallf3ea8cf2010-11-14 08:17:51 +00004354 return CK_FloatingToIntegral;
John McCall1d9b3b22011-09-09 05:25:32 +00004355 case Type::STK_CPointer:
4356 case Type::STK_ObjCObjectPointer:
4357 case Type::STK_BlockPointer:
John McCalldaa8e4e2010-11-15 09:13:47 +00004358 llvm_unreachable("valid complex float->pointer cast?");
4359 case Type::STK_MemberPointer:
4360 llvm_unreachable("member pointer type in C");
John McCallf3ea8cf2010-11-14 08:17:51 +00004361 }
David Blaikie7530c032012-01-17 06:56:22 +00004362 llvm_unreachable("Should have returned before this");
John McCallf3ea8cf2010-11-14 08:17:51 +00004363
John McCalldaa8e4e2010-11-15 09:13:47 +00004364 case Type::STK_IntegralComplex:
4365 switch (DestTy->getScalarTypeKind()) {
4366 case Type::STK_FloatingComplex:
John McCallf3ea8cf2010-11-14 08:17:51 +00004367 return CK_IntegralComplexToFloatingComplex;
John McCalldaa8e4e2010-11-15 09:13:47 +00004368 case Type::STK_IntegralComplex:
John McCallf3ea8cf2010-11-14 08:17:51 +00004369 return CK_IntegralComplexCast;
John McCall8786da72010-12-14 17:51:41 +00004370 case Type::STK_Integral: {
John McCalla180f042011-10-06 23:25:11 +00004371 QualType ET = SrcTy->castAs<ComplexType>()->getElementType();
4372 if (Context.hasSameType(ET, DestTy))
John McCall8786da72010-12-14 17:51:41 +00004373 return CK_IntegralComplexToReal;
John McCalla180f042011-10-06 23:25:11 +00004374 Src = ImpCastExprToType(Src.take(), ET, CK_IntegralComplexToReal);
John McCall8786da72010-12-14 17:51:41 +00004375 return CK_IntegralCast;
4376 }
John McCalldaa8e4e2010-11-15 09:13:47 +00004377 case Type::STK_Bool:
John McCallf3ea8cf2010-11-14 08:17:51 +00004378 return CK_IntegralComplexToBoolean;
John McCalldaa8e4e2010-11-15 09:13:47 +00004379 case Type::STK_Floating:
John McCalla180f042011-10-06 23:25:11 +00004380 Src = ImpCastExprToType(Src.take(),
4381 SrcTy->castAs<ComplexType>()->getElementType(),
4382 CK_IntegralComplexToReal);
John McCallf3ea8cf2010-11-14 08:17:51 +00004383 return CK_IntegralToFloating;
John McCall1d9b3b22011-09-09 05:25:32 +00004384 case Type::STK_CPointer:
4385 case Type::STK_ObjCObjectPointer:
4386 case Type::STK_BlockPointer:
John McCalldaa8e4e2010-11-15 09:13:47 +00004387 llvm_unreachable("valid complex int->pointer cast?");
4388 case Type::STK_MemberPointer:
4389 llvm_unreachable("member pointer type in C");
John McCallf3ea8cf2010-11-14 08:17:51 +00004390 }
David Blaikie7530c032012-01-17 06:56:22 +00004391 llvm_unreachable("Should have returned before this");
Anders Carlsson82debc72009-10-18 18:12:03 +00004392 }
Kovarththanan Rajaratnam19357542010-03-13 10:17:05 +00004393
John McCallf3ea8cf2010-11-14 08:17:51 +00004394 llvm_unreachable("Unhandled scalar cast");
Anders Carlsson82debc72009-10-18 18:12:03 +00004395}
4396
Anders Carlssonc3516322009-10-16 02:48:28 +00004397bool Sema::CheckVectorCast(SourceRange R, QualType VectorTy, QualType Ty,
John McCall2de56d12010-08-25 11:45:40 +00004398 CastKind &Kind) {
Anders Carlssona64db8f2007-11-27 05:51:55 +00004399 assert(VectorTy->isVectorType() && "Not a vector type!");
Mike Stumpeed9cac2009-02-19 03:04:26 +00004400
Anders Carlssona64db8f2007-11-27 05:51:55 +00004401 if (Ty->isVectorType() || Ty->isIntegerType()) {
Chris Lattner98be4942008-03-05 18:54:05 +00004402 if (Context.getTypeSize(VectorTy) != Context.getTypeSize(Ty))
Anders Carlssona64db8f2007-11-27 05:51:55 +00004403 return Diag(R.getBegin(),
Mike Stumpeed9cac2009-02-19 03:04:26 +00004404 Ty->isVectorType() ?
Anders Carlssona64db8f2007-11-27 05:51:55 +00004405 diag::err_invalid_conversion_between_vectors :
Chris Lattnerfa25bbb2008-11-19 05:08:23 +00004406 diag::err_invalid_conversion_between_vector_and_integer)
Chris Lattnerd1625842008-11-24 06:25:27 +00004407 << VectorTy << Ty << R;
Anders Carlssona64db8f2007-11-27 05:51:55 +00004408 } else
4409 return Diag(R.getBegin(),
Chris Lattnerfa25bbb2008-11-19 05:08:23 +00004410 diag::err_invalid_conversion_between_vector_and_scalar)
Chris Lattnerd1625842008-11-24 06:25:27 +00004411 << VectorTy << Ty << R;
Mike Stumpeed9cac2009-02-19 03:04:26 +00004412
John McCall2de56d12010-08-25 11:45:40 +00004413 Kind = CK_BitCast;
Anders Carlssona64db8f2007-11-27 05:51:55 +00004414 return false;
4415}
4416
John Wiegley429bb272011-04-08 18:41:53 +00004417ExprResult Sema::CheckExtVectorCast(SourceRange R, QualType DestTy,
4418 Expr *CastExpr, CastKind &Kind) {
Nate Begeman58d29a42009-06-26 00:50:28 +00004419 assert(DestTy->isExtVectorType() && "Not an extended vector type!");
Kovarththanan Rajaratnam19357542010-03-13 10:17:05 +00004420
Anders Carlsson16a89042009-10-16 05:23:41 +00004421 QualType SrcTy = CastExpr->getType();
Kovarththanan Rajaratnam19357542010-03-13 10:17:05 +00004422
Nate Begeman9b10da62009-06-27 22:05:55 +00004423 // If SrcTy is a VectorType, the total size must match to explicitly cast to
4424 // an ExtVectorType.
Tobias Grosser9df05ea2011-09-22 13:03:14 +00004425 // In OpenCL, casts between vectors of different types are not allowed.
4426 // (See OpenCL 6.2).
Nate Begeman58d29a42009-06-26 00:50:28 +00004427 if (SrcTy->isVectorType()) {
Tobias Grosser9df05ea2011-09-22 13:03:14 +00004428 if (Context.getTypeSize(DestTy) != Context.getTypeSize(SrcTy)
David Blaikie4e4d0842012-03-11 07:00:24 +00004429 || (getLangOpts().OpenCL &&
Tobias Grosser9df05ea2011-09-22 13:03:14 +00004430 (DestTy.getCanonicalType() != SrcTy.getCanonicalType()))) {
John Wiegley429bb272011-04-08 18:41:53 +00004431 Diag(R.getBegin(),diag::err_invalid_conversion_between_ext_vectors)
Nate Begeman58d29a42009-06-26 00:50:28 +00004432 << DestTy << SrcTy << R;
John Wiegley429bb272011-04-08 18:41:53 +00004433 return ExprError();
4434 }
John McCall2de56d12010-08-25 11:45:40 +00004435 Kind = CK_BitCast;
John Wiegley429bb272011-04-08 18:41:53 +00004436 return Owned(CastExpr);
Nate Begeman58d29a42009-06-26 00:50:28 +00004437 }
4438
Nate Begeman1bd1f6e2009-06-28 02:36:38 +00004439 // All non-pointer scalars can be cast to ExtVector type. The appropriate
Nate Begeman58d29a42009-06-26 00:50:28 +00004440 // conversion will take place first from scalar to elt type, and then
4441 // splat from elt type to vector.
Nate Begeman1bd1f6e2009-06-28 02:36:38 +00004442 if (SrcTy->isPointerType())
4443 return Diag(R.getBegin(),
4444 diag::err_invalid_conversion_between_vector_and_scalar)
4445 << DestTy << SrcTy << R;
Eli Friedman73c39ab2009-10-20 08:27:19 +00004446
4447 QualType DestElemTy = DestTy->getAs<ExtVectorType>()->getElementType();
John Wiegley429bb272011-04-08 18:41:53 +00004448 ExprResult CastExprRes = Owned(CastExpr);
John McCalla180f042011-10-06 23:25:11 +00004449 CastKind CK = PrepareScalarCast(CastExprRes, DestElemTy);
John Wiegley429bb272011-04-08 18:41:53 +00004450 if (CastExprRes.isInvalid())
4451 return ExprError();
4452 CastExpr = ImpCastExprToType(CastExprRes.take(), DestElemTy, CK).take();
Kovarththanan Rajaratnam19357542010-03-13 10:17:05 +00004453
John McCall2de56d12010-08-25 11:45:40 +00004454 Kind = CK_VectorSplat;
John Wiegley429bb272011-04-08 18:41:53 +00004455 return Owned(CastExpr);
Nate Begeman58d29a42009-06-26 00:50:28 +00004456}
4457
John McCall60d7b3a2010-08-24 06:29:42 +00004458ExprResult
Argyrios Kyrtzidis0a851832011-07-01 22:22:59 +00004459Sema::ActOnCastExpr(Scope *S, SourceLocation LParenLoc,
4460 Declarator &D, ParsedType &Ty,
Richard Trieuccd891a2011-09-09 01:45:06 +00004461 SourceLocation RParenLoc, Expr *CastExpr) {
4462 assert(!D.isInvalidType() && (CastExpr != 0) &&
Sebastian Redlb8a6aca2009-01-19 22:31:54 +00004463 "ActOnCastExpr(): missing type or expr");
Steve Naroff16beff82007-07-16 23:25:18 +00004464
Richard Trieuccd891a2011-09-09 01:45:06 +00004465 TypeSourceInfo *castTInfo = GetTypeForDeclaratorCast(D, CastExpr->getType());
Argyrios Kyrtzidis0a851832011-07-01 22:22:59 +00004466 if (D.isInvalidType())
4467 return ExprError();
4468
David Blaikie4e4d0842012-03-11 07:00:24 +00004469 if (getLangOpts().CPlusPlus) {
Argyrios Kyrtzidis0a851832011-07-01 22:22:59 +00004470 // Check that there are no default arguments (C++ only).
4471 CheckExtraCXXDefaultArguments(D);
4472 }
4473
John McCalle82247a2011-10-01 05:17:03 +00004474 checkUnusedDeclAttributes(D);
4475
Argyrios Kyrtzidis0a851832011-07-01 22:22:59 +00004476 QualType castType = castTInfo->getType();
4477 Ty = CreateParsedType(castType, castTInfo);
Mike Stump1eb44332009-09-09 15:08:12 +00004478
Argyrios Kyrtzidis707f1012011-07-01 22:22:54 +00004479 bool isVectorLiteral = false;
4480
4481 // Check for an altivec or OpenCL literal,
4482 // i.e. all the elements are integer constants.
Richard Trieuccd891a2011-09-09 01:45:06 +00004483 ParenExpr *PE = dyn_cast<ParenExpr>(CastExpr);
4484 ParenListExpr *PLE = dyn_cast<ParenListExpr>(CastExpr);
David Blaikie4e4d0842012-03-11 07:00:24 +00004485 if ((getLangOpts().AltiVec || getLangOpts().OpenCL)
Tobias Grosser37c31c22011-09-21 18:28:29 +00004486 && castType->isVectorType() && (PE || PLE)) {
Argyrios Kyrtzidis707f1012011-07-01 22:22:54 +00004487 if (PLE && PLE->getNumExprs() == 0) {
4488 Diag(PLE->getExprLoc(), diag::err_altivec_empty_initializer);
4489 return ExprError();
4490 }
4491 if (PE || PLE->getNumExprs() == 1) {
4492 Expr *E = (PE ? PE->getSubExpr() : PLE->getExpr(0));
4493 if (!E->getType()->isVectorType())
4494 isVectorLiteral = true;
4495 }
4496 else
4497 isVectorLiteral = true;
4498 }
4499
4500 // If this is a vector initializer, '(' type ')' '(' init, ..., init ')'
4501 // then handle it as such.
4502 if (isVectorLiteral)
Richard Trieuccd891a2011-09-09 01:45:06 +00004503 return BuildVectorLiteral(LParenLoc, RParenLoc, CastExpr, castTInfo);
Argyrios Kyrtzidis707f1012011-07-01 22:22:54 +00004504
Nate Begeman2ef13e52009-08-10 23:49:36 +00004505 // If the Expr being casted is a ParenListExpr, handle it specially.
Argyrios Kyrtzidis707f1012011-07-01 22:22:54 +00004506 // This is not an AltiVec-style cast, so turn the ParenListExpr into a
4507 // sequence of BinOp comma operators.
Richard Trieuccd891a2011-09-09 01:45:06 +00004508 if (isa<ParenListExpr>(CastExpr)) {
4509 ExprResult Result = MaybeConvertParenListExprToParenExpr(S, CastExpr);
Argyrios Kyrtzidis707f1012011-07-01 22:22:54 +00004510 if (Result.isInvalid()) return ExprError();
Richard Trieuccd891a2011-09-09 01:45:06 +00004511 CastExpr = Result.take();
Argyrios Kyrtzidis707f1012011-07-01 22:22:54 +00004512 }
John McCallb042fdf2010-01-15 18:56:44 +00004513
Richard Trieuccd891a2011-09-09 01:45:06 +00004514 return BuildCStyleCastExpr(LParenLoc, castTInfo, RParenLoc, CastExpr);
John McCallb042fdf2010-01-15 18:56:44 +00004515}
4516
Argyrios Kyrtzidis707f1012011-07-01 22:22:54 +00004517ExprResult Sema::BuildVectorLiteral(SourceLocation LParenLoc,
4518 SourceLocation RParenLoc, Expr *E,
4519 TypeSourceInfo *TInfo) {
4520 assert((isa<ParenListExpr>(E) || isa<ParenExpr>(E)) &&
4521 "Expected paren or paren list expression");
4522
4523 Expr **exprs;
4524 unsigned numExprs;
4525 Expr *subExpr;
4526 if (ParenListExpr *PE = dyn_cast<ParenListExpr>(E)) {
4527 exprs = PE->getExprs();
4528 numExprs = PE->getNumExprs();
4529 } else {
4530 subExpr = cast<ParenExpr>(E)->getSubExpr();
4531 exprs = &subExpr;
4532 numExprs = 1;
4533 }
4534
4535 QualType Ty = TInfo->getType();
4536 assert(Ty->isVectorType() && "Expected vector type");
4537
Chris Lattner5f9e2722011-07-23 10:55:15 +00004538 SmallVector<Expr *, 8> initExprs;
Tanya Lattner61b4bc82011-07-15 23:07:01 +00004539 const VectorType *VTy = Ty->getAs<VectorType>();
4540 unsigned numElems = Ty->getAs<VectorType>()->getNumElements();
4541
Argyrios Kyrtzidis707f1012011-07-01 22:22:54 +00004542 // '(...)' form of vector initialization in AltiVec: the number of
4543 // initializers must be one or must match the size of the vector.
4544 // If a single value is specified in the initializer then it will be
4545 // replicated to all the components of the vector
Tanya Lattner61b4bc82011-07-15 23:07:01 +00004546 if (VTy->getVectorKind() == VectorType::AltiVecVector) {
Argyrios Kyrtzidis707f1012011-07-01 22:22:54 +00004547 // The number of initializers must be one or must match the size of the
4548 // vector. If a single value is specified in the initializer then it will
4549 // be replicated to all the components of the vector
4550 if (numExprs == 1) {
4551 QualType ElemTy = Ty->getAs<VectorType>()->getElementType();
Richard Smith61ffd092011-10-27 23:31:58 +00004552 ExprResult Literal = DefaultLvalueConversion(exprs[0]);
4553 if (Literal.isInvalid())
4554 return ExprError();
Argyrios Kyrtzidis707f1012011-07-01 22:22:54 +00004555 Literal = ImpCastExprToType(Literal.take(), ElemTy,
John McCalla180f042011-10-06 23:25:11 +00004556 PrepareScalarCast(Literal, ElemTy));
Argyrios Kyrtzidis707f1012011-07-01 22:22:54 +00004557 return BuildCStyleCastExpr(LParenLoc, TInfo, RParenLoc, Literal.take());
4558 }
4559 else if (numExprs < numElems) {
4560 Diag(E->getExprLoc(),
4561 diag::err_incorrect_number_of_vector_initializers);
4562 return ExprError();
4563 }
4564 else
Benjamin Kramer14c59822012-02-14 12:06:21 +00004565 initExprs.append(exprs, exprs + numExprs);
Argyrios Kyrtzidis707f1012011-07-01 22:22:54 +00004566 }
Tanya Lattner61b4bc82011-07-15 23:07:01 +00004567 else {
4568 // For OpenCL, when the number of initializers is a single value,
4569 // it will be replicated to all components of the vector.
David Blaikie4e4d0842012-03-11 07:00:24 +00004570 if (getLangOpts().OpenCL &&
Tanya Lattner61b4bc82011-07-15 23:07:01 +00004571 VTy->getVectorKind() == VectorType::GenericVector &&
4572 numExprs == 1) {
4573 QualType ElemTy = Ty->getAs<VectorType>()->getElementType();
Richard Smith61ffd092011-10-27 23:31:58 +00004574 ExprResult Literal = DefaultLvalueConversion(exprs[0]);
4575 if (Literal.isInvalid())
4576 return ExprError();
Tanya Lattner61b4bc82011-07-15 23:07:01 +00004577 Literal = ImpCastExprToType(Literal.take(), ElemTy,
John McCalla180f042011-10-06 23:25:11 +00004578 PrepareScalarCast(Literal, ElemTy));
Tanya Lattner61b4bc82011-07-15 23:07:01 +00004579 return BuildCStyleCastExpr(LParenLoc, TInfo, RParenLoc, Literal.take());
4580 }
4581
Benjamin Kramer14c59822012-02-14 12:06:21 +00004582 initExprs.append(exprs, exprs + numExprs);
Tanya Lattner61b4bc82011-07-15 23:07:01 +00004583 }
Argyrios Kyrtzidis707f1012011-07-01 22:22:54 +00004584 // FIXME: This means that pretty-printing the final AST will produce curly
4585 // braces instead of the original commas.
4586 InitListExpr *initE = new (Context) InitListExpr(Context, LParenLoc,
Benjamin Kramer3b6bef92012-08-24 11:54:20 +00004587 initExprs, RParenLoc);
Argyrios Kyrtzidis707f1012011-07-01 22:22:54 +00004588 initE->setType(Ty);
4589 return BuildCompoundLiteralExpr(LParenLoc, TInfo, RParenLoc, initE);
4590}
4591
Sebastian Redl5b9cc5d2012-02-11 23:51:47 +00004592/// This is not an AltiVec-style cast or or C++ direct-initialization, so turn
4593/// the ParenListExpr into a sequence of comma binary operators.
John McCall60d7b3a2010-08-24 06:29:42 +00004594ExprResult
Richard Trieuccd891a2011-09-09 01:45:06 +00004595Sema::MaybeConvertParenListExprToParenExpr(Scope *S, Expr *OrigExpr) {
4596 ParenListExpr *E = dyn_cast<ParenListExpr>(OrigExpr);
Nate Begeman2ef13e52009-08-10 23:49:36 +00004597 if (!E)
Richard Trieuccd891a2011-09-09 01:45:06 +00004598 return Owned(OrigExpr);
Mike Stump1eb44332009-09-09 15:08:12 +00004599
John McCall60d7b3a2010-08-24 06:29:42 +00004600 ExprResult Result(E->getExpr(0));
Mike Stump1eb44332009-09-09 15:08:12 +00004601
Nate Begeman2ef13e52009-08-10 23:49:36 +00004602 for (unsigned i = 1, e = E->getNumExprs(); i != e && !Result.isInvalid(); ++i)
John McCall9ae2f072010-08-23 23:25:46 +00004603 Result = ActOnBinOp(S, E->getExprLoc(), tok::comma, Result.get(),
4604 E->getExpr(i));
Mike Stump1eb44332009-09-09 15:08:12 +00004605
John McCall9ae2f072010-08-23 23:25:46 +00004606 if (Result.isInvalid()) return ExprError();
4607
4608 return ActOnParenExpr(E->getLParenLoc(), E->getRParenLoc(), Result.get());
Nate Begeman2ef13e52009-08-10 23:49:36 +00004609}
4610
Sebastian Redl5b9cc5d2012-02-11 23:51:47 +00004611ExprResult Sema::ActOnParenListExpr(SourceLocation L,
4612 SourceLocation R,
4613 MultiExprArg Val) {
Benjamin Kramer3b6bef92012-08-24 11:54:20 +00004614 assert(Val.data() != 0 && "ActOnParenOrParenListExpr() missing expr list");
4615 Expr *expr = new (Context) ParenListExpr(Context, L, Val, R);
Nate Begeman2ef13e52009-08-10 23:49:36 +00004616 return Owned(expr);
4617}
4618
Chandler Carruth82214a82011-02-18 23:54:50 +00004619/// \brief Emit a specialized diagnostic when one expression is a null pointer
Richard Trieu26f96072011-09-02 01:51:02 +00004620/// constant and the other is not a pointer. Returns true if a diagnostic is
4621/// emitted.
Richard Trieu33fc7572011-09-06 20:06:39 +00004622bool Sema::DiagnoseConditionalForNull(Expr *LHSExpr, Expr *RHSExpr,
Chandler Carruth82214a82011-02-18 23:54:50 +00004623 SourceLocation QuestionLoc) {
Richard Trieu33fc7572011-09-06 20:06:39 +00004624 Expr *NullExpr = LHSExpr;
4625 Expr *NonPointerExpr = RHSExpr;
Chandler Carruth82214a82011-02-18 23:54:50 +00004626 Expr::NullPointerConstantKind NullKind =
4627 NullExpr->isNullPointerConstant(Context,
4628 Expr::NPC_ValueDependentIsNotNull);
4629
4630 if (NullKind == Expr::NPCK_NotNull) {
Richard Trieu33fc7572011-09-06 20:06:39 +00004631 NullExpr = RHSExpr;
4632 NonPointerExpr = LHSExpr;
Chandler Carruth82214a82011-02-18 23:54:50 +00004633 NullKind =
4634 NullExpr->isNullPointerConstant(Context,
4635 Expr::NPC_ValueDependentIsNotNull);
4636 }
4637
4638 if (NullKind == Expr::NPCK_NotNull)
4639 return false;
4640
David Blaikie50800fc2012-08-08 17:33:31 +00004641 if (NullKind == Expr::NPCK_ZeroExpression)
4642 return false;
4643
4644 if (NullKind == Expr::NPCK_ZeroLiteral) {
Chandler Carruth82214a82011-02-18 23:54:50 +00004645 // In this case, check to make sure that we got here from a "NULL"
4646 // string in the source code.
4647 NullExpr = NullExpr->IgnoreParenImpCasts();
John McCall834e3f62011-03-08 07:59:04 +00004648 SourceLocation loc = NullExpr->getExprLoc();
4649 if (!findMacroSpelling(loc, "NULL"))
Chandler Carruth82214a82011-02-18 23:54:50 +00004650 return false;
4651 }
4652
4653 int DiagType = (NullKind == Expr::NPCK_CXX0X_nullptr);
4654 Diag(QuestionLoc, diag::err_typecheck_cond_incompatible_operands_null)
4655 << NonPointerExpr->getType() << DiagType
4656 << NonPointerExpr->getSourceRange();
4657 return true;
4658}
4659
Richard Trieu26f96072011-09-02 01:51:02 +00004660/// \brief Return false if the condition expression is valid, true otherwise.
4661static bool checkCondition(Sema &S, Expr *Cond) {
4662 QualType CondTy = Cond->getType();
4663
4664 // C99 6.5.15p2
4665 if (CondTy->isScalarType()) return false;
4666
4667 // OpenCL: Sec 6.3.i says the condition is allowed to be a vector or scalar.
David Blaikie4e4d0842012-03-11 07:00:24 +00004668 if (S.getLangOpts().OpenCL && CondTy->isVectorType())
Richard Trieu26f96072011-09-02 01:51:02 +00004669 return false;
4670
4671 // Emit the proper error message.
David Blaikie4e4d0842012-03-11 07:00:24 +00004672 S.Diag(Cond->getLocStart(), S.getLangOpts().OpenCL ?
Richard Trieu26f96072011-09-02 01:51:02 +00004673 diag::err_typecheck_cond_expect_scalar :
4674 diag::err_typecheck_cond_expect_scalar_or_vector)
4675 << CondTy;
4676 return true;
4677}
4678
4679/// \brief Return false if the two expressions can be converted to a vector,
4680/// true otherwise
4681static bool checkConditionalConvertScalarsToVectors(Sema &S, ExprResult &LHS,
4682 ExprResult &RHS,
4683 QualType CondTy) {
4684 // Both operands should be of scalar type.
4685 if (!LHS.get()->getType()->isScalarType()) {
4686 S.Diag(LHS.get()->getLocStart(), diag::err_typecheck_cond_expect_scalar)
4687 << CondTy;
4688 return true;
4689 }
4690 if (!RHS.get()->getType()->isScalarType()) {
4691 S.Diag(RHS.get()->getLocStart(), diag::err_typecheck_cond_expect_scalar)
4692 << CondTy;
4693 return true;
4694 }
4695
4696 // Implicity convert these scalars to the type of the condition.
4697 LHS = S.ImpCastExprToType(LHS.take(), CondTy, CK_IntegralCast);
4698 RHS = S.ImpCastExprToType(RHS.take(), CondTy, CK_IntegralCast);
4699 return false;
4700}
4701
4702/// \brief Handle when one or both operands are void type.
4703static QualType checkConditionalVoidType(Sema &S, ExprResult &LHS,
4704 ExprResult &RHS) {
4705 Expr *LHSExpr = LHS.get();
4706 Expr *RHSExpr = RHS.get();
4707
4708 if (!LHSExpr->getType()->isVoidType())
4709 S.Diag(RHSExpr->getLocStart(), diag::ext_typecheck_cond_one_void)
4710 << RHSExpr->getSourceRange();
4711 if (!RHSExpr->getType()->isVoidType())
4712 S.Diag(LHSExpr->getLocStart(), diag::ext_typecheck_cond_one_void)
4713 << LHSExpr->getSourceRange();
4714 LHS = S.ImpCastExprToType(LHS.take(), S.Context.VoidTy, CK_ToVoid);
4715 RHS = S.ImpCastExprToType(RHS.take(), S.Context.VoidTy, CK_ToVoid);
4716 return S.Context.VoidTy;
4717}
4718
4719/// \brief Return false if the NullExpr can be promoted to PointerTy,
4720/// true otherwise.
4721static bool checkConditionalNullPointer(Sema &S, ExprResult &NullExpr,
4722 QualType PointerTy) {
4723 if ((!PointerTy->isAnyPointerType() && !PointerTy->isBlockPointerType()) ||
4724 !NullExpr.get()->isNullPointerConstant(S.Context,
4725 Expr::NPC_ValueDependentIsNull))
4726 return true;
4727
4728 NullExpr = S.ImpCastExprToType(NullExpr.take(), PointerTy, CK_NullToPointer);
4729 return false;
4730}
4731
4732/// \brief Checks compatibility between two pointers and return the resulting
4733/// type.
4734static QualType checkConditionalPointerCompatibility(Sema &S, ExprResult &LHS,
4735 ExprResult &RHS,
4736 SourceLocation Loc) {
4737 QualType LHSTy = LHS.get()->getType();
4738 QualType RHSTy = RHS.get()->getType();
4739
4740 if (S.Context.hasSameType(LHSTy, RHSTy)) {
4741 // Two identical pointers types are always compatible.
4742 return LHSTy;
4743 }
4744
4745 QualType lhptee, rhptee;
4746
4747 // Get the pointee types.
John McCall1d9b3b22011-09-09 05:25:32 +00004748 if (const BlockPointerType *LHSBTy = LHSTy->getAs<BlockPointerType>()) {
4749 lhptee = LHSBTy->getPointeeType();
4750 rhptee = RHSTy->castAs<BlockPointerType>()->getPointeeType();
Richard Trieu26f96072011-09-02 01:51:02 +00004751 } else {
John McCall1d9b3b22011-09-09 05:25:32 +00004752 lhptee = LHSTy->castAs<PointerType>()->getPointeeType();
4753 rhptee = RHSTy->castAs<PointerType>()->getPointeeType();
Richard Trieu26f96072011-09-02 01:51:02 +00004754 }
4755
Eli Friedmanae916a12012-04-05 22:30:04 +00004756 // C99 6.5.15p6: If both operands are pointers to compatible types or to
4757 // differently qualified versions of compatible types, the result type is
4758 // a pointer to an appropriately qualified version of the composite
4759 // type.
4760
4761 // Only CVR-qualifiers exist in the standard, and the differently-qualified
4762 // clause doesn't make sense for our extensions. E.g. address space 2 should
4763 // be incompatible with address space 3: they may live on different devices or
4764 // anything.
4765 Qualifiers lhQual = lhptee.getQualifiers();
4766 Qualifiers rhQual = rhptee.getQualifiers();
4767
4768 unsigned MergedCVRQual = lhQual.getCVRQualifiers() | rhQual.getCVRQualifiers();
4769 lhQual.removeCVRQualifiers();
4770 rhQual.removeCVRQualifiers();
4771
4772 lhptee = S.Context.getQualifiedType(lhptee.getUnqualifiedType(), lhQual);
4773 rhptee = S.Context.getQualifiedType(rhptee.getUnqualifiedType(), rhQual);
4774
4775 QualType CompositeTy = S.Context.mergeTypes(lhptee, rhptee);
4776
4777 if (CompositeTy.isNull()) {
Richard Trieu26f96072011-09-02 01:51:02 +00004778 S.Diag(Loc, diag::warn_typecheck_cond_incompatible_pointers)
4779 << LHSTy << RHSTy << LHS.get()->getSourceRange()
4780 << RHS.get()->getSourceRange();
4781 // In this situation, we assume void* type. No especially good
4782 // reason, but this is what gcc does, and we do have to pick
4783 // to get a consistent AST.
4784 QualType incompatTy = S.Context.getPointerType(S.Context.VoidTy);
4785 LHS = S.ImpCastExprToType(LHS.take(), incompatTy, CK_BitCast);
4786 RHS = S.ImpCastExprToType(RHS.take(), incompatTy, CK_BitCast);
4787 return incompatTy;
4788 }
4789
4790 // The pointer types are compatible.
Eli Friedmanae916a12012-04-05 22:30:04 +00004791 QualType ResultTy = CompositeTy.withCVRQualifiers(MergedCVRQual);
4792 ResultTy = S.Context.getPointerType(ResultTy);
Richard Trieu26f96072011-09-02 01:51:02 +00004793
Eli Friedmanae916a12012-04-05 22:30:04 +00004794 LHS = S.ImpCastExprToType(LHS.take(), ResultTy, CK_BitCast);
4795 RHS = S.ImpCastExprToType(RHS.take(), ResultTy, CK_BitCast);
4796 return ResultTy;
Richard Trieu26f96072011-09-02 01:51:02 +00004797}
4798
4799/// \brief Return the resulting type when the operands are both block pointers.
4800static QualType checkConditionalBlockPointerCompatibility(Sema &S,
4801 ExprResult &LHS,
4802 ExprResult &RHS,
4803 SourceLocation Loc) {
4804 QualType LHSTy = LHS.get()->getType();
4805 QualType RHSTy = RHS.get()->getType();
4806
4807 if (!LHSTy->isBlockPointerType() || !RHSTy->isBlockPointerType()) {
4808 if (LHSTy->isVoidPointerType() || RHSTy->isVoidPointerType()) {
4809 QualType destType = S.Context.getPointerType(S.Context.VoidTy);
4810 LHS = S.ImpCastExprToType(LHS.take(), destType, CK_BitCast);
4811 RHS = S.ImpCastExprToType(RHS.take(), destType, CK_BitCast);
4812 return destType;
4813 }
4814 S.Diag(Loc, diag::err_typecheck_cond_incompatible_operands)
4815 << LHSTy << RHSTy << LHS.get()->getSourceRange()
4816 << RHS.get()->getSourceRange();
4817 return QualType();
4818 }
4819
4820 // We have 2 block pointer types.
4821 return checkConditionalPointerCompatibility(S, LHS, RHS, Loc);
4822}
4823
4824/// \brief Return the resulting type when the operands are both pointers.
4825static QualType
4826checkConditionalObjectPointersCompatibility(Sema &S, ExprResult &LHS,
4827 ExprResult &RHS,
4828 SourceLocation Loc) {
4829 // get the pointer types
4830 QualType LHSTy = LHS.get()->getType();
4831 QualType RHSTy = RHS.get()->getType();
4832
4833 // get the "pointed to" types
4834 QualType lhptee = LHSTy->getAs<PointerType>()->getPointeeType();
4835 QualType rhptee = RHSTy->getAs<PointerType>()->getPointeeType();
4836
4837 // ignore qualifiers on void (C99 6.5.15p3, clause 6)
4838 if (lhptee->isVoidType() && rhptee->isIncompleteOrObjectType()) {
4839 // Figure out necessary qualifiers (C99 6.5.15p6)
4840 QualType destPointee
4841 = S.Context.getQualifiedType(lhptee, rhptee.getQualifiers());
4842 QualType destType = S.Context.getPointerType(destPointee);
4843 // Add qualifiers if necessary.
4844 LHS = S.ImpCastExprToType(LHS.take(), destType, CK_NoOp);
4845 // Promote to void*.
4846 RHS = S.ImpCastExprToType(RHS.take(), destType, CK_BitCast);
4847 return destType;
4848 }
4849 if (rhptee->isVoidType() && lhptee->isIncompleteOrObjectType()) {
4850 QualType destPointee
4851 = S.Context.getQualifiedType(rhptee, lhptee.getQualifiers());
4852 QualType destType = S.Context.getPointerType(destPointee);
4853 // Add qualifiers if necessary.
4854 RHS = S.ImpCastExprToType(RHS.take(), destType, CK_NoOp);
4855 // Promote to void*.
4856 LHS = S.ImpCastExprToType(LHS.take(), destType, CK_BitCast);
4857 return destType;
4858 }
4859
4860 return checkConditionalPointerCompatibility(S, LHS, RHS, Loc);
4861}
4862
4863/// \brief Return false if the first expression is not an integer and the second
4864/// expression is not a pointer, true otherwise.
4865static bool checkPointerIntegerMismatch(Sema &S, ExprResult &Int,
4866 Expr* PointerExpr, SourceLocation Loc,
Richard Trieuccd891a2011-09-09 01:45:06 +00004867 bool IsIntFirstExpr) {
Richard Trieu26f96072011-09-02 01:51:02 +00004868 if (!PointerExpr->getType()->isPointerType() ||
4869 !Int.get()->getType()->isIntegerType())
4870 return false;
4871
Richard Trieuccd891a2011-09-09 01:45:06 +00004872 Expr *Expr1 = IsIntFirstExpr ? Int.get() : PointerExpr;
4873 Expr *Expr2 = IsIntFirstExpr ? PointerExpr : Int.get();
Richard Trieu26f96072011-09-02 01:51:02 +00004874
4875 S.Diag(Loc, diag::warn_typecheck_cond_pointer_integer_mismatch)
4876 << Expr1->getType() << Expr2->getType()
4877 << Expr1->getSourceRange() << Expr2->getSourceRange();
4878 Int = S.ImpCastExprToType(Int.take(), PointerExpr->getType(),
4879 CK_IntegralToPointer);
4880 return true;
4881}
4882
Richard Trieu33fc7572011-09-06 20:06:39 +00004883/// Note that LHS is not null here, even if this is the gnu "x ?: y" extension.
4884/// In that case, LHS = cond.
Chris Lattnera119a3b2009-02-18 04:38:20 +00004885/// C99 6.5.15
Richard Trieu67e29332011-08-02 04:35:43 +00004886QualType Sema::CheckConditionalOperands(ExprResult &Cond, ExprResult &LHS,
4887 ExprResult &RHS, ExprValueKind &VK,
4888 ExprObjectKind &OK,
Chris Lattnera119a3b2009-02-18 04:38:20 +00004889 SourceLocation QuestionLoc) {
Douglas Gregorfadb53b2011-03-12 01:48:56 +00004890
Richard Trieu33fc7572011-09-06 20:06:39 +00004891 ExprResult LHSResult = CheckPlaceholderExpr(LHS.get());
4892 if (!LHSResult.isUsable()) return QualType();
Benjamin Kramer3fe198b2012-08-23 21:35:17 +00004893 LHS = LHSResult;
Douglas Gregor7ad5d422010-11-09 21:07:58 +00004894
Richard Trieu33fc7572011-09-06 20:06:39 +00004895 ExprResult RHSResult = CheckPlaceholderExpr(RHS.get());
4896 if (!RHSResult.isUsable()) return QualType();
Benjamin Kramer3fe198b2012-08-23 21:35:17 +00004897 RHS = RHSResult;
Douglas Gregor7ad5d422010-11-09 21:07:58 +00004898
Sebastian Redl3201f6b2009-04-16 17:51:27 +00004899 // C++ is sufficiently different to merit its own checker.
David Blaikie4e4d0842012-03-11 07:00:24 +00004900 if (getLangOpts().CPlusPlus)
John McCall56ca35d2011-02-17 10:25:35 +00004901 return CXXCheckConditionalOperands(Cond, LHS, RHS, VK, OK, QuestionLoc);
John McCallf89e55a2010-11-18 06:31:45 +00004902
4903 VK = VK_RValue;
John McCall09431682010-11-18 19:01:18 +00004904 OK = OK_Ordinary;
Sebastian Redl3201f6b2009-04-16 17:51:27 +00004905
John Wiegley429bb272011-04-08 18:41:53 +00004906 Cond = UsualUnaryConversions(Cond.take());
4907 if (Cond.isInvalid())
4908 return QualType();
4909 LHS = UsualUnaryConversions(LHS.take());
4910 if (LHS.isInvalid())
4911 return QualType();
4912 RHS = UsualUnaryConversions(RHS.take());
4913 if (RHS.isInvalid())
4914 return QualType();
4915
4916 QualType CondTy = Cond.get()->getType();
4917 QualType LHSTy = LHS.get()->getType();
4918 QualType RHSTy = RHS.get()->getType();
Steve Naroffc80b4ee2007-07-16 21:54:35 +00004919
Reid Spencer5f016e22007-07-11 17:01:13 +00004920 // first, check the condition.
Richard Trieu26f96072011-09-02 01:51:02 +00004921 if (checkCondition(*this, Cond.get()))
4922 return QualType();
Mike Stumpeed9cac2009-02-19 03:04:26 +00004923
Chris Lattner70d67a92008-01-06 22:42:25 +00004924 // Now check the two expressions.
Nate Begeman2ef13e52009-08-10 23:49:36 +00004925 if (LHSTy->isVectorType() || RHSTy->isVectorType())
Eli Friedmanb9b4b782011-06-23 18:10:35 +00004926 return CheckVectorOperands(LHS, RHS, QuestionLoc, /*isCompAssign*/false);
Douglas Gregor898574e2008-12-05 23:32:09 +00004927
Nate Begeman6155d732010-09-20 22:41:17 +00004928 // OpenCL: If the condition is a vector, and both operands are scalar,
4929 // attempt to implicity convert them to the vector type to act like the
4930 // built in select.
David Blaikie4e4d0842012-03-11 07:00:24 +00004931 if (getLangOpts().OpenCL && CondTy->isVectorType())
Richard Trieu26f96072011-09-02 01:51:02 +00004932 if (checkConditionalConvertScalarsToVectors(*this, LHS, RHS, CondTy))
Nate Begeman6155d732010-09-20 22:41:17 +00004933 return QualType();
Nate Begeman6155d732010-09-20 22:41:17 +00004934
Chris Lattner70d67a92008-01-06 22:42:25 +00004935 // If both operands have arithmetic type, do the usual arithmetic conversions
4936 // to find a common type: C99 6.5.15p3,5.
Chris Lattnerefdc39d2009-02-18 04:28:32 +00004937 if (LHSTy->isArithmeticType() && RHSTy->isArithmeticType()) {
4938 UsualArithmeticConversions(LHS, RHS);
John Wiegley429bb272011-04-08 18:41:53 +00004939 if (LHS.isInvalid() || RHS.isInvalid())
4940 return QualType();
4941 return LHS.get()->getType();
Steve Naroffa4332e22007-07-17 00:58:39 +00004942 }
Mike Stumpeed9cac2009-02-19 03:04:26 +00004943
Chris Lattner70d67a92008-01-06 22:42:25 +00004944 // If both operands are the same structure or union type, the result is that
4945 // type.
Ted Kremenek6217b802009-07-29 21:53:49 +00004946 if (const RecordType *LHSRT = LHSTy->getAs<RecordType>()) { // C99 6.5.15p3
4947 if (const RecordType *RHSRT = RHSTy->getAs<RecordType>())
Chris Lattnera21ddb32007-11-26 01:40:58 +00004948 if (LHSRT->getDecl() == RHSRT->getDecl())
Mike Stumpeed9cac2009-02-19 03:04:26 +00004949 // "If both the operands have structure or union type, the result has
Chris Lattner70d67a92008-01-06 22:42:25 +00004950 // that type." This implies that CV qualifiers are dropped.
Chris Lattnerefdc39d2009-02-18 04:28:32 +00004951 return LHSTy.getUnqualifiedType();
Eli Friedmanb1d796d2009-03-23 00:24:07 +00004952 // FIXME: Type of conditional expression must be complete in C mode.
Reid Spencer5f016e22007-07-11 17:01:13 +00004953 }
Mike Stumpeed9cac2009-02-19 03:04:26 +00004954
Chris Lattner70d67a92008-01-06 22:42:25 +00004955 // C99 6.5.15p5: "If both operands have void type, the result has void type."
Steve Naroffe701c0a2008-05-12 21:44:38 +00004956 // The following || allows only one side to be void (a GCC-ism).
Chris Lattnerefdc39d2009-02-18 04:28:32 +00004957 if (LHSTy->isVoidType() || RHSTy->isVoidType()) {
Richard Trieu26f96072011-09-02 01:51:02 +00004958 return checkConditionalVoidType(*this, LHS, RHS);
Steve Naroffe701c0a2008-05-12 21:44:38 +00004959 }
Richard Trieu26f96072011-09-02 01:51:02 +00004960
Steve Naroffb6d54e52008-01-08 01:11:38 +00004961 // C99 6.5.15p6 - "if one operand is a null pointer constant, the result has
4962 // the type of the other operand."
Richard Trieu26f96072011-09-02 01:51:02 +00004963 if (!checkConditionalNullPointer(*this, RHS, LHSTy)) return LHSTy;
4964 if (!checkConditionalNullPointer(*this, LHS, RHSTy)) return RHSTy;
Kovarththanan Rajaratnam19357542010-03-13 10:17:05 +00004965
Fariborz Jahanianeebc4752009-12-10 19:47:41 +00004966 // All objective-c pointer type analysis is done here.
4967 QualType compositeType = FindCompositeObjCPointerType(LHS, RHS,
4968 QuestionLoc);
John Wiegley429bb272011-04-08 18:41:53 +00004969 if (LHS.isInvalid() || RHS.isInvalid())
4970 return QualType();
Fariborz Jahanianeebc4752009-12-10 19:47:41 +00004971 if (!compositeType.isNull())
4972 return compositeType;
Kovarththanan Rajaratnam19357542010-03-13 10:17:05 +00004973
4974
Steve Naroff7154a772009-07-01 14:36:47 +00004975 // Handle block pointer types.
Richard Trieu26f96072011-09-02 01:51:02 +00004976 if (LHSTy->isBlockPointerType() || RHSTy->isBlockPointerType())
4977 return checkConditionalBlockPointerCompatibility(*this, LHS, RHS,
4978 QuestionLoc);
Kovarththanan Rajaratnam19357542010-03-13 10:17:05 +00004979
Steve Naroff7154a772009-07-01 14:36:47 +00004980 // Check constraints for C object pointers types (C99 6.5.15p3,6).
Richard Trieu26f96072011-09-02 01:51:02 +00004981 if (LHSTy->isPointerType() && RHSTy->isPointerType())
4982 return checkConditionalObjectPointersCompatibility(*this, LHS, RHS,
4983 QuestionLoc);
Mike Stump1eb44332009-09-09 15:08:12 +00004984
John McCall404cd162010-11-13 01:35:44 +00004985 // GCC compatibility: soften pointer/integer mismatch. Note that
4986 // null pointers have been filtered out by this point.
Richard Trieu26f96072011-09-02 01:51:02 +00004987 if (checkPointerIntegerMismatch(*this, LHS, RHS.get(), QuestionLoc,
4988 /*isIntFirstExpr=*/true))
Steve Naroff7154a772009-07-01 14:36:47 +00004989 return RHSTy;
Richard Trieu26f96072011-09-02 01:51:02 +00004990 if (checkPointerIntegerMismatch(*this, RHS, LHS.get(), QuestionLoc,
4991 /*isIntFirstExpr=*/false))
Steve Naroff7154a772009-07-01 14:36:47 +00004992 return LHSTy;
Daniel Dunbar5e155f02008-09-11 23:12:46 +00004993
Chandler Carruth82214a82011-02-18 23:54:50 +00004994 // Emit a better diagnostic if one of the expressions is a null pointer
4995 // constant and the other is not a pointer type. In this case, the user most
4996 // likely forgot to take the address of the other expression.
John Wiegley429bb272011-04-08 18:41:53 +00004997 if (DiagnoseConditionalForNull(LHS.get(), RHS.get(), QuestionLoc))
Chandler Carruth82214a82011-02-18 23:54:50 +00004998 return QualType();
4999
Chris Lattner70d67a92008-01-06 22:42:25 +00005000 // Otherwise, the operands are not compatible.
Chris Lattnerefdc39d2009-02-18 04:28:32 +00005001 Diag(QuestionLoc, diag::err_typecheck_cond_incompatible_operands)
Richard Trieu67e29332011-08-02 04:35:43 +00005002 << LHSTy << RHSTy << LHS.get()->getSourceRange()
5003 << RHS.get()->getSourceRange();
Reid Spencer5f016e22007-07-11 17:01:13 +00005004 return QualType();
5005}
5006
Fariborz Jahanianeebc4752009-12-10 19:47:41 +00005007/// FindCompositeObjCPointerType - Helper method to find composite type of
5008/// two objective-c pointer types of the two input expressions.
John Wiegley429bb272011-04-08 18:41:53 +00005009QualType Sema::FindCompositeObjCPointerType(ExprResult &LHS, ExprResult &RHS,
Richard Trieu67e29332011-08-02 04:35:43 +00005010 SourceLocation QuestionLoc) {
John Wiegley429bb272011-04-08 18:41:53 +00005011 QualType LHSTy = LHS.get()->getType();
5012 QualType RHSTy = RHS.get()->getType();
Kovarththanan Rajaratnam19357542010-03-13 10:17:05 +00005013
Fariborz Jahanianeebc4752009-12-10 19:47:41 +00005014 // Handle things like Class and struct objc_class*. Here we case the result
5015 // to the pseudo-builtin, because that will be implicitly cast back to the
5016 // redefinition type if an attempt is made to access its fields.
5017 if (LHSTy->isObjCClassType() &&
Douglas Gregor01a4cf12011-08-11 20:58:55 +00005018 (Context.hasSameType(RHSTy, Context.getObjCClassRedefinitionType()))) {
John McCall1d9b3b22011-09-09 05:25:32 +00005019 RHS = ImpCastExprToType(RHS.take(), LHSTy, CK_CPointerToObjCPointerCast);
Fariborz Jahanianeebc4752009-12-10 19:47:41 +00005020 return LHSTy;
5021 }
5022 if (RHSTy->isObjCClassType() &&
Douglas Gregor01a4cf12011-08-11 20:58:55 +00005023 (Context.hasSameType(LHSTy, Context.getObjCClassRedefinitionType()))) {
John McCall1d9b3b22011-09-09 05:25:32 +00005024 LHS = ImpCastExprToType(LHS.take(), RHSTy, CK_CPointerToObjCPointerCast);
Fariborz Jahanianeebc4752009-12-10 19:47:41 +00005025 return RHSTy;
5026 }
5027 // And the same for struct objc_object* / id
5028 if (LHSTy->isObjCIdType() &&
Douglas Gregor01a4cf12011-08-11 20:58:55 +00005029 (Context.hasSameType(RHSTy, Context.getObjCIdRedefinitionType()))) {
John McCall1d9b3b22011-09-09 05:25:32 +00005030 RHS = ImpCastExprToType(RHS.take(), LHSTy, CK_CPointerToObjCPointerCast);
Fariborz Jahanianeebc4752009-12-10 19:47:41 +00005031 return LHSTy;
5032 }
5033 if (RHSTy->isObjCIdType() &&
Douglas Gregor01a4cf12011-08-11 20:58:55 +00005034 (Context.hasSameType(LHSTy, Context.getObjCIdRedefinitionType()))) {
John McCall1d9b3b22011-09-09 05:25:32 +00005035 LHS = ImpCastExprToType(LHS.take(), RHSTy, CK_CPointerToObjCPointerCast);
Fariborz Jahanianeebc4752009-12-10 19:47:41 +00005036 return RHSTy;
5037 }
5038 // And the same for struct objc_selector* / SEL
5039 if (Context.isObjCSelType(LHSTy) &&
Douglas Gregor01a4cf12011-08-11 20:58:55 +00005040 (Context.hasSameType(RHSTy, Context.getObjCSelRedefinitionType()))) {
John Wiegley429bb272011-04-08 18:41:53 +00005041 RHS = ImpCastExprToType(RHS.take(), LHSTy, CK_BitCast);
Fariborz Jahanianeebc4752009-12-10 19:47:41 +00005042 return LHSTy;
5043 }
5044 if (Context.isObjCSelType(RHSTy) &&
Douglas Gregor01a4cf12011-08-11 20:58:55 +00005045 (Context.hasSameType(LHSTy, Context.getObjCSelRedefinitionType()))) {
John Wiegley429bb272011-04-08 18:41:53 +00005046 LHS = ImpCastExprToType(LHS.take(), RHSTy, CK_BitCast);
Fariborz Jahanianeebc4752009-12-10 19:47:41 +00005047 return RHSTy;
5048 }
5049 // Check constraints for Objective-C object pointers types.
5050 if (LHSTy->isObjCObjectPointerType() && RHSTy->isObjCObjectPointerType()) {
Kovarththanan Rajaratnam19357542010-03-13 10:17:05 +00005051
Fariborz Jahanianeebc4752009-12-10 19:47:41 +00005052 if (Context.getCanonicalType(LHSTy) == Context.getCanonicalType(RHSTy)) {
5053 // Two identical object pointer types are always compatible.
5054 return LHSTy;
5055 }
John McCall1d9b3b22011-09-09 05:25:32 +00005056 const ObjCObjectPointerType *LHSOPT = LHSTy->castAs<ObjCObjectPointerType>();
5057 const ObjCObjectPointerType *RHSOPT = RHSTy->castAs<ObjCObjectPointerType>();
Fariborz Jahanianeebc4752009-12-10 19:47:41 +00005058 QualType compositeType = LHSTy;
Kovarththanan Rajaratnam19357542010-03-13 10:17:05 +00005059
Fariborz Jahanianeebc4752009-12-10 19:47:41 +00005060 // If both operands are interfaces and either operand can be
5061 // assigned to the other, use that type as the composite
5062 // type. This allows
5063 // xxx ? (A*) a : (B*) b
5064 // where B is a subclass of A.
5065 //
5066 // Additionally, as for assignment, if either type is 'id'
5067 // allow silent coercion. Finally, if the types are
5068 // incompatible then make sure to use 'id' as the composite
5069 // type so the result is acceptable for sending messages to.
Kovarththanan Rajaratnam19357542010-03-13 10:17:05 +00005070
Fariborz Jahanianeebc4752009-12-10 19:47:41 +00005071 // FIXME: Consider unifying with 'areComparableObjCPointerTypes'.
5072 // It could return the composite type.
5073 if (Context.canAssignObjCInterfaces(LHSOPT, RHSOPT)) {
5074 compositeType = RHSOPT->isObjCBuiltinType() ? RHSTy : LHSTy;
5075 } else if (Context.canAssignObjCInterfaces(RHSOPT, LHSOPT)) {
5076 compositeType = LHSOPT->isObjCBuiltinType() ? LHSTy : RHSTy;
5077 } else if ((LHSTy->isObjCQualifiedIdType() ||
5078 RHSTy->isObjCQualifiedIdType()) &&
5079 Context.ObjCQualifiedIdTypesAreCompatible(LHSTy, RHSTy, true)) {
5080 // Need to handle "id<xx>" explicitly.
5081 // GCC allows qualified id and any Objective-C type to devolve to
5082 // id. Currently localizing to here until clear this should be
5083 // part of ObjCQualifiedIdTypesAreCompatible.
5084 compositeType = Context.getObjCIdType();
5085 } else if (LHSTy->isObjCIdType() || RHSTy->isObjCIdType()) {
5086 compositeType = Context.getObjCIdType();
Kovarththanan Rajaratnam19357542010-03-13 10:17:05 +00005087 } else if (!(compositeType =
Fariborz Jahanianeebc4752009-12-10 19:47:41 +00005088 Context.areCommonBaseCompatible(LHSOPT, RHSOPT)).isNull())
5089 ;
5090 else {
5091 Diag(QuestionLoc, diag::ext_typecheck_cond_incompatible_operands)
5092 << LHSTy << RHSTy
John Wiegley429bb272011-04-08 18:41:53 +00005093 << LHS.get()->getSourceRange() << RHS.get()->getSourceRange();
Fariborz Jahanianeebc4752009-12-10 19:47:41 +00005094 QualType incompatTy = Context.getObjCIdType();
John Wiegley429bb272011-04-08 18:41:53 +00005095 LHS = ImpCastExprToType(LHS.take(), incompatTy, CK_BitCast);
5096 RHS = ImpCastExprToType(RHS.take(), incompatTy, CK_BitCast);
Fariborz Jahanianeebc4752009-12-10 19:47:41 +00005097 return incompatTy;
5098 }
5099 // The object pointer types are compatible.
John Wiegley429bb272011-04-08 18:41:53 +00005100 LHS = ImpCastExprToType(LHS.take(), compositeType, CK_BitCast);
5101 RHS = ImpCastExprToType(RHS.take(), compositeType, CK_BitCast);
Fariborz Jahanianeebc4752009-12-10 19:47:41 +00005102 return compositeType;
5103 }
5104 // Check Objective-C object pointer types and 'void *'
5105 if (LHSTy->isVoidPointerType() && RHSTy->isObjCObjectPointerType()) {
David Blaikie4e4d0842012-03-11 07:00:24 +00005106 if (getLangOpts().ObjCAutoRefCount) {
Eli Friedmana66eccb2012-02-25 00:23:44 +00005107 // ARC forbids the implicit conversion of object pointers to 'void *',
5108 // so these types are not compatible.
5109 Diag(QuestionLoc, diag::err_cond_voidptr_arc) << LHSTy << RHSTy
5110 << LHS.get()->getSourceRange() << RHS.get()->getSourceRange();
5111 LHS = RHS = true;
5112 return QualType();
5113 }
Fariborz Jahanianeebc4752009-12-10 19:47:41 +00005114 QualType lhptee = LHSTy->getAs<PointerType>()->getPointeeType();
5115 QualType rhptee = RHSTy->getAs<ObjCObjectPointerType>()->getPointeeType();
5116 QualType destPointee
5117 = Context.getQualifiedType(lhptee, rhptee.getQualifiers());
5118 QualType destType = Context.getPointerType(destPointee);
5119 // Add qualifiers if necessary.
John Wiegley429bb272011-04-08 18:41:53 +00005120 LHS = ImpCastExprToType(LHS.take(), destType, CK_NoOp);
Fariborz Jahanianeebc4752009-12-10 19:47:41 +00005121 // Promote to void*.
John Wiegley429bb272011-04-08 18:41:53 +00005122 RHS = ImpCastExprToType(RHS.take(), destType, CK_BitCast);
Fariborz Jahanianeebc4752009-12-10 19:47:41 +00005123 return destType;
5124 }
5125 if (LHSTy->isObjCObjectPointerType() && RHSTy->isVoidPointerType()) {
David Blaikie4e4d0842012-03-11 07:00:24 +00005126 if (getLangOpts().ObjCAutoRefCount) {
Eli Friedmana66eccb2012-02-25 00:23:44 +00005127 // ARC forbids the implicit conversion of object pointers to 'void *',
5128 // so these types are not compatible.
5129 Diag(QuestionLoc, diag::err_cond_voidptr_arc) << LHSTy << RHSTy
5130 << LHS.get()->getSourceRange() << RHS.get()->getSourceRange();
5131 LHS = RHS = true;
5132 return QualType();
5133 }
Fariborz Jahanianeebc4752009-12-10 19:47:41 +00005134 QualType lhptee = LHSTy->getAs<ObjCObjectPointerType>()->getPointeeType();
5135 QualType rhptee = RHSTy->getAs<PointerType>()->getPointeeType();
5136 QualType destPointee
5137 = Context.getQualifiedType(rhptee, lhptee.getQualifiers());
5138 QualType destType = Context.getPointerType(destPointee);
5139 // Add qualifiers if necessary.
John Wiegley429bb272011-04-08 18:41:53 +00005140 RHS = ImpCastExprToType(RHS.take(), destType, CK_NoOp);
Fariborz Jahanianeebc4752009-12-10 19:47:41 +00005141 // Promote to void*.
John Wiegley429bb272011-04-08 18:41:53 +00005142 LHS = ImpCastExprToType(LHS.take(), destType, CK_BitCast);
Fariborz Jahanianeebc4752009-12-10 19:47:41 +00005143 return destType;
5144 }
5145 return QualType();
5146}
5147
Chandler Carruthf0b60d62011-06-16 01:05:14 +00005148/// SuggestParentheses - Emit a note with a fixit hint that wraps
Hans Wennborg9cfdae32011-06-03 18:00:36 +00005149/// ParenRange in parentheses.
5150static void SuggestParentheses(Sema &Self, SourceLocation Loc,
Chandler Carruthf0b60d62011-06-16 01:05:14 +00005151 const PartialDiagnostic &Note,
5152 SourceRange ParenRange) {
5153 SourceLocation EndLoc = Self.PP.getLocForEndOfToken(ParenRange.getEnd());
5154 if (ParenRange.getBegin().isFileID() && ParenRange.getEnd().isFileID() &&
5155 EndLoc.isValid()) {
5156 Self.Diag(Loc, Note)
5157 << FixItHint::CreateInsertion(ParenRange.getBegin(), "(")
5158 << FixItHint::CreateInsertion(EndLoc, ")");
5159 } else {
5160 // We can't display the parentheses, so just show the bare note.
5161 Self.Diag(Loc, Note) << ParenRange;
Hans Wennborg9cfdae32011-06-03 18:00:36 +00005162 }
Hans Wennborg9cfdae32011-06-03 18:00:36 +00005163}
5164
5165static bool IsArithmeticOp(BinaryOperatorKind Opc) {
5166 return Opc >= BO_Mul && Opc <= BO_Shr;
5167}
5168
Hans Wennborg2f072b42011-06-09 17:06:51 +00005169/// IsArithmeticBinaryExpr - Returns true if E is an arithmetic binary
5170/// expression, either using a built-in or overloaded operator,
Richard Trieu33fc7572011-09-06 20:06:39 +00005171/// and sets *OpCode to the opcode and *RHSExprs to the right-hand side
5172/// expression.
Hans Wennborg2f072b42011-06-09 17:06:51 +00005173static bool IsArithmeticBinaryExpr(Expr *E, BinaryOperatorKind *Opcode,
Richard Trieu33fc7572011-09-06 20:06:39 +00005174 Expr **RHSExprs) {
Hans Wennborgcb4d7c22011-09-12 12:07:30 +00005175 // Don't strip parenthesis: we should not warn if E is in parenthesis.
5176 E = E->IgnoreImpCasts();
Hans Wennborg2f072b42011-06-09 17:06:51 +00005177 E = E->IgnoreConversionOperator();
Hans Wennborgcb4d7c22011-09-12 12:07:30 +00005178 E = E->IgnoreImpCasts();
Hans Wennborg2f072b42011-06-09 17:06:51 +00005179
5180 // Built-in binary operator.
5181 if (BinaryOperator *OP = dyn_cast<BinaryOperator>(E)) {
5182 if (IsArithmeticOp(OP->getOpcode())) {
5183 *Opcode = OP->getOpcode();
Richard Trieu33fc7572011-09-06 20:06:39 +00005184 *RHSExprs = OP->getRHS();
Hans Wennborg2f072b42011-06-09 17:06:51 +00005185 return true;
5186 }
5187 }
5188
5189 // Overloaded operator.
5190 if (CXXOperatorCallExpr *Call = dyn_cast<CXXOperatorCallExpr>(E)) {
5191 if (Call->getNumArgs() != 2)
5192 return false;
5193
5194 // Make sure this is really a binary operator that is safe to pass into
5195 // BinaryOperator::getOverloadedOpcode(), e.g. it's not a subscript op.
5196 OverloadedOperatorKind OO = Call->getOperator();
5197 if (OO < OO_Plus || OO > OO_Arrow)
5198 return false;
5199
5200 BinaryOperatorKind OpKind = BinaryOperator::getOverloadedOpcode(OO);
5201 if (IsArithmeticOp(OpKind)) {
5202 *Opcode = OpKind;
Richard Trieu33fc7572011-09-06 20:06:39 +00005203 *RHSExprs = Call->getArg(1);
Hans Wennborg2f072b42011-06-09 17:06:51 +00005204 return true;
5205 }
5206 }
5207
5208 return false;
5209}
5210
Hans Wennborg9cfdae32011-06-03 18:00:36 +00005211static bool IsLogicOp(BinaryOperatorKind Opc) {
5212 return (Opc >= BO_LT && Opc <= BO_NE) || (Opc >= BO_LAnd && Opc <= BO_LOr);
5213}
5214
Hans Wennborg2f072b42011-06-09 17:06:51 +00005215/// ExprLooksBoolean - Returns true if E looks boolean, i.e. it has boolean type
5216/// or is a logical expression such as (x==y) which has int type, but is
5217/// commonly interpreted as boolean.
5218static bool ExprLooksBoolean(Expr *E) {
5219 E = E->IgnoreParenImpCasts();
5220
5221 if (E->getType()->isBooleanType())
5222 return true;
5223 if (BinaryOperator *OP = dyn_cast<BinaryOperator>(E))
5224 return IsLogicOp(OP->getOpcode());
5225 if (UnaryOperator *OP = dyn_cast<UnaryOperator>(E))
5226 return OP->getOpcode() == UO_LNot;
5227
5228 return false;
5229}
5230
Hans Wennborg9cfdae32011-06-03 18:00:36 +00005231/// DiagnoseConditionalPrecedence - Emit a warning when a conditional operator
5232/// and binary operator are mixed in a way that suggests the programmer assumed
5233/// the conditional operator has higher precedence, for example:
5234/// "int x = a + someBinaryCondition ? 1 : 2".
5235static void DiagnoseConditionalPrecedence(Sema &Self,
5236 SourceLocation OpLoc,
Chandler Carruth43bc78d2011-06-16 01:05:08 +00005237 Expr *Condition,
Richard Trieu33fc7572011-09-06 20:06:39 +00005238 Expr *LHSExpr,
5239 Expr *RHSExpr) {
Hans Wennborg2f072b42011-06-09 17:06:51 +00005240 BinaryOperatorKind CondOpcode;
5241 Expr *CondRHS;
Hans Wennborg9cfdae32011-06-03 18:00:36 +00005242
Chandler Carruth43bc78d2011-06-16 01:05:08 +00005243 if (!IsArithmeticBinaryExpr(Condition, &CondOpcode, &CondRHS))
Hans Wennborg2f072b42011-06-09 17:06:51 +00005244 return;
5245 if (!ExprLooksBoolean(CondRHS))
5246 return;
Hans Wennborg9cfdae32011-06-03 18:00:36 +00005247
Hans Wennborg2f072b42011-06-09 17:06:51 +00005248 // The condition is an arithmetic binary expression, with a right-
5249 // hand side that looks boolean, so warn.
Hans Wennborg9cfdae32011-06-03 18:00:36 +00005250
Chandler Carruthf0b60d62011-06-16 01:05:14 +00005251 Self.Diag(OpLoc, diag::warn_precedence_conditional)
Chandler Carruth43bc78d2011-06-16 01:05:08 +00005252 << Condition->getSourceRange()
Hans Wennborg2f072b42011-06-09 17:06:51 +00005253 << BinaryOperator::getOpcodeStr(CondOpcode);
Hans Wennborg9cfdae32011-06-03 18:00:36 +00005254
Chandler Carruthf0b60d62011-06-16 01:05:14 +00005255 SuggestParentheses(Self, OpLoc,
5256 Self.PDiag(diag::note_precedence_conditional_silence)
5257 << BinaryOperator::getOpcodeStr(CondOpcode),
5258 SourceRange(Condition->getLocStart(), Condition->getLocEnd()));
Chandler Carruth9d5353c2011-06-21 23:04:18 +00005259
5260 SuggestParentheses(Self, OpLoc,
5261 Self.PDiag(diag::note_precedence_conditional_first),
Richard Trieu33fc7572011-09-06 20:06:39 +00005262 SourceRange(CondRHS->getLocStart(), RHSExpr->getLocEnd()));
Hans Wennborg9cfdae32011-06-03 18:00:36 +00005263}
5264
Steve Narofff69936d2007-09-16 03:34:24 +00005265/// ActOnConditionalOp - Parse a ?: operation. Note that 'LHS' may be null
Reid Spencer5f016e22007-07-11 17:01:13 +00005266/// in the case of a the GNU conditional expr extension.
John McCall60d7b3a2010-08-24 06:29:42 +00005267ExprResult Sema::ActOnConditionalOp(SourceLocation QuestionLoc,
John McCall56ca35d2011-02-17 10:25:35 +00005268 SourceLocation ColonLoc,
5269 Expr *CondExpr, Expr *LHSExpr,
5270 Expr *RHSExpr) {
Chris Lattnera21ddb32007-11-26 01:40:58 +00005271 // If this is the gnu "x ?: y" extension, analyze the types as though the LHS
5272 // was the condition.
John McCall56ca35d2011-02-17 10:25:35 +00005273 OpaqueValueExpr *opaqueValue = 0;
5274 Expr *commonExpr = 0;
5275 if (LHSExpr == 0) {
5276 commonExpr = CondExpr;
5277
5278 // We usually want to apply unary conversions *before* saving, except
5279 // in the special case of a C++ l-value conditional.
David Blaikie4e4d0842012-03-11 07:00:24 +00005280 if (!(getLangOpts().CPlusPlus
John McCall56ca35d2011-02-17 10:25:35 +00005281 && !commonExpr->isTypeDependent()
5282 && commonExpr->getValueKind() == RHSExpr->getValueKind()
5283 && commonExpr->isGLValue()
5284 && commonExpr->isOrdinaryOrBitFieldObject()
5285 && RHSExpr->isOrdinaryOrBitFieldObject()
5286 && Context.hasSameType(commonExpr->getType(), RHSExpr->getType()))) {
John Wiegley429bb272011-04-08 18:41:53 +00005287 ExprResult commonRes = UsualUnaryConversions(commonExpr);
5288 if (commonRes.isInvalid())
5289 return ExprError();
5290 commonExpr = commonRes.take();
John McCall56ca35d2011-02-17 10:25:35 +00005291 }
5292
5293 opaqueValue = new (Context) OpaqueValueExpr(commonExpr->getExprLoc(),
5294 commonExpr->getType(),
5295 commonExpr->getValueKind(),
Douglas Gregor97df54e2012-02-23 22:17:26 +00005296 commonExpr->getObjectKind(),
5297 commonExpr);
John McCall56ca35d2011-02-17 10:25:35 +00005298 LHSExpr = CondExpr = opaqueValue;
Fariborz Jahanianf9b949f2010-08-31 18:02:20 +00005299 }
Sebastian Redlb8a6aca2009-01-19 22:31:54 +00005300
John McCallf89e55a2010-11-18 06:31:45 +00005301 ExprValueKind VK = VK_RValue;
John McCall09431682010-11-18 19:01:18 +00005302 ExprObjectKind OK = OK_Ordinary;
John Wiegley429bb272011-04-08 18:41:53 +00005303 ExprResult Cond = Owned(CondExpr), LHS = Owned(LHSExpr), RHS = Owned(RHSExpr);
5304 QualType result = CheckConditionalOperands(Cond, LHS, RHS,
John McCall56ca35d2011-02-17 10:25:35 +00005305 VK, OK, QuestionLoc);
John Wiegley429bb272011-04-08 18:41:53 +00005306 if (result.isNull() || Cond.isInvalid() || LHS.isInvalid() ||
5307 RHS.isInvalid())
Sebastian Redlb8a6aca2009-01-19 22:31:54 +00005308 return ExprError();
5309
Hans Wennborg9cfdae32011-06-03 18:00:36 +00005310 DiagnoseConditionalPrecedence(*this, QuestionLoc, Cond.get(), LHS.get(),
5311 RHS.get());
5312
John McCall56ca35d2011-02-17 10:25:35 +00005313 if (!commonExpr)
John Wiegley429bb272011-04-08 18:41:53 +00005314 return Owned(new (Context) ConditionalOperator(Cond.take(), QuestionLoc,
5315 LHS.take(), ColonLoc,
5316 RHS.take(), result, VK, OK));
John McCall56ca35d2011-02-17 10:25:35 +00005317
5318 return Owned(new (Context)
John Wiegley429bb272011-04-08 18:41:53 +00005319 BinaryConditionalOperator(commonExpr, opaqueValue, Cond.take(), LHS.take(),
Richard Trieu67e29332011-08-02 04:35:43 +00005320 RHS.take(), QuestionLoc, ColonLoc, result, VK,
5321 OK));
Reid Spencer5f016e22007-07-11 17:01:13 +00005322}
5323
John McCalle4be87e2011-01-31 23:13:11 +00005324// checkPointerTypesForAssignment - This is a very tricky routine (despite
Mike Stumpeed9cac2009-02-19 03:04:26 +00005325// being closely modeled after the C99 spec:-). The odd characteristic of this
Reid Spencer5f016e22007-07-11 17:01:13 +00005326// routine is it effectively iqnores the qualifiers on the top level pointee.
5327// This circumvents the usual type rules specified in 6.2.7p1 & 6.7.5.[1-3].
5328// FIXME: add a couple examples in this comment.
John McCalle4be87e2011-01-31 23:13:11 +00005329static Sema::AssignConvertType
Richard Trieu1da27a12011-09-06 20:21:22 +00005330checkPointerTypesForAssignment(Sema &S, QualType LHSType, QualType RHSType) {
5331 assert(LHSType.isCanonical() && "LHS not canonicalized!");
5332 assert(RHSType.isCanonical() && "RHS not canonicalized!");
Mike Stumpeed9cac2009-02-19 03:04:26 +00005333
Reid Spencer5f016e22007-07-11 17:01:13 +00005334 // get the "pointed to" type (ignoring qualifiers at the top level)
John McCall86c05f32011-02-01 00:10:29 +00005335 const Type *lhptee, *rhptee;
5336 Qualifiers lhq, rhq;
Richard Trieu1da27a12011-09-06 20:21:22 +00005337 llvm::tie(lhptee, lhq) = cast<PointerType>(LHSType)->getPointeeType().split();
5338 llvm::tie(rhptee, rhq) = cast<PointerType>(RHSType)->getPointeeType().split();
Mike Stumpeed9cac2009-02-19 03:04:26 +00005339
John McCalle4be87e2011-01-31 23:13:11 +00005340 Sema::AssignConvertType ConvTy = Sema::Compatible;
Mike Stumpeed9cac2009-02-19 03:04:26 +00005341
5342 // C99 6.5.16.1p1: This following citation is common to constraints
5343 // 3 & 4 (below). ...and the type *pointed to* by the left has all the
5344 // qualifiers of the type *pointed to* by the right;
John McCall86c05f32011-02-01 00:10:29 +00005345 Qualifiers lq;
5346
John McCallf85e1932011-06-15 23:02:42 +00005347 // As a special case, 'non-__weak A *' -> 'non-__weak const *' is okay.
5348 if (lhq.getObjCLifetime() != rhq.getObjCLifetime() &&
5349 lhq.compatiblyIncludesObjCLifetime(rhq)) {
5350 // Ignore lifetime for further calculation.
5351 lhq.removeObjCLifetime();
5352 rhq.removeObjCLifetime();
5353 }
5354
John McCall86c05f32011-02-01 00:10:29 +00005355 if (!lhq.compatiblyIncludes(rhq)) {
5356 // Treat address-space mismatches as fatal. TODO: address subspaces
5357 if (lhq.getAddressSpace() != rhq.getAddressSpace())
5358 ConvTy = Sema::IncompatiblePointerDiscardsQualifiers;
5359
John McCallf85e1932011-06-15 23:02:42 +00005360 // It's okay to add or remove GC or lifetime qualifiers when converting to
John McCall22348732011-03-26 02:56:45 +00005361 // and from void*.
John McCall200fa532012-02-08 00:46:36 +00005362 else if (lhq.withoutObjCGCAttr().withoutObjCLifetime()
John McCallf85e1932011-06-15 23:02:42 +00005363 .compatiblyIncludes(
John McCall200fa532012-02-08 00:46:36 +00005364 rhq.withoutObjCGCAttr().withoutObjCLifetime())
John McCall22348732011-03-26 02:56:45 +00005365 && (lhptee->isVoidType() || rhptee->isVoidType()))
5366 ; // keep old
5367
John McCallf85e1932011-06-15 23:02:42 +00005368 // Treat lifetime mismatches as fatal.
5369 else if (lhq.getObjCLifetime() != rhq.getObjCLifetime())
5370 ConvTy = Sema::IncompatiblePointerDiscardsQualifiers;
5371
John McCall86c05f32011-02-01 00:10:29 +00005372 // For GCC compatibility, other qualifier mismatches are treated
5373 // as still compatible in C.
5374 else ConvTy = Sema::CompatiblePointerDiscardsQualifiers;
5375 }
Reid Spencer5f016e22007-07-11 17:01:13 +00005376
Mike Stumpeed9cac2009-02-19 03:04:26 +00005377 // C99 6.5.16.1p1 (constraint 4): If one operand is a pointer to an object or
5378 // incomplete type and the other is a pointer to a qualified or unqualified
Reid Spencer5f016e22007-07-11 17:01:13 +00005379 // version of void...
Chris Lattnerbfe639e2008-01-03 22:56:36 +00005380 if (lhptee->isVoidType()) {
Chris Lattnerd805bec2008-04-02 06:59:01 +00005381 if (rhptee->isIncompleteOrObjectType())
Chris Lattner5cf216b2008-01-04 18:04:52 +00005382 return ConvTy;
Mike Stumpeed9cac2009-02-19 03:04:26 +00005383
Chris Lattnerbfe639e2008-01-03 22:56:36 +00005384 // As an extension, we allow cast to/from void* to function pointer.
Chris Lattnerd805bec2008-04-02 06:59:01 +00005385 assert(rhptee->isFunctionType());
John McCalle4be87e2011-01-31 23:13:11 +00005386 return Sema::FunctionVoidPointer;
Chris Lattnerbfe639e2008-01-03 22:56:36 +00005387 }
Mike Stumpeed9cac2009-02-19 03:04:26 +00005388
Chris Lattnerbfe639e2008-01-03 22:56:36 +00005389 if (rhptee->isVoidType()) {
Chris Lattnerd805bec2008-04-02 06:59:01 +00005390 if (lhptee->isIncompleteOrObjectType())
Chris Lattner5cf216b2008-01-04 18:04:52 +00005391 return ConvTy;
Chris Lattnerbfe639e2008-01-03 22:56:36 +00005392
5393 // As an extension, we allow cast to/from void* to function pointer.
Chris Lattnerd805bec2008-04-02 06:59:01 +00005394 assert(lhptee->isFunctionType());
John McCalle4be87e2011-01-31 23:13:11 +00005395 return Sema::FunctionVoidPointer;
Chris Lattnerbfe639e2008-01-03 22:56:36 +00005396 }
John McCall86c05f32011-02-01 00:10:29 +00005397
Mike Stumpeed9cac2009-02-19 03:04:26 +00005398 // C99 6.5.16.1p1 (constraint 3): both operands are pointers to qualified or
Reid Spencer5f016e22007-07-11 17:01:13 +00005399 // unqualified versions of compatible types, ...
John McCall86c05f32011-02-01 00:10:29 +00005400 QualType ltrans = QualType(lhptee, 0), rtrans = QualType(rhptee, 0);
5401 if (!S.Context.typesAreCompatible(ltrans, rtrans)) {
Eli Friedmanf05c05d2009-03-22 23:59:44 +00005402 // Check if the pointee types are compatible ignoring the sign.
5403 // We explicitly check for char so that we catch "char" vs
5404 // "unsigned char" on systems where "char" is unsigned.
Chris Lattner6a2b9262009-10-17 20:33:28 +00005405 if (lhptee->isCharType())
John McCall86c05f32011-02-01 00:10:29 +00005406 ltrans = S.Context.UnsignedCharTy;
Douglas Gregorf6094622010-07-23 15:58:24 +00005407 else if (lhptee->hasSignedIntegerRepresentation())
John McCall86c05f32011-02-01 00:10:29 +00005408 ltrans = S.Context.getCorrespondingUnsignedType(ltrans);
Kovarththanan Rajaratnam19357542010-03-13 10:17:05 +00005409
Chris Lattner6a2b9262009-10-17 20:33:28 +00005410 if (rhptee->isCharType())
John McCall86c05f32011-02-01 00:10:29 +00005411 rtrans = S.Context.UnsignedCharTy;
Douglas Gregorf6094622010-07-23 15:58:24 +00005412 else if (rhptee->hasSignedIntegerRepresentation())
John McCall86c05f32011-02-01 00:10:29 +00005413 rtrans = S.Context.getCorrespondingUnsignedType(rtrans);
Chris Lattner6a2b9262009-10-17 20:33:28 +00005414
John McCall86c05f32011-02-01 00:10:29 +00005415 if (ltrans == rtrans) {
Eli Friedmanf05c05d2009-03-22 23:59:44 +00005416 // Types are compatible ignoring the sign. Qualifier incompatibility
5417 // takes priority over sign incompatibility because the sign
5418 // warning can be disabled.
John McCalle4be87e2011-01-31 23:13:11 +00005419 if (ConvTy != Sema::Compatible)
Eli Friedmanf05c05d2009-03-22 23:59:44 +00005420 return ConvTy;
John McCall86c05f32011-02-01 00:10:29 +00005421
John McCalle4be87e2011-01-31 23:13:11 +00005422 return Sema::IncompatiblePointerSign;
Eli Friedmanf05c05d2009-03-22 23:59:44 +00005423 }
Kovarththanan Rajaratnam19357542010-03-13 10:17:05 +00005424
Fariborz Jahanian36a862f2009-11-07 20:20:40 +00005425 // If we are a multi-level pointer, it's possible that our issue is simply
5426 // one of qualification - e.g. char ** -> const char ** is not allowed. If
5427 // the eventual target type is the same and the pointers have the same
5428 // level of indirection, this must be the issue.
John McCalle4be87e2011-01-31 23:13:11 +00005429 if (isa<PointerType>(lhptee) && isa<PointerType>(rhptee)) {
Fariborz Jahanian36a862f2009-11-07 20:20:40 +00005430 do {
John McCall86c05f32011-02-01 00:10:29 +00005431 lhptee = cast<PointerType>(lhptee)->getPointeeType().getTypePtr();
5432 rhptee = cast<PointerType>(rhptee)->getPointeeType().getTypePtr();
John McCalle4be87e2011-01-31 23:13:11 +00005433 } while (isa<PointerType>(lhptee) && isa<PointerType>(rhptee));
Kovarththanan Rajaratnam19357542010-03-13 10:17:05 +00005434
John McCall86c05f32011-02-01 00:10:29 +00005435 if (lhptee == rhptee)
John McCalle4be87e2011-01-31 23:13:11 +00005436 return Sema::IncompatibleNestedPointerQualifiers;
Fariborz Jahanian36a862f2009-11-07 20:20:40 +00005437 }
Kovarththanan Rajaratnam19357542010-03-13 10:17:05 +00005438
Eli Friedmanf05c05d2009-03-22 23:59:44 +00005439 // General pointer incompatibility takes priority over qualifiers.
John McCalle4be87e2011-01-31 23:13:11 +00005440 return Sema::IncompatiblePointer;
Eli Friedmanf05c05d2009-03-22 23:59:44 +00005441 }
David Blaikie4e4d0842012-03-11 07:00:24 +00005442 if (!S.getLangOpts().CPlusPlus &&
Fariborz Jahanian53c81672011-10-05 00:05:34 +00005443 S.IsNoReturnConversion(ltrans, rtrans, ltrans))
5444 return Sema::IncompatiblePointer;
Chris Lattner5cf216b2008-01-04 18:04:52 +00005445 return ConvTy;
Reid Spencer5f016e22007-07-11 17:01:13 +00005446}
5447
John McCalle4be87e2011-01-31 23:13:11 +00005448/// checkBlockPointerTypesForAssignment - This routine determines whether two
Steve Naroff1c7d0672008-09-04 15:10:53 +00005449/// block pointer types are compatible or whether a block and normal pointer
5450/// are compatible. It is more restrict than comparing two function pointer
5451// types.
John McCalle4be87e2011-01-31 23:13:11 +00005452static Sema::AssignConvertType
Richard Trieu1da27a12011-09-06 20:21:22 +00005453checkBlockPointerTypesForAssignment(Sema &S, QualType LHSType,
5454 QualType RHSType) {
5455 assert(LHSType.isCanonical() && "LHS not canonicalized!");
5456 assert(RHSType.isCanonical() && "RHS not canonicalized!");
John McCalle4be87e2011-01-31 23:13:11 +00005457
Steve Naroff1c7d0672008-09-04 15:10:53 +00005458 QualType lhptee, rhptee;
Mike Stumpeed9cac2009-02-19 03:04:26 +00005459
Steve Naroff1c7d0672008-09-04 15:10:53 +00005460 // get the "pointed to" type (ignoring qualifiers at the top level)
Richard Trieu1da27a12011-09-06 20:21:22 +00005461 lhptee = cast<BlockPointerType>(LHSType)->getPointeeType();
5462 rhptee = cast<BlockPointerType>(RHSType)->getPointeeType();
Mike Stumpeed9cac2009-02-19 03:04:26 +00005463
John McCalle4be87e2011-01-31 23:13:11 +00005464 // In C++, the types have to match exactly.
David Blaikie4e4d0842012-03-11 07:00:24 +00005465 if (S.getLangOpts().CPlusPlus)
John McCalle4be87e2011-01-31 23:13:11 +00005466 return Sema::IncompatibleBlockPointer;
Mike Stumpeed9cac2009-02-19 03:04:26 +00005467
John McCalle4be87e2011-01-31 23:13:11 +00005468 Sema::AssignConvertType ConvTy = Sema::Compatible;
Mike Stumpeed9cac2009-02-19 03:04:26 +00005469
Steve Naroff1c7d0672008-09-04 15:10:53 +00005470 // For blocks we enforce that qualifiers are identical.
John McCalle4be87e2011-01-31 23:13:11 +00005471 if (lhptee.getLocalQualifiers() != rhptee.getLocalQualifiers())
5472 ConvTy = Sema::CompatiblePointerDiscardsQualifiers;
Mike Stumpeed9cac2009-02-19 03:04:26 +00005473
Richard Trieu1da27a12011-09-06 20:21:22 +00005474 if (!S.Context.typesAreBlockPointerCompatible(LHSType, RHSType))
John McCalle4be87e2011-01-31 23:13:11 +00005475 return Sema::IncompatibleBlockPointer;
5476
Steve Naroff1c7d0672008-09-04 15:10:53 +00005477 return ConvTy;
5478}
5479
John McCalle4be87e2011-01-31 23:13:11 +00005480/// checkObjCPointerTypesForAssignment - Compares two objective-c pointer types
Fariborz Jahanian52efc3f2009-12-08 18:24:49 +00005481/// for assignment compatibility.
John McCalle4be87e2011-01-31 23:13:11 +00005482static Sema::AssignConvertType
Richard Trieu1da27a12011-09-06 20:21:22 +00005483checkObjCPointerTypesForAssignment(Sema &S, QualType LHSType,
5484 QualType RHSType) {
5485 assert(LHSType.isCanonical() && "LHS was not canonicalized!");
5486 assert(RHSType.isCanonical() && "RHS was not canonicalized!");
John McCalle4be87e2011-01-31 23:13:11 +00005487
Richard Trieu1da27a12011-09-06 20:21:22 +00005488 if (LHSType->isObjCBuiltinType()) {
Fariborz Jahaniand4c60902010-03-19 18:06:10 +00005489 // Class is not compatible with ObjC object pointers.
Richard Trieu1da27a12011-09-06 20:21:22 +00005490 if (LHSType->isObjCClassType() && !RHSType->isObjCBuiltinType() &&
5491 !RHSType->isObjCQualifiedClassType())
John McCalle4be87e2011-01-31 23:13:11 +00005492 return Sema::IncompatiblePointer;
5493 return Sema::Compatible;
Fariborz Jahaniand4c60902010-03-19 18:06:10 +00005494 }
Richard Trieu1da27a12011-09-06 20:21:22 +00005495 if (RHSType->isObjCBuiltinType()) {
Richard Trieu1da27a12011-09-06 20:21:22 +00005496 if (RHSType->isObjCClassType() && !LHSType->isObjCBuiltinType() &&
5497 !LHSType->isObjCQualifiedClassType())
Fariborz Jahanian412a4962011-09-15 20:40:18 +00005498 return Sema::IncompatiblePointer;
John McCalle4be87e2011-01-31 23:13:11 +00005499 return Sema::Compatible;
Fariborz Jahaniand4c60902010-03-19 18:06:10 +00005500 }
Richard Trieu1da27a12011-09-06 20:21:22 +00005501 QualType lhptee = LHSType->getAs<ObjCObjectPointerType>()->getPointeeType();
5502 QualType rhptee = RHSType->getAs<ObjCObjectPointerType>()->getPointeeType();
Kovarththanan Rajaratnam19357542010-03-13 10:17:05 +00005503
Fariborz Jahanianf2b4f7b2012-01-12 22:12:08 +00005504 if (!lhptee.isAtLeastAsQualifiedAs(rhptee) &&
5505 // make an exception for id<P>
5506 !LHSType->isObjCQualifiedIdType())
John McCalle4be87e2011-01-31 23:13:11 +00005507 return Sema::CompatiblePointerDiscardsQualifiers;
5508
Richard Trieu1da27a12011-09-06 20:21:22 +00005509 if (S.Context.typesAreCompatible(LHSType, RHSType))
John McCalle4be87e2011-01-31 23:13:11 +00005510 return Sema::Compatible;
Richard Trieu1da27a12011-09-06 20:21:22 +00005511 if (LHSType->isObjCQualifiedIdType() || RHSType->isObjCQualifiedIdType())
John McCalle4be87e2011-01-31 23:13:11 +00005512 return Sema::IncompatibleObjCQualifiedId;
5513 return Sema::IncompatiblePointer;
Fariborz Jahanian52efc3f2009-12-08 18:24:49 +00005514}
5515
John McCall1c23e912010-11-16 02:32:08 +00005516Sema::AssignConvertType
Douglas Gregorb608b982011-01-28 02:26:04 +00005517Sema::CheckAssignmentConstraints(SourceLocation Loc,
Richard Trieu1da27a12011-09-06 20:21:22 +00005518 QualType LHSType, QualType RHSType) {
John McCall1c23e912010-11-16 02:32:08 +00005519 // Fake up an opaque expression. We don't actually care about what
5520 // cast operations are required, so if CheckAssignmentConstraints
5521 // adds casts to this they'll be wasted, but fortunately that doesn't
5522 // usually happen on valid code.
Richard Trieu1da27a12011-09-06 20:21:22 +00005523 OpaqueValueExpr RHSExpr(Loc, RHSType, VK_RValue);
5524 ExprResult RHSPtr = &RHSExpr;
John McCall1c23e912010-11-16 02:32:08 +00005525 CastKind K = CK_Invalid;
5526
Richard Trieu1da27a12011-09-06 20:21:22 +00005527 return CheckAssignmentConstraints(LHSType, RHSPtr, K);
John McCall1c23e912010-11-16 02:32:08 +00005528}
5529
Mike Stumpeed9cac2009-02-19 03:04:26 +00005530/// CheckAssignmentConstraints (C99 6.5.16) - This routine currently
5531/// has code to accommodate several GCC extensions when type checking
Reid Spencer5f016e22007-07-11 17:01:13 +00005532/// pointers. Here are some objectionable examples that GCC considers warnings:
5533///
5534/// int a, *pint;
5535/// short *pshort;
5536/// struct foo *pfoo;
5537///
5538/// pint = pshort; // warning: assignment from incompatible pointer type
5539/// a = pint; // warning: assignment makes integer from pointer without a cast
5540/// pint = a; // warning: assignment makes pointer from integer without a cast
5541/// pint = pfoo; // warning: assignment from incompatible pointer type
5542///
5543/// As a result, the code for dealing with pointers is more complex than the
Mike Stumpeed9cac2009-02-19 03:04:26 +00005544/// C99 spec dictates.
Reid Spencer5f016e22007-07-11 17:01:13 +00005545///
John McCalldaa8e4e2010-11-15 09:13:47 +00005546/// Sets 'Kind' for any result kind except Incompatible.
Chris Lattner5cf216b2008-01-04 18:04:52 +00005547Sema::AssignConvertType
Richard Trieufacef2e2011-09-06 20:30:53 +00005548Sema::CheckAssignmentConstraints(QualType LHSType, ExprResult &RHS,
John McCalldaa8e4e2010-11-15 09:13:47 +00005549 CastKind &Kind) {
Richard Trieufacef2e2011-09-06 20:30:53 +00005550 QualType RHSType = RHS.get()->getType();
5551 QualType OrigLHSType = LHSType;
John McCall1c23e912010-11-16 02:32:08 +00005552
Chris Lattnerfc144e22008-01-04 23:18:45 +00005553 // Get canonical types. We're not formatting these types, just comparing
5554 // them.
Richard Trieufacef2e2011-09-06 20:30:53 +00005555 LHSType = Context.getCanonicalType(LHSType).getUnqualifiedType();
5556 RHSType = Context.getCanonicalType(RHSType).getUnqualifiedType();
Eli Friedmanf8f873d2008-05-30 18:07:22 +00005557
Eli Friedmanb001de72011-10-06 23:00:33 +00005558
John McCallb6cfa242011-01-31 22:28:28 +00005559 // Common case: no conversion required.
Richard Trieufacef2e2011-09-06 20:30:53 +00005560 if (LHSType == RHSType) {
John McCalldaa8e4e2010-11-15 09:13:47 +00005561 Kind = CK_NoOp;
John McCalldaa8e4e2010-11-15 09:13:47 +00005562 return Compatible;
David Chisnall0f436562009-08-17 16:35:33 +00005563 }
5564
Eli Friedman860a3192012-06-16 02:19:17 +00005565 // If we have an atomic type, try a non-atomic assignment, then just add an
5566 // atomic qualification step.
David Chisnall7a7ee302012-01-16 17:27:18 +00005567 if (const AtomicType *AtomicTy = dyn_cast<AtomicType>(LHSType)) {
Eli Friedman860a3192012-06-16 02:19:17 +00005568 Sema::AssignConvertType result =
5569 CheckAssignmentConstraints(AtomicTy->getValueType(), RHS, Kind);
5570 if (result != Compatible)
5571 return result;
5572 if (Kind != CK_NoOp)
5573 RHS = ImpCastExprToType(RHS.take(), AtomicTy->getValueType(), Kind);
5574 Kind = CK_NonAtomicToAtomic;
5575 return Compatible;
David Chisnall7a7ee302012-01-16 17:27:18 +00005576 }
5577
Douglas Gregor9d293df2008-10-28 00:22:11 +00005578 // If the left-hand side is a reference type, then we are in a
5579 // (rare!) case where we've allowed the use of references in C,
5580 // e.g., as a parameter type in a built-in function. In this case,
5581 // just make sure that the type referenced is compatible with the
5582 // right-hand side type. The caller is responsible for adjusting
Richard Trieufacef2e2011-09-06 20:30:53 +00005583 // LHSType so that the resulting expression does not have reference
Douglas Gregor9d293df2008-10-28 00:22:11 +00005584 // type.
Richard Trieufacef2e2011-09-06 20:30:53 +00005585 if (const ReferenceType *LHSTypeRef = LHSType->getAs<ReferenceType>()) {
5586 if (Context.typesAreCompatible(LHSTypeRef->getPointeeType(), RHSType)) {
John McCalldaa8e4e2010-11-15 09:13:47 +00005587 Kind = CK_LValueBitCast;
Anders Carlsson793680e2007-10-12 23:56:29 +00005588 return Compatible;
John McCalldaa8e4e2010-11-15 09:13:47 +00005589 }
Chris Lattnerfc144e22008-01-04 23:18:45 +00005590 return Incompatible;
Fariborz Jahanian411f3732007-12-19 17:45:58 +00005591 }
John McCallb6cfa242011-01-31 22:28:28 +00005592
Nate Begeman1bd1f6e2009-06-28 02:36:38 +00005593 // Allow scalar to ExtVector assignments, and assignments of an ExtVector type
5594 // to the same ExtVector type.
Richard Trieufacef2e2011-09-06 20:30:53 +00005595 if (LHSType->isExtVectorType()) {
5596 if (RHSType->isExtVectorType())
John McCalldaa8e4e2010-11-15 09:13:47 +00005597 return Incompatible;
Richard Trieufacef2e2011-09-06 20:30:53 +00005598 if (RHSType->isArithmeticType()) {
John McCall1c23e912010-11-16 02:32:08 +00005599 // CK_VectorSplat does T -> vector T, so first cast to the
5600 // element type.
Richard Trieufacef2e2011-09-06 20:30:53 +00005601 QualType elType = cast<ExtVectorType>(LHSType)->getElementType();
5602 if (elType != RHSType) {
John McCalla180f042011-10-06 23:25:11 +00005603 Kind = PrepareScalarCast(RHS, elType);
Richard Trieufacef2e2011-09-06 20:30:53 +00005604 RHS = ImpCastExprToType(RHS.take(), elType, Kind);
John McCall1c23e912010-11-16 02:32:08 +00005605 }
5606 Kind = CK_VectorSplat;
Nate Begeman1bd1f6e2009-06-28 02:36:38 +00005607 return Compatible;
John McCalldaa8e4e2010-11-15 09:13:47 +00005608 }
Nate Begeman1bd1f6e2009-06-28 02:36:38 +00005609 }
Mike Stump1eb44332009-09-09 15:08:12 +00005610
John McCallb6cfa242011-01-31 22:28:28 +00005611 // Conversions to or from vector type.
Richard Trieufacef2e2011-09-06 20:30:53 +00005612 if (LHSType->isVectorType() || RHSType->isVectorType()) {
5613 if (LHSType->isVectorType() && RHSType->isVectorType()) {
Bob Wilsonde3deea2010-12-02 00:25:15 +00005614 // Allow assignments of an AltiVec vector type to an equivalent GCC
5615 // vector type and vice versa
Richard Trieufacef2e2011-09-06 20:30:53 +00005616 if (Context.areCompatibleVectorTypes(LHSType, RHSType)) {
Bob Wilsonde3deea2010-12-02 00:25:15 +00005617 Kind = CK_BitCast;
5618 return Compatible;
5619 }
5620
Douglas Gregor255210e2010-08-06 10:14:59 +00005621 // If we are allowing lax vector conversions, and LHS and RHS are both
5622 // vectors, the total size only needs to be the same. This is a bitcast;
5623 // no bits are changed but the result type is different.
David Blaikie4e4d0842012-03-11 07:00:24 +00005624 if (getLangOpts().LaxVectorConversions &&
Richard Trieufacef2e2011-09-06 20:30:53 +00005625 (Context.getTypeSize(LHSType) == Context.getTypeSize(RHSType))) {
John McCall0c6d28d2010-11-15 10:08:00 +00005626 Kind = CK_BitCast;
Anders Carlssonb0f90cc2009-01-30 23:17:46 +00005627 return IncompatibleVectors;
John McCalldaa8e4e2010-11-15 09:13:47 +00005628 }
Chris Lattnere8b3e962008-01-04 23:32:24 +00005629 }
5630 return Incompatible;
Mike Stumpeed9cac2009-02-19 03:04:26 +00005631 }
Eli Friedmanf8f873d2008-05-30 18:07:22 +00005632
John McCallb6cfa242011-01-31 22:28:28 +00005633 // Arithmetic conversions.
Richard Trieufacef2e2011-09-06 20:30:53 +00005634 if (LHSType->isArithmeticType() && RHSType->isArithmeticType() &&
David Blaikie4e4d0842012-03-11 07:00:24 +00005635 !(getLangOpts().CPlusPlus && LHSType->isEnumeralType())) {
John McCalla180f042011-10-06 23:25:11 +00005636 Kind = PrepareScalarCast(RHS, LHSType);
Reid Spencer5f016e22007-07-11 17:01:13 +00005637 return Compatible;
John McCalldaa8e4e2010-11-15 09:13:47 +00005638 }
Eli Friedmanf8f873d2008-05-30 18:07:22 +00005639
John McCallb6cfa242011-01-31 22:28:28 +00005640 // Conversions to normal pointers.
Richard Trieufacef2e2011-09-06 20:30:53 +00005641 if (const PointerType *LHSPointer = dyn_cast<PointerType>(LHSType)) {
John McCallb6cfa242011-01-31 22:28:28 +00005642 // U* -> T*
Richard Trieufacef2e2011-09-06 20:30:53 +00005643 if (isa<PointerType>(RHSType)) {
John McCalldaa8e4e2010-11-15 09:13:47 +00005644 Kind = CK_BitCast;
Richard Trieufacef2e2011-09-06 20:30:53 +00005645 return checkPointerTypesForAssignment(*this, LHSType, RHSType);
John McCalldaa8e4e2010-11-15 09:13:47 +00005646 }
Mike Stumpeed9cac2009-02-19 03:04:26 +00005647
John McCallb6cfa242011-01-31 22:28:28 +00005648 // int -> T*
Richard Trieufacef2e2011-09-06 20:30:53 +00005649 if (RHSType->isIntegerType()) {
John McCallb6cfa242011-01-31 22:28:28 +00005650 Kind = CK_IntegralToPointer; // FIXME: null?
5651 return IntToPointer;
Steve Naroff14108da2009-07-10 23:34:53 +00005652 }
John McCallb6cfa242011-01-31 22:28:28 +00005653
5654 // C pointers are not compatible with ObjC object pointers,
5655 // with two exceptions:
Richard Trieufacef2e2011-09-06 20:30:53 +00005656 if (isa<ObjCObjectPointerType>(RHSType)) {
John McCallb6cfa242011-01-31 22:28:28 +00005657 // - conversions to void*
Richard Trieufacef2e2011-09-06 20:30:53 +00005658 if (LHSPointer->getPointeeType()->isVoidType()) {
John McCall1d9b3b22011-09-09 05:25:32 +00005659 Kind = CK_BitCast;
John McCallb6cfa242011-01-31 22:28:28 +00005660 return Compatible;
5661 }
5662
5663 // - conversions from 'Class' to the redefinition type
Richard Trieufacef2e2011-09-06 20:30:53 +00005664 if (RHSType->isObjCClassType() &&
5665 Context.hasSameType(LHSType,
Douglas Gregor01a4cf12011-08-11 20:58:55 +00005666 Context.getObjCClassRedefinitionType())) {
John McCalldaa8e4e2010-11-15 09:13:47 +00005667 Kind = CK_BitCast;
Douglas Gregor63a94902008-11-27 00:44:28 +00005668 return Compatible;
John McCalldaa8e4e2010-11-15 09:13:47 +00005669 }
Douglas Gregorc737acb2011-09-27 16:10:05 +00005670
John McCallb6cfa242011-01-31 22:28:28 +00005671 Kind = CK_BitCast;
5672 return IncompatiblePointer;
5673 }
5674
5675 // U^ -> void*
Richard Trieufacef2e2011-09-06 20:30:53 +00005676 if (RHSType->getAs<BlockPointerType>()) {
5677 if (LHSPointer->getPointeeType()->isVoidType()) {
John McCallb6cfa242011-01-31 22:28:28 +00005678 Kind = CK_BitCast;
Steve Naroffb4406862008-09-29 18:10:17 +00005679 return Compatible;
John McCalldaa8e4e2010-11-15 09:13:47 +00005680 }
Steve Naroffb4406862008-09-29 18:10:17 +00005681 }
John McCallb6cfa242011-01-31 22:28:28 +00005682
Steve Naroff1c7d0672008-09-04 15:10:53 +00005683 return Incompatible;
5684 }
5685
John McCallb6cfa242011-01-31 22:28:28 +00005686 // Conversions to block pointers.
Richard Trieufacef2e2011-09-06 20:30:53 +00005687 if (isa<BlockPointerType>(LHSType)) {
John McCallb6cfa242011-01-31 22:28:28 +00005688 // U^ -> T^
Richard Trieufacef2e2011-09-06 20:30:53 +00005689 if (RHSType->isBlockPointerType()) {
John McCall1d9b3b22011-09-09 05:25:32 +00005690 Kind = CK_BitCast;
Richard Trieufacef2e2011-09-06 20:30:53 +00005691 return checkBlockPointerTypesForAssignment(*this, LHSType, RHSType);
John McCallb6cfa242011-01-31 22:28:28 +00005692 }
5693
5694 // int or null -> T^
Richard Trieufacef2e2011-09-06 20:30:53 +00005695 if (RHSType->isIntegerType()) {
John McCalldaa8e4e2010-11-15 09:13:47 +00005696 Kind = CK_IntegralToPointer; // FIXME: null
Eli Friedmand8f4f432009-02-25 04:20:42 +00005697 return IntToBlockPointer;
John McCalldaa8e4e2010-11-15 09:13:47 +00005698 }
5699
John McCallb6cfa242011-01-31 22:28:28 +00005700 // id -> T^
David Blaikie4e4d0842012-03-11 07:00:24 +00005701 if (getLangOpts().ObjC1 && RHSType->isObjCIdType()) {
John McCallb6cfa242011-01-31 22:28:28 +00005702 Kind = CK_AnyPointerToBlockPointerCast;
Steve Naroffb4406862008-09-29 18:10:17 +00005703 return Compatible;
John McCallb6cfa242011-01-31 22:28:28 +00005704 }
Steve Naroffb4406862008-09-29 18:10:17 +00005705
John McCallb6cfa242011-01-31 22:28:28 +00005706 // void* -> T^
Richard Trieufacef2e2011-09-06 20:30:53 +00005707 if (const PointerType *RHSPT = RHSType->getAs<PointerType>())
John McCallb6cfa242011-01-31 22:28:28 +00005708 if (RHSPT->getPointeeType()->isVoidType()) {
5709 Kind = CK_AnyPointerToBlockPointerCast;
Douglas Gregor63a94902008-11-27 00:44:28 +00005710 return Compatible;
John McCallb6cfa242011-01-31 22:28:28 +00005711 }
John McCalldaa8e4e2010-11-15 09:13:47 +00005712
Chris Lattnerfc144e22008-01-04 23:18:45 +00005713 return Incompatible;
5714 }
5715
John McCallb6cfa242011-01-31 22:28:28 +00005716 // Conversions to Objective-C pointers.
Richard Trieufacef2e2011-09-06 20:30:53 +00005717 if (isa<ObjCObjectPointerType>(LHSType)) {
John McCallb6cfa242011-01-31 22:28:28 +00005718 // A* -> B*
Richard Trieufacef2e2011-09-06 20:30:53 +00005719 if (RHSType->isObjCObjectPointerType()) {
John McCallb6cfa242011-01-31 22:28:28 +00005720 Kind = CK_BitCast;
Fariborz Jahanian04e5a252011-07-07 18:55:47 +00005721 Sema::AssignConvertType result =
Richard Trieufacef2e2011-09-06 20:30:53 +00005722 checkObjCPointerTypesForAssignment(*this, LHSType, RHSType);
David Blaikie4e4d0842012-03-11 07:00:24 +00005723 if (getLangOpts().ObjCAutoRefCount &&
Fariborz Jahanian04e5a252011-07-07 18:55:47 +00005724 result == Compatible &&
Richard Trieufacef2e2011-09-06 20:30:53 +00005725 !CheckObjCARCUnavailableWeakConversion(OrigLHSType, RHSType))
Fariborz Jahanian7a084ec2011-07-07 23:04:17 +00005726 result = IncompatibleObjCWeakRef;
Fariborz Jahanian04e5a252011-07-07 18:55:47 +00005727 return result;
John McCallb6cfa242011-01-31 22:28:28 +00005728 }
5729
5730 // int or null -> A*
Richard Trieufacef2e2011-09-06 20:30:53 +00005731 if (RHSType->isIntegerType()) {
John McCalldaa8e4e2010-11-15 09:13:47 +00005732 Kind = CK_IntegralToPointer; // FIXME: null
Steve Naroff14108da2009-07-10 23:34:53 +00005733 return IntToPointer;
John McCalldaa8e4e2010-11-15 09:13:47 +00005734 }
5735
John McCallb6cfa242011-01-31 22:28:28 +00005736 // In general, C pointers are not compatible with ObjC object pointers,
5737 // with two exceptions:
Richard Trieufacef2e2011-09-06 20:30:53 +00005738 if (isa<PointerType>(RHSType)) {
John McCall1d9b3b22011-09-09 05:25:32 +00005739 Kind = CK_CPointerToObjCPointerCast;
5740
John McCallb6cfa242011-01-31 22:28:28 +00005741 // - conversions from 'void*'
Richard Trieufacef2e2011-09-06 20:30:53 +00005742 if (RHSType->isVoidPointerType()) {
Steve Naroff67ef8ea2009-07-20 17:56:53 +00005743 return Compatible;
John McCallb6cfa242011-01-31 22:28:28 +00005744 }
5745
5746 // - conversions to 'Class' from its redefinition type
Richard Trieufacef2e2011-09-06 20:30:53 +00005747 if (LHSType->isObjCClassType() &&
5748 Context.hasSameType(RHSType,
Douglas Gregor01a4cf12011-08-11 20:58:55 +00005749 Context.getObjCClassRedefinitionType())) {
John McCallb6cfa242011-01-31 22:28:28 +00005750 return Compatible;
5751 }
5752
Steve Naroff67ef8ea2009-07-20 17:56:53 +00005753 return IncompatiblePointer;
Steve Naroff14108da2009-07-10 23:34:53 +00005754 }
John McCallb6cfa242011-01-31 22:28:28 +00005755
5756 // T^ -> A*
Richard Trieufacef2e2011-09-06 20:30:53 +00005757 if (RHSType->isBlockPointerType()) {
John McCalldc05b112011-09-10 01:16:55 +00005758 maybeExtendBlockObject(*this, RHS);
John McCall1d9b3b22011-09-09 05:25:32 +00005759 Kind = CK_BlockPointerToObjCPointerCast;
Steve Naroff14108da2009-07-10 23:34:53 +00005760 return Compatible;
John McCallb6cfa242011-01-31 22:28:28 +00005761 }
5762
Steve Naroff14108da2009-07-10 23:34:53 +00005763 return Incompatible;
5764 }
John McCallb6cfa242011-01-31 22:28:28 +00005765
5766 // Conversions from pointers that are not covered by the above.
Richard Trieufacef2e2011-09-06 20:30:53 +00005767 if (isa<PointerType>(RHSType)) {
John McCallb6cfa242011-01-31 22:28:28 +00005768 // T* -> _Bool
Richard Trieufacef2e2011-09-06 20:30:53 +00005769 if (LHSType == Context.BoolTy) {
John McCalldaa8e4e2010-11-15 09:13:47 +00005770 Kind = CK_PointerToBoolean;
Eli Friedmanf8f873d2008-05-30 18:07:22 +00005771 return Compatible;
John McCalldaa8e4e2010-11-15 09:13:47 +00005772 }
Eli Friedmanf8f873d2008-05-30 18:07:22 +00005773
John McCallb6cfa242011-01-31 22:28:28 +00005774 // T* -> int
Richard Trieufacef2e2011-09-06 20:30:53 +00005775 if (LHSType->isIntegerType()) {
John McCalldaa8e4e2010-11-15 09:13:47 +00005776 Kind = CK_PointerToIntegral;
Chris Lattnerb7b61152008-01-04 18:22:42 +00005777 return PointerToInt;
John McCalldaa8e4e2010-11-15 09:13:47 +00005778 }
Mike Stumpeed9cac2009-02-19 03:04:26 +00005779
Chris Lattnerfc144e22008-01-04 23:18:45 +00005780 return Incompatible;
Chris Lattnerfc144e22008-01-04 23:18:45 +00005781 }
John McCallb6cfa242011-01-31 22:28:28 +00005782
5783 // Conversions from Objective-C pointers that are not covered by the above.
Richard Trieufacef2e2011-09-06 20:30:53 +00005784 if (isa<ObjCObjectPointerType>(RHSType)) {
John McCallb6cfa242011-01-31 22:28:28 +00005785 // T* -> _Bool
Richard Trieufacef2e2011-09-06 20:30:53 +00005786 if (LHSType == Context.BoolTy) {
John McCalldaa8e4e2010-11-15 09:13:47 +00005787 Kind = CK_PointerToBoolean;
Steve Naroff14108da2009-07-10 23:34:53 +00005788 return Compatible;
John McCalldaa8e4e2010-11-15 09:13:47 +00005789 }
Steve Naroff14108da2009-07-10 23:34:53 +00005790
John McCallb6cfa242011-01-31 22:28:28 +00005791 // T* -> int
Richard Trieufacef2e2011-09-06 20:30:53 +00005792 if (LHSType->isIntegerType()) {
John McCalldaa8e4e2010-11-15 09:13:47 +00005793 Kind = CK_PointerToIntegral;
Steve Naroff14108da2009-07-10 23:34:53 +00005794 return PointerToInt;
John McCalldaa8e4e2010-11-15 09:13:47 +00005795 }
5796
Steve Naroff14108da2009-07-10 23:34:53 +00005797 return Incompatible;
5798 }
Eli Friedmanf8f873d2008-05-30 18:07:22 +00005799
John McCallb6cfa242011-01-31 22:28:28 +00005800 // struct A -> struct B
Richard Trieufacef2e2011-09-06 20:30:53 +00005801 if (isa<TagType>(LHSType) && isa<TagType>(RHSType)) {
5802 if (Context.typesAreCompatible(LHSType, RHSType)) {
John McCalldaa8e4e2010-11-15 09:13:47 +00005803 Kind = CK_NoOp;
Reid Spencer5f016e22007-07-11 17:01:13 +00005804 return Compatible;
John McCalldaa8e4e2010-11-15 09:13:47 +00005805 }
Reid Spencer5f016e22007-07-11 17:01:13 +00005806 }
John McCallb6cfa242011-01-31 22:28:28 +00005807
Reid Spencer5f016e22007-07-11 17:01:13 +00005808 return Incompatible;
5809}
5810
Douglas Gregor0c74e8a2009-04-29 22:16:16 +00005811/// \brief Constructs a transparent union from an expression that is
5812/// used to initialize the transparent union.
Richard Trieu67e29332011-08-02 04:35:43 +00005813static void ConstructTransparentUnion(Sema &S, ASTContext &C,
5814 ExprResult &EResult, QualType UnionType,
5815 FieldDecl *Field) {
Douglas Gregor0c74e8a2009-04-29 22:16:16 +00005816 // Build an initializer list that designates the appropriate member
5817 // of the transparent union.
John Wiegley429bb272011-04-08 18:41:53 +00005818 Expr *E = EResult.take();
Ted Kremenek709210f2010-04-13 23:39:13 +00005819 InitListExpr *Initializer = new (C) InitListExpr(C, SourceLocation(),
Benjamin Kramer3b6bef92012-08-24 11:54:20 +00005820 E, SourceLocation());
Douglas Gregor0c74e8a2009-04-29 22:16:16 +00005821 Initializer->setType(UnionType);
5822 Initializer->setInitializedFieldInUnion(Field);
5823
5824 // Build a compound literal constructing a value of the transparent
5825 // union type from this initializer list.
John McCall42f56b52010-01-18 19:35:47 +00005826 TypeSourceInfo *unionTInfo = C.getTrivialTypeSourceInfo(UnionType);
John Wiegley429bb272011-04-08 18:41:53 +00005827 EResult = S.Owned(
5828 new (C) CompoundLiteralExpr(SourceLocation(), unionTInfo, UnionType,
5829 VK_RValue, Initializer, false));
Douglas Gregor0c74e8a2009-04-29 22:16:16 +00005830}
5831
5832Sema::AssignConvertType
Richard Trieu67e29332011-08-02 04:35:43 +00005833Sema::CheckTransparentUnionArgumentConstraints(QualType ArgType,
Richard Trieuf7720da2011-09-06 20:40:12 +00005834 ExprResult &RHS) {
5835 QualType RHSType = RHS.get()->getType();
Douglas Gregor0c74e8a2009-04-29 22:16:16 +00005836
Mike Stump1eb44332009-09-09 15:08:12 +00005837 // If the ArgType is a Union type, we want to handle a potential
Douglas Gregor0c74e8a2009-04-29 22:16:16 +00005838 // transparent_union GCC extension.
5839 const RecordType *UT = ArgType->getAsUnionType();
Argyrios Kyrtzidis40b598e2009-06-30 02:34:44 +00005840 if (!UT || !UT->getDecl()->hasAttr<TransparentUnionAttr>())
Douglas Gregor0c74e8a2009-04-29 22:16:16 +00005841 return Incompatible;
5842
5843 // The field to initialize within the transparent union.
5844 RecordDecl *UD = UT->getDecl();
5845 FieldDecl *InitField = 0;
5846 // It's compatible if the expression matches any of the fields.
Argyrios Kyrtzidis17945a02009-06-30 02:36:12 +00005847 for (RecordDecl::field_iterator it = UD->field_begin(),
5848 itend = UD->field_end();
Douglas Gregor0c74e8a2009-04-29 22:16:16 +00005849 it != itend; ++it) {
5850 if (it->getType()->isPointerType()) {
5851 // If the transparent union contains a pointer type, we allow:
5852 // 1) void pointer
5853 // 2) null pointer constant
Richard Trieuf7720da2011-09-06 20:40:12 +00005854 if (RHSType->isPointerType())
John McCall1d9b3b22011-09-09 05:25:32 +00005855 if (RHSType->castAs<PointerType>()->getPointeeType()->isVoidType()) {
Richard Trieuf7720da2011-09-06 20:40:12 +00005856 RHS = ImpCastExprToType(RHS.take(), it->getType(), CK_BitCast);
David Blaikie581deb32012-06-06 20:45:41 +00005857 InitField = *it;
Douglas Gregor0c74e8a2009-04-29 22:16:16 +00005858 break;
5859 }
Mike Stump1eb44332009-09-09 15:08:12 +00005860
Richard Trieuf7720da2011-09-06 20:40:12 +00005861 if (RHS.get()->isNullPointerConstant(Context,
5862 Expr::NPC_ValueDependentIsNull)) {
5863 RHS = ImpCastExprToType(RHS.take(), it->getType(),
5864 CK_NullToPointer);
David Blaikie581deb32012-06-06 20:45:41 +00005865 InitField = *it;
Douglas Gregor0c74e8a2009-04-29 22:16:16 +00005866 break;
5867 }
5868 }
5869
John McCalldaa8e4e2010-11-15 09:13:47 +00005870 CastKind Kind = CK_Invalid;
Richard Trieuf7720da2011-09-06 20:40:12 +00005871 if (CheckAssignmentConstraints(it->getType(), RHS, Kind)
Douglas Gregor0c74e8a2009-04-29 22:16:16 +00005872 == Compatible) {
Richard Trieuf7720da2011-09-06 20:40:12 +00005873 RHS = ImpCastExprToType(RHS.take(), it->getType(), Kind);
David Blaikie581deb32012-06-06 20:45:41 +00005874 InitField = *it;
Douglas Gregor0c74e8a2009-04-29 22:16:16 +00005875 break;
5876 }
5877 }
5878
5879 if (!InitField)
5880 return Incompatible;
5881
Richard Trieuf7720da2011-09-06 20:40:12 +00005882 ConstructTransparentUnion(*this, Context, RHS, ArgType, InitField);
Douglas Gregor0c74e8a2009-04-29 22:16:16 +00005883 return Compatible;
5884}
5885
Chris Lattner5cf216b2008-01-04 18:04:52 +00005886Sema::AssignConvertType
Sebastian Redl14b0c192011-09-24 17:48:00 +00005887Sema::CheckSingleAssignmentConstraints(QualType LHSType, ExprResult &RHS,
5888 bool Diagnose) {
David Blaikie4e4d0842012-03-11 07:00:24 +00005889 if (getLangOpts().CPlusPlus) {
Eli Friedmanb001de72011-10-06 23:00:33 +00005890 if (!LHSType->isRecordType() && !LHSType->isAtomicType()) {
Douglas Gregor98cd5992008-10-21 23:43:52 +00005891 // C++ 5.17p3: If the left operand is not of class type, the
5892 // expression is implicitly converted (C++ 4) to the
5893 // cv-unqualified type of the left operand.
Sebastian Redl091fffe2011-10-16 18:19:06 +00005894 ExprResult Res;
5895 if (Diagnose) {
5896 Res = PerformImplicitConversion(RHS.get(), LHSType.getUnqualifiedType(),
5897 AA_Assigning);
5898 } else {
5899 ImplicitConversionSequence ICS =
5900 TryImplicitConversion(RHS.get(), LHSType.getUnqualifiedType(),
5901 /*SuppressUserConversions=*/false,
5902 /*AllowExplicit=*/false,
5903 /*InOverloadResolution=*/false,
5904 /*CStyle=*/false,
5905 /*AllowObjCWritebackConversion=*/false);
5906 if (ICS.isFailure())
5907 return Incompatible;
5908 Res = PerformImplicitConversion(RHS.get(), LHSType.getUnqualifiedType(),
5909 ICS, AA_Assigning);
5910 }
John Wiegley429bb272011-04-08 18:41:53 +00005911 if (Res.isInvalid())
Douglas Gregor98cd5992008-10-21 23:43:52 +00005912 return Incompatible;
Fariborz Jahanian7a084ec2011-07-07 23:04:17 +00005913 Sema::AssignConvertType result = Compatible;
David Blaikie4e4d0842012-03-11 07:00:24 +00005914 if (getLangOpts().ObjCAutoRefCount &&
Richard Trieuf7720da2011-09-06 20:40:12 +00005915 !CheckObjCARCUnavailableWeakConversion(LHSType,
5916 RHS.get()->getType()))
Fariborz Jahanian7a084ec2011-07-07 23:04:17 +00005917 result = IncompatibleObjCWeakRef;
Benjamin Kramer3fe198b2012-08-23 21:35:17 +00005918 RHS = Res;
Fariborz Jahanian7a084ec2011-07-07 23:04:17 +00005919 return result;
Douglas Gregor98cd5992008-10-21 23:43:52 +00005920 }
5921
5922 // FIXME: Currently, we fall through and treat C++ classes like C
5923 // structures.
Eli Friedmanb001de72011-10-06 23:00:33 +00005924 // FIXME: We also fall through for atomics; not sure what should
5925 // happen there, though.
Sebastian Redl14b0c192011-09-24 17:48:00 +00005926 }
Douglas Gregor98cd5992008-10-21 23:43:52 +00005927
Steve Naroff529a4ad2007-11-27 17:58:44 +00005928 // C99 6.5.16.1p1: the left operand is a pointer and the right is
5929 // a null pointer constant.
Richard Trieuf7720da2011-09-06 20:40:12 +00005930 if ((LHSType->isPointerType() ||
5931 LHSType->isObjCObjectPointerType() ||
5932 LHSType->isBlockPointerType())
5933 && RHS.get()->isNullPointerConstant(Context,
5934 Expr::NPC_ValueDependentIsNull)) {
5935 RHS = ImpCastExprToType(RHS.take(), LHSType, CK_NullToPointer);
Steve Naroff529a4ad2007-11-27 17:58:44 +00005936 return Compatible;
5937 }
Mike Stumpeed9cac2009-02-19 03:04:26 +00005938
Chris Lattner943140e2007-10-16 02:55:40 +00005939 // This check seems unnatural, however it is necessary to ensure the proper
Steve Naroff90045e82007-07-13 23:32:42 +00005940 // conversion of functions/arrays. If the conversion were done for all
Douglas Gregor02a24ee2009-11-03 16:56:39 +00005941 // DeclExpr's (created by ActOnIdExpression), it would mess up the unary
Nick Lewyckyc133e9e2010-08-05 06:27:49 +00005942 // expressions that suppress this implicit conversion (&, sizeof).
Chris Lattner943140e2007-10-16 02:55:40 +00005943 //
Mike Stumpeed9cac2009-02-19 03:04:26 +00005944 // Suppress this for references: C++ 8.5.3p5.
Richard Trieuf7720da2011-09-06 20:40:12 +00005945 if (!LHSType->isReferenceType()) {
5946 RHS = DefaultFunctionArrayLvalueConversion(RHS.take());
5947 if (RHS.isInvalid())
John Wiegley429bb272011-04-08 18:41:53 +00005948 return Incompatible;
5949 }
Steve Narofff1120de2007-08-24 22:33:52 +00005950
John McCalldaa8e4e2010-11-15 09:13:47 +00005951 CastKind Kind = CK_Invalid;
Chris Lattner5cf216b2008-01-04 18:04:52 +00005952 Sema::AssignConvertType result =
Richard Trieuf7720da2011-09-06 20:40:12 +00005953 CheckAssignmentConstraints(LHSType, RHS, Kind);
Mike Stumpeed9cac2009-02-19 03:04:26 +00005954
Steve Narofff1120de2007-08-24 22:33:52 +00005955 // C99 6.5.16.1p2: The value of the right operand is converted to the
5956 // type of the assignment expression.
Douglas Gregor9d293df2008-10-28 00:22:11 +00005957 // CheckAssignmentConstraints allows the left-hand side to be a reference,
5958 // so that we can use references in built-in functions even in C.
5959 // The getNonReferenceType() call makes sure that the resulting expression
5960 // does not have reference type.
Richard Trieuf7720da2011-09-06 20:40:12 +00005961 if (result != Incompatible && RHS.get()->getType() != LHSType)
5962 RHS = ImpCastExprToType(RHS.take(),
5963 LHSType.getNonLValueExprType(Context), Kind);
Steve Narofff1120de2007-08-24 22:33:52 +00005964 return result;
Steve Naroff90045e82007-07-13 23:32:42 +00005965}
5966
Richard Trieuf7720da2011-09-06 20:40:12 +00005967QualType Sema::InvalidOperands(SourceLocation Loc, ExprResult &LHS,
5968 ExprResult &RHS) {
Chris Lattnerc9c7c4e2008-11-18 22:52:51 +00005969 Diag(Loc, diag::err_typecheck_invalid_operands)
Richard Trieuf7720da2011-09-06 20:40:12 +00005970 << LHS.get()->getType() << RHS.get()->getType()
5971 << LHS.get()->getSourceRange() << RHS.get()->getSourceRange();
Chris Lattnerca5eede2007-12-12 05:47:28 +00005972 return QualType();
Reid Spencer5f016e22007-07-11 17:01:13 +00005973}
5974
Richard Trieu08062aa2011-09-06 21:01:04 +00005975QualType Sema::CheckVectorOperands(ExprResult &LHS, ExprResult &RHS,
Richard Trieuccd891a2011-09-09 01:45:06 +00005976 SourceLocation Loc, bool IsCompAssign) {
Richard Smith9c129f82011-10-28 03:31:48 +00005977 if (!IsCompAssign) {
5978 LHS = DefaultFunctionArrayLvalueConversion(LHS.take());
5979 if (LHS.isInvalid())
5980 return QualType();
5981 }
5982 RHS = DefaultFunctionArrayLvalueConversion(RHS.take());
5983 if (RHS.isInvalid())
5984 return QualType();
5985
Mike Stumpeed9cac2009-02-19 03:04:26 +00005986 // For conversion purposes, we ignore any qualifiers.
Nate Begeman1330b0e2008-04-04 01:30:25 +00005987 // For example, "const float" and "float" are equivalent.
Richard Trieu08062aa2011-09-06 21:01:04 +00005988 QualType LHSType =
5989 Context.getCanonicalType(LHS.get()->getType()).getUnqualifiedType();
5990 QualType RHSType =
5991 Context.getCanonicalType(RHS.get()->getType()).getUnqualifiedType();
Mike Stumpeed9cac2009-02-19 03:04:26 +00005992
Nate Begemanbe2341d2008-07-14 18:02:46 +00005993 // If the vector types are identical, return.
Richard Trieu08062aa2011-09-06 21:01:04 +00005994 if (LHSType == RHSType)
5995 return LHSType;
Nate Begeman4119d1a2007-12-30 02:59:45 +00005996
Douglas Gregor255210e2010-08-06 10:14:59 +00005997 // Handle the case of equivalent AltiVec and GCC vector types
Richard Trieu08062aa2011-09-06 21:01:04 +00005998 if (LHSType->isVectorType() && RHSType->isVectorType() &&
5999 Context.areCompatibleVectorTypes(LHSType, RHSType)) {
6000 if (LHSType->isExtVectorType()) {
6001 RHS = ImpCastExprToType(RHS.take(), LHSType, CK_BitCast);
6002 return LHSType;
Eli Friedmanb9b4b782011-06-23 18:10:35 +00006003 }
6004
Richard Trieuccd891a2011-09-09 01:45:06 +00006005 if (!IsCompAssign)
Richard Trieu08062aa2011-09-06 21:01:04 +00006006 LHS = ImpCastExprToType(LHS.take(), RHSType, CK_BitCast);
6007 return RHSType;
Douglas Gregor255210e2010-08-06 10:14:59 +00006008 }
6009
David Blaikie4e4d0842012-03-11 07:00:24 +00006010 if (getLangOpts().LaxVectorConversions &&
Richard Trieu08062aa2011-09-06 21:01:04 +00006011 Context.getTypeSize(LHSType) == Context.getTypeSize(RHSType)) {
Eli Friedmanb9b4b782011-06-23 18:10:35 +00006012 // If we are allowing lax vector conversions, and LHS and RHS are both
6013 // vectors, the total size only needs to be the same. This is a
6014 // bitcast; no bits are changed but the result type is different.
6015 // FIXME: Should we really be allowing this?
Richard Trieu08062aa2011-09-06 21:01:04 +00006016 RHS = ImpCastExprToType(RHS.take(), LHSType, CK_BitCast);
6017 return LHSType;
Eli Friedmanb9b4b782011-06-23 18:10:35 +00006018 }
6019
Nate Begeman1bd1f6e2009-06-28 02:36:38 +00006020 // Canonicalize the ExtVector to the LHS, remember if we swapped so we can
6021 // swap back (so that we don't reverse the inputs to a subtract, for instance.
6022 bool swapped = false;
Richard Trieuccd891a2011-09-09 01:45:06 +00006023 if (RHSType->isExtVectorType() && !IsCompAssign) {
Nate Begeman1bd1f6e2009-06-28 02:36:38 +00006024 swapped = true;
Richard Trieu08062aa2011-09-06 21:01:04 +00006025 std::swap(RHS, LHS);
6026 std::swap(RHSType, LHSType);
Nate Begeman1bd1f6e2009-06-28 02:36:38 +00006027 }
Mike Stump1eb44332009-09-09 15:08:12 +00006028
Nate Begemandde25982009-06-28 19:12:57 +00006029 // Handle the case of an ext vector and scalar.
Richard Trieu08062aa2011-09-06 21:01:04 +00006030 if (const ExtVectorType *LV = LHSType->getAs<ExtVectorType>()) {
Nate Begeman1bd1f6e2009-06-28 02:36:38 +00006031 QualType EltTy = LV->getElementType();
Richard Trieu08062aa2011-09-06 21:01:04 +00006032 if (EltTy->isIntegralType(Context) && RHSType->isIntegralType(Context)) {
6033 int order = Context.getIntegerTypeOrder(EltTy, RHSType);
John McCalldaa8e4e2010-11-15 09:13:47 +00006034 if (order > 0)
Richard Trieu08062aa2011-09-06 21:01:04 +00006035 RHS = ImpCastExprToType(RHS.take(), EltTy, CK_IntegralCast);
John McCalldaa8e4e2010-11-15 09:13:47 +00006036 if (order >= 0) {
Richard Trieu08062aa2011-09-06 21:01:04 +00006037 RHS = ImpCastExprToType(RHS.take(), LHSType, CK_VectorSplat);
6038 if (swapped) std::swap(RHS, LHS);
6039 return LHSType;
Nate Begeman1bd1f6e2009-06-28 02:36:38 +00006040 }
6041 }
Richard Trieu08062aa2011-09-06 21:01:04 +00006042 if (EltTy->isRealFloatingType() && RHSType->isScalarType() &&
6043 RHSType->isRealFloatingType()) {
6044 int order = Context.getFloatingTypeOrder(EltTy, RHSType);
John McCalldaa8e4e2010-11-15 09:13:47 +00006045 if (order > 0)
Richard Trieu08062aa2011-09-06 21:01:04 +00006046 RHS = ImpCastExprToType(RHS.take(), EltTy, CK_FloatingCast);
John McCalldaa8e4e2010-11-15 09:13:47 +00006047 if (order >= 0) {
Richard Trieu08062aa2011-09-06 21:01:04 +00006048 RHS = ImpCastExprToType(RHS.take(), LHSType, CK_VectorSplat);
6049 if (swapped) std::swap(RHS, LHS);
6050 return LHSType;
Nate Begeman1bd1f6e2009-06-28 02:36:38 +00006051 }
Nate Begeman4119d1a2007-12-30 02:59:45 +00006052 }
6053 }
Mike Stump1eb44332009-09-09 15:08:12 +00006054
Nate Begemandde25982009-06-28 19:12:57 +00006055 // Vectors of different size or scalar and non-ext-vector are errors.
Richard Trieu08062aa2011-09-06 21:01:04 +00006056 if (swapped) std::swap(RHS, LHS);
Chris Lattnerc9c7c4e2008-11-18 22:52:51 +00006057 Diag(Loc, diag::err_typecheck_vector_not_convertable)
Richard Trieu08062aa2011-09-06 21:01:04 +00006058 << LHS.get()->getType() << RHS.get()->getType()
6059 << LHS.get()->getSourceRange() << RHS.get()->getSourceRange();
Reid Spencer5f016e22007-07-11 17:01:13 +00006060 return QualType();
Sebastian Redl22460502009-02-07 00:15:38 +00006061}
6062
Richard Trieu481037f2011-09-16 00:53:10 +00006063// checkArithmeticNull - Detect when a NULL constant is used improperly in an
6064// expression. These are mainly cases where the null pointer is used as an
6065// integer instead of a pointer.
6066static void checkArithmeticNull(Sema &S, ExprResult &LHS, ExprResult &RHS,
6067 SourceLocation Loc, bool IsCompare) {
6068 // The canonical way to check for a GNU null is with isNullPointerConstant,
6069 // but we use a bit of a hack here for speed; this is a relatively
6070 // hot path, and isNullPointerConstant is slow.
6071 bool LHSNull = isa<GNUNullExpr>(LHS.get()->IgnoreParenImpCasts());
6072 bool RHSNull = isa<GNUNullExpr>(RHS.get()->IgnoreParenImpCasts());
6073
6074 QualType NonNullType = LHSNull ? RHS.get()->getType() : LHS.get()->getType();
6075
6076 // Avoid analyzing cases where the result will either be invalid (and
6077 // diagnosed as such) or entirely valid and not something to warn about.
6078 if ((!LHSNull && !RHSNull) || NonNullType->isBlockPointerType() ||
6079 NonNullType->isMemberPointerType() || NonNullType->isFunctionType())
6080 return;
6081
6082 // Comparison operations would not make sense with a null pointer no matter
6083 // what the other expression is.
6084 if (!IsCompare) {
6085 S.Diag(Loc, diag::warn_null_in_arithmetic_operation)
6086 << (LHSNull ? LHS.get()->getSourceRange() : SourceRange())
6087 << (RHSNull ? RHS.get()->getSourceRange() : SourceRange());
6088 return;
6089 }
6090
6091 // The rest of the operations only make sense with a null pointer
6092 // if the other expression is a pointer.
6093 if (LHSNull == RHSNull || NonNullType->isAnyPointerType() ||
6094 NonNullType->canDecayToPointerType())
6095 return;
6096
6097 S.Diag(Loc, diag::warn_null_in_comparison_operation)
6098 << LHSNull /* LHS is NULL */ << NonNullType
6099 << LHS.get()->getSourceRange() << RHS.get()->getSourceRange();
6100}
6101
Richard Trieu08062aa2011-09-06 21:01:04 +00006102QualType Sema::CheckMultiplyDivideOperands(ExprResult &LHS, ExprResult &RHS,
Richard Trieu67e29332011-08-02 04:35:43 +00006103 SourceLocation Loc,
Richard Trieuccd891a2011-09-09 01:45:06 +00006104 bool IsCompAssign, bool IsDiv) {
Richard Trieu481037f2011-09-16 00:53:10 +00006105 checkArithmeticNull(*this, LHS, RHS, Loc, /*isCompare=*/false);
6106
Richard Trieu08062aa2011-09-06 21:01:04 +00006107 if (LHS.get()->getType()->isVectorType() ||
6108 RHS.get()->getType()->isVectorType())
Richard Trieuccd891a2011-09-09 01:45:06 +00006109 return CheckVectorOperands(LHS, RHS, Loc, IsCompAssign);
Mike Stumpeed9cac2009-02-19 03:04:26 +00006110
Richard Trieuccd891a2011-09-09 01:45:06 +00006111 QualType compType = UsualArithmeticConversions(LHS, RHS, IsCompAssign);
Richard Trieu08062aa2011-09-06 21:01:04 +00006112 if (LHS.isInvalid() || RHS.isInvalid())
John Wiegley429bb272011-04-08 18:41:53 +00006113 return QualType();
Mike Stumpeed9cac2009-02-19 03:04:26 +00006114
David Chisnall7a7ee302012-01-16 17:27:18 +00006115
Eli Friedman860a3192012-06-16 02:19:17 +00006116 if (compType.isNull() || !compType->isArithmeticType())
Richard Trieu08062aa2011-09-06 21:01:04 +00006117 return InvalidOperands(Loc, LHS, RHS);
Kovarththanan Rajaratnam19357542010-03-13 10:17:05 +00006118
Chris Lattner7ef655a2010-01-12 21:23:57 +00006119 // Check for division by zero.
Richard Trieuccd891a2011-09-09 01:45:06 +00006120 if (IsDiv &&
Richard Trieu08062aa2011-09-06 21:01:04 +00006121 RHS.get()->isNullPointerConstant(Context,
Richard Trieu67e29332011-08-02 04:35:43 +00006122 Expr::NPC_ValueDependentIsNotNull))
Richard Trieu08062aa2011-09-06 21:01:04 +00006123 DiagRuntimeBehavior(Loc, RHS.get(), PDiag(diag::warn_division_by_zero)
6124 << RHS.get()->getSourceRange());
Kovarththanan Rajaratnam19357542010-03-13 10:17:05 +00006125
Chris Lattner7ef655a2010-01-12 21:23:57 +00006126 return compType;
Reid Spencer5f016e22007-07-11 17:01:13 +00006127}
6128
Chris Lattner7ef655a2010-01-12 21:23:57 +00006129QualType Sema::CheckRemainderOperands(
Richard Trieuccd891a2011-09-09 01:45:06 +00006130 ExprResult &LHS, ExprResult &RHS, SourceLocation Loc, bool IsCompAssign) {
Richard Trieu481037f2011-09-16 00:53:10 +00006131 checkArithmeticNull(*this, LHS, RHS, Loc, /*isCompare=*/false);
6132
Richard Trieu08062aa2011-09-06 21:01:04 +00006133 if (LHS.get()->getType()->isVectorType() ||
6134 RHS.get()->getType()->isVectorType()) {
6135 if (LHS.get()->getType()->hasIntegerRepresentation() &&
6136 RHS.get()->getType()->hasIntegerRepresentation())
Richard Trieuccd891a2011-09-09 01:45:06 +00006137 return CheckVectorOperands(LHS, RHS, Loc, IsCompAssign);
Richard Trieu08062aa2011-09-06 21:01:04 +00006138 return InvalidOperands(Loc, LHS, RHS);
Daniel Dunbar523aa602009-01-05 22:55:36 +00006139 }
Steve Naroff90045e82007-07-13 23:32:42 +00006140
Richard Trieuccd891a2011-09-09 01:45:06 +00006141 QualType compType = UsualArithmeticConversions(LHS, RHS, IsCompAssign);
Richard Trieu08062aa2011-09-06 21:01:04 +00006142 if (LHS.isInvalid() || RHS.isInvalid())
John Wiegley429bb272011-04-08 18:41:53 +00006143 return QualType();
Mike Stumpeed9cac2009-02-19 03:04:26 +00006144
Eli Friedman860a3192012-06-16 02:19:17 +00006145 if (compType.isNull() || !compType->isIntegerType())
Richard Trieu08062aa2011-09-06 21:01:04 +00006146 return InvalidOperands(Loc, LHS, RHS);
Kovarththanan Rajaratnam19357542010-03-13 10:17:05 +00006147
Chris Lattner7ef655a2010-01-12 21:23:57 +00006148 // Check for remainder by zero.
Richard Trieu08062aa2011-09-06 21:01:04 +00006149 if (RHS.get()->isNullPointerConstant(Context,
Richard Trieu67e29332011-08-02 04:35:43 +00006150 Expr::NPC_ValueDependentIsNotNull))
Richard Trieu08062aa2011-09-06 21:01:04 +00006151 DiagRuntimeBehavior(Loc, RHS.get(), PDiag(diag::warn_remainder_by_zero)
6152 << RHS.get()->getSourceRange());
Kovarththanan Rajaratnam19357542010-03-13 10:17:05 +00006153
Chris Lattner7ef655a2010-01-12 21:23:57 +00006154 return compType;
Reid Spencer5f016e22007-07-11 17:01:13 +00006155}
6156
Chandler Carruth13b21be2011-06-27 08:02:19 +00006157/// \brief Diagnose invalid arithmetic on two void pointers.
6158static void diagnoseArithmeticOnTwoVoidPointers(Sema &S, SourceLocation Loc,
Richard Trieudef75842011-09-06 21:13:51 +00006159 Expr *LHSExpr, Expr *RHSExpr) {
David Blaikie4e4d0842012-03-11 07:00:24 +00006160 S.Diag(Loc, S.getLangOpts().CPlusPlus
Chandler Carruth13b21be2011-06-27 08:02:19 +00006161 ? diag::err_typecheck_pointer_arith_void_type
6162 : diag::ext_gnu_void_ptr)
Richard Trieudef75842011-09-06 21:13:51 +00006163 << 1 /* two pointers */ << LHSExpr->getSourceRange()
6164 << RHSExpr->getSourceRange();
Chandler Carruth13b21be2011-06-27 08:02:19 +00006165}
6166
6167/// \brief Diagnose invalid arithmetic on a void pointer.
6168static void diagnoseArithmeticOnVoidPointer(Sema &S, SourceLocation Loc,
6169 Expr *Pointer) {
David Blaikie4e4d0842012-03-11 07:00:24 +00006170 S.Diag(Loc, S.getLangOpts().CPlusPlus
Chandler Carruth13b21be2011-06-27 08:02:19 +00006171 ? diag::err_typecheck_pointer_arith_void_type
6172 : diag::ext_gnu_void_ptr)
6173 << 0 /* one pointer */ << Pointer->getSourceRange();
6174}
6175
6176/// \brief Diagnose invalid arithmetic on two function pointers.
6177static void diagnoseArithmeticOnTwoFunctionPointers(Sema &S, SourceLocation Loc,
6178 Expr *LHS, Expr *RHS) {
6179 assert(LHS->getType()->isAnyPointerType());
6180 assert(RHS->getType()->isAnyPointerType());
David Blaikie4e4d0842012-03-11 07:00:24 +00006181 S.Diag(Loc, S.getLangOpts().CPlusPlus
Chandler Carruth13b21be2011-06-27 08:02:19 +00006182 ? diag::err_typecheck_pointer_arith_function_type
6183 : diag::ext_gnu_ptr_func_arith)
6184 << 1 /* two pointers */ << LHS->getType()->getPointeeType()
6185 // We only show the second type if it differs from the first.
6186 << (unsigned)!S.Context.hasSameUnqualifiedType(LHS->getType(),
6187 RHS->getType())
6188 << RHS->getType()->getPointeeType()
6189 << LHS->getSourceRange() << RHS->getSourceRange();
6190}
6191
6192/// \brief Diagnose invalid arithmetic on a function pointer.
6193static void diagnoseArithmeticOnFunctionPointer(Sema &S, SourceLocation Loc,
6194 Expr *Pointer) {
6195 assert(Pointer->getType()->isAnyPointerType());
David Blaikie4e4d0842012-03-11 07:00:24 +00006196 S.Diag(Loc, S.getLangOpts().CPlusPlus
Chandler Carruth13b21be2011-06-27 08:02:19 +00006197 ? diag::err_typecheck_pointer_arith_function_type
6198 : diag::ext_gnu_ptr_func_arith)
6199 << 0 /* one pointer */ << Pointer->getType()->getPointeeType()
6200 << 0 /* one pointer, so only one type */
6201 << Pointer->getSourceRange();
6202}
6203
Richard Trieud9f19342011-09-12 18:08:02 +00006204/// \brief Emit error if Operand is incomplete pointer type
Richard Trieu097ecd22011-09-02 02:15:37 +00006205///
6206/// \returns True if pointer has incomplete type
6207static bool checkArithmeticIncompletePointerType(Sema &S, SourceLocation Loc,
6208 Expr *Operand) {
John McCall1503f0d2012-07-31 05:14:30 +00006209 assert(Operand->getType()->isAnyPointerType() &&
6210 !Operand->getType()->isDependentType());
6211 QualType PointeeTy = Operand->getType()->getPointeeType();
6212 return S.RequireCompleteType(Loc, PointeeTy,
6213 diag::err_typecheck_arithmetic_incomplete_type,
6214 PointeeTy, Operand->getSourceRange());
Richard Trieu097ecd22011-09-02 02:15:37 +00006215}
6216
Chandler Carruth13b21be2011-06-27 08:02:19 +00006217/// \brief Check the validity of an arithmetic pointer operand.
6218///
6219/// If the operand has pointer type, this code will check for pointer types
6220/// which are invalid in arithmetic operations. These will be diagnosed
6221/// appropriately, including whether or not the use is supported as an
6222/// extension.
6223///
6224/// \returns True when the operand is valid to use (even if as an extension).
6225static bool checkArithmeticOpPointerOperand(Sema &S, SourceLocation Loc,
6226 Expr *Operand) {
6227 if (!Operand->getType()->isAnyPointerType()) return true;
6228
6229 QualType PointeeTy = Operand->getType()->getPointeeType();
6230 if (PointeeTy->isVoidType()) {
6231 diagnoseArithmeticOnVoidPointer(S, Loc, Operand);
David Blaikie4e4d0842012-03-11 07:00:24 +00006232 return !S.getLangOpts().CPlusPlus;
Chandler Carruth13b21be2011-06-27 08:02:19 +00006233 }
6234 if (PointeeTy->isFunctionType()) {
6235 diagnoseArithmeticOnFunctionPointer(S, Loc, Operand);
David Blaikie4e4d0842012-03-11 07:00:24 +00006236 return !S.getLangOpts().CPlusPlus;
Chandler Carruth13b21be2011-06-27 08:02:19 +00006237 }
6238
Richard Trieu097ecd22011-09-02 02:15:37 +00006239 if (checkArithmeticIncompletePointerType(S, Loc, Operand)) return false;
Chandler Carruth13b21be2011-06-27 08:02:19 +00006240
6241 return true;
6242}
6243
6244/// \brief Check the validity of a binary arithmetic operation w.r.t. pointer
6245/// operands.
6246///
6247/// This routine will diagnose any invalid arithmetic on pointer operands much
6248/// like \see checkArithmeticOpPointerOperand. However, it has special logic
6249/// for emitting a single diagnostic even for operations where both LHS and RHS
6250/// are (potentially problematic) pointers.
6251///
6252/// \returns True when the operand is valid to use (even if as an extension).
6253static bool checkArithmeticBinOpPointerOperands(Sema &S, SourceLocation Loc,
Richard Trieudef75842011-09-06 21:13:51 +00006254 Expr *LHSExpr, Expr *RHSExpr) {
6255 bool isLHSPointer = LHSExpr->getType()->isAnyPointerType();
6256 bool isRHSPointer = RHSExpr->getType()->isAnyPointerType();
Chandler Carruth13b21be2011-06-27 08:02:19 +00006257 if (!isLHSPointer && !isRHSPointer) return true;
6258
6259 QualType LHSPointeeTy, RHSPointeeTy;
Richard Trieudef75842011-09-06 21:13:51 +00006260 if (isLHSPointer) LHSPointeeTy = LHSExpr->getType()->getPointeeType();
6261 if (isRHSPointer) RHSPointeeTy = RHSExpr->getType()->getPointeeType();
Chandler Carruth13b21be2011-06-27 08:02:19 +00006262
6263 // Check for arithmetic on pointers to incomplete types.
6264 bool isLHSVoidPtr = isLHSPointer && LHSPointeeTy->isVoidType();
6265 bool isRHSVoidPtr = isRHSPointer && RHSPointeeTy->isVoidType();
6266 if (isLHSVoidPtr || isRHSVoidPtr) {
Richard Trieudef75842011-09-06 21:13:51 +00006267 if (!isRHSVoidPtr) diagnoseArithmeticOnVoidPointer(S, Loc, LHSExpr);
6268 else if (!isLHSVoidPtr) diagnoseArithmeticOnVoidPointer(S, Loc, RHSExpr);
6269 else diagnoseArithmeticOnTwoVoidPointers(S, Loc, LHSExpr, RHSExpr);
Chandler Carruth13b21be2011-06-27 08:02:19 +00006270
David Blaikie4e4d0842012-03-11 07:00:24 +00006271 return !S.getLangOpts().CPlusPlus;
Chandler Carruth13b21be2011-06-27 08:02:19 +00006272 }
6273
6274 bool isLHSFuncPtr = isLHSPointer && LHSPointeeTy->isFunctionType();
6275 bool isRHSFuncPtr = isRHSPointer && RHSPointeeTy->isFunctionType();
6276 if (isLHSFuncPtr || isRHSFuncPtr) {
Richard Trieudef75842011-09-06 21:13:51 +00006277 if (!isRHSFuncPtr) diagnoseArithmeticOnFunctionPointer(S, Loc, LHSExpr);
6278 else if (!isLHSFuncPtr) diagnoseArithmeticOnFunctionPointer(S, Loc,
6279 RHSExpr);
6280 else diagnoseArithmeticOnTwoFunctionPointers(S, Loc, LHSExpr, RHSExpr);
Chandler Carruth13b21be2011-06-27 08:02:19 +00006281
David Blaikie4e4d0842012-03-11 07:00:24 +00006282 return !S.getLangOpts().CPlusPlus;
Chandler Carruth13b21be2011-06-27 08:02:19 +00006283 }
6284
John McCall1503f0d2012-07-31 05:14:30 +00006285 if (isLHSPointer && checkArithmeticIncompletePointerType(S, Loc, LHSExpr))
6286 return false;
6287 if (isRHSPointer && checkArithmeticIncompletePointerType(S, Loc, RHSExpr))
6288 return false;
Richard Trieu097ecd22011-09-02 02:15:37 +00006289
Chandler Carruth13b21be2011-06-27 08:02:19 +00006290 return true;
6291}
6292
Nico Weber1cb2d742012-03-02 22:01:22 +00006293/// diagnoseStringPlusInt - Emit a warning when adding an integer to a string
6294/// literal.
6295static void diagnoseStringPlusInt(Sema &Self, SourceLocation OpLoc,
6296 Expr *LHSExpr, Expr *RHSExpr) {
6297 StringLiteral* StrExpr = dyn_cast<StringLiteral>(LHSExpr->IgnoreImpCasts());
6298 Expr* IndexExpr = RHSExpr;
6299 if (!StrExpr) {
6300 StrExpr = dyn_cast<StringLiteral>(RHSExpr->IgnoreImpCasts());
6301 IndexExpr = LHSExpr;
6302 }
6303
6304 bool IsStringPlusInt = StrExpr &&
6305 IndexExpr->getType()->isIntegralOrUnscopedEnumerationType();
6306 if (!IsStringPlusInt)
6307 return;
6308
6309 llvm::APSInt index;
6310 if (IndexExpr->EvaluateAsInt(index, Self.getASTContext())) {
6311 unsigned StrLenWithNull = StrExpr->getLength() + 1;
6312 if (index.isNonNegative() &&
6313 index <= llvm::APSInt(llvm::APInt(index.getBitWidth(), StrLenWithNull),
6314 index.isUnsigned()))
6315 return;
6316 }
6317
6318 SourceRange DiagRange(LHSExpr->getLocStart(), RHSExpr->getLocEnd());
6319 Self.Diag(OpLoc, diag::warn_string_plus_int)
6320 << DiagRange << IndexExpr->IgnoreImpCasts()->getType();
6321
6322 // Only print a fixit for "str" + int, not for int + "str".
6323 if (IndexExpr == RHSExpr) {
6324 SourceLocation EndLoc = Self.PP.getLocForEndOfToken(RHSExpr->getLocEnd());
6325 Self.Diag(OpLoc, diag::note_string_plus_int_silence)
6326 << FixItHint::CreateInsertion(LHSExpr->getLocStart(), "&")
6327 << FixItHint::CreateReplacement(SourceRange(OpLoc), "[")
6328 << FixItHint::CreateInsertion(EndLoc, "]");
6329 } else
6330 Self.Diag(OpLoc, diag::note_string_plus_int_silence);
6331}
6332
Richard Trieud9f19342011-09-12 18:08:02 +00006333/// \brief Emit error when two pointers are incompatible.
Richard Trieudb44a6b2011-09-01 22:53:23 +00006334static void diagnosePointerIncompatibility(Sema &S, SourceLocation Loc,
Richard Trieudef75842011-09-06 21:13:51 +00006335 Expr *LHSExpr, Expr *RHSExpr) {
6336 assert(LHSExpr->getType()->isAnyPointerType());
6337 assert(RHSExpr->getType()->isAnyPointerType());
Richard Trieudb44a6b2011-09-01 22:53:23 +00006338 S.Diag(Loc, diag::err_typecheck_sub_ptr_compatible)
Richard Trieudef75842011-09-06 21:13:51 +00006339 << LHSExpr->getType() << RHSExpr->getType() << LHSExpr->getSourceRange()
6340 << RHSExpr->getSourceRange();
Richard Trieudb44a6b2011-09-01 22:53:23 +00006341}
6342
Chris Lattner7ef655a2010-01-12 21:23:57 +00006343QualType Sema::CheckAdditionOperands( // C99 6.5.6
Nico Weber1cb2d742012-03-02 22:01:22 +00006344 ExprResult &LHS, ExprResult &RHS, SourceLocation Loc, unsigned Opc,
6345 QualType* CompLHSTy) {
Richard Trieu481037f2011-09-16 00:53:10 +00006346 checkArithmeticNull(*this, LHS, RHS, Loc, /*isCompare=*/false);
6347
Richard Trieudef75842011-09-06 21:13:51 +00006348 if (LHS.get()->getType()->isVectorType() ||
6349 RHS.get()->getType()->isVectorType()) {
6350 QualType compType = CheckVectorOperands(LHS, RHS, Loc, CompLHSTy);
Eli Friedmanab3a8522009-03-28 01:22:36 +00006351 if (CompLHSTy) *CompLHSTy = compType;
6352 return compType;
6353 }
Steve Naroff49b45262007-07-13 16:58:59 +00006354
Richard Trieudef75842011-09-06 21:13:51 +00006355 QualType compType = UsualArithmeticConversions(LHS, RHS, CompLHSTy);
6356 if (LHS.isInvalid() || RHS.isInvalid())
John Wiegley429bb272011-04-08 18:41:53 +00006357 return QualType();
Eli Friedmand72d16e2008-05-18 18:08:51 +00006358
Nico Weber1cb2d742012-03-02 22:01:22 +00006359 // Diagnose "string literal" '+' int.
6360 if (Opc == BO_Add)
6361 diagnoseStringPlusInt(*this, Loc, LHS.get(), RHS.get());
6362
Reid Spencer5f016e22007-07-11 17:01:13 +00006363 // handle the common case first (both operands are arithmetic).
Eli Friedman860a3192012-06-16 02:19:17 +00006364 if (!compType.isNull() && compType->isArithmeticType()) {
Eli Friedmanab3a8522009-03-28 01:22:36 +00006365 if (CompLHSTy) *CompLHSTy = compType;
Steve Naroff9f5fa9b2007-08-24 19:07:16 +00006366 return compType;
Eli Friedmanab3a8522009-03-28 01:22:36 +00006367 }
Reid Spencer5f016e22007-07-11 17:01:13 +00006368
John McCall1503f0d2012-07-31 05:14:30 +00006369 // Type-checking. Ultimately the pointer's going to be in PExp;
6370 // note that we bias towards the LHS being the pointer.
6371 Expr *PExp = LHS.get(), *IExp = RHS.get();
Eli Friedmand72d16e2008-05-18 18:08:51 +00006372
John McCall1503f0d2012-07-31 05:14:30 +00006373 bool isObjCPointer;
6374 if (PExp->getType()->isPointerType()) {
6375 isObjCPointer = false;
6376 } else if (PExp->getType()->isObjCObjectPointerType()) {
6377 isObjCPointer = true;
6378 } else {
6379 std::swap(PExp, IExp);
6380 if (PExp->getType()->isPointerType()) {
6381 isObjCPointer = false;
6382 } else if (PExp->getType()->isObjCObjectPointerType()) {
6383 isObjCPointer = true;
6384 } else {
6385 return InvalidOperands(Loc, LHS, RHS);
6386 }
6387 }
6388 assert(PExp->getType()->isAnyPointerType());
Chandler Carruth13b21be2011-06-27 08:02:19 +00006389
Richard Trieu6eef9fb2011-09-12 18:37:54 +00006390 if (!IExp->getType()->isIntegerType())
6391 return InvalidOperands(Loc, LHS, RHS);
Mike Stump1eb44332009-09-09 15:08:12 +00006392
Richard Trieu6eef9fb2011-09-12 18:37:54 +00006393 if (!checkArithmeticOpPointerOperand(*this, Loc, PExp))
6394 return QualType();
Kaelyn Uhraind6c88652011-08-05 23:18:04 +00006395
John McCall1503f0d2012-07-31 05:14:30 +00006396 if (isObjCPointer && checkArithmeticOnObjCPointer(*this, Loc, PExp))
Richard Trieu6eef9fb2011-09-12 18:37:54 +00006397 return QualType();
6398
6399 // Check array bounds for pointer arithemtic
6400 CheckArrayAccess(PExp, IExp);
6401
6402 if (CompLHSTy) {
6403 QualType LHSTy = Context.isPromotableBitField(LHS.get());
6404 if (LHSTy.isNull()) {
6405 LHSTy = LHS.get()->getType();
6406 if (LHSTy->isPromotableIntegerType())
6407 LHSTy = Context.getPromotedIntegerType(LHSTy);
Eli Friedmand72d16e2008-05-18 18:08:51 +00006408 }
Richard Trieu6eef9fb2011-09-12 18:37:54 +00006409 *CompLHSTy = LHSTy;
Eli Friedmand72d16e2008-05-18 18:08:51 +00006410 }
6411
Richard Trieu6eef9fb2011-09-12 18:37:54 +00006412 return PExp->getType();
Reid Spencer5f016e22007-07-11 17:01:13 +00006413}
6414
Chris Lattnereca7be62008-04-07 05:30:13 +00006415// C99 6.5.6
Richard Trieudef75842011-09-06 21:13:51 +00006416QualType Sema::CheckSubtractionOperands(ExprResult &LHS, ExprResult &RHS,
Richard Trieu67e29332011-08-02 04:35:43 +00006417 SourceLocation Loc,
6418 QualType* CompLHSTy) {
Richard Trieu481037f2011-09-16 00:53:10 +00006419 checkArithmeticNull(*this, LHS, RHS, Loc, /*isCompare=*/false);
6420
Richard Trieudef75842011-09-06 21:13:51 +00006421 if (LHS.get()->getType()->isVectorType() ||
6422 RHS.get()->getType()->isVectorType()) {
6423 QualType compType = CheckVectorOperands(LHS, RHS, Loc, CompLHSTy);
Eli Friedmanab3a8522009-03-28 01:22:36 +00006424 if (CompLHSTy) *CompLHSTy = compType;
6425 return compType;
6426 }
Mike Stumpeed9cac2009-02-19 03:04:26 +00006427
Richard Trieudef75842011-09-06 21:13:51 +00006428 QualType compType = UsualArithmeticConversions(LHS, RHS, CompLHSTy);
6429 if (LHS.isInvalid() || RHS.isInvalid())
John Wiegley429bb272011-04-08 18:41:53 +00006430 return QualType();
Mike Stumpeed9cac2009-02-19 03:04:26 +00006431
Chris Lattner6e4ab612007-12-09 21:53:25 +00006432 // Enforce type constraints: C99 6.5.6p3.
Mike Stumpeed9cac2009-02-19 03:04:26 +00006433
Chris Lattner6e4ab612007-12-09 21:53:25 +00006434 // Handle the common case first (both operands are arithmetic).
Eli Friedman860a3192012-06-16 02:19:17 +00006435 if (!compType.isNull() && compType->isArithmeticType()) {
Eli Friedmanab3a8522009-03-28 01:22:36 +00006436 if (CompLHSTy) *CompLHSTy = compType;
Steve Naroff9f5fa9b2007-08-24 19:07:16 +00006437 return compType;
Eli Friedmanab3a8522009-03-28 01:22:36 +00006438 }
Mike Stump1eb44332009-09-09 15:08:12 +00006439
Chris Lattner6e4ab612007-12-09 21:53:25 +00006440 // Either ptr - int or ptr - ptr.
Richard Trieudef75842011-09-06 21:13:51 +00006441 if (LHS.get()->getType()->isAnyPointerType()) {
6442 QualType lpointee = LHS.get()->getType()->getPointeeType();
Mike Stumpeed9cac2009-02-19 03:04:26 +00006443
Chris Lattnerb5f15622009-04-24 23:50:08 +00006444 // Diagnose bad cases where we step over interface counts.
John McCall1503f0d2012-07-31 05:14:30 +00006445 if (LHS.get()->getType()->isObjCObjectPointerType() &&
6446 checkArithmeticOnObjCPointer(*this, Loc, LHS.get()))
Chris Lattnerb5f15622009-04-24 23:50:08 +00006447 return QualType();
Mike Stump1eb44332009-09-09 15:08:12 +00006448
Chris Lattner6e4ab612007-12-09 21:53:25 +00006449 // The result type of a pointer-int computation is the pointer type.
Richard Trieudef75842011-09-06 21:13:51 +00006450 if (RHS.get()->getType()->isIntegerType()) {
6451 if (!checkArithmeticOpPointerOperand(*this, Loc, LHS.get()))
Chandler Carruth13b21be2011-06-27 08:02:19 +00006452 return QualType();
Douglas Gregore7450f52009-03-24 19:52:54 +00006453
Kaelyn Uhraind6c88652011-08-05 23:18:04 +00006454 // Check array bounds for pointer arithemtic
Richard Smith25b009a2011-12-16 19:31:14 +00006455 CheckArrayAccess(LHS.get(), RHS.get(), /*ArraySubscriptExpr*/0,
6456 /*AllowOnePastEnd*/true, /*IndexNegated*/true);
Kaelyn Uhraind6c88652011-08-05 23:18:04 +00006457
Richard Trieudef75842011-09-06 21:13:51 +00006458 if (CompLHSTy) *CompLHSTy = LHS.get()->getType();
6459 return LHS.get()->getType();
Douglas Gregore7450f52009-03-24 19:52:54 +00006460 }
Mike Stumpeed9cac2009-02-19 03:04:26 +00006461
Chris Lattner6e4ab612007-12-09 21:53:25 +00006462 // Handle pointer-pointer subtractions.
Richard Trieu67e29332011-08-02 04:35:43 +00006463 if (const PointerType *RHSPTy
Richard Trieudef75842011-09-06 21:13:51 +00006464 = RHS.get()->getType()->getAs<PointerType>()) {
Eli Friedman8e54ad02008-02-08 01:19:44 +00006465 QualType rpointee = RHSPTy->getPointeeType();
Mike Stumpeed9cac2009-02-19 03:04:26 +00006466
David Blaikie4e4d0842012-03-11 07:00:24 +00006467 if (getLangOpts().CPlusPlus) {
Eli Friedman88d936b2009-05-16 13:54:38 +00006468 // Pointee types must be the same: C++ [expr.add]
6469 if (!Context.hasSameUnqualifiedType(lpointee, rpointee)) {
Richard Trieudef75842011-09-06 21:13:51 +00006470 diagnosePointerIncompatibility(*this, Loc, LHS.get(), RHS.get());
Eli Friedman88d936b2009-05-16 13:54:38 +00006471 }
6472 } else {
6473 // Pointee types must be compatible C99 6.5.6p3
6474 if (!Context.typesAreCompatible(
6475 Context.getCanonicalType(lpointee).getUnqualifiedType(),
6476 Context.getCanonicalType(rpointee).getUnqualifiedType())) {
Richard Trieudef75842011-09-06 21:13:51 +00006477 diagnosePointerIncompatibility(*this, Loc, LHS.get(), RHS.get());
Eli Friedman88d936b2009-05-16 13:54:38 +00006478 return QualType();
6479 }
Chris Lattner6e4ab612007-12-09 21:53:25 +00006480 }
Mike Stumpeed9cac2009-02-19 03:04:26 +00006481
Chandler Carruth13b21be2011-06-27 08:02:19 +00006482 if (!checkArithmeticBinOpPointerOperands(*this, Loc,
Richard Trieudef75842011-09-06 21:13:51 +00006483 LHS.get(), RHS.get()))
Chandler Carruth13b21be2011-06-27 08:02:19 +00006484 return QualType();
Eli Friedmanab3a8522009-03-28 01:22:36 +00006485
Richard Trieudef75842011-09-06 21:13:51 +00006486 if (CompLHSTy) *CompLHSTy = LHS.get()->getType();
Chris Lattner6e4ab612007-12-09 21:53:25 +00006487 return Context.getPointerDiffType();
6488 }
6489 }
Mike Stumpeed9cac2009-02-19 03:04:26 +00006490
Richard Trieudef75842011-09-06 21:13:51 +00006491 return InvalidOperands(Loc, LHS, RHS);
Reid Spencer5f016e22007-07-11 17:01:13 +00006492}
6493
Douglas Gregor1274ccd2010-10-08 23:50:27 +00006494static bool isScopedEnumerationType(QualType T) {
6495 if (const EnumType *ET = dyn_cast<EnumType>(T))
6496 return ET->getDecl()->isScoped();
6497 return false;
6498}
6499
Richard Trieu1c8cfbf2011-09-06 21:21:28 +00006500static void DiagnoseBadShiftValues(Sema& S, ExprResult &LHS, ExprResult &RHS,
Chandler Carruth21206d52011-02-23 23:34:11 +00006501 SourceLocation Loc, unsigned Opc,
Richard Trieu1c8cfbf2011-09-06 21:21:28 +00006502 QualType LHSType) {
Chandler Carruth21206d52011-02-23 23:34:11 +00006503 llvm::APSInt Right;
6504 // Check right/shifter operand
Richard Trieu1c8cfbf2011-09-06 21:21:28 +00006505 if (RHS.get()->isValueDependent() ||
6506 !RHS.get()->isIntegerConstantExpr(Right, S.Context))
Chandler Carruth21206d52011-02-23 23:34:11 +00006507 return;
6508
6509 if (Right.isNegative()) {
Richard Trieu1c8cfbf2011-09-06 21:21:28 +00006510 S.DiagRuntimeBehavior(Loc, RHS.get(),
Ted Kremenek082bf7a2011-03-01 18:09:31 +00006511 S.PDiag(diag::warn_shift_negative)
Richard Trieu1c8cfbf2011-09-06 21:21:28 +00006512 << RHS.get()->getSourceRange());
Chandler Carruth21206d52011-02-23 23:34:11 +00006513 return;
6514 }
6515 llvm::APInt LeftBits(Right.getBitWidth(),
Richard Trieu1c8cfbf2011-09-06 21:21:28 +00006516 S.Context.getTypeSize(LHS.get()->getType()));
Chandler Carruth21206d52011-02-23 23:34:11 +00006517 if (Right.uge(LeftBits)) {
Richard Trieu1c8cfbf2011-09-06 21:21:28 +00006518 S.DiagRuntimeBehavior(Loc, RHS.get(),
Ted Kremenek425a31e2011-03-01 19:13:22 +00006519 S.PDiag(diag::warn_shift_gt_typewidth)
Richard Trieu1c8cfbf2011-09-06 21:21:28 +00006520 << RHS.get()->getSourceRange());
Chandler Carruth21206d52011-02-23 23:34:11 +00006521 return;
6522 }
6523 if (Opc != BO_Shl)
6524 return;
6525
6526 // When left shifting an ICE which is signed, we can check for overflow which
6527 // according to C++ has undefined behavior ([expr.shift] 5.8/2). Unsigned
6528 // integers have defined behavior modulo one more than the maximum value
6529 // representable in the result type, so never warn for those.
6530 llvm::APSInt Left;
Richard Trieu1c8cfbf2011-09-06 21:21:28 +00006531 if (LHS.get()->isValueDependent() ||
6532 !LHS.get()->isIntegerConstantExpr(Left, S.Context) ||
6533 LHSType->hasUnsignedIntegerRepresentation())
Chandler Carruth21206d52011-02-23 23:34:11 +00006534 return;
6535 llvm::APInt ResultBits =
6536 static_cast<llvm::APInt&>(Right) + Left.getMinSignedBits();
6537 if (LeftBits.uge(ResultBits))
6538 return;
6539 llvm::APSInt Result = Left.extend(ResultBits.getLimitedValue());
6540 Result = Result.shl(Right);
6541
Ted Kremenekfa821382011-06-15 00:54:52 +00006542 // Print the bit representation of the signed integer as an unsigned
6543 // hexadecimal number.
Dylan Noblesmithf7ccbad2012-02-05 02:13:05 +00006544 SmallString<40> HexResult;
Ted Kremenekfa821382011-06-15 00:54:52 +00006545 Result.toString(HexResult, 16, /*Signed =*/false, /*Literal =*/true);
6546
Chandler Carruth21206d52011-02-23 23:34:11 +00006547 // If we are only missing a sign bit, this is less likely to result in actual
6548 // bugs -- if the result is cast back to an unsigned type, it will have the
6549 // expected value. Thus we place this behind a different warning that can be
6550 // turned off separately if needed.
6551 if (LeftBits == ResultBits - 1) {
Ted Kremenekfa821382011-06-15 00:54:52 +00006552 S.Diag(Loc, diag::warn_shift_result_sets_sign_bit)
Richard Trieu1c8cfbf2011-09-06 21:21:28 +00006553 << HexResult.str() << LHSType
6554 << LHS.get()->getSourceRange() << RHS.get()->getSourceRange();
Chandler Carruth21206d52011-02-23 23:34:11 +00006555 return;
6556 }
6557
6558 S.Diag(Loc, diag::warn_shift_result_gt_typewidth)
Richard Trieu1c8cfbf2011-09-06 21:21:28 +00006559 << HexResult.str() << Result.getMinSignedBits() << LHSType
6560 << Left.getBitWidth() << LHS.get()->getSourceRange()
6561 << RHS.get()->getSourceRange();
Chandler Carruth21206d52011-02-23 23:34:11 +00006562}
6563
Chris Lattnereca7be62008-04-07 05:30:13 +00006564// C99 6.5.7
Richard Trieu1c8cfbf2011-09-06 21:21:28 +00006565QualType Sema::CheckShiftOperands(ExprResult &LHS, ExprResult &RHS,
Richard Trieu67e29332011-08-02 04:35:43 +00006566 SourceLocation Loc, unsigned Opc,
Richard Trieuccd891a2011-09-09 01:45:06 +00006567 bool IsCompAssign) {
Richard Trieu481037f2011-09-16 00:53:10 +00006568 checkArithmeticNull(*this, LHS, RHS, Loc, /*isCompare=*/false);
6569
Chris Lattnerca5eede2007-12-12 05:47:28 +00006570 // C99 6.5.7p2: Each of the operands shall have integer type.
Richard Trieu1c8cfbf2011-09-06 21:21:28 +00006571 if (!LHS.get()->getType()->hasIntegerRepresentation() ||
6572 !RHS.get()->getType()->hasIntegerRepresentation())
6573 return InvalidOperands(Loc, LHS, RHS);
Mike Stumpeed9cac2009-02-19 03:04:26 +00006574
Douglas Gregor1274ccd2010-10-08 23:50:27 +00006575 // C++0x: Don't allow scoped enums. FIXME: Use something better than
6576 // hasIntegerRepresentation() above instead of this.
Richard Trieu1c8cfbf2011-09-06 21:21:28 +00006577 if (isScopedEnumerationType(LHS.get()->getType()) ||
6578 isScopedEnumerationType(RHS.get()->getType())) {
6579 return InvalidOperands(Loc, LHS, RHS);
Douglas Gregor1274ccd2010-10-08 23:50:27 +00006580 }
6581
Nate Begeman2207d792009-10-25 02:26:48 +00006582 // Vector shifts promote their scalar inputs to vector type.
Richard Trieu1c8cfbf2011-09-06 21:21:28 +00006583 if (LHS.get()->getType()->isVectorType() ||
6584 RHS.get()->getType()->isVectorType())
Richard Trieuccd891a2011-09-09 01:45:06 +00006585 return CheckVectorOperands(LHS, RHS, Loc, IsCompAssign);
Nate Begeman2207d792009-10-25 02:26:48 +00006586
Chris Lattnerca5eede2007-12-12 05:47:28 +00006587 // Shifts don't perform usual arithmetic conversions, they just do integer
6588 // promotions on each operand. C99 6.5.7p3
Eli Friedmanab3a8522009-03-28 01:22:36 +00006589
John McCall1bc80af2010-12-16 19:28:59 +00006590 // For the LHS, do usual unary conversions, but then reset them away
6591 // if this is a compound assignment.
Richard Trieu1c8cfbf2011-09-06 21:21:28 +00006592 ExprResult OldLHS = LHS;
6593 LHS = UsualUnaryConversions(LHS.take());
6594 if (LHS.isInvalid())
John Wiegley429bb272011-04-08 18:41:53 +00006595 return QualType();
Richard Trieu1c8cfbf2011-09-06 21:21:28 +00006596 QualType LHSType = LHS.get()->getType();
Richard Trieuccd891a2011-09-09 01:45:06 +00006597 if (IsCompAssign) LHS = OldLHS;
John McCall1bc80af2010-12-16 19:28:59 +00006598
6599 // The RHS is simpler.
Richard Trieu1c8cfbf2011-09-06 21:21:28 +00006600 RHS = UsualUnaryConversions(RHS.take());
6601 if (RHS.isInvalid())
John Wiegley429bb272011-04-08 18:41:53 +00006602 return QualType();
Mike Stumpeed9cac2009-02-19 03:04:26 +00006603
Ryan Flynnd0439682009-08-07 16:20:20 +00006604 // Sanity-check shift operands
Richard Trieu1c8cfbf2011-09-06 21:21:28 +00006605 DiagnoseBadShiftValues(*this, LHS, RHS, Loc, Opc, LHSType);
Ryan Flynnd0439682009-08-07 16:20:20 +00006606
Chris Lattnerca5eede2007-12-12 05:47:28 +00006607 // "The type of the result is that of the promoted left operand."
Richard Trieu1c8cfbf2011-09-06 21:21:28 +00006608 return LHSType;
Reid Spencer5f016e22007-07-11 17:01:13 +00006609}
6610
Chandler Carruth99919472010-07-10 12:30:03 +00006611static bool IsWithinTemplateSpecialization(Decl *D) {
6612 if (DeclContext *DC = D->getDeclContext()) {
6613 if (isa<ClassTemplateSpecializationDecl>(DC))
6614 return true;
6615 if (FunctionDecl *FD = dyn_cast<FunctionDecl>(DC))
6616 return FD->isFunctionTemplateSpecialization();
6617 }
6618 return false;
6619}
6620
Richard Trieue648ac32011-09-02 03:48:46 +00006621/// If two different enums are compared, raise a warning.
Richard Trieuba261492011-09-06 21:27:33 +00006622static void checkEnumComparison(Sema &S, SourceLocation Loc, ExprResult &LHS,
6623 ExprResult &RHS) {
6624 QualType LHSStrippedType = LHS.get()->IgnoreParenImpCasts()->getType();
6625 QualType RHSStrippedType = RHS.get()->IgnoreParenImpCasts()->getType();
Richard Trieue648ac32011-09-02 03:48:46 +00006626
6627 const EnumType *LHSEnumType = LHSStrippedType->getAs<EnumType>();
6628 if (!LHSEnumType)
6629 return;
6630 const EnumType *RHSEnumType = RHSStrippedType->getAs<EnumType>();
6631 if (!RHSEnumType)
6632 return;
6633
6634 // Ignore anonymous enums.
6635 if (!LHSEnumType->getDecl()->getIdentifier())
6636 return;
6637 if (!RHSEnumType->getDecl()->getIdentifier())
6638 return;
6639
6640 if (S.Context.hasSameUnqualifiedType(LHSStrippedType, RHSStrippedType))
6641 return;
6642
6643 S.Diag(Loc, diag::warn_comparison_of_mixed_enum_types)
6644 << LHSStrippedType << RHSStrippedType
Richard Trieuba261492011-09-06 21:27:33 +00006645 << LHS.get()->getSourceRange() << RHS.get()->getSourceRange();
Richard Trieue648ac32011-09-02 03:48:46 +00006646}
6647
Richard Trieu7be1be02011-09-02 02:55:45 +00006648/// \brief Diagnose bad pointer comparisons.
6649static void diagnoseDistinctPointerComparison(Sema &S, SourceLocation Loc,
Richard Trieuba261492011-09-06 21:27:33 +00006650 ExprResult &LHS, ExprResult &RHS,
Richard Trieuccd891a2011-09-09 01:45:06 +00006651 bool IsError) {
6652 S.Diag(Loc, IsError ? diag::err_typecheck_comparison_of_distinct_pointers
Richard Trieu7be1be02011-09-02 02:55:45 +00006653 : diag::ext_typecheck_comparison_of_distinct_pointers)
Richard Trieuba261492011-09-06 21:27:33 +00006654 << LHS.get()->getType() << RHS.get()->getType()
6655 << LHS.get()->getSourceRange() << RHS.get()->getSourceRange();
Richard Trieu7be1be02011-09-02 02:55:45 +00006656}
6657
6658/// \brief Returns false if the pointers are converted to a composite type,
6659/// true otherwise.
6660static bool convertPointersToCompositeType(Sema &S, SourceLocation Loc,
Richard Trieuba261492011-09-06 21:27:33 +00006661 ExprResult &LHS, ExprResult &RHS) {
Richard Trieu7be1be02011-09-02 02:55:45 +00006662 // C++ [expr.rel]p2:
6663 // [...] Pointer conversions (4.10) and qualification
6664 // conversions (4.4) are performed on pointer operands (or on
6665 // a pointer operand and a null pointer constant) to bring
6666 // them to their composite pointer type. [...]
6667 //
6668 // C++ [expr.eq]p1 uses the same notion for (in)equality
6669 // comparisons of pointers.
6670
6671 // C++ [expr.eq]p2:
6672 // In addition, pointers to members can be compared, or a pointer to
6673 // member and a null pointer constant. Pointer to member conversions
6674 // (4.11) and qualification conversions (4.4) are performed to bring
6675 // them to a common type. If one operand is a null pointer constant,
6676 // the common type is the type of the other operand. Otherwise, the
6677 // common type is a pointer to member type similar (4.4) to the type
6678 // of one of the operands, with a cv-qualification signature (4.4)
6679 // that is the union of the cv-qualification signatures of the operand
6680 // types.
6681
Richard Trieuba261492011-09-06 21:27:33 +00006682 QualType LHSType = LHS.get()->getType();
6683 QualType RHSType = RHS.get()->getType();
6684 assert((LHSType->isPointerType() && RHSType->isPointerType()) ||
6685 (LHSType->isMemberPointerType() && RHSType->isMemberPointerType()));
Richard Trieu7be1be02011-09-02 02:55:45 +00006686
6687 bool NonStandardCompositeType = false;
Richard Trieu43dff1b2011-09-02 21:44:27 +00006688 bool *BoolPtr = S.isSFINAEContext() ? 0 : &NonStandardCompositeType;
Richard Trieuba261492011-09-06 21:27:33 +00006689 QualType T = S.FindCompositePointerType(Loc, LHS, RHS, BoolPtr);
Richard Trieu7be1be02011-09-02 02:55:45 +00006690 if (T.isNull()) {
Richard Trieuba261492011-09-06 21:27:33 +00006691 diagnoseDistinctPointerComparison(S, Loc, LHS, RHS, /*isError*/true);
Richard Trieu7be1be02011-09-02 02:55:45 +00006692 return true;
6693 }
6694
6695 if (NonStandardCompositeType)
6696 S.Diag(Loc, diag::ext_typecheck_comparison_of_distinct_pointers_nonstandard)
Richard Trieuba261492011-09-06 21:27:33 +00006697 << LHSType << RHSType << T << LHS.get()->getSourceRange()
6698 << RHS.get()->getSourceRange();
Richard Trieu7be1be02011-09-02 02:55:45 +00006699
Richard Trieuba261492011-09-06 21:27:33 +00006700 LHS = S.ImpCastExprToType(LHS.take(), T, CK_BitCast);
6701 RHS = S.ImpCastExprToType(RHS.take(), T, CK_BitCast);
Richard Trieu7be1be02011-09-02 02:55:45 +00006702 return false;
6703}
6704
6705static void diagnoseFunctionPointerToVoidComparison(Sema &S, SourceLocation Loc,
Richard Trieuba261492011-09-06 21:27:33 +00006706 ExprResult &LHS,
6707 ExprResult &RHS,
Richard Trieuccd891a2011-09-09 01:45:06 +00006708 bool IsError) {
6709 S.Diag(Loc, IsError ? diag::err_typecheck_comparison_of_fptr_to_void
6710 : diag::ext_typecheck_comparison_of_fptr_to_void)
Richard Trieuba261492011-09-06 21:27:33 +00006711 << LHS.get()->getType() << RHS.get()->getType()
6712 << LHS.get()->getSourceRange() << RHS.get()->getSourceRange();
Richard Trieu7be1be02011-09-02 02:55:45 +00006713}
6714
Jordan Rose9f63a452012-06-08 21:14:25 +00006715static bool isObjCObjectLiteral(ExprResult &E) {
6716 switch (E.get()->getStmtClass()) {
6717 case Stmt::ObjCArrayLiteralClass:
6718 case Stmt::ObjCDictionaryLiteralClass:
6719 case Stmt::ObjCStringLiteralClass:
6720 case Stmt::ObjCBoxedExprClass:
6721 return true;
6722 default:
6723 // Note that ObjCBoolLiteral is NOT an object literal!
6724 return false;
6725 }
6726}
6727
Jordan Rose8d872ca2012-07-17 17:46:40 +00006728static bool hasIsEqualMethod(Sema &S, const Expr *LHS, const Expr *RHS) {
6729 // Get the LHS object's interface type.
6730 QualType Type = LHS->getType();
6731 QualType InterfaceType;
6732 if (const ObjCObjectPointerType *PTy = Type->getAs<ObjCObjectPointerType>()) {
6733 InterfaceType = PTy->getPointeeType();
6734 if (const ObjCObjectType *iQFaceTy =
6735 InterfaceType->getAsObjCQualifiedInterfaceType())
6736 InterfaceType = iQFaceTy->getBaseType();
6737 } else {
6738 // If this is not actually an Objective-C object, bail out.
6739 return false;
6740 }
6741
6742 // If the RHS isn't an Objective-C object, bail out.
6743 if (!RHS->getType()->isObjCObjectPointerType())
6744 return false;
6745
6746 // Try to find the -isEqual: method.
6747 Selector IsEqualSel = S.NSAPIObj->getIsEqualSelector();
6748 ObjCMethodDecl *Method = S.LookupMethodInObjectType(IsEqualSel,
6749 InterfaceType,
6750 /*instance=*/true);
6751 if (!Method) {
6752 if (Type->isObjCIdType()) {
6753 // For 'id', just check the global pool.
6754 Method = S.LookupInstanceMethodInGlobalPool(IsEqualSel, SourceRange(),
6755 /*receiverId=*/true,
6756 /*warn=*/false);
6757 } else {
6758 // Check protocols.
6759 Method = S.LookupMethodInQualifiedType(IsEqualSel,
6760 cast<ObjCObjectPointerType>(Type),
6761 /*instance=*/true);
6762 }
6763 }
6764
6765 if (!Method)
6766 return false;
6767
6768 QualType T = Method->param_begin()[0]->getType();
6769 if (!T->isObjCObjectPointerType())
6770 return false;
6771
6772 QualType R = Method->getResultType();
6773 if (!R->isScalarType())
6774 return false;
6775
6776 return true;
6777}
6778
6779static void diagnoseObjCLiteralComparison(Sema &S, SourceLocation Loc,
6780 ExprResult &LHS, ExprResult &RHS,
6781 BinaryOperator::Opcode Opc){
Jordan Rosed5209ae2012-07-17 17:46:48 +00006782 Expr *Literal;
6783 Expr *Other;
6784 if (isObjCObjectLiteral(LHS)) {
6785 Literal = LHS.get();
6786 Other = RHS.get();
6787 } else {
6788 Literal = RHS.get();
6789 Other = LHS.get();
6790 }
6791
6792 // Don't warn on comparisons against nil.
6793 Other = Other->IgnoreParenCasts();
6794 if (Other->isNullPointerConstant(S.getASTContext(),
6795 Expr::NPC_ValueDependentIsNotNull))
6796 return;
Jordan Rose9f63a452012-06-08 21:14:25 +00006797
Jordan Roseeec207f2012-07-17 17:46:44 +00006798 // This should be kept in sync with warn_objc_literal_comparison.
Jordan Rosed5209ae2012-07-17 17:46:48 +00006799 // LK_String should always be last, since it has its own warning flag.
Jordan Roseeec207f2012-07-17 17:46:44 +00006800 enum {
6801 LK_Array,
6802 LK_Dictionary,
6803 LK_Numeric,
6804 LK_Boxed,
6805 LK_String
6806 } LiteralKind;
6807
Jordan Rose9f63a452012-06-08 21:14:25 +00006808 switch (Literal->getStmtClass()) {
6809 case Stmt::ObjCStringLiteralClass:
6810 // "string literal"
Jordan Roseeec207f2012-07-17 17:46:44 +00006811 LiteralKind = LK_String;
Jordan Rose9f63a452012-06-08 21:14:25 +00006812 break;
6813 case Stmt::ObjCArrayLiteralClass:
6814 // "array literal"
Jordan Roseeec207f2012-07-17 17:46:44 +00006815 LiteralKind = LK_Array;
Jordan Rose9f63a452012-06-08 21:14:25 +00006816 break;
6817 case Stmt::ObjCDictionaryLiteralClass:
6818 // "dictionary literal"
Jordan Roseeec207f2012-07-17 17:46:44 +00006819 LiteralKind = LK_Dictionary;
Jordan Rose9f63a452012-06-08 21:14:25 +00006820 break;
6821 case Stmt::ObjCBoxedExprClass: {
6822 Expr *Inner = cast<ObjCBoxedExpr>(Literal)->getSubExpr();
6823 switch (Inner->getStmtClass()) {
6824 case Stmt::IntegerLiteralClass:
6825 case Stmt::FloatingLiteralClass:
6826 case Stmt::CharacterLiteralClass:
6827 case Stmt::ObjCBoolLiteralExprClass:
6828 case Stmt::CXXBoolLiteralExprClass:
6829 // "numeric literal"
Jordan Roseeec207f2012-07-17 17:46:44 +00006830 LiteralKind = LK_Numeric;
Jordan Rose9f63a452012-06-08 21:14:25 +00006831 break;
6832 case Stmt::ImplicitCastExprClass: {
6833 CastKind CK = cast<CastExpr>(Inner)->getCastKind();
6834 // Boolean literals can be represented by implicit casts.
6835 if (CK == CK_IntegralToBoolean || CK == CK_IntegralCast) {
Jordan Roseeec207f2012-07-17 17:46:44 +00006836 LiteralKind = LK_Numeric;
Jordan Rose9f63a452012-06-08 21:14:25 +00006837 break;
6838 }
6839 // FALLTHROUGH
6840 }
6841 default:
6842 // "boxed expression"
Jordan Roseeec207f2012-07-17 17:46:44 +00006843 LiteralKind = LK_Boxed;
Jordan Rose9f63a452012-06-08 21:14:25 +00006844 break;
6845 }
6846 break;
6847 }
6848 default:
6849 llvm_unreachable("Unknown Objective-C object literal kind");
6850 }
6851
Jordan Roseeec207f2012-07-17 17:46:44 +00006852 if (LiteralKind == LK_String)
6853 S.Diag(Loc, diag::warn_objc_string_literal_comparison)
6854 << Literal->getSourceRange();
6855 else
6856 S.Diag(Loc, diag::warn_objc_literal_comparison)
6857 << LiteralKind << Literal->getSourceRange();
Jordan Rose9f63a452012-06-08 21:14:25 +00006858
Jordan Rose8d872ca2012-07-17 17:46:40 +00006859 if (BinaryOperator::isEqualityOp(Opc) &&
6860 hasIsEqualMethod(S, LHS.get(), RHS.get())) {
6861 SourceLocation Start = LHS.get()->getLocStart();
6862 SourceLocation End = S.PP.getLocForEndOfToken(RHS.get()->getLocEnd());
6863 SourceRange OpRange(Loc, S.PP.getLocForEndOfToken(Loc));
Jordan Rose6deae7c2012-07-09 16:54:44 +00006864
Jordan Rose8d872ca2012-07-17 17:46:40 +00006865 S.Diag(Loc, diag::note_objc_literal_comparison_isequal)
6866 << FixItHint::CreateInsertion(Start, Opc == BO_EQ ? "[" : "![")
6867 << FixItHint::CreateReplacement(OpRange, "isEqual:")
6868 << FixItHint::CreateInsertion(End, "]");
Jordan Rose9f63a452012-06-08 21:14:25 +00006869 }
Jordan Rose9f63a452012-06-08 21:14:25 +00006870}
6871
Douglas Gregor0c6db942009-05-04 06:07:12 +00006872// C99 6.5.8, C++ [expr.rel]
Richard Trieuf1775fb2011-09-06 21:43:51 +00006873QualType Sema::CheckCompareOperands(ExprResult &LHS, ExprResult &RHS,
Richard Trieu67e29332011-08-02 04:35:43 +00006874 SourceLocation Loc, unsigned OpaqueOpc,
Richard Trieuccd891a2011-09-09 01:45:06 +00006875 bool IsRelational) {
Richard Trieu481037f2011-09-16 00:53:10 +00006876 checkArithmeticNull(*this, LHS, RHS, Loc, /*isCompare=*/true);
6877
John McCall2de56d12010-08-25 11:45:40 +00006878 BinaryOperatorKind Opc = (BinaryOperatorKind) OpaqueOpc;
Douglas Gregora86b8322009-04-06 18:45:53 +00006879
Chris Lattner02dd4b12009-12-05 05:40:13 +00006880 // Handle vector comparisons separately.
Richard Trieuf1775fb2011-09-06 21:43:51 +00006881 if (LHS.get()->getType()->isVectorType() ||
6882 RHS.get()->getType()->isVectorType())
Richard Trieuccd891a2011-09-09 01:45:06 +00006883 return CheckVectorCompareOperands(LHS, RHS, Loc, IsRelational);
Mike Stumpeed9cac2009-02-19 03:04:26 +00006884
Richard Trieuf1775fb2011-09-06 21:43:51 +00006885 QualType LHSType = LHS.get()->getType();
6886 QualType RHSType = RHS.get()->getType();
Benjamin Kramerfec09592011-09-03 08:46:20 +00006887
Richard Trieuf1775fb2011-09-06 21:43:51 +00006888 Expr *LHSStripped = LHS.get()->IgnoreParenImpCasts();
6889 Expr *RHSStripped = RHS.get()->IgnoreParenImpCasts();
Chandler Carruth543cb652011-02-17 08:37:06 +00006890
Richard Trieuf1775fb2011-09-06 21:43:51 +00006891 checkEnumComparison(*this, Loc, LHS, RHS);
Chandler Carruth543cb652011-02-17 08:37:06 +00006892
Richard Trieuf1775fb2011-09-06 21:43:51 +00006893 if (!LHSType->hasFloatingRepresentation() &&
Richard Trieuccd891a2011-09-09 01:45:06 +00006894 !(LHSType->isBlockPointerType() && IsRelational) &&
Richard Trieuf1775fb2011-09-06 21:43:51 +00006895 !LHS.get()->getLocStart().isMacroID() &&
6896 !RHS.get()->getLocStart().isMacroID()) {
Chris Lattner55660a72009-03-08 19:39:53 +00006897 // For non-floating point types, check for self-comparisons of the form
6898 // x == x, x != x, x < x, etc. These always evaluate to a constant, and
6899 // often indicate logic errors in the program.
Chandler Carruth64d092c2010-07-12 06:23:38 +00006900 //
6901 // NOTE: Don't warn about comparison expressions resulting from macro
6902 // expansion. Also don't warn about comparisons which are only self
6903 // comparisons within a template specialization. The warnings should catch
6904 // obvious cases in the definition of the template anyways. The idea is to
6905 // warn when the typed comparison operator will always evaluate to the same
6906 // result.
Chandler Carruth99919472010-07-10 12:30:03 +00006907 if (DeclRefExpr* DRL = dyn_cast<DeclRefExpr>(LHSStripped)) {
Douglas Gregord64fdd02010-06-08 19:50:34 +00006908 if (DeclRefExpr* DRR = dyn_cast<DeclRefExpr>(RHSStripped)) {
Ted Kremenekfbcb0eb2010-09-16 00:03:01 +00006909 if (DRL->getDecl() == DRR->getDecl() &&
Chandler Carruth99919472010-07-10 12:30:03 +00006910 !IsWithinTemplateSpecialization(DRL->getDecl())) {
Ted Kremenek351ba912011-02-23 01:52:04 +00006911 DiagRuntimeBehavior(Loc, 0, PDiag(diag::warn_comparison_always)
Douglas Gregord64fdd02010-06-08 19:50:34 +00006912 << 0 // self-
John McCall2de56d12010-08-25 11:45:40 +00006913 << (Opc == BO_EQ
6914 || Opc == BO_LE
6915 || Opc == BO_GE));
Richard Trieuf1775fb2011-09-06 21:43:51 +00006916 } else if (LHSType->isArrayType() && RHSType->isArrayType() &&
Douglas Gregord64fdd02010-06-08 19:50:34 +00006917 !DRL->getDecl()->getType()->isReferenceType() &&
6918 !DRR->getDecl()->getType()->isReferenceType()) {
6919 // what is it always going to eval to?
6920 char always_evals_to;
6921 switch(Opc) {
John McCall2de56d12010-08-25 11:45:40 +00006922 case BO_EQ: // e.g. array1 == array2
Douglas Gregord64fdd02010-06-08 19:50:34 +00006923 always_evals_to = 0; // false
6924 break;
John McCall2de56d12010-08-25 11:45:40 +00006925 case BO_NE: // e.g. array1 != array2
Douglas Gregord64fdd02010-06-08 19:50:34 +00006926 always_evals_to = 1; // true
6927 break;
6928 default:
6929 // best we can say is 'a constant'
6930 always_evals_to = 2; // e.g. array1 <= array2
6931 break;
6932 }
Ted Kremenek351ba912011-02-23 01:52:04 +00006933 DiagRuntimeBehavior(Loc, 0, PDiag(diag::warn_comparison_always)
Douglas Gregord64fdd02010-06-08 19:50:34 +00006934 << 1 // array
6935 << always_evals_to);
6936 }
6937 }
Chandler Carruth99919472010-07-10 12:30:03 +00006938 }
Mike Stump1eb44332009-09-09 15:08:12 +00006939
Chris Lattner55660a72009-03-08 19:39:53 +00006940 if (isa<CastExpr>(LHSStripped))
6941 LHSStripped = LHSStripped->IgnoreParenCasts();
6942 if (isa<CastExpr>(RHSStripped))
6943 RHSStripped = RHSStripped->IgnoreParenCasts();
Mike Stump1eb44332009-09-09 15:08:12 +00006944
Chris Lattner55660a72009-03-08 19:39:53 +00006945 // Warn about comparisons against a string constant (unless the other
6946 // operand is null), the user probably wants strcmp.
Douglas Gregora86b8322009-04-06 18:45:53 +00006947 Expr *literalString = 0;
6948 Expr *literalStringStripped = 0;
Chris Lattner55660a72009-03-08 19:39:53 +00006949 if ((isa<StringLiteral>(LHSStripped) || isa<ObjCEncodeExpr>(LHSStripped)) &&
Kovarththanan Rajaratnam19357542010-03-13 10:17:05 +00006950 !RHSStripped->isNullPointerConstant(Context,
Douglas Gregorce940492009-09-25 04:25:58 +00006951 Expr::NPC_ValueDependentIsNull)) {
Richard Trieuf1775fb2011-09-06 21:43:51 +00006952 literalString = LHS.get();
Douglas Gregora86b8322009-04-06 18:45:53 +00006953 literalStringStripped = LHSStripped;
Mike Stumpac5fc7c2009-08-04 21:02:39 +00006954 } else if ((isa<StringLiteral>(RHSStripped) ||
6955 isa<ObjCEncodeExpr>(RHSStripped)) &&
Kovarththanan Rajaratnam19357542010-03-13 10:17:05 +00006956 !LHSStripped->isNullPointerConstant(Context,
Douglas Gregorce940492009-09-25 04:25:58 +00006957 Expr::NPC_ValueDependentIsNull)) {
Richard Trieuf1775fb2011-09-06 21:43:51 +00006958 literalString = RHS.get();
Douglas Gregora86b8322009-04-06 18:45:53 +00006959 literalStringStripped = RHSStripped;
6960 }
6961
6962 if (literalString) {
6963 std::string resultComparison;
6964 switch (Opc) {
John McCall2de56d12010-08-25 11:45:40 +00006965 case BO_LT: resultComparison = ") < 0"; break;
6966 case BO_GT: resultComparison = ") > 0"; break;
6967 case BO_LE: resultComparison = ") <= 0"; break;
6968 case BO_GE: resultComparison = ") >= 0"; break;
6969 case BO_EQ: resultComparison = ") == 0"; break;
6970 case BO_NE: resultComparison = ") != 0"; break;
David Blaikieb219cfc2011-09-23 05:06:16 +00006971 default: llvm_unreachable("Invalid comparison operator");
Douglas Gregora86b8322009-04-06 18:45:53 +00006972 }
Kovarththanan Rajaratnam19357542010-03-13 10:17:05 +00006973
Ted Kremenek351ba912011-02-23 01:52:04 +00006974 DiagRuntimeBehavior(Loc, 0,
Douglas Gregord1e4d9b2010-01-12 23:18:54 +00006975 PDiag(diag::warn_stringcompare)
6976 << isa<ObjCEncodeExpr>(literalStringStripped)
Ted Kremenek03a4bee2010-04-09 20:26:53 +00006977 << literalString->getSourceRange());
Douglas Gregora86b8322009-04-06 18:45:53 +00006978 }
Ted Kremenek3ca0bf22007-10-29 16:58:49 +00006979 }
Mike Stumpeed9cac2009-02-19 03:04:26 +00006980
Douglas Gregord64fdd02010-06-08 19:50:34 +00006981 // C99 6.5.8p3 / C99 6.5.9p4
Richard Trieuf1775fb2011-09-06 21:43:51 +00006982 if (LHS.get()->getType()->isArithmeticType() &&
6983 RHS.get()->getType()->isArithmeticType()) {
6984 UsualArithmeticConversions(LHS, RHS);
6985 if (LHS.isInvalid() || RHS.isInvalid())
John Wiegley429bb272011-04-08 18:41:53 +00006986 return QualType();
6987 }
Douglas Gregord64fdd02010-06-08 19:50:34 +00006988 else {
Richard Trieuf1775fb2011-09-06 21:43:51 +00006989 LHS = UsualUnaryConversions(LHS.take());
6990 if (LHS.isInvalid())
John Wiegley429bb272011-04-08 18:41:53 +00006991 return QualType();
6992
Richard Trieuf1775fb2011-09-06 21:43:51 +00006993 RHS = UsualUnaryConversions(RHS.take());
6994 if (RHS.isInvalid())
John Wiegley429bb272011-04-08 18:41:53 +00006995 return QualType();
Douglas Gregord64fdd02010-06-08 19:50:34 +00006996 }
6997
Richard Trieuf1775fb2011-09-06 21:43:51 +00006998 LHSType = LHS.get()->getType();
6999 RHSType = RHS.get()->getType();
Douglas Gregord64fdd02010-06-08 19:50:34 +00007000
Douglas Gregor447b69e2008-11-19 03:25:36 +00007001 // The result of comparisons is 'bool' in C++, 'int' in C.
Argyrios Kyrtzidis16f744b2011-02-18 20:55:15 +00007002 QualType ResultTy = Context.getLogicalOperationType();
Douglas Gregor447b69e2008-11-19 03:25:36 +00007003
Richard Trieuccd891a2011-09-09 01:45:06 +00007004 if (IsRelational) {
Richard Trieuf1775fb2011-09-06 21:43:51 +00007005 if (LHSType->isRealType() && RHSType->isRealType())
Douglas Gregor447b69e2008-11-19 03:25:36 +00007006 return ResultTy;
Chris Lattnera5937dd2007-08-26 01:18:55 +00007007 } else {
Ted Kremenek72cb1ae2007-10-29 17:13:39 +00007008 // Check for comparisons of floating point operands using != and ==.
Richard Trieuf1775fb2011-09-06 21:43:51 +00007009 if (LHSType->hasFloatingRepresentation())
7010 CheckFloatComparison(Loc, LHS.get(), RHS.get());
Mike Stumpeed9cac2009-02-19 03:04:26 +00007011
Richard Trieuf1775fb2011-09-06 21:43:51 +00007012 if (LHSType->isArithmeticType() && RHSType->isArithmeticType())
Douglas Gregor447b69e2008-11-19 03:25:36 +00007013 return ResultTy;
Chris Lattnera5937dd2007-08-26 01:18:55 +00007014 }
Mike Stumpeed9cac2009-02-19 03:04:26 +00007015
Richard Trieuf1775fb2011-09-06 21:43:51 +00007016 bool LHSIsNull = LHS.get()->isNullPointerConstant(Context,
Douglas Gregorce940492009-09-25 04:25:58 +00007017 Expr::NPC_ValueDependentIsNull);
Richard Trieuf1775fb2011-09-06 21:43:51 +00007018 bool RHSIsNull = RHS.get()->isNullPointerConstant(Context,
Douglas Gregorce940492009-09-25 04:25:58 +00007019 Expr::NPC_ValueDependentIsNull);
Mike Stumpeed9cac2009-02-19 03:04:26 +00007020
Douglas Gregor6e5122c2010-06-15 21:38:40 +00007021 // All of the following pointer-related warnings are GCC extensions, except
7022 // when handling null pointer constants.
Richard Trieuf1775fb2011-09-06 21:43:51 +00007023 if (LHSType->isPointerType() && RHSType->isPointerType()) { // C99 6.5.8p2
Chris Lattnerbc896f52008-04-03 05:07:25 +00007024 QualType LCanPointeeTy =
John McCall1d9b3b22011-09-09 05:25:32 +00007025 LHSType->castAs<PointerType>()->getPointeeType().getCanonicalType();
Chris Lattnerbc896f52008-04-03 05:07:25 +00007026 QualType RCanPointeeTy =
John McCall1d9b3b22011-09-09 05:25:32 +00007027 RHSType->castAs<PointerType>()->getPointeeType().getCanonicalType();
Mike Stumpeed9cac2009-02-19 03:04:26 +00007028
David Blaikie4e4d0842012-03-11 07:00:24 +00007029 if (getLangOpts().CPlusPlus) {
Eli Friedman3075e762009-08-23 00:27:47 +00007030 if (LCanPointeeTy == RCanPointeeTy)
7031 return ResultTy;
Richard Trieuccd891a2011-09-09 01:45:06 +00007032 if (!IsRelational &&
Fariborz Jahanian51874dd2009-12-21 18:19:17 +00007033 (LCanPointeeTy->isVoidType() || RCanPointeeTy->isVoidType())) {
7034 // Valid unless comparison between non-null pointer and function pointer
7035 // This is a gcc extension compatibility comparison.
Douglas Gregor6e5122c2010-06-15 21:38:40 +00007036 // In a SFINAE context, we treat this as a hard error to maintain
7037 // conformance with the C++ standard.
Fariborz Jahanian51874dd2009-12-21 18:19:17 +00007038 if ((LCanPointeeTy->isFunctionType() || RCanPointeeTy->isFunctionType())
7039 && !LHSIsNull && !RHSIsNull) {
Richard Trieu7be1be02011-09-02 02:55:45 +00007040 diagnoseFunctionPointerToVoidComparison(
Richard Trieuf1775fb2011-09-06 21:43:51 +00007041 *this, Loc, LHS, RHS, /*isError*/ isSFINAEContext());
Douglas Gregor6e5122c2010-06-15 21:38:40 +00007042
7043 if (isSFINAEContext())
7044 return QualType();
7045
Richard Trieuf1775fb2011-09-06 21:43:51 +00007046 RHS = ImpCastExprToType(RHS.take(), LHSType, CK_BitCast);
Fariborz Jahanian51874dd2009-12-21 18:19:17 +00007047 return ResultTy;
7048 }
7049 }
Anders Carlsson0c8209e2010-11-04 03:17:43 +00007050
Richard Trieuf1775fb2011-09-06 21:43:51 +00007051 if (convertPointersToCompositeType(*this, Loc, LHS, RHS))
Douglas Gregor0c6db942009-05-04 06:07:12 +00007052 return QualType();
Richard Trieu7be1be02011-09-02 02:55:45 +00007053 else
7054 return ResultTy;
Douglas Gregor0c6db942009-05-04 06:07:12 +00007055 }
Eli Friedman3075e762009-08-23 00:27:47 +00007056 // C99 6.5.9p2 and C99 6.5.8p2
7057 if (Context.typesAreCompatible(LCanPointeeTy.getUnqualifiedType(),
7058 RCanPointeeTy.getUnqualifiedType())) {
7059 // Valid unless a relational comparison of function pointers
Richard Trieuccd891a2011-09-09 01:45:06 +00007060 if (IsRelational && LCanPointeeTy->isFunctionType()) {
Eli Friedman3075e762009-08-23 00:27:47 +00007061 Diag(Loc, diag::ext_typecheck_ordered_comparison_of_function_pointers)
Richard Trieuf1775fb2011-09-06 21:43:51 +00007062 << LHSType << RHSType << LHS.get()->getSourceRange()
7063 << RHS.get()->getSourceRange();
Eli Friedman3075e762009-08-23 00:27:47 +00007064 }
Richard Trieuccd891a2011-09-09 01:45:06 +00007065 } else if (!IsRelational &&
Eli Friedman3075e762009-08-23 00:27:47 +00007066 (LCanPointeeTy->isVoidType() || RCanPointeeTy->isVoidType())) {
7067 // Valid unless comparison between non-null pointer and function pointer
7068 if ((LCanPointeeTy->isFunctionType() || RCanPointeeTy->isFunctionType())
Richard Trieu7be1be02011-09-02 02:55:45 +00007069 && !LHSIsNull && !RHSIsNull)
Richard Trieuf1775fb2011-09-06 21:43:51 +00007070 diagnoseFunctionPointerToVoidComparison(*this, Loc, LHS, RHS,
Richard Trieu7be1be02011-09-02 02:55:45 +00007071 /*isError*/false);
Eli Friedman3075e762009-08-23 00:27:47 +00007072 } else {
7073 // Invalid
Richard Trieuf1775fb2011-09-06 21:43:51 +00007074 diagnoseDistinctPointerComparison(*this, Loc, LHS, RHS, /*isError*/false);
Reid Spencer5f016e22007-07-11 17:01:13 +00007075 }
John McCall34d6f932011-03-11 04:25:25 +00007076 if (LCanPointeeTy != RCanPointeeTy) {
7077 if (LHSIsNull && !RHSIsNull)
Richard Trieuf1775fb2011-09-06 21:43:51 +00007078 LHS = ImpCastExprToType(LHS.take(), RHSType, CK_BitCast);
John McCall34d6f932011-03-11 04:25:25 +00007079 else
Richard Trieuf1775fb2011-09-06 21:43:51 +00007080 RHS = ImpCastExprToType(RHS.take(), LHSType, CK_BitCast);
John McCall34d6f932011-03-11 04:25:25 +00007081 }
Douglas Gregor447b69e2008-11-19 03:25:36 +00007082 return ResultTy;
Steve Naroffe77fd3c2007-08-16 21:48:38 +00007083 }
Mike Stump1eb44332009-09-09 15:08:12 +00007084
David Blaikie4e4d0842012-03-11 07:00:24 +00007085 if (getLangOpts().CPlusPlus) {
Anders Carlsson0c8209e2010-11-04 03:17:43 +00007086 // Comparison of nullptr_t with itself.
Richard Trieuf1775fb2011-09-06 21:43:51 +00007087 if (LHSType->isNullPtrType() && RHSType->isNullPtrType())
Anders Carlsson0c8209e2010-11-04 03:17:43 +00007088 return ResultTy;
7089
Mike Stump1eb44332009-09-09 15:08:12 +00007090 // Comparison of pointers with null pointer constants and equality
Douglas Gregor20b3e992009-08-24 17:42:35 +00007091 // comparisons of member pointers to null pointer constants.
Mike Stump1eb44332009-09-09 15:08:12 +00007092 if (RHSIsNull &&
Richard Trieuf1775fb2011-09-06 21:43:51 +00007093 ((LHSType->isAnyPointerType() || LHSType->isNullPtrType()) ||
Richard Trieuccd891a2011-09-09 01:45:06 +00007094 (!IsRelational &&
Richard Trieuf1775fb2011-09-06 21:43:51 +00007095 (LHSType->isMemberPointerType() || LHSType->isBlockPointerType())))) {
7096 RHS = ImpCastExprToType(RHS.take(), LHSType,
7097 LHSType->isMemberPointerType()
John McCall2de56d12010-08-25 11:45:40 +00007098 ? CK_NullToMemberPointer
John McCall404cd162010-11-13 01:35:44 +00007099 : CK_NullToPointer);
Sebastian Redl6e8ed162009-05-10 18:38:11 +00007100 return ResultTy;
7101 }
Douglas Gregor20b3e992009-08-24 17:42:35 +00007102 if (LHSIsNull &&
Richard Trieuf1775fb2011-09-06 21:43:51 +00007103 ((RHSType->isAnyPointerType() || RHSType->isNullPtrType()) ||
Richard Trieuccd891a2011-09-09 01:45:06 +00007104 (!IsRelational &&
Richard Trieuf1775fb2011-09-06 21:43:51 +00007105 (RHSType->isMemberPointerType() || RHSType->isBlockPointerType())))) {
7106 LHS = ImpCastExprToType(LHS.take(), RHSType,
7107 RHSType->isMemberPointerType()
John McCall2de56d12010-08-25 11:45:40 +00007108 ? CK_NullToMemberPointer
John McCall404cd162010-11-13 01:35:44 +00007109 : CK_NullToPointer);
Sebastian Redl6e8ed162009-05-10 18:38:11 +00007110 return ResultTy;
7111 }
Douglas Gregor20b3e992009-08-24 17:42:35 +00007112
7113 // Comparison of member pointers.
Richard Trieuccd891a2011-09-09 01:45:06 +00007114 if (!IsRelational &&
Richard Trieuf1775fb2011-09-06 21:43:51 +00007115 LHSType->isMemberPointerType() && RHSType->isMemberPointerType()) {
7116 if (convertPointersToCompositeType(*this, Loc, LHS, RHS))
Douglas Gregor20b3e992009-08-24 17:42:35 +00007117 return QualType();
Richard Trieu7be1be02011-09-02 02:55:45 +00007118 else
7119 return ResultTy;
Douglas Gregor20b3e992009-08-24 17:42:35 +00007120 }
Douglas Gregor90566c02011-03-01 17:16:20 +00007121
7122 // Handle scoped enumeration types specifically, since they don't promote
7123 // to integers.
Richard Trieuf1775fb2011-09-06 21:43:51 +00007124 if (LHS.get()->getType()->isEnumeralType() &&
7125 Context.hasSameUnqualifiedType(LHS.get()->getType(),
7126 RHS.get()->getType()))
Douglas Gregor90566c02011-03-01 17:16:20 +00007127 return ResultTy;
Sebastian Redl6e8ed162009-05-10 18:38:11 +00007128 }
Mike Stump1eb44332009-09-09 15:08:12 +00007129
Steve Naroff1c7d0672008-09-04 15:10:53 +00007130 // Handle block pointer types.
Richard Trieuccd891a2011-09-09 01:45:06 +00007131 if (!IsRelational && LHSType->isBlockPointerType() &&
Richard Trieuf1775fb2011-09-06 21:43:51 +00007132 RHSType->isBlockPointerType()) {
John McCall1d9b3b22011-09-09 05:25:32 +00007133 QualType lpointee = LHSType->castAs<BlockPointerType>()->getPointeeType();
7134 QualType rpointee = RHSType->castAs<BlockPointerType>()->getPointeeType();
Mike Stumpeed9cac2009-02-19 03:04:26 +00007135
Steve Naroff1c7d0672008-09-04 15:10:53 +00007136 if (!LHSIsNull && !RHSIsNull &&
Eli Friedman26784c12009-06-08 05:08:54 +00007137 !Context.typesAreCompatible(lpointee, rpointee)) {
Chris Lattnerc9c7c4e2008-11-18 22:52:51 +00007138 Diag(Loc, diag::err_typecheck_comparison_of_distinct_blocks)
Richard Trieuf1775fb2011-09-06 21:43:51 +00007139 << LHSType << RHSType << LHS.get()->getSourceRange()
7140 << RHS.get()->getSourceRange();
Steve Naroff1c7d0672008-09-04 15:10:53 +00007141 }
Richard Trieuf1775fb2011-09-06 21:43:51 +00007142 RHS = ImpCastExprToType(RHS.take(), LHSType, CK_BitCast);
Douglas Gregor447b69e2008-11-19 03:25:36 +00007143 return ResultTy;
Steve Naroff1c7d0672008-09-04 15:10:53 +00007144 }
John Wiegley429bb272011-04-08 18:41:53 +00007145
Steve Naroff59f53942008-09-28 01:11:11 +00007146 // Allow block pointers to be compared with null pointer constants.
Richard Trieuccd891a2011-09-09 01:45:06 +00007147 if (!IsRelational
Richard Trieuf1775fb2011-09-06 21:43:51 +00007148 && ((LHSType->isBlockPointerType() && RHSType->isPointerType())
7149 || (LHSType->isPointerType() && RHSType->isBlockPointerType()))) {
Steve Naroff59f53942008-09-28 01:11:11 +00007150 if (!LHSIsNull && !RHSIsNull) {
Richard Trieuf1775fb2011-09-06 21:43:51 +00007151 if (!((RHSType->isPointerType() && RHSType->castAs<PointerType>()
Mike Stumpdd3e1662009-05-07 03:14:14 +00007152 ->getPointeeType()->isVoidType())
Richard Trieuf1775fb2011-09-06 21:43:51 +00007153 || (LHSType->isPointerType() && LHSType->castAs<PointerType>()
Mike Stumpdd3e1662009-05-07 03:14:14 +00007154 ->getPointeeType()->isVoidType())))
7155 Diag(Loc, diag::err_typecheck_comparison_of_distinct_blocks)
Richard Trieuf1775fb2011-09-06 21:43:51 +00007156 << LHSType << RHSType << LHS.get()->getSourceRange()
7157 << RHS.get()->getSourceRange();
Steve Naroff59f53942008-09-28 01:11:11 +00007158 }
John McCall34d6f932011-03-11 04:25:25 +00007159 if (LHSIsNull && !RHSIsNull)
John McCall1d9b3b22011-09-09 05:25:32 +00007160 LHS = ImpCastExprToType(LHS.take(), RHSType,
7161 RHSType->isPointerType() ? CK_BitCast
7162 : CK_AnyPointerToBlockPointerCast);
John McCall34d6f932011-03-11 04:25:25 +00007163 else
John McCall1d9b3b22011-09-09 05:25:32 +00007164 RHS = ImpCastExprToType(RHS.take(), LHSType,
7165 LHSType->isPointerType() ? CK_BitCast
7166 : CK_AnyPointerToBlockPointerCast);
Douglas Gregor447b69e2008-11-19 03:25:36 +00007167 return ResultTy;
Steve Naroff59f53942008-09-28 01:11:11 +00007168 }
Steve Naroff1c7d0672008-09-04 15:10:53 +00007169
Richard Trieuf1775fb2011-09-06 21:43:51 +00007170 if (LHSType->isObjCObjectPointerType() ||
7171 RHSType->isObjCObjectPointerType()) {
7172 const PointerType *LPT = LHSType->getAs<PointerType>();
7173 const PointerType *RPT = RHSType->getAs<PointerType>();
John McCall34d6f932011-03-11 04:25:25 +00007174 if (LPT || RPT) {
7175 bool LPtrToVoid = LPT ? LPT->getPointeeType()->isVoidType() : false;
7176 bool RPtrToVoid = RPT ? RPT->getPointeeType()->isVoidType() : false;
Mike Stumpeed9cac2009-02-19 03:04:26 +00007177
Steve Naroffa8069f12008-11-17 19:49:16 +00007178 if (!LPtrToVoid && !RPtrToVoid &&
Richard Trieuf1775fb2011-09-06 21:43:51 +00007179 !Context.typesAreCompatible(LHSType, RHSType)) {
7180 diagnoseDistinctPointerComparison(*this, Loc, LHS, RHS,
Richard Trieu7be1be02011-09-02 02:55:45 +00007181 /*isError*/false);
Steve Naroffa5ad8632008-10-27 10:33:19 +00007182 }
John McCall34d6f932011-03-11 04:25:25 +00007183 if (LHSIsNull && !RHSIsNull)
John McCall1d9b3b22011-09-09 05:25:32 +00007184 LHS = ImpCastExprToType(LHS.take(), RHSType,
7185 RPT ? CK_BitCast :CK_CPointerToObjCPointerCast);
John McCall34d6f932011-03-11 04:25:25 +00007186 else
John McCall1d9b3b22011-09-09 05:25:32 +00007187 RHS = ImpCastExprToType(RHS.take(), LHSType,
7188 LPT ? CK_BitCast :CK_CPointerToObjCPointerCast);
Douglas Gregor447b69e2008-11-19 03:25:36 +00007189 return ResultTy;
Steve Naroff87f3b932008-10-20 18:19:10 +00007190 }
Richard Trieuf1775fb2011-09-06 21:43:51 +00007191 if (LHSType->isObjCObjectPointerType() &&
7192 RHSType->isObjCObjectPointerType()) {
7193 if (!Context.areComparableObjCPointerTypes(LHSType, RHSType))
7194 diagnoseDistinctPointerComparison(*this, Loc, LHS, RHS,
Richard Trieu7be1be02011-09-02 02:55:45 +00007195 /*isError*/false);
Jordan Rose9f63a452012-06-08 21:14:25 +00007196 if (isObjCObjectLiteral(LHS) || isObjCObjectLiteral(RHS))
Jordan Rose8d872ca2012-07-17 17:46:40 +00007197 diagnoseObjCLiteralComparison(*this, Loc, LHS, RHS, Opc);
Jordan Rose9f63a452012-06-08 21:14:25 +00007198
John McCall34d6f932011-03-11 04:25:25 +00007199 if (LHSIsNull && !RHSIsNull)
Richard Trieuf1775fb2011-09-06 21:43:51 +00007200 LHS = ImpCastExprToType(LHS.take(), RHSType, CK_BitCast);
John McCall34d6f932011-03-11 04:25:25 +00007201 else
Richard Trieuf1775fb2011-09-06 21:43:51 +00007202 RHS = ImpCastExprToType(RHS.take(), LHSType, CK_BitCast);
Douglas Gregor447b69e2008-11-19 03:25:36 +00007203 return ResultTy;
Steve Naroff20373222008-06-03 14:04:54 +00007204 }
Fariborz Jahanian7359f042007-12-20 01:06:58 +00007205 }
Richard Trieuf1775fb2011-09-06 21:43:51 +00007206 if ((LHSType->isAnyPointerType() && RHSType->isIntegerType()) ||
7207 (LHSType->isIntegerType() && RHSType->isAnyPointerType())) {
Chris Lattner06c0f5b2009-08-23 00:03:44 +00007208 unsigned DiagID = 0;
Douglas Gregor6e5122c2010-06-15 21:38:40 +00007209 bool isError = false;
Richard Trieuf1775fb2011-09-06 21:43:51 +00007210 if ((LHSIsNull && LHSType->isIntegerType()) ||
7211 (RHSIsNull && RHSType->isIntegerType())) {
David Blaikie4e4d0842012-03-11 07:00:24 +00007212 if (IsRelational && !getLangOpts().CPlusPlus)
Chris Lattner06c0f5b2009-08-23 00:03:44 +00007213 DiagID = diag::ext_typecheck_ordered_comparison_of_pointer_and_zero;
David Blaikie4e4d0842012-03-11 07:00:24 +00007214 } else if (IsRelational && !getLangOpts().CPlusPlus)
Chris Lattner06c0f5b2009-08-23 00:03:44 +00007215 DiagID = diag::ext_typecheck_ordered_comparison_of_pointer_integer;
David Blaikie4e4d0842012-03-11 07:00:24 +00007216 else if (getLangOpts().CPlusPlus) {
Douglas Gregor6e5122c2010-06-15 21:38:40 +00007217 DiagID = diag::err_typecheck_comparison_of_pointer_integer;
7218 isError = true;
7219 } else
Chris Lattner06c0f5b2009-08-23 00:03:44 +00007220 DiagID = diag::ext_typecheck_comparison_of_pointer_integer;
Mike Stump1eb44332009-09-09 15:08:12 +00007221
Chris Lattner06c0f5b2009-08-23 00:03:44 +00007222 if (DiagID) {
Chris Lattner6365e3e2009-08-22 18:58:31 +00007223 Diag(Loc, DiagID)
Richard Trieuf1775fb2011-09-06 21:43:51 +00007224 << LHSType << RHSType << LHS.get()->getSourceRange()
7225 << RHS.get()->getSourceRange();
Douglas Gregor6e5122c2010-06-15 21:38:40 +00007226 if (isError)
7227 return QualType();
Chris Lattner6365e3e2009-08-22 18:58:31 +00007228 }
Douglas Gregor6e5122c2010-06-15 21:38:40 +00007229
Richard Trieuf1775fb2011-09-06 21:43:51 +00007230 if (LHSType->isIntegerType())
7231 LHS = ImpCastExprToType(LHS.take(), RHSType,
John McCall404cd162010-11-13 01:35:44 +00007232 LHSIsNull ? CK_NullToPointer : CK_IntegralToPointer);
Chris Lattner06c0f5b2009-08-23 00:03:44 +00007233 else
Richard Trieuf1775fb2011-09-06 21:43:51 +00007234 RHS = ImpCastExprToType(RHS.take(), LHSType,
John McCall404cd162010-11-13 01:35:44 +00007235 RHSIsNull ? CK_NullToPointer : CK_IntegralToPointer);
Douglas Gregor447b69e2008-11-19 03:25:36 +00007236 return ResultTy;
Reid Spencer5f016e22007-07-11 17:01:13 +00007237 }
Douglas Gregor6e5122c2010-06-15 21:38:40 +00007238
Steve Naroff39218df2008-09-04 16:56:14 +00007239 // Handle block pointers.
Richard Trieuccd891a2011-09-09 01:45:06 +00007240 if (!IsRelational && RHSIsNull
Richard Trieuf1775fb2011-09-06 21:43:51 +00007241 && LHSType->isBlockPointerType() && RHSType->isIntegerType()) {
7242 RHS = ImpCastExprToType(RHS.take(), LHSType, CK_NullToPointer);
Douglas Gregor447b69e2008-11-19 03:25:36 +00007243 return ResultTy;
Steve Naroff39218df2008-09-04 16:56:14 +00007244 }
Richard Trieuccd891a2011-09-09 01:45:06 +00007245 if (!IsRelational && LHSIsNull
Richard Trieuf1775fb2011-09-06 21:43:51 +00007246 && LHSType->isIntegerType() && RHSType->isBlockPointerType()) {
7247 LHS = ImpCastExprToType(LHS.take(), RHSType, CK_NullToPointer);
Douglas Gregor447b69e2008-11-19 03:25:36 +00007248 return ResultTy;
Steve Naroff39218df2008-09-04 16:56:14 +00007249 }
Douglas Gregor90566c02011-03-01 17:16:20 +00007250
Richard Trieuf1775fb2011-09-06 21:43:51 +00007251 return InvalidOperands(Loc, LHS, RHS);
Reid Spencer5f016e22007-07-11 17:01:13 +00007252}
7253
Tanya Lattner4f692c22012-01-16 21:02:28 +00007254
7255// Return a signed type that is of identical size and number of elements.
7256// For floating point vectors, return an integer type of identical size
7257// and number of elements.
7258QualType Sema::GetSignedVectorType(QualType V) {
7259 const VectorType *VTy = V->getAs<VectorType>();
7260 unsigned TypeSize = Context.getTypeSize(VTy->getElementType());
7261 if (TypeSize == Context.getTypeSize(Context.CharTy))
7262 return Context.getExtVectorType(Context.CharTy, VTy->getNumElements());
7263 else if (TypeSize == Context.getTypeSize(Context.ShortTy))
7264 return Context.getExtVectorType(Context.ShortTy, VTy->getNumElements());
7265 else if (TypeSize == Context.getTypeSize(Context.IntTy))
7266 return Context.getExtVectorType(Context.IntTy, VTy->getNumElements());
7267 else if (TypeSize == Context.getTypeSize(Context.LongTy))
7268 return Context.getExtVectorType(Context.LongTy, VTy->getNumElements());
7269 assert(TypeSize == Context.getTypeSize(Context.LongLongTy) &&
7270 "Unhandled vector element size in vector compare");
7271 return Context.getExtVectorType(Context.LongLongTy, VTy->getNumElements());
7272}
7273
Nate Begemanbe2341d2008-07-14 18:02:46 +00007274/// CheckVectorCompareOperands - vector comparisons are a clang extension that
Mike Stumpeed9cac2009-02-19 03:04:26 +00007275/// operates on extended vector types. Instead of producing an IntTy result,
Nate Begemanbe2341d2008-07-14 18:02:46 +00007276/// like a scalar comparison, a vector comparison produces a vector of integer
7277/// types.
Richard Trieu9f60dee2011-09-07 01:19:57 +00007278QualType Sema::CheckVectorCompareOperands(ExprResult &LHS, ExprResult &RHS,
Chris Lattner29a1cfb2008-11-18 01:30:42 +00007279 SourceLocation Loc,
Richard Trieuccd891a2011-09-09 01:45:06 +00007280 bool IsRelational) {
Nate Begemanbe2341d2008-07-14 18:02:46 +00007281 // Check to make sure we're operating on vectors of the same type and width,
7282 // Allowing one side to be a scalar of element type.
Richard Trieu9f60dee2011-09-07 01:19:57 +00007283 QualType vType = CheckVectorOperands(LHS, RHS, Loc, /*isCompAssign*/false);
Nate Begemanbe2341d2008-07-14 18:02:46 +00007284 if (vType.isNull())
7285 return vType;
Mike Stumpeed9cac2009-02-19 03:04:26 +00007286
Richard Trieu9f60dee2011-09-07 01:19:57 +00007287 QualType LHSType = LHS.get()->getType();
Mike Stumpeed9cac2009-02-19 03:04:26 +00007288
Anton Yartsev7870b132011-03-27 15:36:07 +00007289 // If AltiVec, the comparison results in a numeric type, i.e.
7290 // bool for C++, int for C
Anton Yartsev6305f722011-03-28 21:00:05 +00007291 if (vType->getAs<VectorType>()->getVectorKind() == VectorType::AltiVecVector)
Anton Yartsev7870b132011-03-27 15:36:07 +00007292 return Context.getLogicalOperationType();
7293
Nate Begemanbe2341d2008-07-14 18:02:46 +00007294 // For non-floating point types, check for self-comparisons of the form
7295 // x == x, x != x, x < x, etc. These always evaluate to a constant, and
7296 // often indicate logic errors in the program.
Richard Trieu9f60dee2011-09-07 01:19:57 +00007297 if (!LHSType->hasFloatingRepresentation()) {
Richard Smith9c129f82011-10-28 03:31:48 +00007298 if (DeclRefExpr* DRL
7299 = dyn_cast<DeclRefExpr>(LHS.get()->IgnoreParenImpCasts()))
7300 if (DeclRefExpr* DRR
7301 = dyn_cast<DeclRefExpr>(RHS.get()->IgnoreParenImpCasts()))
Nate Begemanbe2341d2008-07-14 18:02:46 +00007302 if (DRL->getDecl() == DRR->getDecl())
Ted Kremenek351ba912011-02-23 01:52:04 +00007303 DiagRuntimeBehavior(Loc, 0,
Douglas Gregord64fdd02010-06-08 19:50:34 +00007304 PDiag(diag::warn_comparison_always)
7305 << 0 // self-
7306 << 2 // "a constant"
7307 );
Nate Begemanbe2341d2008-07-14 18:02:46 +00007308 }
Mike Stumpeed9cac2009-02-19 03:04:26 +00007309
Nate Begemanbe2341d2008-07-14 18:02:46 +00007310 // Check for comparisons of floating point operands using != and ==.
Richard Trieuccd891a2011-09-09 01:45:06 +00007311 if (!IsRelational && LHSType->hasFloatingRepresentation()) {
David Blaikie52e4c602012-01-16 05:16:03 +00007312 assert (RHS.get()->getType()->hasFloatingRepresentation());
Richard Trieu9f60dee2011-09-07 01:19:57 +00007313 CheckFloatComparison(Loc, LHS.get(), RHS.get());
Nate Begemanbe2341d2008-07-14 18:02:46 +00007314 }
Tanya Lattner4f692c22012-01-16 21:02:28 +00007315
7316 // Return a signed type for the vector.
7317 return GetSignedVectorType(LHSType);
7318}
Mike Stumpeed9cac2009-02-19 03:04:26 +00007319
Tanya Lattnerb0f9dd22012-01-19 01:16:16 +00007320QualType Sema::CheckVectorLogicalOperands(ExprResult &LHS, ExprResult &RHS,
7321 SourceLocation Loc) {
Tanya Lattner4f692c22012-01-16 21:02:28 +00007322 // Ensure that either both operands are of the same vector type, or
7323 // one operand is of a vector type and the other is of its element type.
7324 QualType vType = CheckVectorOperands(LHS, RHS, Loc, false);
7325 if (vType.isNull() || vType->isFloatingType())
7326 return InvalidOperands(Loc, LHS, RHS);
7327
7328 return GetSignedVectorType(LHS.get()->getType());
Nate Begemanbe2341d2008-07-14 18:02:46 +00007329}
7330
Reid Spencer5f016e22007-07-11 17:01:13 +00007331inline QualType Sema::CheckBitwiseOperands(
Richard Trieuccd891a2011-09-09 01:45:06 +00007332 ExprResult &LHS, ExprResult &RHS, SourceLocation Loc, bool IsCompAssign) {
Richard Trieu481037f2011-09-16 00:53:10 +00007333 checkArithmeticNull(*this, LHS, RHS, Loc, /*isCompare=*/false);
7334
Richard Trieu9f60dee2011-09-07 01:19:57 +00007335 if (LHS.get()->getType()->isVectorType() ||
7336 RHS.get()->getType()->isVectorType()) {
7337 if (LHS.get()->getType()->hasIntegerRepresentation() &&
7338 RHS.get()->getType()->hasIntegerRepresentation())
Richard Trieuccd891a2011-09-09 01:45:06 +00007339 return CheckVectorOperands(LHS, RHS, Loc, IsCompAssign);
Douglas Gregorf6094622010-07-23 15:58:24 +00007340
Richard Trieu9f60dee2011-09-07 01:19:57 +00007341 return InvalidOperands(Loc, LHS, RHS);
Douglas Gregorf6094622010-07-23 15:58:24 +00007342 }
Steve Naroff90045e82007-07-13 23:32:42 +00007343
Richard Trieu9f60dee2011-09-07 01:19:57 +00007344 ExprResult LHSResult = Owned(LHS), RHSResult = Owned(RHS);
7345 QualType compType = UsualArithmeticConversions(LHSResult, RHSResult,
Richard Trieuccd891a2011-09-09 01:45:06 +00007346 IsCompAssign);
Richard Trieu9f60dee2011-09-07 01:19:57 +00007347 if (LHSResult.isInvalid() || RHSResult.isInvalid())
John Wiegley429bb272011-04-08 18:41:53 +00007348 return QualType();
Richard Trieu9f60dee2011-09-07 01:19:57 +00007349 LHS = LHSResult.take();
7350 RHS = RHSResult.take();
Mike Stumpeed9cac2009-02-19 03:04:26 +00007351
Eli Friedman860a3192012-06-16 02:19:17 +00007352 if (!compType.isNull() && compType->isIntegralOrUnscopedEnumerationType())
Steve Naroff9f5fa9b2007-08-24 19:07:16 +00007353 return compType;
Richard Trieu9f60dee2011-09-07 01:19:57 +00007354 return InvalidOperands(Loc, LHS, RHS);
Reid Spencer5f016e22007-07-11 17:01:13 +00007355}
7356
7357inline QualType Sema::CheckLogicalOperands( // C99 6.5.[13,14]
Richard Trieu9f60dee2011-09-07 01:19:57 +00007358 ExprResult &LHS, ExprResult &RHS, SourceLocation Loc, unsigned Opc) {
Chris Lattner90a8f272010-07-13 19:41:32 +00007359
Tanya Lattner4f692c22012-01-16 21:02:28 +00007360 // Check vector operands differently.
7361 if (LHS.get()->getType()->isVectorType() || RHS.get()->getType()->isVectorType())
7362 return CheckVectorLogicalOperands(LHS, RHS, Loc);
7363
Chris Lattner90a8f272010-07-13 19:41:32 +00007364 // Diagnose cases where the user write a logical and/or but probably meant a
7365 // bitwise one. We do this when the LHS is a non-bool integer and the RHS
7366 // is a constant.
Richard Trieu9f60dee2011-09-07 01:19:57 +00007367 if (LHS.get()->getType()->isIntegerType() &&
7368 !LHS.get()->getType()->isBooleanType() &&
7369 RHS.get()->getType()->isIntegerType() && !RHS.get()->isValueDependent() &&
Richard Trieue5adf592011-07-15 00:00:51 +00007370 // Don't warn in macros or template instantiations.
7371 !Loc.isMacroID() && ActiveTemplateInstantiations.empty()) {
Chris Lattnerb7690b42010-07-24 01:10:11 +00007372 // If the RHS can be constant folded, and if it constant folds to something
7373 // that isn't 0 or 1 (which indicate a potential logical operation that
7374 // happened to fold to true/false) then warn.
Chandler Carruth0683a142011-05-31 05:41:42 +00007375 // Parens on the RHS are ignored.
Richard Smith909c5552011-10-16 23:01:09 +00007376 llvm::APSInt Result;
7377 if (RHS.get()->EvaluateAsInt(Result, Context))
David Blaikie4e4d0842012-03-11 07:00:24 +00007378 if ((getLangOpts().Bool && !RHS.get()->getType()->isBooleanType()) ||
Richard Smith909c5552011-10-16 23:01:09 +00007379 (Result != 0 && Result != 1)) {
Chandler Carruth0683a142011-05-31 05:41:42 +00007380 Diag(Loc, diag::warn_logical_instead_of_bitwise)
Richard Trieu9f60dee2011-09-07 01:19:57 +00007381 << RHS.get()->getSourceRange()
Matt Beaumont-Gay9b127f32011-08-15 17:50:06 +00007382 << (Opc == BO_LAnd ? "&&" : "||");
7383 // Suggest replacing the logical operator with the bitwise version
7384 Diag(Loc, diag::note_logical_instead_of_bitwise_change_operator)
7385 << (Opc == BO_LAnd ? "&" : "|")
7386 << FixItHint::CreateReplacement(SourceRange(
7387 Loc, Lexer::getLocForEndOfToken(Loc, 0, getSourceManager(),
David Blaikie4e4d0842012-03-11 07:00:24 +00007388 getLangOpts())),
Matt Beaumont-Gay9b127f32011-08-15 17:50:06 +00007389 Opc == BO_LAnd ? "&" : "|");
7390 if (Opc == BO_LAnd)
7391 // Suggest replacing "Foo() && kNonZero" with "Foo()"
7392 Diag(Loc, diag::note_logical_instead_of_bitwise_remove_constant)
7393 << FixItHint::CreateRemoval(
7394 SourceRange(
Richard Trieu9f60dee2011-09-07 01:19:57 +00007395 Lexer::getLocForEndOfToken(LHS.get()->getLocEnd(),
Matt Beaumont-Gay9b127f32011-08-15 17:50:06 +00007396 0, getSourceManager(),
David Blaikie4e4d0842012-03-11 07:00:24 +00007397 getLangOpts()),
Richard Trieu9f60dee2011-09-07 01:19:57 +00007398 RHS.get()->getLocEnd()));
Matt Beaumont-Gay9b127f32011-08-15 17:50:06 +00007399 }
Chris Lattnerb7690b42010-07-24 01:10:11 +00007400 }
Chris Lattner90a8f272010-07-13 19:41:32 +00007401
David Blaikie4e4d0842012-03-11 07:00:24 +00007402 if (!Context.getLangOpts().CPlusPlus) {
Richard Trieu9f60dee2011-09-07 01:19:57 +00007403 LHS = UsualUnaryConversions(LHS.take());
7404 if (LHS.isInvalid())
John Wiegley429bb272011-04-08 18:41:53 +00007405 return QualType();
Mike Stumpeed9cac2009-02-19 03:04:26 +00007406
Richard Trieu9f60dee2011-09-07 01:19:57 +00007407 RHS = UsualUnaryConversions(RHS.take());
7408 if (RHS.isInvalid())
John Wiegley429bb272011-04-08 18:41:53 +00007409 return QualType();
7410
Richard Trieu9f60dee2011-09-07 01:19:57 +00007411 if (!LHS.get()->getType()->isScalarType() ||
7412 !RHS.get()->getType()->isScalarType())
7413 return InvalidOperands(Loc, LHS, RHS);
Kovarththanan Rajaratnam19357542010-03-13 10:17:05 +00007414
Anders Carlssona4c98cd2009-11-23 21:47:44 +00007415 return Context.IntTy;
Anders Carlsson04905012009-10-16 01:44:21 +00007416 }
Kovarththanan Rajaratnam19357542010-03-13 10:17:05 +00007417
John McCall75f7c0f2010-06-04 00:29:51 +00007418 // The following is safe because we only use this method for
7419 // non-overloadable operands.
7420
Anders Carlssona4c98cd2009-11-23 21:47:44 +00007421 // C++ [expr.log.and]p1
7422 // C++ [expr.log.or]p1
John McCall75f7c0f2010-06-04 00:29:51 +00007423 // The operands are both contextually converted to type bool.
Richard Trieu9f60dee2011-09-07 01:19:57 +00007424 ExprResult LHSRes = PerformContextuallyConvertToBool(LHS.get());
7425 if (LHSRes.isInvalid())
7426 return InvalidOperands(Loc, LHS, RHS);
Benjamin Kramer3fe198b2012-08-23 21:35:17 +00007427 LHS = LHSRes;
John Wiegley429bb272011-04-08 18:41:53 +00007428
Richard Trieu9f60dee2011-09-07 01:19:57 +00007429 ExprResult RHSRes = PerformContextuallyConvertToBool(RHS.get());
7430 if (RHSRes.isInvalid())
7431 return InvalidOperands(Loc, LHS, RHS);
Benjamin Kramer3fe198b2012-08-23 21:35:17 +00007432 RHS = RHSRes;
Kovarththanan Rajaratnam19357542010-03-13 10:17:05 +00007433
Anders Carlssona4c98cd2009-11-23 21:47:44 +00007434 // C++ [expr.log.and]p2
7435 // C++ [expr.log.or]p2
7436 // The result is a bool.
7437 return Context.BoolTy;
Reid Spencer5f016e22007-07-11 17:01:13 +00007438}
7439
Fariborz Jahaniand1fa6442009-01-12 19:55:42 +00007440/// IsReadonlyProperty - Verify that otherwise a valid l-value expression
7441/// is a read-only property; return true if so. A readonly property expression
7442/// depends on various declarations and thus must be treated specially.
7443///
Mike Stump1eb44332009-09-09 15:08:12 +00007444static bool IsReadonlyProperty(Expr *E, Sema &S) {
John McCall3c3b7f92011-10-25 17:37:35 +00007445 const ObjCPropertyRefExpr *PropExpr = dyn_cast<ObjCPropertyRefExpr>(E);
7446 if (!PropExpr) return false;
7447 if (PropExpr->isImplicitProperty()) return false;
John McCall12f78a62010-12-02 01:19:52 +00007448
John McCall3c3b7f92011-10-25 17:37:35 +00007449 ObjCPropertyDecl *PDecl = PropExpr->getExplicitProperty();
7450 QualType BaseType = PropExpr->isSuperReceiver() ?
John McCall12f78a62010-12-02 01:19:52 +00007451 PropExpr->getSuperReceiverType() :
Fariborz Jahanian8ac2d442010-10-14 16:04:05 +00007452 PropExpr->getBase()->getType();
7453
John McCall3c3b7f92011-10-25 17:37:35 +00007454 if (const ObjCObjectPointerType *OPT =
7455 BaseType->getAsObjCInterfacePointerType())
7456 if (ObjCInterfaceDecl *IFace = OPT->getInterfaceDecl())
7457 if (S.isPropertyReadonly(PDecl, IFace))
7458 return true;
Fariborz Jahaniand1fa6442009-01-12 19:55:42 +00007459 return false;
7460}
7461
Fariborz Jahanian077f4902011-03-26 19:48:30 +00007462static bool IsReadonlyMessage(Expr *E, Sema &S) {
John McCall3c3b7f92011-10-25 17:37:35 +00007463 const MemberExpr *ME = dyn_cast<MemberExpr>(E);
7464 if (!ME) return false;
7465 if (!isa<FieldDecl>(ME->getMemberDecl())) return false;
7466 ObjCMessageExpr *Base =
7467 dyn_cast<ObjCMessageExpr>(ME->getBase()->IgnoreParenImpCasts());
7468 if (!Base) return false;
7469 return Base->getMethodDecl() != 0;
Fariborz Jahanian077f4902011-03-26 19:48:30 +00007470}
7471
John McCall78dae242012-03-13 00:37:01 +00007472/// Is the given expression (which must be 'const') a reference to a
7473/// variable which was originally non-const, but which has become
7474/// 'const' due to being captured within a block?
7475enum NonConstCaptureKind { NCCK_None, NCCK_Block, NCCK_Lambda };
7476static NonConstCaptureKind isReferenceToNonConstCapture(Sema &S, Expr *E) {
7477 assert(E->isLValue() && E->getType().isConstQualified());
7478 E = E->IgnoreParens();
7479
7480 // Must be a reference to a declaration from an enclosing scope.
7481 DeclRefExpr *DRE = dyn_cast<DeclRefExpr>(E);
7482 if (!DRE) return NCCK_None;
7483 if (!DRE->refersToEnclosingLocal()) return NCCK_None;
7484
7485 // The declaration must be a variable which is not declared 'const'.
7486 VarDecl *var = dyn_cast<VarDecl>(DRE->getDecl());
7487 if (!var) return NCCK_None;
7488 if (var->getType().isConstQualified()) return NCCK_None;
7489 assert(var->hasLocalStorage() && "capture added 'const' to non-local?");
7490
7491 // Decide whether the first capture was for a block or a lambda.
7492 DeclContext *DC = S.CurContext;
7493 while (DC->getParent() != var->getDeclContext())
7494 DC = DC->getParent();
7495 return (isa<BlockDecl>(DC) ? NCCK_Block : NCCK_Lambda);
7496}
7497
Chris Lattnerf67bd9f2008-11-18 01:22:49 +00007498/// CheckForModifiableLvalue - Verify that E is a modifiable lvalue. If not,
7499/// emit an error and return true. If so, return false.
7500static bool CheckForModifiableLvalue(Expr *E, SourceLocation Loc, Sema &S) {
Fariborz Jahaniane7ea28a2012-04-10 17:30:10 +00007501 assert(!E->hasPlaceholderType(BuiltinType::PseudoObject));
Daniel Dunbar44e35f72009-04-15 00:08:05 +00007502 SourceLocation OrigLoc = Loc;
Mike Stump1eb44332009-09-09 15:08:12 +00007503 Expr::isModifiableLvalueResult IsLV = E->isModifiableLvalue(S.Context,
Daniel Dunbar44e35f72009-04-15 00:08:05 +00007504 &Loc);
Fariborz Jahaniand1fa6442009-01-12 19:55:42 +00007505 if (IsLV == Expr::MLV_Valid && IsReadonlyProperty(E, S))
7506 IsLV = Expr::MLV_ReadonlyProperty;
Fariborz Jahanian077f4902011-03-26 19:48:30 +00007507 else if (IsLV == Expr::MLV_ClassTemporary && IsReadonlyMessage(E, S))
7508 IsLV = Expr::MLV_InvalidMessageExpression;
Chris Lattnerf67bd9f2008-11-18 01:22:49 +00007509 if (IsLV == Expr::MLV_Valid)
7510 return false;
Mike Stumpeed9cac2009-02-19 03:04:26 +00007511
Chris Lattnerf67bd9f2008-11-18 01:22:49 +00007512 unsigned Diag = 0;
7513 bool NeedType = false;
7514 switch (IsLV) { // C99 6.5.16p2
John McCallf85e1932011-06-15 23:02:42 +00007515 case Expr::MLV_ConstQualified:
7516 Diag = diag::err_typecheck_assign_const;
7517
John McCall78dae242012-03-13 00:37:01 +00007518 // Use a specialized diagnostic when we're assigning to an object
7519 // from an enclosing function or block.
7520 if (NonConstCaptureKind NCCK = isReferenceToNonConstCapture(S, E)) {
7521 if (NCCK == NCCK_Block)
7522 Diag = diag::err_block_decl_ref_not_modifiable_lvalue;
7523 else
7524 Diag = diag::err_lambda_decl_ref_not_modifiable_lvalue;
7525 break;
7526 }
7527
John McCall7acddac2011-06-17 06:42:21 +00007528 // In ARC, use some specialized diagnostics for occasions where we
7529 // infer 'const'. These are always pseudo-strong variables.
David Blaikie4e4d0842012-03-11 07:00:24 +00007530 if (S.getLangOpts().ObjCAutoRefCount) {
John McCallf85e1932011-06-15 23:02:42 +00007531 DeclRefExpr *declRef = dyn_cast<DeclRefExpr>(E->IgnoreParenCasts());
7532 if (declRef && isa<VarDecl>(declRef->getDecl())) {
7533 VarDecl *var = cast<VarDecl>(declRef->getDecl());
7534
John McCall7acddac2011-06-17 06:42:21 +00007535 // Use the normal diagnostic if it's pseudo-__strong but the
7536 // user actually wrote 'const'.
7537 if (var->isARCPseudoStrong() &&
7538 (!var->getTypeSourceInfo() ||
7539 !var->getTypeSourceInfo()->getType().isConstQualified())) {
7540 // There are two pseudo-strong cases:
7541 // - self
John McCallf85e1932011-06-15 23:02:42 +00007542 ObjCMethodDecl *method = S.getCurMethodDecl();
7543 if (method && var == method->getSelfDecl())
Ted Kremenek2bbcd5c2011-11-14 21:59:25 +00007544 Diag = method->isClassMethod()
7545 ? diag::err_typecheck_arc_assign_self_class_method
7546 : diag::err_typecheck_arc_assign_self;
John McCall7acddac2011-06-17 06:42:21 +00007547
7548 // - fast enumeration variables
7549 else
John McCallf85e1932011-06-15 23:02:42 +00007550 Diag = diag::err_typecheck_arr_assign_enumeration;
John McCall7acddac2011-06-17 06:42:21 +00007551
John McCallf85e1932011-06-15 23:02:42 +00007552 SourceRange Assign;
7553 if (Loc != OrigLoc)
7554 Assign = SourceRange(OrigLoc, OrigLoc);
7555 S.Diag(Loc, Diag) << E->getSourceRange() << Assign;
7556 // We need to preserve the AST regardless, so migration tool
7557 // can do its job.
7558 return false;
7559 }
7560 }
7561 }
7562
7563 break;
Mike Stumpeed9cac2009-02-19 03:04:26 +00007564 case Expr::MLV_ArrayType:
Richard Smith36d02af2012-06-04 22:27:30 +00007565 case Expr::MLV_ArrayTemporary:
Chris Lattnerf67bd9f2008-11-18 01:22:49 +00007566 Diag = diag::err_typecheck_array_not_modifiable_lvalue;
7567 NeedType = true;
7568 break;
Mike Stumpeed9cac2009-02-19 03:04:26 +00007569 case Expr::MLV_NotObjectType:
Chris Lattnerf67bd9f2008-11-18 01:22:49 +00007570 Diag = diag::err_typecheck_non_object_not_modifiable_lvalue;
7571 NeedType = true;
7572 break;
Chris Lattnerca354fa2008-11-17 19:51:54 +00007573 case Expr::MLV_LValueCast:
Chris Lattnerf67bd9f2008-11-18 01:22:49 +00007574 Diag = diag::err_typecheck_lvalue_casts_not_supported;
7575 break;
Douglas Gregore873fb72010-02-16 21:39:57 +00007576 case Expr::MLV_Valid:
7577 llvm_unreachable("did not take early return for MLV_Valid");
Chris Lattner5cf216b2008-01-04 18:04:52 +00007578 case Expr::MLV_InvalidExpression:
Douglas Gregore873fb72010-02-16 21:39:57 +00007579 case Expr::MLV_MemberFunction:
7580 case Expr::MLV_ClassTemporary:
Chris Lattnerf67bd9f2008-11-18 01:22:49 +00007581 Diag = diag::err_typecheck_expression_not_modifiable_lvalue;
7582 break;
Chris Lattner5cf216b2008-01-04 18:04:52 +00007583 case Expr::MLV_IncompleteType:
7584 case Expr::MLV_IncompleteVoidType:
Douglas Gregor86447ec2009-03-09 16:13:40 +00007585 return S.RequireCompleteType(Loc, E->getType(),
Douglas Gregord10099e2012-05-04 16:32:21 +00007586 diag::err_typecheck_incomplete_type_not_modifiable_lvalue, E);
Chris Lattner5cf216b2008-01-04 18:04:52 +00007587 case Expr::MLV_DuplicateVectorComponents:
Chris Lattnerf67bd9f2008-11-18 01:22:49 +00007588 Diag = diag::err_typecheck_duplicate_vector_components_not_mlvalue;
7589 break;
Fariborz Jahanian5daf5702008-11-22 18:39:36 +00007590 case Expr::MLV_ReadonlyProperty:
Fariborz Jahanianba8d2d62008-11-22 20:25:50 +00007591 case Expr::MLV_NoSetterProperty:
John McCall3c3b7f92011-10-25 17:37:35 +00007592 llvm_unreachable("readonly properties should be processed differently");
Fariborz Jahanian077f4902011-03-26 19:48:30 +00007593 case Expr::MLV_InvalidMessageExpression:
7594 Diag = diag::error_readonly_message_assignment;
7595 break;
Fariborz Jahanian2514a302009-12-15 23:59:41 +00007596 case Expr::MLV_SubObjCPropertySetting:
7597 Diag = diag::error_no_subobject_property_setting;
7598 break;
Reid Spencer5f016e22007-07-11 17:01:13 +00007599 }
Steve Naroffd1861fd2007-07-31 12:34:36 +00007600
Daniel Dunbar44e35f72009-04-15 00:08:05 +00007601 SourceRange Assign;
7602 if (Loc != OrigLoc)
7603 Assign = SourceRange(OrigLoc, OrigLoc);
Chris Lattnerf67bd9f2008-11-18 01:22:49 +00007604 if (NeedType)
Daniel Dunbar44e35f72009-04-15 00:08:05 +00007605 S.Diag(Loc, Diag) << E->getType() << E->getSourceRange() << Assign;
Chris Lattnerf67bd9f2008-11-18 01:22:49 +00007606 else
Mike Stump1eb44332009-09-09 15:08:12 +00007607 S.Diag(Loc, Diag) << E->getSourceRange() << Assign;
Chris Lattnerf67bd9f2008-11-18 01:22:49 +00007608 return true;
7609}
7610
Nico Weber7c81b432012-07-03 02:03:06 +00007611static void CheckIdentityFieldAssignment(Expr *LHSExpr, Expr *RHSExpr,
7612 SourceLocation Loc,
7613 Sema &Sema) {
7614 // C / C++ fields
Nico Weber43bb1792012-06-28 23:53:12 +00007615 MemberExpr *ML = dyn_cast<MemberExpr>(LHSExpr);
7616 MemberExpr *MR = dyn_cast<MemberExpr>(RHSExpr);
7617 if (ML && MR && ML->getMemberDecl() == MR->getMemberDecl()) {
7618 if (isa<CXXThisExpr>(ML->getBase()) && isa<CXXThisExpr>(MR->getBase()))
Nico Weber7c81b432012-07-03 02:03:06 +00007619 Sema.Diag(Loc, diag::warn_identity_field_assign) << 0;
Nico Weber43bb1792012-06-28 23:53:12 +00007620 }
Chris Lattnerf67bd9f2008-11-18 01:22:49 +00007621
Nico Weber7c81b432012-07-03 02:03:06 +00007622 // Objective-C instance variables
Nico Weber43bb1792012-06-28 23:53:12 +00007623 ObjCIvarRefExpr *OL = dyn_cast<ObjCIvarRefExpr>(LHSExpr);
7624 ObjCIvarRefExpr *OR = dyn_cast<ObjCIvarRefExpr>(RHSExpr);
7625 if (OL && OR && OL->getDecl() == OR->getDecl()) {
7626 DeclRefExpr *RL = dyn_cast<DeclRefExpr>(OL->getBase()->IgnoreImpCasts());
7627 DeclRefExpr *RR = dyn_cast<DeclRefExpr>(OR->getBase()->IgnoreImpCasts());
7628 if (RL && RR && RL->getDecl() == RR->getDecl())
Nico Weber7c81b432012-07-03 02:03:06 +00007629 Sema.Diag(Loc, diag::warn_identity_field_assign) << 1;
Nico Weber43bb1792012-06-28 23:53:12 +00007630 }
7631}
Chris Lattnerf67bd9f2008-11-18 01:22:49 +00007632
7633// C99 6.5.16.1
Richard Trieu268942b2011-09-07 01:33:52 +00007634QualType Sema::CheckAssignmentOperands(Expr *LHSExpr, ExprResult &RHS,
Chris Lattner29a1cfb2008-11-18 01:30:42 +00007635 SourceLocation Loc,
7636 QualType CompoundType) {
John McCall3c3b7f92011-10-25 17:37:35 +00007637 assert(!LHSExpr->hasPlaceholderType(BuiltinType::PseudoObject));
7638
Chris Lattner29a1cfb2008-11-18 01:30:42 +00007639 // Verify that LHS is a modifiable lvalue, and emit error if not.
Richard Trieu268942b2011-09-07 01:33:52 +00007640 if (CheckForModifiableLvalue(LHSExpr, Loc, *this))
Chris Lattnerf67bd9f2008-11-18 01:22:49 +00007641 return QualType();
Chris Lattner29a1cfb2008-11-18 01:30:42 +00007642
Richard Trieu268942b2011-09-07 01:33:52 +00007643 QualType LHSType = LHSExpr->getType();
Richard Trieu67e29332011-08-02 04:35:43 +00007644 QualType RHSType = CompoundType.isNull() ? RHS.get()->getType() :
7645 CompoundType;
Chris Lattner5cf216b2008-01-04 18:04:52 +00007646 AssignConvertType ConvTy;
Chris Lattner29a1cfb2008-11-18 01:30:42 +00007647 if (CompoundType.isNull()) {
Nico Weber43bb1792012-06-28 23:53:12 +00007648 Expr *RHSCheck = RHS.get();
7649
Nico Weber7c81b432012-07-03 02:03:06 +00007650 CheckIdentityFieldAssignment(LHSExpr, RHSCheck, Loc, *this);
Nico Weber43bb1792012-06-28 23:53:12 +00007651
Fariborz Jahaniane2a901a2010-06-07 22:02:01 +00007652 QualType LHSTy(LHSType);
Fariborz Jahaniane2a901a2010-06-07 22:02:01 +00007653 ConvTy = CheckSingleAssignmentConstraints(LHSTy, RHS);
John Wiegley429bb272011-04-08 18:41:53 +00007654 if (RHS.isInvalid())
7655 return QualType();
Fariborz Jahanianfa23c1d2009-01-13 23:34:40 +00007656 // Special case of NSObject attributes on c-style pointer types.
7657 if (ConvTy == IncompatiblePointer &&
7658 ((Context.isObjCNSObjectType(LHSType) &&
Steve Narofff4954562009-07-16 15:41:00 +00007659 RHSType->isObjCObjectPointerType()) ||
Fariborz Jahanianfa23c1d2009-01-13 23:34:40 +00007660 (Context.isObjCNSObjectType(RHSType) &&
Steve Narofff4954562009-07-16 15:41:00 +00007661 LHSType->isObjCObjectPointerType())))
Fariborz Jahanianfa23c1d2009-01-13 23:34:40 +00007662 ConvTy = Compatible;
Mike Stumpeed9cac2009-02-19 03:04:26 +00007663
John McCallf89e55a2010-11-18 06:31:45 +00007664 if (ConvTy == Compatible &&
Fariborz Jahanian466f45a2012-01-24 19:40:13 +00007665 LHSType->isObjCObjectType())
Fariborz Jahanian7b383e42012-01-24 18:05:45 +00007666 Diag(Loc, diag::err_objc_object_assignment)
7667 << LHSType;
John McCallf89e55a2010-11-18 06:31:45 +00007668
Chris Lattner2c156472008-08-21 18:04:13 +00007669 // If the RHS is a unary plus or minus, check to see if they = and + are
7670 // right next to each other. If so, the user may have typo'd "x =+ 4"
7671 // instead of "x += 4".
Chris Lattner2c156472008-08-21 18:04:13 +00007672 if (ImplicitCastExpr *ICE = dyn_cast<ImplicitCastExpr>(RHSCheck))
7673 RHSCheck = ICE->getSubExpr();
7674 if (UnaryOperator *UO = dyn_cast<UnaryOperator>(RHSCheck)) {
John McCall2de56d12010-08-25 11:45:40 +00007675 if ((UO->getOpcode() == UO_Plus ||
7676 UO->getOpcode() == UO_Minus) &&
Chris Lattner29a1cfb2008-11-18 01:30:42 +00007677 Loc.isFileID() && UO->getOperatorLoc().isFileID() &&
Chris Lattner2c156472008-08-21 18:04:13 +00007678 // Only if the two operators are exactly adjacent.
Argyrios Kyrtzidisa64ccef2011-09-19 20:40:19 +00007679 Loc.getLocWithOffset(1) == UO->getOperatorLoc() &&
Chris Lattner399bd1b2009-03-08 06:51:10 +00007680 // And there is a space or other character before the subexpr of the
7681 // unary +/-. We don't want to warn on "x=-1".
Argyrios Kyrtzidisa64ccef2011-09-19 20:40:19 +00007682 Loc.getLocWithOffset(2) != UO->getSubExpr()->getLocStart() &&
Chris Lattner3e872092009-03-09 07:11:10 +00007683 UO->getSubExpr()->getLocStart().isFileID()) {
Chris Lattnerd3a94e22008-11-20 06:06:08 +00007684 Diag(Loc, diag::warn_not_compound_assign)
John McCall2de56d12010-08-25 11:45:40 +00007685 << (UO->getOpcode() == UO_Plus ? "+" : "-")
Chris Lattnerd3a94e22008-11-20 06:06:08 +00007686 << SourceRange(UO->getOperatorLoc(), UO->getOperatorLoc());
Chris Lattner399bd1b2009-03-08 06:51:10 +00007687 }
Chris Lattner2c156472008-08-21 18:04:13 +00007688 }
John McCallf85e1932011-06-15 23:02:42 +00007689
7690 if (ConvTy == Compatible) {
7691 if (LHSType.getObjCLifetime() == Qualifiers::OCL_Strong)
Richard Trieu268942b2011-09-07 01:33:52 +00007692 checkRetainCycles(LHSExpr, RHS.get());
David Blaikie4e4d0842012-03-11 07:00:24 +00007693 else if (getLangOpts().ObjCAutoRefCount)
Richard Trieu268942b2011-09-07 01:33:52 +00007694 checkUnsafeExprAssigns(Loc, LHSExpr, RHS.get());
John McCallf85e1932011-06-15 23:02:42 +00007695 }
Chris Lattner2c156472008-08-21 18:04:13 +00007696 } else {
7697 // Compound assignment "x += y"
Douglas Gregorb608b982011-01-28 02:26:04 +00007698 ConvTy = CheckAssignmentConstraints(Loc, LHSType, RHSType);
Chris Lattner2c156472008-08-21 18:04:13 +00007699 }
Chris Lattner5cf216b2008-01-04 18:04:52 +00007700
Chris Lattner29a1cfb2008-11-18 01:30:42 +00007701 if (DiagnoseAssignmentResult(ConvTy, Loc, LHSType, RHSType,
John Wiegley429bb272011-04-08 18:41:53 +00007702 RHS.get(), AA_Assigning))
Chris Lattner5cf216b2008-01-04 18:04:52 +00007703 return QualType();
Mike Stumpeed9cac2009-02-19 03:04:26 +00007704
Richard Trieu268942b2011-09-07 01:33:52 +00007705 CheckForNullPointerDereference(*this, LHSExpr);
Kaelyn Uhraind6c88652011-08-05 23:18:04 +00007706
Reid Spencer5f016e22007-07-11 17:01:13 +00007707 // C99 6.5.16p3: The type of an assignment expression is the type of the
7708 // left operand unless the left operand has qualified type, in which case
Mike Stumpeed9cac2009-02-19 03:04:26 +00007709 // it is the unqualified version of the type of the left operand.
Reid Spencer5f016e22007-07-11 17:01:13 +00007710 // C99 6.5.16.1p2: In simple assignment, the value of the right operand
7711 // is converted to the type of the assignment expression (above).
Chris Lattner73d0d4f2007-08-30 17:45:32 +00007712 // C++ 5.17p1: the type of the assignment expression is that of its left
Douglas Gregor2d833e32009-05-02 00:36:19 +00007713 // operand.
David Blaikie4e4d0842012-03-11 07:00:24 +00007714 return (getLangOpts().CPlusPlus
John McCall2bf6f492010-10-12 02:19:57 +00007715 ? LHSType : LHSType.getUnqualifiedType());
Reid Spencer5f016e22007-07-11 17:01:13 +00007716}
7717
Chris Lattner29a1cfb2008-11-18 01:30:42 +00007718// C99 6.5.17
John Wiegley429bb272011-04-08 18:41:53 +00007719static QualType CheckCommaOperands(Sema &S, ExprResult &LHS, ExprResult &RHS,
John McCall09431682010-11-18 19:01:18 +00007720 SourceLocation Loc) {
John McCallfb8721c2011-04-10 19:13:55 +00007721 LHS = S.CheckPlaceholderExpr(LHS.take());
7722 RHS = S.CheckPlaceholderExpr(RHS.take());
John Wiegley429bb272011-04-08 18:41:53 +00007723 if (LHS.isInvalid() || RHS.isInvalid())
Douglas Gregor7ad5d422010-11-09 21:07:58 +00007724 return QualType();
7725
John McCallcf2e5062010-10-12 07:14:40 +00007726 // C's comma performs lvalue conversion (C99 6.3.2.1) on both its
7727 // operands, but not unary promotions.
7728 // C++'s comma does not do any conversions at all (C++ [expr.comma]p1).
Eli Friedmanb1d796d2009-03-23 00:24:07 +00007729
John McCallf6a16482010-12-04 03:47:34 +00007730 // So we treat the LHS as a ignored value, and in C++ we allow the
7731 // containing site to determine what should be done with the RHS.
John Wiegley429bb272011-04-08 18:41:53 +00007732 LHS = S.IgnoredValueConversions(LHS.take());
7733 if (LHS.isInvalid())
7734 return QualType();
John McCallf6a16482010-12-04 03:47:34 +00007735
Eli Friedmana6115062012-05-24 00:47:05 +00007736 S.DiagnoseUnusedExprResult(LHS.get());
7737
David Blaikie4e4d0842012-03-11 07:00:24 +00007738 if (!S.getLangOpts().CPlusPlus) {
John Wiegley429bb272011-04-08 18:41:53 +00007739 RHS = S.DefaultFunctionArrayLvalueConversion(RHS.take());
7740 if (RHS.isInvalid())
7741 return QualType();
7742 if (!RHS.get()->getType()->isVoidType())
Richard Trieu67e29332011-08-02 04:35:43 +00007743 S.RequireCompleteType(Loc, RHS.get()->getType(),
7744 diag::err_incomplete_type);
John McCallcf2e5062010-10-12 07:14:40 +00007745 }
Eli Friedmanb1d796d2009-03-23 00:24:07 +00007746
John Wiegley429bb272011-04-08 18:41:53 +00007747 return RHS.get()->getType();
Reid Spencer5f016e22007-07-11 17:01:13 +00007748}
7749
Steve Naroff49b45262007-07-13 16:58:59 +00007750/// CheckIncrementDecrementOperand - unlike most "Check" methods, this routine
7751/// doesn't need to call UsualUnaryConversions or UsualArithmeticConversions.
John McCall09431682010-11-18 19:01:18 +00007752static QualType CheckIncrementDecrementOperand(Sema &S, Expr *Op,
7753 ExprValueKind &VK,
7754 SourceLocation OpLoc,
Richard Trieuccd891a2011-09-09 01:45:06 +00007755 bool IsInc, bool IsPrefix) {
Sebastian Redl28507842009-02-26 14:39:58 +00007756 if (Op->isTypeDependent())
John McCall09431682010-11-18 19:01:18 +00007757 return S.Context.DependentTy;
Sebastian Redl28507842009-02-26 14:39:58 +00007758
Chris Lattner3528d352008-11-21 07:05:48 +00007759 QualType ResType = Op->getType();
David Chisnall7a7ee302012-01-16 17:27:18 +00007760 // Atomic types can be used for increment / decrement where the non-atomic
7761 // versions can, so ignore the _Atomic() specifier for the purpose of
7762 // checking.
7763 if (const AtomicType *ResAtomicType = ResType->getAs<AtomicType>())
7764 ResType = ResAtomicType->getValueType();
7765
Chris Lattner3528d352008-11-21 07:05:48 +00007766 assert(!ResType.isNull() && "no type for increment/decrement expression");
Reid Spencer5f016e22007-07-11 17:01:13 +00007767
David Blaikie4e4d0842012-03-11 07:00:24 +00007768 if (S.getLangOpts().CPlusPlus && ResType->isBooleanType()) {
Sebastian Redle6d5a4a2008-12-20 09:35:34 +00007769 // Decrement of bool is not allowed.
Richard Trieuccd891a2011-09-09 01:45:06 +00007770 if (!IsInc) {
John McCall09431682010-11-18 19:01:18 +00007771 S.Diag(OpLoc, diag::err_decrement_bool) << Op->getSourceRange();
Sebastian Redle6d5a4a2008-12-20 09:35:34 +00007772 return QualType();
7773 }
7774 // Increment of bool sets it to true, but is deprecated.
John McCall09431682010-11-18 19:01:18 +00007775 S.Diag(OpLoc, diag::warn_increment_bool) << Op->getSourceRange();
Sebastian Redle6d5a4a2008-12-20 09:35:34 +00007776 } else if (ResType->isRealType()) {
Chris Lattner3528d352008-11-21 07:05:48 +00007777 // OK!
John McCall1503f0d2012-07-31 05:14:30 +00007778 } else if (ResType->isPointerType()) {
Chris Lattner3528d352008-11-21 07:05:48 +00007779 // C99 6.5.2.4p2, 6.5.6p2
Chandler Carruth13b21be2011-06-27 08:02:19 +00007780 if (!checkArithmeticOpPointerOperand(S, OpLoc, Op))
Douglas Gregor4ec339f2009-01-19 19:26:10 +00007781 return QualType();
John McCall1503f0d2012-07-31 05:14:30 +00007782 } else if (ResType->isObjCObjectPointerType()) {
7783 // On modern runtimes, ObjC pointer arithmetic is forbidden.
7784 // Otherwise, we just need a complete type.
7785 if (checkArithmeticIncompletePointerType(S, OpLoc, Op) ||
7786 checkArithmeticOnObjCPointer(S, OpLoc, Op))
7787 return QualType();
Eli Friedman5b088a12010-01-03 00:20:48 +00007788 } else if (ResType->isAnyComplexType()) {
Chris Lattner3528d352008-11-21 07:05:48 +00007789 // C99 does not support ++/-- on complex types, we allow as an extension.
John McCall09431682010-11-18 19:01:18 +00007790 S.Diag(OpLoc, diag::ext_integer_increment_complex)
Chris Lattnerd1625842008-11-24 06:25:27 +00007791 << ResType << Op->getSourceRange();
John McCall2cd11fe2010-10-12 02:09:17 +00007792 } else if (ResType->isPlaceholderType()) {
John McCallfb8721c2011-04-10 19:13:55 +00007793 ExprResult PR = S.CheckPlaceholderExpr(Op);
John McCall2cd11fe2010-10-12 02:09:17 +00007794 if (PR.isInvalid()) return QualType();
John McCall09431682010-11-18 19:01:18 +00007795 return CheckIncrementDecrementOperand(S, PR.take(), VK, OpLoc,
Richard Trieuccd891a2011-09-09 01:45:06 +00007796 IsInc, IsPrefix);
David Blaikie4e4d0842012-03-11 07:00:24 +00007797 } else if (S.getLangOpts().AltiVec && ResType->isVectorType()) {
Anton Yartsev683564a2011-02-07 02:17:30 +00007798 // OK! ( C/C++ Language Extensions for CBEA(Version 2.6) 10.3 )
Chris Lattner3528d352008-11-21 07:05:48 +00007799 } else {
John McCall09431682010-11-18 19:01:18 +00007800 S.Diag(OpLoc, diag::err_typecheck_illegal_increment_decrement)
Richard Trieuccd891a2011-09-09 01:45:06 +00007801 << ResType << int(IsInc) << Op->getSourceRange();
Chris Lattner3528d352008-11-21 07:05:48 +00007802 return QualType();
Reid Spencer5f016e22007-07-11 17:01:13 +00007803 }
Mike Stumpeed9cac2009-02-19 03:04:26 +00007804 // At this point, we know we have a real, complex or pointer type.
Steve Naroffdd10e022007-08-23 21:37:33 +00007805 // Now make sure the operand is a modifiable lvalue.
John McCall09431682010-11-18 19:01:18 +00007806 if (CheckForModifiableLvalue(Op, OpLoc, S))
Reid Spencer5f016e22007-07-11 17:01:13 +00007807 return QualType();
Sean Hunt1e3f5ba2010-04-28 23:02:27 +00007808 // In C++, a prefix increment is the same type as the operand. Otherwise
7809 // (in C or with postfix), the increment is the unqualified type of the
7810 // operand.
David Blaikie4e4d0842012-03-11 07:00:24 +00007811 if (IsPrefix && S.getLangOpts().CPlusPlus) {
John McCall09431682010-11-18 19:01:18 +00007812 VK = VK_LValue;
7813 return ResType;
7814 } else {
7815 VK = VK_RValue;
7816 return ResType.getUnqualifiedType();
7817 }
Reid Spencer5f016e22007-07-11 17:01:13 +00007818}
Fariborz Jahanianc4e1a682010-09-14 23:02:38 +00007819
7820
Anders Carlsson369dee42008-02-01 07:15:58 +00007821/// getPrimaryDecl - Helper function for CheckAddressOfOperand().
Reid Spencer5f016e22007-07-11 17:01:13 +00007822/// This routine allows us to typecheck complex/recursive expressions
Daniel Dunbar1e76ce62008-08-04 20:02:37 +00007823/// where the declaration is needed for type checking. We only need to
7824/// handle cases when the expression references a function designator
7825/// or is an lvalue. Here are some examples:
7826/// - &(x) => x
7827/// - &*****f => f for f a function designator.
7828/// - &s.xx => s
7829/// - &s.zz[1].yy -> s, if zz is an array
7830/// - *(x + 1) -> x, if x is an array
7831/// - &"123"[2] -> 0
7832/// - & __real__ x -> x
John McCall5808ce42011-02-03 08:15:49 +00007833static ValueDecl *getPrimaryDecl(Expr *E) {
Chris Lattnerf0467b32008-04-02 04:24:33 +00007834 switch (E->getStmtClass()) {
Reid Spencer5f016e22007-07-11 17:01:13 +00007835 case Stmt::DeclRefExprClass:
Chris Lattnerf0467b32008-04-02 04:24:33 +00007836 return cast<DeclRefExpr>(E)->getDecl();
Reid Spencer5f016e22007-07-11 17:01:13 +00007837 case Stmt::MemberExprClass:
Eli Friedman23d58ce2009-04-20 08:23:18 +00007838 // If this is an arrow operator, the address is an offset from
7839 // the base's value, so the object the base refers to is
7840 // irrelevant.
Chris Lattnerf0467b32008-04-02 04:24:33 +00007841 if (cast<MemberExpr>(E)->isArrow())
Chris Lattnerf82228f2007-11-16 17:46:48 +00007842 return 0;
Eli Friedman23d58ce2009-04-20 08:23:18 +00007843 // Otherwise, the expression refers to a part of the base
Chris Lattnerf0467b32008-04-02 04:24:33 +00007844 return getPrimaryDecl(cast<MemberExpr>(E)->getBase());
Anders Carlsson369dee42008-02-01 07:15:58 +00007845 case Stmt::ArraySubscriptExprClass: {
Mike Stump390b4cc2009-05-16 07:39:55 +00007846 // FIXME: This code shouldn't be necessary! We should catch the implicit
7847 // promotion of register arrays earlier.
Eli Friedman23d58ce2009-04-20 08:23:18 +00007848 Expr* Base = cast<ArraySubscriptExpr>(E)->getBase();
7849 if (ImplicitCastExpr* ICE = dyn_cast<ImplicitCastExpr>(Base)) {
7850 if (ICE->getSubExpr()->getType()->isArrayType())
7851 return getPrimaryDecl(ICE->getSubExpr());
7852 }
7853 return 0;
Anders Carlsson369dee42008-02-01 07:15:58 +00007854 }
Daniel Dunbar1e76ce62008-08-04 20:02:37 +00007855 case Stmt::UnaryOperatorClass: {
7856 UnaryOperator *UO = cast<UnaryOperator>(E);
Mike Stumpeed9cac2009-02-19 03:04:26 +00007857
Daniel Dunbar1e76ce62008-08-04 20:02:37 +00007858 switch(UO->getOpcode()) {
John McCall2de56d12010-08-25 11:45:40 +00007859 case UO_Real:
7860 case UO_Imag:
7861 case UO_Extension:
Daniel Dunbar1e76ce62008-08-04 20:02:37 +00007862 return getPrimaryDecl(UO->getSubExpr());
7863 default:
7864 return 0;
7865 }
7866 }
Reid Spencer5f016e22007-07-11 17:01:13 +00007867 case Stmt::ParenExprClass:
Chris Lattnerf0467b32008-04-02 04:24:33 +00007868 return getPrimaryDecl(cast<ParenExpr>(E)->getSubExpr());
Chris Lattnerf82228f2007-11-16 17:46:48 +00007869 case Stmt::ImplicitCastExprClass:
Eli Friedman23d58ce2009-04-20 08:23:18 +00007870 // If the result of an implicit cast is an l-value, we care about
7871 // the sub-expression; otherwise, the result here doesn't matter.
Chris Lattnerf0467b32008-04-02 04:24:33 +00007872 return getPrimaryDecl(cast<ImplicitCastExpr>(E)->getSubExpr());
Reid Spencer5f016e22007-07-11 17:01:13 +00007873 default:
7874 return 0;
7875 }
7876}
7877
Richard Trieu5520f232011-09-07 21:46:33 +00007878namespace {
7879 enum {
7880 AO_Bit_Field = 0,
7881 AO_Vector_Element = 1,
7882 AO_Property_Expansion = 2,
7883 AO_Register_Variable = 3,
7884 AO_No_Error = 4
7885 };
7886}
Richard Trieu09a26ad2011-09-02 00:47:55 +00007887/// \brief Diagnose invalid operand for address of operations.
7888///
7889/// \param Type The type of operand which cannot have its address taken.
Richard Trieu09a26ad2011-09-02 00:47:55 +00007890static void diagnoseAddressOfInvalidType(Sema &S, SourceLocation Loc,
7891 Expr *E, unsigned Type) {
7892 S.Diag(Loc, diag::err_typecheck_address_of) << Type << E->getSourceRange();
7893}
7894
Reid Spencer5f016e22007-07-11 17:01:13 +00007895/// CheckAddressOfOperand - The operand of & must be either a function
Mike Stumpeed9cac2009-02-19 03:04:26 +00007896/// designator or an lvalue designating an object. If it is an lvalue, the
Reid Spencer5f016e22007-07-11 17:01:13 +00007897/// object cannot be declared with storage class register or be a bit field.
Mike Stumpeed9cac2009-02-19 03:04:26 +00007898/// Note: The usual conversions are *not* applied to the operand of the &
Reid Spencer5f016e22007-07-11 17:01:13 +00007899/// operator (C99 6.3.2.1p[2-4]), and its result is never an lvalue.
Mike Stumpeed9cac2009-02-19 03:04:26 +00007900/// In C++, the operand might be an overloaded function name, in which case
Douglas Gregor904eed32008-11-10 20:40:00 +00007901/// we allow the '&' but retain the overloaded-function type.
John McCall3c3b7f92011-10-25 17:37:35 +00007902static QualType CheckAddressOfOperand(Sema &S, ExprResult &OrigOp,
John McCall09431682010-11-18 19:01:18 +00007903 SourceLocation OpLoc) {
John McCall3c3b7f92011-10-25 17:37:35 +00007904 if (const BuiltinType *PTy = OrigOp.get()->getType()->getAsPlaceholderType()){
7905 if (PTy->getKind() == BuiltinType::Overload) {
7906 if (!isa<OverloadExpr>(OrigOp.get()->IgnoreParens())) {
7907 S.Diag(OpLoc, diag::err_typecheck_invalid_lvalue_addrof)
7908 << OrigOp.get()->getSourceRange();
7909 return QualType();
7910 }
7911
7912 return S.Context.OverloadTy;
7913 }
7914
7915 if (PTy->getKind() == BuiltinType::UnknownAny)
7916 return S.Context.UnknownAnyTy;
7917
7918 if (PTy->getKind() == BuiltinType::BoundMember) {
7919 S.Diag(OpLoc, diag::err_invalid_form_pointer_member_function)
7920 << OrigOp.get()->getSourceRange();
Douglas Gregor44efed02011-10-09 19:10:41 +00007921 return QualType();
7922 }
John McCall3c3b7f92011-10-25 17:37:35 +00007923
7924 OrigOp = S.CheckPlaceholderExpr(OrigOp.take());
7925 if (OrigOp.isInvalid()) return QualType();
John McCall864c0412011-04-26 20:42:42 +00007926 }
John McCall9c72c602010-08-27 09:08:28 +00007927
John McCall3c3b7f92011-10-25 17:37:35 +00007928 if (OrigOp.get()->isTypeDependent())
7929 return S.Context.DependentTy;
7930
7931 assert(!OrigOp.get()->getType()->isPlaceholderType());
John McCall2cd11fe2010-10-12 02:09:17 +00007932
John McCall9c72c602010-08-27 09:08:28 +00007933 // Make sure to ignore parentheses in subsequent checks
John McCall3c3b7f92011-10-25 17:37:35 +00007934 Expr *op = OrigOp.get()->IgnoreParens();
Douglas Gregor9103bb22008-12-17 22:52:20 +00007935
David Blaikie4e4d0842012-03-11 07:00:24 +00007936 if (S.getLangOpts().C99) {
Steve Naroff08f19672008-01-13 17:10:08 +00007937 // Implement C99-only parts of addressof rules.
7938 if (UnaryOperator* uOp = dyn_cast<UnaryOperator>(op)) {
John McCall2de56d12010-08-25 11:45:40 +00007939 if (uOp->getOpcode() == UO_Deref)
Steve Naroff08f19672008-01-13 17:10:08 +00007940 // Per C99 6.5.3.2, the address of a deref always returns a valid result
7941 // (assuming the deref expression is valid).
7942 return uOp->getSubExpr()->getType();
7943 }
7944 // Technically, there should be a check for array subscript
7945 // expressions here, but the result of one is always an lvalue anyway.
7946 }
John McCall5808ce42011-02-03 08:15:49 +00007947 ValueDecl *dcl = getPrimaryDecl(op);
John McCall7eb0a9e2010-11-24 05:12:34 +00007948 Expr::LValueClassification lval = op->ClassifyLValue(S.Context);
Richard Trieu5520f232011-09-07 21:46:33 +00007949 unsigned AddressOfError = AO_No_Error;
Nuno Lopes6b6609f2008-12-16 22:59:47 +00007950
Fariborz Jahanian077f4902011-03-26 19:48:30 +00007951 if (lval == Expr::LV_ClassTemporary) {
John McCall09431682010-11-18 19:01:18 +00007952 bool sfinae = S.isSFINAEContext();
7953 S.Diag(OpLoc, sfinae ? diag::err_typecheck_addrof_class_temporary
7954 : diag::ext_typecheck_addrof_class_temporary)
Douglas Gregore873fb72010-02-16 21:39:57 +00007955 << op->getType() << op->getSourceRange();
John McCall09431682010-11-18 19:01:18 +00007956 if (sfinae)
Douglas Gregore873fb72010-02-16 21:39:57 +00007957 return QualType();
John McCall9c72c602010-08-27 09:08:28 +00007958 } else if (isa<ObjCSelectorExpr>(op)) {
John McCall09431682010-11-18 19:01:18 +00007959 return S.Context.getPointerType(op->getType());
John McCall9c72c602010-08-27 09:08:28 +00007960 } else if (lval == Expr::LV_MemberFunction) {
7961 // If it's an instance method, make a member pointer.
7962 // The expression must have exactly the form &A::foo.
7963
7964 // If the underlying expression isn't a decl ref, give up.
7965 if (!isa<DeclRefExpr>(op)) {
John McCall09431682010-11-18 19:01:18 +00007966 S.Diag(OpLoc, diag::err_invalid_form_pointer_member_function)
John McCall3c3b7f92011-10-25 17:37:35 +00007967 << OrigOp.get()->getSourceRange();
John McCall9c72c602010-08-27 09:08:28 +00007968 return QualType();
7969 }
7970 DeclRefExpr *DRE = cast<DeclRefExpr>(op);
7971 CXXMethodDecl *MD = cast<CXXMethodDecl>(DRE->getDecl());
7972
7973 // The id-expression was parenthesized.
John McCall3c3b7f92011-10-25 17:37:35 +00007974 if (OrigOp.get() != DRE) {
John McCall09431682010-11-18 19:01:18 +00007975 S.Diag(OpLoc, diag::err_parens_pointer_member_function)
John McCall3c3b7f92011-10-25 17:37:35 +00007976 << OrigOp.get()->getSourceRange();
John McCall9c72c602010-08-27 09:08:28 +00007977
7978 // The method was named without a qualifier.
7979 } else if (!DRE->getQualifier()) {
John McCall09431682010-11-18 19:01:18 +00007980 S.Diag(OpLoc, diag::err_unqualified_pointer_member_function)
John McCall9c72c602010-08-27 09:08:28 +00007981 << op->getSourceRange();
7982 }
7983
John McCall09431682010-11-18 19:01:18 +00007984 return S.Context.getMemberPointerType(op->getType(),
7985 S.Context.getTypeDeclType(MD->getParent()).getTypePtr());
John McCall9c72c602010-08-27 09:08:28 +00007986 } else if (lval != Expr::LV_Valid && lval != Expr::LV_IncompleteVoidType) {
Eli Friedman441cf102009-05-16 23:27:50 +00007987 // C99 6.5.3.2p1
Eli Friedman23d58ce2009-04-20 08:23:18 +00007988 // The operand must be either an l-value or a function designator
Eli Friedman441cf102009-05-16 23:27:50 +00007989 if (!op->getType()->isFunctionType()) {
John McCall3c3b7f92011-10-25 17:37:35 +00007990 // Use a special diagnostic for loads from property references.
John McCall4b9c2d22011-11-06 09:01:30 +00007991 if (isa<PseudoObjectExpr>(op)) {
John McCall3c3b7f92011-10-25 17:37:35 +00007992 AddressOfError = AO_Property_Expansion;
7993 } else {
7994 // FIXME: emit more specific diag...
7995 S.Diag(OpLoc, diag::err_typecheck_invalid_lvalue_addrof)
7996 << op->getSourceRange();
7997 return QualType();
7998 }
Reid Spencer5f016e22007-07-11 17:01:13 +00007999 }
John McCall7eb0a9e2010-11-24 05:12:34 +00008000 } else if (op->getObjectKind() == OK_BitField) { // C99 6.5.3.2p1
Eli Friedman23d58ce2009-04-20 08:23:18 +00008001 // The operand cannot be a bit-field
Richard Trieu5520f232011-09-07 21:46:33 +00008002 AddressOfError = AO_Bit_Field;
John McCall7eb0a9e2010-11-24 05:12:34 +00008003 } else if (op->getObjectKind() == OK_VectorComponent) {
Eli Friedman23d58ce2009-04-20 08:23:18 +00008004 // The operand cannot be an element of a vector
Richard Trieu5520f232011-09-07 21:46:33 +00008005 AddressOfError = AO_Vector_Element;
Steve Naroffbcb2b612008-02-29 23:30:25 +00008006 } else if (dcl) { // C99 6.5.3.2p1
Mike Stumpeed9cac2009-02-19 03:04:26 +00008007 // We have an lvalue with a decl. Make sure the decl is not declared
Reid Spencer5f016e22007-07-11 17:01:13 +00008008 // with the register storage-class specifier.
8009 if (const VarDecl *vd = dyn_cast<VarDecl>(dcl)) {
Fariborz Jahanian4020f872010-08-24 22:21:48 +00008010 // in C++ it is not error to take address of a register
8011 // variable (c++03 7.1.1P3)
John McCalld931b082010-08-26 03:08:43 +00008012 if (vd->getStorageClass() == SC_Register &&
David Blaikie4e4d0842012-03-11 07:00:24 +00008013 !S.getLangOpts().CPlusPlus) {
Richard Trieu5520f232011-09-07 21:46:33 +00008014 AddressOfError = AO_Register_Variable;
Reid Spencer5f016e22007-07-11 17:01:13 +00008015 }
John McCallba135432009-11-21 08:51:07 +00008016 } else if (isa<FunctionTemplateDecl>(dcl)) {
John McCall09431682010-11-18 19:01:18 +00008017 return S.Context.OverloadTy;
John McCall5808ce42011-02-03 08:15:49 +00008018 } else if (isa<FieldDecl>(dcl) || isa<IndirectFieldDecl>(dcl)) {
Douglas Gregor29882052008-12-10 21:26:49 +00008019 // Okay: we can take the address of a field.
Sebastian Redlebc07d52009-02-03 20:19:35 +00008020 // Could be a pointer to member, though, if there is an explicit
8021 // scope qualifier for the class.
Douglas Gregora2813ce2009-10-23 18:54:35 +00008022 if (isa<DeclRefExpr>(op) && cast<DeclRefExpr>(op)->getQualifier()) {
Sebastian Redlebc07d52009-02-03 20:19:35 +00008023 DeclContext *Ctx = dcl->getDeclContext();
Anders Carlssonf9e48bd2009-07-08 21:45:58 +00008024 if (Ctx && Ctx->isRecord()) {
John McCall5808ce42011-02-03 08:15:49 +00008025 if (dcl->getType()->isReferenceType()) {
John McCall09431682010-11-18 19:01:18 +00008026 S.Diag(OpLoc,
8027 diag::err_cannot_form_pointer_to_member_of_reference_type)
John McCall5808ce42011-02-03 08:15:49 +00008028 << dcl->getDeclName() << dcl->getType();
Anders Carlssonf9e48bd2009-07-08 21:45:58 +00008029 return QualType();
8030 }
Mike Stump1eb44332009-09-09 15:08:12 +00008031
Argyrios Kyrtzidis0413db42011-01-31 07:04:29 +00008032 while (cast<RecordDecl>(Ctx)->isAnonymousStructOrUnion())
8033 Ctx = Ctx->getParent();
John McCall09431682010-11-18 19:01:18 +00008034 return S.Context.getMemberPointerType(op->getType(),
8035 S.Context.getTypeDeclType(cast<RecordDecl>(Ctx)).getTypePtr());
Anders Carlssonf9e48bd2009-07-08 21:45:58 +00008036 }
Sebastian Redlebc07d52009-02-03 20:19:35 +00008037 }
Eli Friedman7b2f51c2011-08-26 20:28:17 +00008038 } else if (!isa<FunctionDecl>(dcl) && !isa<NonTypeTemplateParmDecl>(dcl))
David Blaikieb219cfc2011-09-23 05:06:16 +00008039 llvm_unreachable("Unknown/unexpected decl type");
Reid Spencer5f016e22007-07-11 17:01:13 +00008040 }
Sebastian Redl33b399a2009-02-04 21:23:32 +00008041
Richard Trieu5520f232011-09-07 21:46:33 +00008042 if (AddressOfError != AO_No_Error) {
8043 diagnoseAddressOfInvalidType(S, OpLoc, op, AddressOfError);
8044 return QualType();
8045 }
8046
Eli Friedman441cf102009-05-16 23:27:50 +00008047 if (lval == Expr::LV_IncompleteVoidType) {
8048 // Taking the address of a void variable is technically illegal, but we
8049 // allow it in cases which are otherwise valid.
8050 // Example: "extern void x; void* y = &x;".
John McCall09431682010-11-18 19:01:18 +00008051 S.Diag(OpLoc, diag::ext_typecheck_addrof_void) << op->getSourceRange();
Eli Friedman441cf102009-05-16 23:27:50 +00008052 }
8053
Reid Spencer5f016e22007-07-11 17:01:13 +00008054 // If the operand has type "type", the result has type "pointer to type".
Douglas Gregor8f70ddb2010-07-29 16:05:45 +00008055 if (op->getType()->isObjCObjectType())
John McCall09431682010-11-18 19:01:18 +00008056 return S.Context.getObjCObjectPointerType(op->getType());
8057 return S.Context.getPointerType(op->getType());
Reid Spencer5f016e22007-07-11 17:01:13 +00008058}
8059
Chris Lattnerfd79a9d2010-07-05 19:17:26 +00008060/// CheckIndirectionOperand - Type check unary indirection (prefix '*').
John McCall09431682010-11-18 19:01:18 +00008061static QualType CheckIndirectionOperand(Sema &S, Expr *Op, ExprValueKind &VK,
8062 SourceLocation OpLoc) {
Sebastian Redl28507842009-02-26 14:39:58 +00008063 if (Op->isTypeDependent())
John McCall09431682010-11-18 19:01:18 +00008064 return S.Context.DependentTy;
Sebastian Redl28507842009-02-26 14:39:58 +00008065
John Wiegley429bb272011-04-08 18:41:53 +00008066 ExprResult ConvResult = S.UsualUnaryConversions(Op);
8067 if (ConvResult.isInvalid())
8068 return QualType();
8069 Op = ConvResult.take();
Chris Lattnerfd79a9d2010-07-05 19:17:26 +00008070 QualType OpTy = Op->getType();
8071 QualType Result;
Argyrios Kyrtzidisf4bbbf02011-05-02 18:21:19 +00008072
8073 if (isa<CXXReinterpretCastExpr>(Op)) {
8074 QualType OpOrigType = Op->IgnoreParenCasts()->getType();
8075 S.CheckCompatibleReinterpretCast(OpOrigType, OpTy, /*IsDereference*/true,
8076 Op->getSourceRange());
8077 }
8078
Chris Lattnerfd79a9d2010-07-05 19:17:26 +00008079 // Note that per both C89 and C99, indirection is always legal, even if OpTy
8080 // is an incomplete type or void. It would be possible to warn about
8081 // dereferencing a void pointer, but it's completely well-defined, and such a
8082 // warning is unlikely to catch any mistakes.
8083 if (const PointerType *PT = OpTy->getAs<PointerType>())
8084 Result = PT->getPointeeType();
8085 else if (const ObjCObjectPointerType *OPT =
8086 OpTy->getAs<ObjCObjectPointerType>())
8087 Result = OPT->getPointeeType();
John McCall2cd11fe2010-10-12 02:09:17 +00008088 else {
John McCallfb8721c2011-04-10 19:13:55 +00008089 ExprResult PR = S.CheckPlaceholderExpr(Op);
John McCall2cd11fe2010-10-12 02:09:17 +00008090 if (PR.isInvalid()) return QualType();
John McCall09431682010-11-18 19:01:18 +00008091 if (PR.take() != Op)
8092 return CheckIndirectionOperand(S, PR.take(), VK, OpLoc);
John McCall2cd11fe2010-10-12 02:09:17 +00008093 }
Mike Stumpeed9cac2009-02-19 03:04:26 +00008094
Chris Lattnerfd79a9d2010-07-05 19:17:26 +00008095 if (Result.isNull()) {
John McCall09431682010-11-18 19:01:18 +00008096 S.Diag(OpLoc, diag::err_typecheck_indirection_requires_pointer)
Chris Lattnerfd79a9d2010-07-05 19:17:26 +00008097 << OpTy << Op->getSourceRange();
8098 return QualType();
8099 }
John McCall09431682010-11-18 19:01:18 +00008100
8101 // Dereferences are usually l-values...
8102 VK = VK_LValue;
8103
8104 // ...except that certain expressions are never l-values in C.
David Blaikie4e4d0842012-03-11 07:00:24 +00008105 if (!S.getLangOpts().CPlusPlus && Result.isCForbiddenLValueType())
John McCall09431682010-11-18 19:01:18 +00008106 VK = VK_RValue;
Chris Lattnerfd79a9d2010-07-05 19:17:26 +00008107
8108 return Result;
Reid Spencer5f016e22007-07-11 17:01:13 +00008109}
8110
John McCall2de56d12010-08-25 11:45:40 +00008111static inline BinaryOperatorKind ConvertTokenKindToBinaryOpcode(
Reid Spencer5f016e22007-07-11 17:01:13 +00008112 tok::TokenKind Kind) {
John McCall2de56d12010-08-25 11:45:40 +00008113 BinaryOperatorKind Opc;
Reid Spencer5f016e22007-07-11 17:01:13 +00008114 switch (Kind) {
David Blaikieb219cfc2011-09-23 05:06:16 +00008115 default: llvm_unreachable("Unknown binop!");
John McCall2de56d12010-08-25 11:45:40 +00008116 case tok::periodstar: Opc = BO_PtrMemD; break;
8117 case tok::arrowstar: Opc = BO_PtrMemI; break;
8118 case tok::star: Opc = BO_Mul; break;
8119 case tok::slash: Opc = BO_Div; break;
8120 case tok::percent: Opc = BO_Rem; break;
8121 case tok::plus: Opc = BO_Add; break;
8122 case tok::minus: Opc = BO_Sub; break;
8123 case tok::lessless: Opc = BO_Shl; break;
8124 case tok::greatergreater: Opc = BO_Shr; break;
8125 case tok::lessequal: Opc = BO_LE; break;
8126 case tok::less: Opc = BO_LT; break;
8127 case tok::greaterequal: Opc = BO_GE; break;
8128 case tok::greater: Opc = BO_GT; break;
8129 case tok::exclaimequal: Opc = BO_NE; break;
8130 case tok::equalequal: Opc = BO_EQ; break;
8131 case tok::amp: Opc = BO_And; break;
8132 case tok::caret: Opc = BO_Xor; break;
8133 case tok::pipe: Opc = BO_Or; break;
8134 case tok::ampamp: Opc = BO_LAnd; break;
8135 case tok::pipepipe: Opc = BO_LOr; break;
8136 case tok::equal: Opc = BO_Assign; break;
8137 case tok::starequal: Opc = BO_MulAssign; break;
8138 case tok::slashequal: Opc = BO_DivAssign; break;
8139 case tok::percentequal: Opc = BO_RemAssign; break;
8140 case tok::plusequal: Opc = BO_AddAssign; break;
8141 case tok::minusequal: Opc = BO_SubAssign; break;
8142 case tok::lesslessequal: Opc = BO_ShlAssign; break;
8143 case tok::greatergreaterequal: Opc = BO_ShrAssign; break;
8144 case tok::ampequal: Opc = BO_AndAssign; break;
8145 case tok::caretequal: Opc = BO_XorAssign; break;
8146 case tok::pipeequal: Opc = BO_OrAssign; break;
8147 case tok::comma: Opc = BO_Comma; break;
Reid Spencer5f016e22007-07-11 17:01:13 +00008148 }
8149 return Opc;
8150}
8151
John McCall2de56d12010-08-25 11:45:40 +00008152static inline UnaryOperatorKind ConvertTokenKindToUnaryOpcode(
Reid Spencer5f016e22007-07-11 17:01:13 +00008153 tok::TokenKind Kind) {
John McCall2de56d12010-08-25 11:45:40 +00008154 UnaryOperatorKind Opc;
Reid Spencer5f016e22007-07-11 17:01:13 +00008155 switch (Kind) {
David Blaikieb219cfc2011-09-23 05:06:16 +00008156 default: llvm_unreachable("Unknown unary op!");
John McCall2de56d12010-08-25 11:45:40 +00008157 case tok::plusplus: Opc = UO_PreInc; break;
8158 case tok::minusminus: Opc = UO_PreDec; break;
8159 case tok::amp: Opc = UO_AddrOf; break;
8160 case tok::star: Opc = UO_Deref; break;
8161 case tok::plus: Opc = UO_Plus; break;
8162 case tok::minus: Opc = UO_Minus; break;
8163 case tok::tilde: Opc = UO_Not; break;
8164 case tok::exclaim: Opc = UO_LNot; break;
8165 case tok::kw___real: Opc = UO_Real; break;
8166 case tok::kw___imag: Opc = UO_Imag; break;
8167 case tok::kw___extension__: Opc = UO_Extension; break;
Reid Spencer5f016e22007-07-11 17:01:13 +00008168 }
8169 return Opc;
8170}
8171
Chandler Carruth9f7a6ee2011-01-04 06:52:15 +00008172/// DiagnoseSelfAssignment - Emits a warning if a value is assigned to itself.
8173/// This warning is only emitted for builtin assignment operations. It is also
8174/// suppressed in the event of macro expansions.
Richard Trieu268942b2011-09-07 01:33:52 +00008175static void DiagnoseSelfAssignment(Sema &S, Expr *LHSExpr, Expr *RHSExpr,
Chandler Carruth9f7a6ee2011-01-04 06:52:15 +00008176 SourceLocation OpLoc) {
8177 if (!S.ActiveTemplateInstantiations.empty())
8178 return;
8179 if (OpLoc.isInvalid() || OpLoc.isMacroID())
8180 return;
Richard Trieu268942b2011-09-07 01:33:52 +00008181 LHSExpr = LHSExpr->IgnoreParenImpCasts();
8182 RHSExpr = RHSExpr->IgnoreParenImpCasts();
8183 const DeclRefExpr *LHSDeclRef = dyn_cast<DeclRefExpr>(LHSExpr);
8184 const DeclRefExpr *RHSDeclRef = dyn_cast<DeclRefExpr>(RHSExpr);
8185 if (!LHSDeclRef || !RHSDeclRef ||
8186 LHSDeclRef->getLocation().isMacroID() ||
8187 RHSDeclRef->getLocation().isMacroID())
Chandler Carruth9f7a6ee2011-01-04 06:52:15 +00008188 return;
Richard Trieu268942b2011-09-07 01:33:52 +00008189 const ValueDecl *LHSDecl =
8190 cast<ValueDecl>(LHSDeclRef->getDecl()->getCanonicalDecl());
8191 const ValueDecl *RHSDecl =
8192 cast<ValueDecl>(RHSDeclRef->getDecl()->getCanonicalDecl());
8193 if (LHSDecl != RHSDecl)
Chandler Carruth9f7a6ee2011-01-04 06:52:15 +00008194 return;
Richard Trieu268942b2011-09-07 01:33:52 +00008195 if (LHSDecl->getType().isVolatileQualified())
Chandler Carruth9f7a6ee2011-01-04 06:52:15 +00008196 return;
Richard Trieu268942b2011-09-07 01:33:52 +00008197 if (const ReferenceType *RefTy = LHSDecl->getType()->getAs<ReferenceType>())
Chandler Carruth9f7a6ee2011-01-04 06:52:15 +00008198 if (RefTy->getPointeeType().isVolatileQualified())
8199 return;
8200
8201 S.Diag(OpLoc, diag::warn_self_assignment)
Richard Trieu268942b2011-09-07 01:33:52 +00008202 << LHSDeclRef->getType()
8203 << LHSExpr->getSourceRange() << RHSExpr->getSourceRange();
Chandler Carruth9f7a6ee2011-01-04 06:52:15 +00008204}
8205
Douglas Gregoreaebc752008-11-06 23:29:22 +00008206/// CreateBuiltinBinOp - Creates a new built-in binary operation with
8207/// operator @p Opc at location @c TokLoc. This routine only supports
8208/// built-in operations; ActOnBinOp handles overloaded operators.
John McCall60d7b3a2010-08-24 06:29:42 +00008209ExprResult Sema::CreateBuiltinBinOp(SourceLocation OpLoc,
Argyrios Kyrtzidisb1fa3dc2011-01-05 20:09:36 +00008210 BinaryOperatorKind Opc,
Richard Trieu78ea78b2011-09-07 01:49:20 +00008211 Expr *LHSExpr, Expr *RHSExpr) {
David Blaikie4e4d0842012-03-11 07:00:24 +00008212 if (getLangOpts().CPlusPlus0x && isa<InitListExpr>(RHSExpr)) {
Sebastian Redl0d8ab2e2012-02-27 20:34:02 +00008213 // The syntax only allows initializer lists on the RHS of assignment,
8214 // so we don't need to worry about accepting invalid code for
8215 // non-assignment operators.
8216 // C++11 5.17p9:
8217 // The meaning of x = {v} [...] is that of x = T(v) [...]. The meaning
8218 // of x = {} is x = T().
8219 InitializationKind Kind =
8220 InitializationKind::CreateDirectList(RHSExpr->getLocStart());
8221 InitializedEntity Entity =
8222 InitializedEntity::InitializeTemporary(LHSExpr->getType());
8223 InitializationSequence InitSeq(*this, Entity, Kind, &RHSExpr, 1);
Benjamin Kramer5354e772012-08-23 23:38:35 +00008224 ExprResult Init = InitSeq.Perform(*this, Entity, Kind, RHSExpr);
Sebastian Redl0d8ab2e2012-02-27 20:34:02 +00008225 if (Init.isInvalid())
8226 return Init;
8227 RHSExpr = Init.take();
8228 }
8229
Richard Trieu78ea78b2011-09-07 01:49:20 +00008230 ExprResult LHS = Owned(LHSExpr), RHS = Owned(RHSExpr);
Eli Friedmanab3a8522009-03-28 01:22:36 +00008231 QualType ResultTy; // Result type of the binary operator.
Eli Friedmanab3a8522009-03-28 01:22:36 +00008232 // The following two variables are used for compound assignment operators
8233 QualType CompLHSTy; // Type of LHS after promotions for computation
8234 QualType CompResultTy; // Type of computation result
John McCallf89e55a2010-11-18 06:31:45 +00008235 ExprValueKind VK = VK_RValue;
8236 ExprObjectKind OK = OK_Ordinary;
Douglas Gregoreaebc752008-11-06 23:29:22 +00008237
8238 switch (Opc) {
John McCall2de56d12010-08-25 11:45:40 +00008239 case BO_Assign:
Richard Trieu78ea78b2011-09-07 01:49:20 +00008240 ResultTy = CheckAssignmentOperands(LHS.get(), RHS, OpLoc, QualType());
David Blaikie4e4d0842012-03-11 07:00:24 +00008241 if (getLangOpts().CPlusPlus &&
Richard Trieu78ea78b2011-09-07 01:49:20 +00008242 LHS.get()->getObjectKind() != OK_ObjCProperty) {
8243 VK = LHS.get()->getValueKind();
8244 OK = LHS.get()->getObjectKind();
John McCallf89e55a2010-11-18 06:31:45 +00008245 }
Chandler Carruth9f7a6ee2011-01-04 06:52:15 +00008246 if (!ResultTy.isNull())
Richard Trieu78ea78b2011-09-07 01:49:20 +00008247 DiagnoseSelfAssignment(*this, LHS.get(), RHS.get(), OpLoc);
Douglas Gregoreaebc752008-11-06 23:29:22 +00008248 break;
John McCall2de56d12010-08-25 11:45:40 +00008249 case BO_PtrMemD:
8250 case BO_PtrMemI:
Richard Trieu78ea78b2011-09-07 01:49:20 +00008251 ResultTy = CheckPointerToMemberOperands(LHS, RHS, VK, OpLoc,
John McCall2de56d12010-08-25 11:45:40 +00008252 Opc == BO_PtrMemI);
Sebastian Redl22460502009-02-07 00:15:38 +00008253 break;
John McCall2de56d12010-08-25 11:45:40 +00008254 case BO_Mul:
8255 case BO_Div:
Richard Trieu78ea78b2011-09-07 01:49:20 +00008256 ResultTy = CheckMultiplyDivideOperands(LHS, RHS, OpLoc, false,
John McCall2de56d12010-08-25 11:45:40 +00008257 Opc == BO_Div);
Douglas Gregoreaebc752008-11-06 23:29:22 +00008258 break;
John McCall2de56d12010-08-25 11:45:40 +00008259 case BO_Rem:
Richard Trieu78ea78b2011-09-07 01:49:20 +00008260 ResultTy = CheckRemainderOperands(LHS, RHS, OpLoc);
Douglas Gregoreaebc752008-11-06 23:29:22 +00008261 break;
John McCall2de56d12010-08-25 11:45:40 +00008262 case BO_Add:
Nico Weber1cb2d742012-03-02 22:01:22 +00008263 ResultTy = CheckAdditionOperands(LHS, RHS, OpLoc, Opc);
Douglas Gregoreaebc752008-11-06 23:29:22 +00008264 break;
John McCall2de56d12010-08-25 11:45:40 +00008265 case BO_Sub:
Richard Trieu78ea78b2011-09-07 01:49:20 +00008266 ResultTy = CheckSubtractionOperands(LHS, RHS, OpLoc);
Douglas Gregoreaebc752008-11-06 23:29:22 +00008267 break;
John McCall2de56d12010-08-25 11:45:40 +00008268 case BO_Shl:
8269 case BO_Shr:
Richard Trieu78ea78b2011-09-07 01:49:20 +00008270 ResultTy = CheckShiftOperands(LHS, RHS, OpLoc, Opc);
Douglas Gregoreaebc752008-11-06 23:29:22 +00008271 break;
John McCall2de56d12010-08-25 11:45:40 +00008272 case BO_LE:
8273 case BO_LT:
8274 case BO_GE:
8275 case BO_GT:
Richard Trieu78ea78b2011-09-07 01:49:20 +00008276 ResultTy = CheckCompareOperands(LHS, RHS, OpLoc, Opc, true);
Douglas Gregoreaebc752008-11-06 23:29:22 +00008277 break;
John McCall2de56d12010-08-25 11:45:40 +00008278 case BO_EQ:
8279 case BO_NE:
Richard Trieu78ea78b2011-09-07 01:49:20 +00008280 ResultTy = CheckCompareOperands(LHS, RHS, OpLoc, Opc, false);
Douglas Gregoreaebc752008-11-06 23:29:22 +00008281 break;
John McCall2de56d12010-08-25 11:45:40 +00008282 case BO_And:
8283 case BO_Xor:
8284 case BO_Or:
Richard Trieu78ea78b2011-09-07 01:49:20 +00008285 ResultTy = CheckBitwiseOperands(LHS, RHS, OpLoc);
Douglas Gregoreaebc752008-11-06 23:29:22 +00008286 break;
John McCall2de56d12010-08-25 11:45:40 +00008287 case BO_LAnd:
8288 case BO_LOr:
Richard Trieu78ea78b2011-09-07 01:49:20 +00008289 ResultTy = CheckLogicalOperands(LHS, RHS, OpLoc, Opc);
Douglas Gregoreaebc752008-11-06 23:29:22 +00008290 break;
John McCall2de56d12010-08-25 11:45:40 +00008291 case BO_MulAssign:
8292 case BO_DivAssign:
Richard Trieu78ea78b2011-09-07 01:49:20 +00008293 CompResultTy = CheckMultiplyDivideOperands(LHS, RHS, OpLoc, true,
John McCallf89e55a2010-11-18 06:31:45 +00008294 Opc == BO_DivAssign);
Eli Friedmanab3a8522009-03-28 01:22:36 +00008295 CompLHSTy = CompResultTy;
Richard Trieu78ea78b2011-09-07 01:49:20 +00008296 if (!CompResultTy.isNull() && !LHS.isInvalid() && !RHS.isInvalid())
8297 ResultTy = CheckAssignmentOperands(LHS.get(), RHS, OpLoc, CompResultTy);
Douglas Gregoreaebc752008-11-06 23:29:22 +00008298 break;
John McCall2de56d12010-08-25 11:45:40 +00008299 case BO_RemAssign:
Richard Trieu78ea78b2011-09-07 01:49:20 +00008300 CompResultTy = CheckRemainderOperands(LHS, RHS, OpLoc, true);
Eli Friedmanab3a8522009-03-28 01:22:36 +00008301 CompLHSTy = CompResultTy;
Richard Trieu78ea78b2011-09-07 01:49:20 +00008302 if (!CompResultTy.isNull() && !LHS.isInvalid() && !RHS.isInvalid())
8303 ResultTy = CheckAssignmentOperands(LHS.get(), RHS, OpLoc, CompResultTy);
Douglas Gregoreaebc752008-11-06 23:29:22 +00008304 break;
John McCall2de56d12010-08-25 11:45:40 +00008305 case BO_AddAssign:
Nico Weber1cb2d742012-03-02 22:01:22 +00008306 CompResultTy = CheckAdditionOperands(LHS, RHS, OpLoc, Opc, &CompLHSTy);
Richard Trieu78ea78b2011-09-07 01:49:20 +00008307 if (!CompResultTy.isNull() && !LHS.isInvalid() && !RHS.isInvalid())
8308 ResultTy = CheckAssignmentOperands(LHS.get(), RHS, OpLoc, CompResultTy);
Douglas Gregoreaebc752008-11-06 23:29:22 +00008309 break;
John McCall2de56d12010-08-25 11:45:40 +00008310 case BO_SubAssign:
Richard Trieu78ea78b2011-09-07 01:49:20 +00008311 CompResultTy = CheckSubtractionOperands(LHS, RHS, OpLoc, &CompLHSTy);
8312 if (!CompResultTy.isNull() && !LHS.isInvalid() && !RHS.isInvalid())
8313 ResultTy = CheckAssignmentOperands(LHS.get(), RHS, OpLoc, CompResultTy);
Douglas Gregoreaebc752008-11-06 23:29:22 +00008314 break;
John McCall2de56d12010-08-25 11:45:40 +00008315 case BO_ShlAssign:
8316 case BO_ShrAssign:
Richard Trieu78ea78b2011-09-07 01:49:20 +00008317 CompResultTy = CheckShiftOperands(LHS, RHS, OpLoc, Opc, true);
Eli Friedmanab3a8522009-03-28 01:22:36 +00008318 CompLHSTy = CompResultTy;
Richard Trieu78ea78b2011-09-07 01:49:20 +00008319 if (!CompResultTy.isNull() && !LHS.isInvalid() && !RHS.isInvalid())
8320 ResultTy = CheckAssignmentOperands(LHS.get(), RHS, OpLoc, CompResultTy);
Douglas Gregoreaebc752008-11-06 23:29:22 +00008321 break;
John McCall2de56d12010-08-25 11:45:40 +00008322 case BO_AndAssign:
8323 case BO_XorAssign:
8324 case BO_OrAssign:
Richard Trieu78ea78b2011-09-07 01:49:20 +00008325 CompResultTy = CheckBitwiseOperands(LHS, RHS, OpLoc, true);
Eli Friedmanab3a8522009-03-28 01:22:36 +00008326 CompLHSTy = CompResultTy;
Richard Trieu78ea78b2011-09-07 01:49:20 +00008327 if (!CompResultTy.isNull() && !LHS.isInvalid() && !RHS.isInvalid())
8328 ResultTy = CheckAssignmentOperands(LHS.get(), RHS, OpLoc, CompResultTy);
Douglas Gregoreaebc752008-11-06 23:29:22 +00008329 break;
John McCall2de56d12010-08-25 11:45:40 +00008330 case BO_Comma:
Richard Trieu78ea78b2011-09-07 01:49:20 +00008331 ResultTy = CheckCommaOperands(*this, LHS, RHS, OpLoc);
David Blaikie4e4d0842012-03-11 07:00:24 +00008332 if (getLangOpts().CPlusPlus && !RHS.isInvalid()) {
Richard Trieu78ea78b2011-09-07 01:49:20 +00008333 VK = RHS.get()->getValueKind();
8334 OK = RHS.get()->getObjectKind();
John McCallf89e55a2010-11-18 06:31:45 +00008335 }
Douglas Gregoreaebc752008-11-06 23:29:22 +00008336 break;
8337 }
Richard Trieu78ea78b2011-09-07 01:49:20 +00008338 if (ResultTy.isNull() || LHS.isInvalid() || RHS.isInvalid())
Sebastian Redlb8a6aca2009-01-19 22:31:54 +00008339 return ExprError();
Kaelyn Uhraind6c88652011-08-05 23:18:04 +00008340
8341 // Check for array bounds violations for both sides of the BinaryOperator
Richard Trieu78ea78b2011-09-07 01:49:20 +00008342 CheckArrayAccess(LHS.get());
8343 CheckArrayAccess(RHS.get());
Kaelyn Uhraind6c88652011-08-05 23:18:04 +00008344
Eli Friedmanab3a8522009-03-28 01:22:36 +00008345 if (CompResultTy.isNull())
Richard Trieu78ea78b2011-09-07 01:49:20 +00008346 return Owned(new (Context) BinaryOperator(LHS.take(), RHS.take(), Opc,
John Wiegley429bb272011-04-08 18:41:53 +00008347 ResultTy, VK, OK, OpLoc));
David Blaikie4e4d0842012-03-11 07:00:24 +00008348 if (getLangOpts().CPlusPlus && LHS.get()->getObjectKind() !=
Richard Trieu67e29332011-08-02 04:35:43 +00008349 OK_ObjCProperty) {
John McCallf89e55a2010-11-18 06:31:45 +00008350 VK = VK_LValue;
Richard Trieu78ea78b2011-09-07 01:49:20 +00008351 OK = LHS.get()->getObjectKind();
John McCallf89e55a2010-11-18 06:31:45 +00008352 }
Richard Trieu78ea78b2011-09-07 01:49:20 +00008353 return Owned(new (Context) CompoundAssignOperator(LHS.take(), RHS.take(), Opc,
John Wiegley429bb272011-04-08 18:41:53 +00008354 ResultTy, VK, OK, CompLHSTy,
John McCallf89e55a2010-11-18 06:31:45 +00008355 CompResultTy, OpLoc));
Douglas Gregoreaebc752008-11-06 23:29:22 +00008356}
8357
Sebastian Redlaee3c932009-10-27 12:10:02 +00008358/// DiagnoseBitwisePrecedence - Emit a warning when bitwise and comparison
8359/// operators are mixed in a way that suggests that the programmer forgot that
8360/// comparison operators have higher precedence. The most typical example of
8361/// such code is "flags & 0x0020 != 0", which is equivalent to "flags & 1".
John McCall2de56d12010-08-25 11:45:40 +00008362static void DiagnoseBitwisePrecedence(Sema &Self, BinaryOperatorKind Opc,
Richard Trieu78ea78b2011-09-07 01:49:20 +00008363 SourceLocation OpLoc, Expr *LHSExpr,
8364 Expr *RHSExpr) {
Sebastian Redlaee3c932009-10-27 12:10:02 +00008365 typedef BinaryOperator BinOp;
Richard Trieu78ea78b2011-09-07 01:49:20 +00008366 BinOp::Opcode LHSopc = static_cast<BinOp::Opcode>(-1),
8367 RHSopc = static_cast<BinOp::Opcode>(-1);
8368 if (BinOp *BO = dyn_cast<BinOp>(LHSExpr))
8369 LHSopc = BO->getOpcode();
8370 if (BinOp *BO = dyn_cast<BinOp>(RHSExpr))
8371 RHSopc = BO->getOpcode();
Sebastian Redl9e1d29b2009-10-26 15:24:15 +00008372
8373 // Subs are not binary operators.
Richard Trieu78ea78b2011-09-07 01:49:20 +00008374 if (LHSopc == -1 && RHSopc == -1)
Sebastian Redl9e1d29b2009-10-26 15:24:15 +00008375 return;
8376
8377 // Bitwise operations are sometimes used as eager logical ops.
8378 // Don't diagnose this.
Richard Trieu78ea78b2011-09-07 01:49:20 +00008379 if ((BinOp::isComparisonOp(LHSopc) || BinOp::isBitwiseOp(LHSopc)) &&
8380 (BinOp::isComparisonOp(RHSopc) || BinOp::isBitwiseOp(RHSopc)))
Sebastian Redl9e1d29b2009-10-26 15:24:15 +00008381 return;
8382
Richard Trieu78ea78b2011-09-07 01:49:20 +00008383 bool isLeftComp = BinOp::isComparisonOp(LHSopc);
8384 bool isRightComp = BinOp::isComparisonOp(RHSopc);
Richard Trieu70979d42011-08-10 22:41:34 +00008385 if (!isLeftComp && !isRightComp) return;
8386
Richard Trieu78ea78b2011-09-07 01:49:20 +00008387 SourceRange DiagRange = isLeftComp ? SourceRange(LHSExpr->getLocStart(),
8388 OpLoc)
8389 : SourceRange(OpLoc, RHSExpr->getLocEnd());
8390 std::string OpStr = isLeftComp ? BinOp::getOpcodeStr(LHSopc)
8391 : BinOp::getOpcodeStr(RHSopc);
Richard Trieu70979d42011-08-10 22:41:34 +00008392 SourceRange ParensRange = isLeftComp ?
Richard Trieu78ea78b2011-09-07 01:49:20 +00008393 SourceRange(cast<BinOp>(LHSExpr)->getRHS()->getLocStart(),
8394 RHSExpr->getLocEnd())
8395 : SourceRange(LHSExpr->getLocStart(),
8396 cast<BinOp>(RHSExpr)->getLHS()->getLocStart());
Richard Trieu70979d42011-08-10 22:41:34 +00008397
8398 Self.Diag(OpLoc, diag::warn_precedence_bitwise_rel)
8399 << DiagRange << BinOp::getOpcodeStr(Opc) << OpStr;
8400 SuggestParentheses(Self, OpLoc,
8401 Self.PDiag(diag::note_precedence_bitwise_silence) << OpStr,
Nico Weber40e29992012-06-03 07:07:00 +00008402 (isLeftComp ? LHSExpr : RHSExpr)->getSourceRange());
Richard Trieu70979d42011-08-10 22:41:34 +00008403 SuggestParentheses(Self, OpLoc,
8404 Self.PDiag(diag::note_precedence_bitwise_first) << BinOp::getOpcodeStr(Opc),
8405 ParensRange);
Sebastian Redl9e1d29b2009-10-26 15:24:15 +00008406}
8407
Argyrios Kyrtzidis33f46e22011-06-20 18:41:26 +00008408/// \brief It accepts a '&' expr that is inside a '|' one.
8409/// Emit a diagnostic together with a fixit hint that wraps the '&' expression
8410/// in parentheses.
8411static void
8412EmitDiagnosticForBitwiseAndInBitwiseOr(Sema &Self, SourceLocation OpLoc,
8413 BinaryOperator *Bop) {
8414 assert(Bop->getOpcode() == BO_And);
8415 Self.Diag(Bop->getOperatorLoc(), diag::warn_bitwise_and_in_bitwise_or)
8416 << Bop->getSourceRange() << OpLoc;
8417 SuggestParentheses(Self, Bop->getOperatorLoc(),
8418 Self.PDiag(diag::note_bitwise_and_in_bitwise_or_silence),
8419 Bop->getSourceRange());
8420}
8421
Argyrios Kyrtzidis567bb712010-11-17 18:26:36 +00008422/// \brief It accepts a '&&' expr that is inside a '||' one.
8423/// Emit a diagnostic together with a fixit hint that wraps the '&&' expression
8424/// in parentheses.
8425static void
8426EmitDiagnosticForLogicalAndInLogicalOr(Sema &Self, SourceLocation OpLoc,
Argyrios Kyrtzidisa61aedc2011-04-22 19:16:27 +00008427 BinaryOperator *Bop) {
8428 assert(Bop->getOpcode() == BO_LAnd);
Chandler Carruthf0b60d62011-06-16 01:05:14 +00008429 Self.Diag(Bop->getOperatorLoc(), diag::warn_logical_and_in_logical_or)
8430 << Bop->getSourceRange() << OpLoc;
Argyrios Kyrtzidisa61aedc2011-04-22 19:16:27 +00008431 SuggestParentheses(Self, Bop->getOperatorLoc(),
Argyrios Kyrtzidis567bb712010-11-17 18:26:36 +00008432 Self.PDiag(diag::note_logical_and_in_logical_or_silence),
Chandler Carruthf0b60d62011-06-16 01:05:14 +00008433 Bop->getSourceRange());
Argyrios Kyrtzidis567bb712010-11-17 18:26:36 +00008434}
8435
8436/// \brief Returns true if the given expression can be evaluated as a constant
8437/// 'true'.
8438static bool EvaluatesAsTrue(Sema &S, Expr *E) {
8439 bool Res;
8440 return E->EvaluateAsBooleanCondition(Res, S.getASTContext()) && Res;
8441}
8442
Argyrios Kyrtzidis47d512c2010-11-17 19:18:19 +00008443/// \brief Returns true if the given expression can be evaluated as a constant
8444/// 'false'.
8445static bool EvaluatesAsFalse(Sema &S, Expr *E) {
8446 bool Res;
8447 return E->EvaluateAsBooleanCondition(Res, S.getASTContext()) && !Res;
8448}
8449
Argyrios Kyrtzidis567bb712010-11-17 18:26:36 +00008450/// \brief Look for '&&' in the left hand of a '||' expr.
8451static void DiagnoseLogicalAndInLogicalOrLHS(Sema &S, SourceLocation OpLoc,
Richard Trieubefece12011-09-07 02:02:10 +00008452 Expr *LHSExpr, Expr *RHSExpr) {
8453 if (BinaryOperator *Bop = dyn_cast<BinaryOperator>(LHSExpr)) {
Argyrios Kyrtzidisbee77f72010-11-16 21:00:12 +00008454 if (Bop->getOpcode() == BO_LAnd) {
Argyrios Kyrtzidis47d512c2010-11-17 19:18:19 +00008455 // If it's "a && b || 0" don't warn since the precedence doesn't matter.
Richard Trieubefece12011-09-07 02:02:10 +00008456 if (EvaluatesAsFalse(S, RHSExpr))
Argyrios Kyrtzidis47d512c2010-11-17 19:18:19 +00008457 return;
Argyrios Kyrtzidis567bb712010-11-17 18:26:36 +00008458 // If it's "1 && a || b" don't warn since the precedence doesn't matter.
8459 if (!EvaluatesAsTrue(S, Bop->getLHS()))
8460 return EmitDiagnosticForLogicalAndInLogicalOr(S, OpLoc, Bop);
8461 } else if (Bop->getOpcode() == BO_LOr) {
8462 if (BinaryOperator *RBop = dyn_cast<BinaryOperator>(Bop->getRHS())) {
8463 // If it's "a || b && 1 || c" we didn't warn earlier for
8464 // "a || b && 1", but warn now.
8465 if (RBop->getOpcode() == BO_LAnd && EvaluatesAsTrue(S, RBop->getRHS()))
8466 return EmitDiagnosticForLogicalAndInLogicalOr(S, OpLoc, RBop);
8467 }
8468 }
8469 }
8470}
8471
8472/// \brief Look for '&&' in the right hand of a '||' expr.
8473static void DiagnoseLogicalAndInLogicalOrRHS(Sema &S, SourceLocation OpLoc,
Richard Trieubefece12011-09-07 02:02:10 +00008474 Expr *LHSExpr, Expr *RHSExpr) {
8475 if (BinaryOperator *Bop = dyn_cast<BinaryOperator>(RHSExpr)) {
Argyrios Kyrtzidis567bb712010-11-17 18:26:36 +00008476 if (Bop->getOpcode() == BO_LAnd) {
Argyrios Kyrtzidis47d512c2010-11-17 19:18:19 +00008477 // If it's "0 || a && b" don't warn since the precedence doesn't matter.
Richard Trieubefece12011-09-07 02:02:10 +00008478 if (EvaluatesAsFalse(S, LHSExpr))
Argyrios Kyrtzidis47d512c2010-11-17 19:18:19 +00008479 return;
Argyrios Kyrtzidis567bb712010-11-17 18:26:36 +00008480 // If it's "a || b && 1" don't warn since the precedence doesn't matter.
8481 if (!EvaluatesAsTrue(S, Bop->getRHS()))
8482 return EmitDiagnosticForLogicalAndInLogicalOr(S, OpLoc, Bop);
Argyrios Kyrtzidisbee77f72010-11-16 21:00:12 +00008483 }
8484 }
8485}
8486
Argyrios Kyrtzidis33f46e22011-06-20 18:41:26 +00008487/// \brief Look for '&' in the left or right hand of a '|' expr.
8488static void DiagnoseBitwiseAndInBitwiseOr(Sema &S, SourceLocation OpLoc,
8489 Expr *OrArg) {
8490 if (BinaryOperator *Bop = dyn_cast<BinaryOperator>(OrArg)) {
8491 if (Bop->getOpcode() == BO_And)
8492 return EmitDiagnosticForBitwiseAndInBitwiseOr(S, OpLoc, Bop);
8493 }
8494}
8495
Sebastian Redl9e1d29b2009-10-26 15:24:15 +00008496/// DiagnoseBinOpPrecedence - Emit warnings for expressions with tricky
Argyrios Kyrtzidisbee77f72010-11-16 21:00:12 +00008497/// precedence.
John McCall2de56d12010-08-25 11:45:40 +00008498static void DiagnoseBinOpPrecedence(Sema &Self, BinaryOperatorKind Opc,
Richard Trieubefece12011-09-07 02:02:10 +00008499 SourceLocation OpLoc, Expr *LHSExpr,
8500 Expr *RHSExpr){
Argyrios Kyrtzidisbee77f72010-11-16 21:00:12 +00008501 // Diagnose "arg1 'bitwise' arg2 'eq' arg3".
Sebastian Redlaee3c932009-10-27 12:10:02 +00008502 if (BinaryOperator::isBitwiseOp(Opc))
Richard Trieubefece12011-09-07 02:02:10 +00008503 DiagnoseBitwisePrecedence(Self, Opc, OpLoc, LHSExpr, RHSExpr);
Argyrios Kyrtzidis33f46e22011-06-20 18:41:26 +00008504
8505 // Diagnose "arg1 & arg2 | arg3"
8506 if (Opc == BO_Or && !OpLoc.isMacroID()/* Don't warn in macros. */) {
Richard Trieubefece12011-09-07 02:02:10 +00008507 DiagnoseBitwiseAndInBitwiseOr(Self, OpLoc, LHSExpr);
8508 DiagnoseBitwiseAndInBitwiseOr(Self, OpLoc, RHSExpr);
Argyrios Kyrtzidis33f46e22011-06-20 18:41:26 +00008509 }
Argyrios Kyrtzidisbee77f72010-11-16 21:00:12 +00008510
Argyrios Kyrtzidis567bb712010-11-17 18:26:36 +00008511 // Warn about arg1 || arg2 && arg3, as GCC 4.3+ does.
8512 // We don't warn for 'assert(a || b && "bad")' since this is safe.
Argyrios Kyrtzidisd92ccaa2010-11-17 18:54:22 +00008513 if (Opc == BO_LOr && !OpLoc.isMacroID()/* Don't warn in macros. */) {
Richard Trieubefece12011-09-07 02:02:10 +00008514 DiagnoseLogicalAndInLogicalOrLHS(Self, OpLoc, LHSExpr, RHSExpr);
8515 DiagnoseLogicalAndInLogicalOrRHS(Self, OpLoc, LHSExpr, RHSExpr);
Argyrios Kyrtzidisbee77f72010-11-16 21:00:12 +00008516 }
Sebastian Redl9e1d29b2009-10-26 15:24:15 +00008517}
8518
Reid Spencer5f016e22007-07-11 17:01:13 +00008519// Binary Operators. 'Tok' is the token for the operator.
John McCall60d7b3a2010-08-24 06:29:42 +00008520ExprResult Sema::ActOnBinOp(Scope *S, SourceLocation TokLoc,
John McCall2de56d12010-08-25 11:45:40 +00008521 tok::TokenKind Kind,
Richard Trieubefece12011-09-07 02:02:10 +00008522 Expr *LHSExpr, Expr *RHSExpr) {
John McCall2de56d12010-08-25 11:45:40 +00008523 BinaryOperatorKind Opc = ConvertTokenKindToBinaryOpcode(Kind);
Richard Trieubefece12011-09-07 02:02:10 +00008524 assert((LHSExpr != 0) && "ActOnBinOp(): missing left expression");
8525 assert((RHSExpr != 0) && "ActOnBinOp(): missing right expression");
Reid Spencer5f016e22007-07-11 17:01:13 +00008526
Sebastian Redl9e1d29b2009-10-26 15:24:15 +00008527 // Emit warnings for tricky precedence issues, e.g. "bitfield & 0x4 == 0"
Richard Trieubefece12011-09-07 02:02:10 +00008528 DiagnoseBinOpPrecedence(*this, Opc, TokLoc, LHSExpr, RHSExpr);
Sebastian Redl9e1d29b2009-10-26 15:24:15 +00008529
Richard Trieubefece12011-09-07 02:02:10 +00008530 return BuildBinOp(S, TokLoc, Opc, LHSExpr, RHSExpr);
Douglas Gregor6ca7cfb2009-11-05 00:51:44 +00008531}
8532
John McCall3c3b7f92011-10-25 17:37:35 +00008533/// Build an overloaded binary operator expression in the given scope.
8534static ExprResult BuildOverloadedBinOp(Sema &S, Scope *Sc, SourceLocation OpLoc,
8535 BinaryOperatorKind Opc,
8536 Expr *LHS, Expr *RHS) {
8537 // Find all of the overloaded operators visible from this
8538 // point. We perform both an operator-name lookup from the local
8539 // scope and an argument-dependent lookup based on the types of
8540 // the arguments.
8541 UnresolvedSet<16> Functions;
8542 OverloadedOperatorKind OverOp
8543 = BinaryOperator::getOverloadedOperator(Opc);
8544 if (Sc && OverOp != OO_None)
8545 S.LookupOverloadedOperatorName(OverOp, Sc, LHS->getType(),
8546 RHS->getType(), Functions);
8547
8548 // Build the (potentially-overloaded, potentially-dependent)
8549 // binary operation.
8550 return S.CreateOverloadedBinOp(OpLoc, Opc, Functions, LHS, RHS);
8551}
8552
John McCall60d7b3a2010-08-24 06:29:42 +00008553ExprResult Sema::BuildBinOp(Scope *S, SourceLocation OpLoc,
John McCall2de56d12010-08-25 11:45:40 +00008554 BinaryOperatorKind Opc,
Richard Trieubefece12011-09-07 02:02:10 +00008555 Expr *LHSExpr, Expr *RHSExpr) {
John McCallac516502011-10-28 01:04:34 +00008556 // We want to end up calling one of checkPseudoObjectAssignment
8557 // (if the LHS is a pseudo-object), BuildOverloadedBinOp (if
8558 // both expressions are overloadable or either is type-dependent),
8559 // or CreateBuiltinBinOp (in any other case). We also want to get
8560 // any placeholder types out of the way.
8561
John McCall3c3b7f92011-10-25 17:37:35 +00008562 // Handle pseudo-objects in the LHS.
8563 if (const BuiltinType *pty = LHSExpr->getType()->getAsPlaceholderType()) {
8564 // Assignments with a pseudo-object l-value need special analysis.
8565 if (pty->getKind() == BuiltinType::PseudoObject &&
8566 BinaryOperator::isAssignmentOp(Opc))
8567 return checkPseudoObjectAssignment(S, OpLoc, Opc, LHSExpr, RHSExpr);
8568
8569 // Don't resolve overloads if the other type is overloadable.
8570 if (pty->getKind() == BuiltinType::Overload) {
8571 // We can't actually test that if we still have a placeholder,
8572 // though. Fortunately, none of the exceptions we see in that
John McCallac516502011-10-28 01:04:34 +00008573 // code below are valid when the LHS is an overload set. Note
8574 // that an overload set can be dependently-typed, but it never
8575 // instantiates to having an overloadable type.
John McCall3c3b7f92011-10-25 17:37:35 +00008576 ExprResult resolvedRHS = CheckPlaceholderExpr(RHSExpr);
8577 if (resolvedRHS.isInvalid()) return ExprError();
8578 RHSExpr = resolvedRHS.take();
8579
John McCallac516502011-10-28 01:04:34 +00008580 if (RHSExpr->isTypeDependent() ||
8581 RHSExpr->getType()->isOverloadableType())
John McCall3c3b7f92011-10-25 17:37:35 +00008582 return BuildOverloadedBinOp(*this, S, OpLoc, Opc, LHSExpr, RHSExpr);
8583 }
8584
8585 ExprResult LHS = CheckPlaceholderExpr(LHSExpr);
8586 if (LHS.isInvalid()) return ExprError();
8587 LHSExpr = LHS.take();
8588 }
8589
8590 // Handle pseudo-objects in the RHS.
8591 if (const BuiltinType *pty = RHSExpr->getType()->getAsPlaceholderType()) {
8592 // An overload in the RHS can potentially be resolved by the type
8593 // being assigned to.
John McCallac516502011-10-28 01:04:34 +00008594 if (Opc == BO_Assign && pty->getKind() == BuiltinType::Overload) {
8595 if (LHSExpr->isTypeDependent() || RHSExpr->isTypeDependent())
8596 return BuildOverloadedBinOp(*this, S, OpLoc, Opc, LHSExpr, RHSExpr);
8597
Eli Friedman87884912012-01-17 21:27:43 +00008598 if (LHSExpr->getType()->isOverloadableType())
8599 return BuildOverloadedBinOp(*this, S, OpLoc, Opc, LHSExpr, RHSExpr);
8600
John McCall3c3b7f92011-10-25 17:37:35 +00008601 return CreateBuiltinBinOp(OpLoc, Opc, LHSExpr, RHSExpr);
John McCallac516502011-10-28 01:04:34 +00008602 }
John McCall3c3b7f92011-10-25 17:37:35 +00008603
8604 // Don't resolve overloads if the other type is overloadable.
8605 if (pty->getKind() == BuiltinType::Overload &&
8606 LHSExpr->getType()->isOverloadableType())
8607 return BuildOverloadedBinOp(*this, S, OpLoc, Opc, LHSExpr, RHSExpr);
8608
8609 ExprResult resolvedRHS = CheckPlaceholderExpr(RHSExpr);
8610 if (!resolvedRHS.isUsable()) return ExprError();
8611 RHSExpr = resolvedRHS.take();
8612 }
8613
David Blaikie4e4d0842012-03-11 07:00:24 +00008614 if (getLangOpts().CPlusPlus) {
John McCallac516502011-10-28 01:04:34 +00008615 // If either expression is type-dependent, always build an
8616 // overloaded op.
8617 if (LHSExpr->isTypeDependent() || RHSExpr->isTypeDependent())
8618 return BuildOverloadedBinOp(*this, S, OpLoc, Opc, LHSExpr, RHSExpr);
Kovarththanan Rajaratnam19357542010-03-13 10:17:05 +00008619
John McCallac516502011-10-28 01:04:34 +00008620 // Otherwise, build an overloaded op if either expression has an
8621 // overloadable type.
8622 if (LHSExpr->getType()->isOverloadableType() ||
8623 RHSExpr->getType()->isOverloadableType())
John McCall3c3b7f92011-10-25 17:37:35 +00008624 return BuildOverloadedBinOp(*this, S, OpLoc, Opc, LHSExpr, RHSExpr);
Sebastian Redlb8a6aca2009-01-19 22:31:54 +00008625 }
Kovarththanan Rajaratnam19357542010-03-13 10:17:05 +00008626
Douglas Gregoreaebc752008-11-06 23:29:22 +00008627 // Build a built-in binary operation.
Richard Trieubefece12011-09-07 02:02:10 +00008628 return CreateBuiltinBinOp(OpLoc, Opc, LHSExpr, RHSExpr);
Reid Spencer5f016e22007-07-11 17:01:13 +00008629}
8630
John McCall60d7b3a2010-08-24 06:29:42 +00008631ExprResult Sema::CreateBuiltinUnaryOp(SourceLocation OpLoc,
Argyrios Kyrtzidisb1fa3dc2011-01-05 20:09:36 +00008632 UnaryOperatorKind Opc,
John Wiegley429bb272011-04-08 18:41:53 +00008633 Expr *InputExpr) {
8634 ExprResult Input = Owned(InputExpr);
John McCallf89e55a2010-11-18 06:31:45 +00008635 ExprValueKind VK = VK_RValue;
8636 ExprObjectKind OK = OK_Ordinary;
Reid Spencer5f016e22007-07-11 17:01:13 +00008637 QualType resultType;
8638 switch (Opc) {
John McCall2de56d12010-08-25 11:45:40 +00008639 case UO_PreInc:
8640 case UO_PreDec:
8641 case UO_PostInc:
8642 case UO_PostDec:
John Wiegley429bb272011-04-08 18:41:53 +00008643 resultType = CheckIncrementDecrementOperand(*this, Input.get(), VK, OpLoc,
John McCall2de56d12010-08-25 11:45:40 +00008644 Opc == UO_PreInc ||
8645 Opc == UO_PostInc,
8646 Opc == UO_PreInc ||
8647 Opc == UO_PreDec);
Reid Spencer5f016e22007-07-11 17:01:13 +00008648 break;
John McCall2de56d12010-08-25 11:45:40 +00008649 case UO_AddrOf:
John McCall3c3b7f92011-10-25 17:37:35 +00008650 resultType = CheckAddressOfOperand(*this, Input, OpLoc);
Reid Spencer5f016e22007-07-11 17:01:13 +00008651 break;
John McCall1de4d4e2011-04-07 08:22:57 +00008652 case UO_Deref: {
John Wiegley429bb272011-04-08 18:41:53 +00008653 Input = DefaultFunctionArrayLvalueConversion(Input.take());
Eli Friedmana6c66ce2012-08-31 00:14:07 +00008654 if (Input.isInvalid()) return ExprError();
John Wiegley429bb272011-04-08 18:41:53 +00008655 resultType = CheckIndirectionOperand(*this, Input.get(), VK, OpLoc);
Reid Spencer5f016e22007-07-11 17:01:13 +00008656 break;
John McCall1de4d4e2011-04-07 08:22:57 +00008657 }
John McCall2de56d12010-08-25 11:45:40 +00008658 case UO_Plus:
8659 case UO_Minus:
John Wiegley429bb272011-04-08 18:41:53 +00008660 Input = UsualUnaryConversions(Input.take());
8661 if (Input.isInvalid()) return ExprError();
8662 resultType = Input.get()->getType();
Sebastian Redl28507842009-02-26 14:39:58 +00008663 if (resultType->isDependentType())
8664 break;
Douglas Gregor00619622010-06-22 23:41:02 +00008665 if (resultType->isArithmeticType() || // C99 6.5.3.3p1
8666 resultType->isVectorType())
Douglas Gregor74253732008-11-19 15:42:04 +00008667 break;
David Blaikie4e4d0842012-03-11 07:00:24 +00008668 else if (getLangOpts().CPlusPlus && // C++ [expr.unary.op]p6-7
Douglas Gregor74253732008-11-19 15:42:04 +00008669 resultType->isEnumeralType())
8670 break;
David Blaikie4e4d0842012-03-11 07:00:24 +00008671 else if (getLangOpts().CPlusPlus && // C++ [expr.unary.op]p6
John McCall2de56d12010-08-25 11:45:40 +00008672 Opc == UO_Plus &&
Douglas Gregor74253732008-11-19 15:42:04 +00008673 resultType->isPointerType())
8674 break;
8675
Sebastian Redl0eb23302009-01-19 00:08:26 +00008676 return ExprError(Diag(OpLoc, diag::err_typecheck_unary_expr)
John Wiegley429bb272011-04-08 18:41:53 +00008677 << resultType << Input.get()->getSourceRange());
8678
John McCall2de56d12010-08-25 11:45:40 +00008679 case UO_Not: // bitwise complement
John Wiegley429bb272011-04-08 18:41:53 +00008680 Input = UsualUnaryConversions(Input.take());
8681 if (Input.isInvalid()) return ExprError();
8682 resultType = Input.get()->getType();
Sebastian Redl28507842009-02-26 14:39:58 +00008683 if (resultType->isDependentType())
8684 break;
Chris Lattner02a65142008-07-25 23:52:49 +00008685 // C99 6.5.3.3p1. We allow complex int and float as a GCC extension.
8686 if (resultType->isComplexType() || resultType->isComplexIntegerType())
8687 // C99 does not support '~' for complex conjugation.
Chris Lattnerd3a94e22008-11-20 06:06:08 +00008688 Diag(OpLoc, diag::ext_integer_complement_complex)
John Wiegley429bb272011-04-08 18:41:53 +00008689 << resultType << Input.get()->getSourceRange();
John McCall2cd11fe2010-10-12 02:09:17 +00008690 else if (resultType->hasIntegerRepresentation())
8691 break;
John McCall3c3b7f92011-10-25 17:37:35 +00008692 else {
Sebastian Redl0eb23302009-01-19 00:08:26 +00008693 return ExprError(Diag(OpLoc, diag::err_typecheck_unary_expr)
John Wiegley429bb272011-04-08 18:41:53 +00008694 << resultType << Input.get()->getSourceRange());
John McCall2cd11fe2010-10-12 02:09:17 +00008695 }
Reid Spencer5f016e22007-07-11 17:01:13 +00008696 break;
John Wiegley429bb272011-04-08 18:41:53 +00008697
John McCall2de56d12010-08-25 11:45:40 +00008698 case UO_LNot: // logical negation
Reid Spencer5f016e22007-07-11 17:01:13 +00008699 // Unlike +/-/~, integer promotions aren't done here (C99 6.5.3.3p5).
John Wiegley429bb272011-04-08 18:41:53 +00008700 Input = DefaultFunctionArrayLvalueConversion(Input.take());
8701 if (Input.isInvalid()) return ExprError();
8702 resultType = Input.get()->getType();
Anton Korobeynikovaa4a99b2011-10-14 23:23:15 +00008703
8704 // Though we still have to promote half FP to float...
8705 if (resultType->isHalfType()) {
8706 Input = ImpCastExprToType(Input.take(), Context.FloatTy, CK_FloatingCast).take();
8707 resultType = Context.FloatTy;
8708 }
8709
Sebastian Redl28507842009-02-26 14:39:58 +00008710 if (resultType->isDependentType())
8711 break;
Abramo Bagnara737d5442011-04-07 09:26:19 +00008712 if (resultType->isScalarType()) {
8713 // C99 6.5.3.3p1: ok, fallthrough;
David Blaikie4e4d0842012-03-11 07:00:24 +00008714 if (Context.getLangOpts().CPlusPlus) {
Abramo Bagnara737d5442011-04-07 09:26:19 +00008715 // C++03 [expr.unary.op]p8, C++0x [expr.unary.op]p9:
8716 // operand contextually converted to bool.
John Wiegley429bb272011-04-08 18:41:53 +00008717 Input = ImpCastExprToType(Input.take(), Context.BoolTy,
8718 ScalarTypeToBooleanCastKind(resultType));
Abramo Bagnara737d5442011-04-07 09:26:19 +00008719 }
Tanya Lattnerb0f9dd22012-01-19 01:16:16 +00008720 } else if (resultType->isExtVectorType()) {
Tanya Lattner4f692c22012-01-16 21:02:28 +00008721 // Vector logical not returns the signed variant of the operand type.
8722 resultType = GetSignedVectorType(resultType);
8723 break;
John McCall2cd11fe2010-10-12 02:09:17 +00008724 } else {
Sebastian Redl0eb23302009-01-19 00:08:26 +00008725 return ExprError(Diag(OpLoc, diag::err_typecheck_unary_expr)
John Wiegley429bb272011-04-08 18:41:53 +00008726 << resultType << Input.get()->getSourceRange());
John McCall2cd11fe2010-10-12 02:09:17 +00008727 }
Douglas Gregorea844f32010-09-20 17:13:33 +00008728
Reid Spencer5f016e22007-07-11 17:01:13 +00008729 // LNot always has type int. C99 6.5.3.3p5.
Sebastian Redl0eb23302009-01-19 00:08:26 +00008730 // In C++, it's bool. C++ 5.3.1p8
Argyrios Kyrtzidis16f744b2011-02-18 20:55:15 +00008731 resultType = Context.getLogicalOperationType();
Reid Spencer5f016e22007-07-11 17:01:13 +00008732 break;
John McCall2de56d12010-08-25 11:45:40 +00008733 case UO_Real:
8734 case UO_Imag:
John McCall09431682010-11-18 19:01:18 +00008735 resultType = CheckRealImagOperand(*this, Input, OpLoc, Opc == UO_Real);
Richard Smithdfb80de2012-02-18 20:53:32 +00008736 // _Real maps ordinary l-values into ordinary l-values. _Imag maps ordinary
8737 // complex l-values to ordinary l-values and all other values to r-values.
John Wiegley429bb272011-04-08 18:41:53 +00008738 if (Input.isInvalid()) return ExprError();
Richard Smithdfb80de2012-02-18 20:53:32 +00008739 if (Opc == UO_Real || Input.get()->getType()->isAnyComplexType()) {
8740 if (Input.get()->getValueKind() != VK_RValue &&
8741 Input.get()->getObjectKind() == OK_Ordinary)
8742 VK = Input.get()->getValueKind();
David Blaikie4e4d0842012-03-11 07:00:24 +00008743 } else if (!getLangOpts().CPlusPlus) {
Richard Smithdfb80de2012-02-18 20:53:32 +00008744 // In C, a volatile scalar is read by __imag. In C++, it is not.
8745 Input = DefaultLvalueConversion(Input.take());
8746 }
Chris Lattnerdbb36972007-08-24 21:16:53 +00008747 break;
John McCall2de56d12010-08-25 11:45:40 +00008748 case UO_Extension:
John Wiegley429bb272011-04-08 18:41:53 +00008749 resultType = Input.get()->getType();
8750 VK = Input.get()->getValueKind();
8751 OK = Input.get()->getObjectKind();
Reid Spencer5f016e22007-07-11 17:01:13 +00008752 break;
8753 }
John Wiegley429bb272011-04-08 18:41:53 +00008754 if (resultType.isNull() || Input.isInvalid())
Sebastian Redl0eb23302009-01-19 00:08:26 +00008755 return ExprError();
Douglas Gregorbc736fc2009-03-13 23:49:33 +00008756
Kaelyn Uhraind6c88652011-08-05 23:18:04 +00008757 // Check for array bounds violations in the operand of the UnaryOperator,
8758 // except for the '*' and '&' operators that have to be handled specially
8759 // by CheckArrayAccess (as there are special cases like &array[arraysize]
8760 // that are explicitly defined as valid by the standard).
8761 if (Opc != UO_AddrOf && Opc != UO_Deref)
8762 CheckArrayAccess(Input.get());
8763
John Wiegley429bb272011-04-08 18:41:53 +00008764 return Owned(new (Context) UnaryOperator(Input.take(), Opc, resultType,
John McCallf89e55a2010-11-18 06:31:45 +00008765 VK, OK, OpLoc));
Reid Spencer5f016e22007-07-11 17:01:13 +00008766}
8767
Douglas Gregord3d08532011-12-14 21:23:13 +00008768/// \brief Determine whether the given expression is a qualified member
8769/// access expression, of a form that could be turned into a pointer to member
8770/// with the address-of operator.
8771static bool isQualifiedMemberAccess(Expr *E) {
8772 if (DeclRefExpr *DRE = dyn_cast<DeclRefExpr>(E)) {
8773 if (!DRE->getQualifier())
8774 return false;
8775
8776 ValueDecl *VD = DRE->getDecl();
8777 if (!VD->isCXXClassMember())
8778 return false;
8779
8780 if (isa<FieldDecl>(VD) || isa<IndirectFieldDecl>(VD))
8781 return true;
8782 if (CXXMethodDecl *Method = dyn_cast<CXXMethodDecl>(VD))
8783 return Method->isInstance();
8784
8785 return false;
8786 }
8787
8788 if (UnresolvedLookupExpr *ULE = dyn_cast<UnresolvedLookupExpr>(E)) {
8789 if (!ULE->getQualifier())
8790 return false;
8791
8792 for (UnresolvedLookupExpr::decls_iterator D = ULE->decls_begin(),
8793 DEnd = ULE->decls_end();
8794 D != DEnd; ++D) {
8795 if (CXXMethodDecl *Method = dyn_cast<CXXMethodDecl>(*D)) {
8796 if (Method->isInstance())
8797 return true;
8798 } else {
8799 // Overload set does not contain methods.
8800 break;
8801 }
8802 }
8803
8804 return false;
8805 }
8806
8807 return false;
8808}
8809
John McCall60d7b3a2010-08-24 06:29:42 +00008810ExprResult Sema::BuildUnaryOp(Scope *S, SourceLocation OpLoc,
Richard Trieuccd891a2011-09-09 01:45:06 +00008811 UnaryOperatorKind Opc, Expr *Input) {
John McCall3c3b7f92011-10-25 17:37:35 +00008812 // First things first: handle placeholders so that the
8813 // overloaded-operator check considers the right type.
8814 if (const BuiltinType *pty = Input->getType()->getAsPlaceholderType()) {
8815 // Increment and decrement of pseudo-object references.
8816 if (pty->getKind() == BuiltinType::PseudoObject &&
8817 UnaryOperator::isIncrementDecrementOp(Opc))
8818 return checkPseudoObjectIncDec(S, OpLoc, Opc, Input);
8819
8820 // extension is always a builtin operator.
8821 if (Opc == UO_Extension)
8822 return CreateBuiltinUnaryOp(OpLoc, Opc, Input);
8823
8824 // & gets special logic for several kinds of placeholder.
8825 // The builtin code knows what to do.
8826 if (Opc == UO_AddrOf &&
8827 (pty->getKind() == BuiltinType::Overload ||
8828 pty->getKind() == BuiltinType::UnknownAny ||
8829 pty->getKind() == BuiltinType::BoundMember))
8830 return CreateBuiltinUnaryOp(OpLoc, Opc, Input);
8831
8832 // Anything else needs to be handled now.
8833 ExprResult Result = CheckPlaceholderExpr(Input);
8834 if (Result.isInvalid()) return ExprError();
8835 Input = Result.take();
8836 }
8837
David Blaikie4e4d0842012-03-11 07:00:24 +00008838 if (getLangOpts().CPlusPlus && Input->getType()->isOverloadableType() &&
Douglas Gregord3d08532011-12-14 21:23:13 +00008839 UnaryOperator::getOverloadedOperator(Opc) != OO_None &&
8840 !(Opc == UO_AddrOf && isQualifiedMemberAccess(Input))) {
Douglas Gregorbc736fc2009-03-13 23:49:33 +00008841 // Find all of the overloaded operators visible from this
8842 // point. We perform both an operator-name lookup from the local
8843 // scope and an argument-dependent lookup based on the types of
8844 // the arguments.
John McCall6e266892010-01-26 03:27:55 +00008845 UnresolvedSet<16> Functions;
Douglas Gregorbc736fc2009-03-13 23:49:33 +00008846 OverloadedOperatorKind OverOp = UnaryOperator::getOverloadedOperator(Opc);
John McCall6e266892010-01-26 03:27:55 +00008847 if (S && OverOp != OO_None)
8848 LookupOverloadedOperatorName(OverOp, S, Input->getType(), QualType(),
8849 Functions);
Kovarththanan Rajaratnam19357542010-03-13 10:17:05 +00008850
John McCall9ae2f072010-08-23 23:25:46 +00008851 return CreateOverloadedUnaryOp(OpLoc, Opc, Functions, Input);
Douglas Gregorbc736fc2009-03-13 23:49:33 +00008852 }
Kovarththanan Rajaratnam19357542010-03-13 10:17:05 +00008853
John McCall9ae2f072010-08-23 23:25:46 +00008854 return CreateBuiltinUnaryOp(OpLoc, Opc, Input);
Douglas Gregorbc736fc2009-03-13 23:49:33 +00008855}
8856
Douglas Gregor6ca7cfb2009-11-05 00:51:44 +00008857// Unary Operators. 'Tok' is the token for the operator.
John McCall60d7b3a2010-08-24 06:29:42 +00008858ExprResult Sema::ActOnUnaryOp(Scope *S, SourceLocation OpLoc,
John McCallf4c73712011-01-19 06:33:43 +00008859 tok::TokenKind Op, Expr *Input) {
John McCall9ae2f072010-08-23 23:25:46 +00008860 return BuildUnaryOp(S, OpLoc, ConvertTokenKindToUnaryOpcode(Op), Input);
Douglas Gregor6ca7cfb2009-11-05 00:51:44 +00008861}
8862
Steve Naroff1b273c42007-09-16 14:56:35 +00008863/// ActOnAddrLabel - Parse the GNU address of label extension: "&&foo".
Chris Lattnerad8dcf42011-02-17 07:39:24 +00008864ExprResult Sema::ActOnAddrLabel(SourceLocation OpLoc, SourceLocation LabLoc,
Chris Lattner57ad3782011-02-17 20:34:02 +00008865 LabelDecl *TheDecl) {
Chris Lattnerad8dcf42011-02-17 07:39:24 +00008866 TheDecl->setUsed();
Reid Spencer5f016e22007-07-11 17:01:13 +00008867 // Create the AST node. The address of a label always has type 'void*'.
Chris Lattnerad8dcf42011-02-17 07:39:24 +00008868 return Owned(new (Context) AddrLabelExpr(OpLoc, LabLoc, TheDecl,
Sebastian Redlf53597f2009-03-15 17:47:39 +00008869 Context.getPointerType(Context.VoidTy)));
Reid Spencer5f016e22007-07-11 17:01:13 +00008870}
8871
John McCallf85e1932011-06-15 23:02:42 +00008872/// Given the last statement in a statement-expression, check whether
8873/// the result is a producing expression (like a call to an
8874/// ns_returns_retained function) and, if so, rebuild it to hoist the
8875/// release out of the full-expression. Otherwise, return null.
8876/// Cannot fail.
Richard Trieuccd891a2011-09-09 01:45:06 +00008877static Expr *maybeRebuildARCConsumingStmt(Stmt *Statement) {
John McCallf85e1932011-06-15 23:02:42 +00008878 // Should always be wrapped with one of these.
Richard Trieuccd891a2011-09-09 01:45:06 +00008879 ExprWithCleanups *cleanups = dyn_cast<ExprWithCleanups>(Statement);
John McCallf85e1932011-06-15 23:02:42 +00008880 if (!cleanups) return 0;
8881
8882 ImplicitCastExpr *cast = dyn_cast<ImplicitCastExpr>(cleanups->getSubExpr());
John McCall33e56f32011-09-10 06:18:15 +00008883 if (!cast || cast->getCastKind() != CK_ARCConsumeObject)
John McCallf85e1932011-06-15 23:02:42 +00008884 return 0;
8885
8886 // Splice out the cast. This shouldn't modify any interesting
8887 // features of the statement.
8888 Expr *producer = cast->getSubExpr();
8889 assert(producer->getType() == cast->getType());
8890 assert(producer->getValueKind() == cast->getValueKind());
8891 cleanups->setSubExpr(producer);
8892 return cleanups;
8893}
8894
John McCall73f428c2012-04-04 01:27:53 +00008895void Sema::ActOnStartStmtExpr() {
8896 PushExpressionEvaluationContext(ExprEvalContexts.back().Context);
8897}
8898
8899void Sema::ActOnStmtExprError() {
John McCall7f39d512012-04-06 18:20:53 +00008900 // Note that function is also called by TreeTransform when leaving a
8901 // StmtExpr scope without rebuilding anything.
8902
John McCall73f428c2012-04-04 01:27:53 +00008903 DiscardCleanupsInEvaluationContext();
8904 PopExpressionEvaluationContext();
8905}
8906
John McCall60d7b3a2010-08-24 06:29:42 +00008907ExprResult
John McCall9ae2f072010-08-23 23:25:46 +00008908Sema::ActOnStmtExpr(SourceLocation LPLoc, Stmt *SubStmt,
Sebastian Redlf53597f2009-03-15 17:47:39 +00008909 SourceLocation RPLoc) { // "({..})"
Chris Lattnerab18c4c2007-07-24 16:58:17 +00008910 assert(SubStmt && isa<CompoundStmt>(SubStmt) && "Invalid action invocation!");
8911 CompoundStmt *Compound = cast<CompoundStmt>(SubStmt);
8912
John McCall73f428c2012-04-04 01:27:53 +00008913 if (hasAnyUnrecoverableErrorsInThisFunction())
8914 DiscardCleanupsInEvaluationContext();
8915 assert(!ExprNeedsCleanups && "cleanups within StmtExpr not correctly bound!");
8916 PopExpressionEvaluationContext();
8917
Douglas Gregordd8f5692010-03-10 04:54:39 +00008918 bool isFileScope
8919 = (getCurFunctionOrMethodDecl() == 0) && (getCurBlock() == 0);
Chris Lattner4a049f02009-04-25 19:11:05 +00008920 if (isFileScope)
Sebastian Redlf53597f2009-03-15 17:47:39 +00008921 return ExprError(Diag(LPLoc, diag::err_stmtexpr_file_scope));
Eli Friedmandca2b732009-01-24 23:09:00 +00008922
Chris Lattnerab18c4c2007-07-24 16:58:17 +00008923 // FIXME: there are a variety of strange constraints to enforce here, for
8924 // example, it is not possible to goto into a stmt expression apparently.
8925 // More semantic analysis is needed.
Mike Stumpeed9cac2009-02-19 03:04:26 +00008926
Chris Lattnerab18c4c2007-07-24 16:58:17 +00008927 // If there are sub stmts in the compound stmt, take the type of the last one
8928 // as the type of the stmtexpr.
8929 QualType Ty = Context.VoidTy;
Fariborz Jahaniane946fc82010-10-25 23:27:26 +00008930 bool StmtExprMayBindToTemp = false;
Chris Lattner611b2ec2008-07-26 19:51:01 +00008931 if (!Compound->body_empty()) {
8932 Stmt *LastStmt = Compound->body_back();
Fariborz Jahaniane946fc82010-10-25 23:27:26 +00008933 LabelStmt *LastLabelStmt = 0;
Chris Lattner611b2ec2008-07-26 19:51:01 +00008934 // If LastStmt is a label, skip down through into the body.
Fariborz Jahaniane946fc82010-10-25 23:27:26 +00008935 while (LabelStmt *Label = dyn_cast<LabelStmt>(LastStmt)) {
8936 LastLabelStmt = Label;
Chris Lattner611b2ec2008-07-26 19:51:01 +00008937 LastStmt = Label->getSubStmt();
Fariborz Jahaniane946fc82010-10-25 23:27:26 +00008938 }
John McCallf85e1932011-06-15 23:02:42 +00008939
John Wiegley429bb272011-04-08 18:41:53 +00008940 if (Expr *LastE = dyn_cast<Expr>(LastStmt)) {
John McCallf6a16482010-12-04 03:47:34 +00008941 // Do function/array conversion on the last expression, but not
8942 // lvalue-to-rvalue. However, initialize an unqualified type.
John Wiegley429bb272011-04-08 18:41:53 +00008943 ExprResult LastExpr = DefaultFunctionArrayConversion(LastE);
8944 if (LastExpr.isInvalid())
8945 return ExprError();
8946 Ty = LastExpr.get()->getType().getUnqualifiedType();
John McCallf6a16482010-12-04 03:47:34 +00008947
John Wiegley429bb272011-04-08 18:41:53 +00008948 if (!Ty->isDependentType() && !LastExpr.get()->isTypeDependent()) {
John McCallf85e1932011-06-15 23:02:42 +00008949 // In ARC, if the final expression ends in a consume, splice
8950 // the consume out and bind it later. In the alternate case
8951 // (when dealing with a retainable type), the result
8952 // initialization will create a produce. In both cases the
8953 // result will be +1, and we'll need to balance that out with
8954 // a bind.
8955 if (Expr *rebuiltLastStmt
8956 = maybeRebuildARCConsumingStmt(LastExpr.get())) {
8957 LastExpr = rebuiltLastStmt;
8958 } else {
8959 LastExpr = PerformCopyInitialization(
Fariborz Jahaniane946fc82010-10-25 23:27:26 +00008960 InitializedEntity::InitializeResult(LPLoc,
8961 Ty,
8962 false),
8963 SourceLocation(),
John McCallf85e1932011-06-15 23:02:42 +00008964 LastExpr);
8965 }
8966
John Wiegley429bb272011-04-08 18:41:53 +00008967 if (LastExpr.isInvalid())
Fariborz Jahaniane946fc82010-10-25 23:27:26 +00008968 return ExprError();
John Wiegley429bb272011-04-08 18:41:53 +00008969 if (LastExpr.get() != 0) {
Fariborz Jahaniane946fc82010-10-25 23:27:26 +00008970 if (!LastLabelStmt)
John Wiegley429bb272011-04-08 18:41:53 +00008971 Compound->setLastStmt(LastExpr.take());
Fariborz Jahaniane946fc82010-10-25 23:27:26 +00008972 else
John Wiegley429bb272011-04-08 18:41:53 +00008973 LastLabelStmt->setSubStmt(LastExpr.take());
Fariborz Jahaniane946fc82010-10-25 23:27:26 +00008974 StmtExprMayBindToTemp = true;
8975 }
8976 }
8977 }
Chris Lattner611b2ec2008-07-26 19:51:01 +00008978 }
Mike Stumpeed9cac2009-02-19 03:04:26 +00008979
Eli Friedmanb1d796d2009-03-23 00:24:07 +00008980 // FIXME: Check that expression type is complete/non-abstract; statement
8981 // expressions are not lvalues.
Fariborz Jahaniane946fc82010-10-25 23:27:26 +00008982 Expr *ResStmtExpr = new (Context) StmtExpr(Compound, Ty, LPLoc, RPLoc);
8983 if (StmtExprMayBindToTemp)
8984 return MaybeBindToTemporary(ResStmtExpr);
8985 return Owned(ResStmtExpr);
Chris Lattnerab18c4c2007-07-24 16:58:17 +00008986}
Steve Naroffd34e9152007-08-01 22:05:33 +00008987
John McCall60d7b3a2010-08-24 06:29:42 +00008988ExprResult Sema::BuildBuiltinOffsetOf(SourceLocation BuiltinLoc,
John McCall2cd11fe2010-10-12 02:09:17 +00008989 TypeSourceInfo *TInfo,
8990 OffsetOfComponent *CompPtr,
8991 unsigned NumComponents,
8992 SourceLocation RParenLoc) {
Douglas Gregor8ecdb652010-04-28 22:16:22 +00008993 QualType ArgTy = TInfo->getType();
Sebastian Redl28507842009-02-26 14:39:58 +00008994 bool Dependent = ArgTy->isDependentType();
Abramo Bagnarabd054db2010-05-20 10:00:11 +00008995 SourceRange TypeRange = TInfo->getTypeLoc().getLocalSourceRange();
Douglas Gregor8ecdb652010-04-28 22:16:22 +00008996
Chris Lattner73d0d4f2007-08-30 17:45:32 +00008997 // We must have at least one component that refers to the type, and the first
8998 // one is known to be a field designator. Verify that the ArgTy represents
8999 // a struct/union/class.
Sebastian Redl28507842009-02-26 14:39:58 +00009000 if (!Dependent && !ArgTy->isRecordType())
Douglas Gregor8ecdb652010-04-28 22:16:22 +00009001 return ExprError(Diag(BuiltinLoc, diag::err_offsetof_record_type)
9002 << ArgTy << TypeRange);
9003
9004 // Type must be complete per C99 7.17p3 because a declaring a variable
9005 // with an incomplete type would be ill-formed.
9006 if (!Dependent
9007 && RequireCompleteType(BuiltinLoc, ArgTy,
Douglas Gregord10099e2012-05-04 16:32:21 +00009008 diag::err_offsetof_incomplete_type, TypeRange))
Douglas Gregor8ecdb652010-04-28 22:16:22 +00009009 return ExprError();
9010
Chris Lattner9e2b75c2007-08-31 21:49:13 +00009011 // offsetof with non-identifier designators (e.g. "offsetof(x, a.b[c])") are a
9012 // GCC extension, diagnose them.
Eli Friedman35183ac2009-02-27 06:44:11 +00009013 // FIXME: This diagnostic isn't actually visible because the location is in
9014 // a system header!
Chris Lattner9e2b75c2007-08-31 21:49:13 +00009015 if (NumComponents != 1)
Chris Lattnerdcd5ef12008-11-19 05:27:50 +00009016 Diag(BuiltinLoc, diag::ext_offsetof_extended_field_designator)
9017 << SourceRange(CompPtr[1].LocStart, CompPtr[NumComponents-1].LocEnd);
Douglas Gregor8ecdb652010-04-28 22:16:22 +00009018
9019 bool DidWarnAboutNonPOD = false;
9020 QualType CurrentType = ArgTy;
9021 typedef OffsetOfExpr::OffsetOfNode OffsetOfNode;
Chris Lattner5f9e2722011-07-23 10:55:15 +00009022 SmallVector<OffsetOfNode, 4> Comps;
9023 SmallVector<Expr*, 4> Exprs;
Douglas Gregor8ecdb652010-04-28 22:16:22 +00009024 for (unsigned i = 0; i != NumComponents; ++i) {
9025 const OffsetOfComponent &OC = CompPtr[i];
9026 if (OC.isBrackets) {
9027 // Offset of an array sub-field. TODO: Should we allow vector elements?
9028 if (!CurrentType->isDependentType()) {
9029 const ArrayType *AT = Context.getAsArrayType(CurrentType);
9030 if(!AT)
9031 return ExprError(Diag(OC.LocEnd, diag::err_offsetof_array_type)
9032 << CurrentType);
9033 CurrentType = AT->getElementType();
9034 } else
9035 CurrentType = Context.DependentTy;
9036
Richard Smithea011432011-10-17 23:29:39 +00009037 ExprResult IdxRval = DefaultLvalueConversion(static_cast<Expr*>(OC.U.E));
9038 if (IdxRval.isInvalid())
9039 return ExprError();
9040 Expr *Idx = IdxRval.take();
9041
Douglas Gregor8ecdb652010-04-28 22:16:22 +00009042 // The expression must be an integral expression.
9043 // FIXME: An integral constant expression?
Douglas Gregor8ecdb652010-04-28 22:16:22 +00009044 if (!Idx->isTypeDependent() && !Idx->isValueDependent() &&
9045 !Idx->getType()->isIntegerType())
9046 return ExprError(Diag(Idx->getLocStart(),
9047 diag::err_typecheck_subscript_not_integer)
9048 << Idx->getSourceRange());
Richard Smithd82e5d32011-10-17 05:48:07 +00009049
Douglas Gregor8ecdb652010-04-28 22:16:22 +00009050 // Record this array index.
9051 Comps.push_back(OffsetOfNode(OC.LocStart, Exprs.size(), OC.LocEnd));
Richard Smithea011432011-10-17 23:29:39 +00009052 Exprs.push_back(Idx);
Douglas Gregor8ecdb652010-04-28 22:16:22 +00009053 continue;
9054 }
9055
9056 // Offset of a field.
9057 if (CurrentType->isDependentType()) {
9058 // We have the offset of a field, but we can't look into the dependent
9059 // type. Just record the identifier of the field.
9060 Comps.push_back(OffsetOfNode(OC.LocStart, OC.U.IdentInfo, OC.LocEnd));
9061 CurrentType = Context.DependentTy;
9062 continue;
9063 }
9064
9065 // We need to have a complete type to look into.
9066 if (RequireCompleteType(OC.LocStart, CurrentType,
9067 diag::err_offsetof_incomplete_type))
9068 return ExprError();
9069
9070 // Look for the designated field.
9071 const RecordType *RC = CurrentType->getAs<RecordType>();
9072 if (!RC)
9073 return ExprError(Diag(OC.LocEnd, diag::err_offsetof_record_type)
9074 << CurrentType);
9075 RecordDecl *RD = RC->getDecl();
9076
9077 // C++ [lib.support.types]p5:
9078 // The macro offsetof accepts a restricted set of type arguments in this
9079 // International Standard. type shall be a POD structure or a POD union
9080 // (clause 9).
Benjamin Kramer98f71aa2012-04-28 11:14:51 +00009081 // C++11 [support.types]p4:
9082 // If type is not a standard-layout class (Clause 9), the results are
9083 // undefined.
Douglas Gregor8ecdb652010-04-28 22:16:22 +00009084 if (CXXRecordDecl *CRD = dyn_cast<CXXRecordDecl>(RD)) {
Benjamin Kramer98f71aa2012-04-28 11:14:51 +00009085 bool IsSafe = LangOpts.CPlusPlus0x? CRD->isStandardLayout() : CRD->isPOD();
9086 unsigned DiagID =
9087 LangOpts.CPlusPlus0x? diag::warn_offsetof_non_standardlayout_type
9088 : diag::warn_offsetof_non_pod_type;
9089
9090 if (!IsSafe && !DidWarnAboutNonPOD &&
Ted Kremenek762696f2011-02-23 01:51:43 +00009091 DiagRuntimeBehavior(BuiltinLoc, 0,
Benjamin Kramer98f71aa2012-04-28 11:14:51 +00009092 PDiag(DiagID)
Douglas Gregor8ecdb652010-04-28 22:16:22 +00009093 << SourceRange(CompPtr[0].LocStart, OC.LocEnd)
9094 << CurrentType))
9095 DidWarnAboutNonPOD = true;
9096 }
9097
9098 // Look for the field.
9099 LookupResult R(*this, OC.U.IdentInfo, OC.LocStart, LookupMemberName);
9100 LookupQualifiedName(R, RD);
9101 FieldDecl *MemberDecl = R.getAsSingle<FieldDecl>();
Francois Pichet87c2e122010-11-21 06:08:52 +00009102 IndirectFieldDecl *IndirectMemberDecl = 0;
9103 if (!MemberDecl) {
Benjamin Kramerd9811462010-11-21 14:11:41 +00009104 if ((IndirectMemberDecl = R.getAsSingle<IndirectFieldDecl>()))
Francois Pichet87c2e122010-11-21 06:08:52 +00009105 MemberDecl = IndirectMemberDecl->getAnonField();
9106 }
9107
Douglas Gregor8ecdb652010-04-28 22:16:22 +00009108 if (!MemberDecl)
9109 return ExprError(Diag(BuiltinLoc, diag::err_no_member)
9110 << OC.U.IdentInfo << RD << SourceRange(OC.LocStart,
9111 OC.LocEnd));
9112
Douglas Gregor9d5d60f2010-04-28 22:36:06 +00009113 // C99 7.17p3:
9114 // (If the specified member is a bit-field, the behavior is undefined.)
9115 //
9116 // We diagnose this as an error.
Richard Smitha6b8b2c2011-10-10 18:28:20 +00009117 if (MemberDecl->isBitField()) {
Douglas Gregor9d5d60f2010-04-28 22:36:06 +00009118 Diag(OC.LocEnd, diag::err_offsetof_bitfield)
9119 << MemberDecl->getDeclName()
9120 << SourceRange(BuiltinLoc, RParenLoc);
9121 Diag(MemberDecl->getLocation(), diag::note_bitfield_decl);
9122 return ExprError();
9123 }
Eli Friedman19410a72010-08-05 10:11:36 +00009124
9125 RecordDecl *Parent = MemberDecl->getParent();
Francois Pichet87c2e122010-11-21 06:08:52 +00009126 if (IndirectMemberDecl)
9127 Parent = cast<RecordDecl>(IndirectMemberDecl->getDeclContext());
Eli Friedman19410a72010-08-05 10:11:36 +00009128
Douglas Gregorcc8a5d52010-04-29 00:18:15 +00009129 // If the member was found in a base class, introduce OffsetOfNodes for
9130 // the base class indirections.
9131 CXXBasePaths Paths(/*FindAmbiguities=*/true, /*RecordPaths=*/true,
9132 /*DetectVirtual=*/false);
Eli Friedman19410a72010-08-05 10:11:36 +00009133 if (IsDerivedFrom(CurrentType, Context.getTypeDeclType(Parent), Paths)) {
Douglas Gregorcc8a5d52010-04-29 00:18:15 +00009134 CXXBasePath &Path = Paths.front();
9135 for (CXXBasePath::iterator B = Path.begin(), BEnd = Path.end();
9136 B != BEnd; ++B)
9137 Comps.push_back(OffsetOfNode(B->Base));
9138 }
Eli Friedman19410a72010-08-05 10:11:36 +00009139
Francois Pichet87c2e122010-11-21 06:08:52 +00009140 if (IndirectMemberDecl) {
9141 for (IndirectFieldDecl::chain_iterator FI =
9142 IndirectMemberDecl->chain_begin(),
9143 FEnd = IndirectMemberDecl->chain_end(); FI != FEnd; FI++) {
9144 assert(isa<FieldDecl>(*FI));
9145 Comps.push_back(OffsetOfNode(OC.LocStart,
9146 cast<FieldDecl>(*FI), OC.LocEnd));
9147 }
9148 } else
Douglas Gregor8ecdb652010-04-28 22:16:22 +00009149 Comps.push_back(OffsetOfNode(OC.LocStart, MemberDecl, OC.LocEnd));
Francois Pichet87c2e122010-11-21 06:08:52 +00009150
Douglas Gregor8ecdb652010-04-28 22:16:22 +00009151 CurrentType = MemberDecl->getType().getNonReferenceType();
9152 }
9153
9154 return Owned(OffsetOfExpr::Create(Context, Context.getSizeType(), BuiltinLoc,
Benjamin Kramer3b6bef92012-08-24 11:54:20 +00009155 TInfo, Comps, Exprs, RParenLoc));
Douglas Gregor8ecdb652010-04-28 22:16:22 +00009156}
Mike Stumpeed9cac2009-02-19 03:04:26 +00009157
John McCall60d7b3a2010-08-24 06:29:42 +00009158ExprResult Sema::ActOnBuiltinOffsetOf(Scope *S,
John McCall2cd11fe2010-10-12 02:09:17 +00009159 SourceLocation BuiltinLoc,
9160 SourceLocation TypeLoc,
Richard Trieuccd891a2011-09-09 01:45:06 +00009161 ParsedType ParsedArgTy,
John McCall2cd11fe2010-10-12 02:09:17 +00009162 OffsetOfComponent *CompPtr,
9163 unsigned NumComponents,
Richard Trieuccd891a2011-09-09 01:45:06 +00009164 SourceLocation RParenLoc) {
John McCall2cd11fe2010-10-12 02:09:17 +00009165
Douglas Gregor8ecdb652010-04-28 22:16:22 +00009166 TypeSourceInfo *ArgTInfo;
Richard Trieuccd891a2011-09-09 01:45:06 +00009167 QualType ArgTy = GetTypeFromParser(ParsedArgTy, &ArgTInfo);
Douglas Gregor8ecdb652010-04-28 22:16:22 +00009168 if (ArgTy.isNull())
9169 return ExprError();
9170
Eli Friedman5a15dc12010-08-05 10:15:45 +00009171 if (!ArgTInfo)
9172 ArgTInfo = Context.getTrivialTypeSourceInfo(ArgTy, TypeLoc);
9173
9174 return BuildBuiltinOffsetOf(BuiltinLoc, ArgTInfo, CompPtr, NumComponents,
Richard Trieuccd891a2011-09-09 01:45:06 +00009175 RParenLoc);
Chris Lattner73d0d4f2007-08-30 17:45:32 +00009176}
9177
9178
John McCall60d7b3a2010-08-24 06:29:42 +00009179ExprResult Sema::ActOnChooseExpr(SourceLocation BuiltinLoc,
John McCall2cd11fe2010-10-12 02:09:17 +00009180 Expr *CondExpr,
9181 Expr *LHSExpr, Expr *RHSExpr,
9182 SourceLocation RPLoc) {
Steve Naroffd04fdd52007-08-03 21:21:27 +00009183 assert((CondExpr && LHSExpr && RHSExpr) && "Missing type argument(s)");
9184
John McCallf89e55a2010-11-18 06:31:45 +00009185 ExprValueKind VK = VK_RValue;
9186 ExprObjectKind OK = OK_Ordinary;
Sebastian Redl28507842009-02-26 14:39:58 +00009187 QualType resType;
Douglas Gregorce940492009-09-25 04:25:58 +00009188 bool ValueDependent = false;
Douglas Gregorc9ecc572009-05-19 22:43:30 +00009189 if (CondExpr->isTypeDependent() || CondExpr->isValueDependent()) {
Sebastian Redl28507842009-02-26 14:39:58 +00009190 resType = Context.DependentTy;
Douglas Gregorce940492009-09-25 04:25:58 +00009191 ValueDependent = true;
Sebastian Redl28507842009-02-26 14:39:58 +00009192 } else {
9193 // The conditional expression is required to be a constant expression.
9194 llvm::APSInt condEval(32);
Douglas Gregorab41fe92012-05-04 22:38:52 +00009195 ExprResult CondICE
9196 = VerifyIntegerConstantExpression(CondExpr, &condEval,
9197 diag::err_typecheck_choose_expr_requires_constant, false);
Richard Smith282e7e62012-02-04 09:53:13 +00009198 if (CondICE.isInvalid())
9199 return ExprError();
9200 CondExpr = CondICE.take();
Steve Naroffd04fdd52007-08-03 21:21:27 +00009201
Sebastian Redl28507842009-02-26 14:39:58 +00009202 // If the condition is > zero, then the AST type is the same as the LSHExpr.
John McCallf89e55a2010-11-18 06:31:45 +00009203 Expr *ActiveExpr = condEval.getZExtValue() ? LHSExpr : RHSExpr;
9204
9205 resType = ActiveExpr->getType();
9206 ValueDependent = ActiveExpr->isValueDependent();
9207 VK = ActiveExpr->getValueKind();
9208 OK = ActiveExpr->getObjectKind();
Sebastian Redl28507842009-02-26 14:39:58 +00009209 }
9210
Sebastian Redlf53597f2009-03-15 17:47:39 +00009211 return Owned(new (Context) ChooseExpr(BuiltinLoc, CondExpr, LHSExpr, RHSExpr,
John McCallf89e55a2010-11-18 06:31:45 +00009212 resType, VK, OK, RPLoc,
Douglas Gregorce940492009-09-25 04:25:58 +00009213 resType->isDependentType(),
9214 ValueDependent));
Steve Naroffd04fdd52007-08-03 21:21:27 +00009215}
9216
Steve Naroff4eb206b2008-09-03 18:15:37 +00009217//===----------------------------------------------------------------------===//
9218// Clang Extensions.
9219//===----------------------------------------------------------------------===//
9220
9221/// ActOnBlockStart - This callback is invoked when a block literal is started.
Richard Trieuccd891a2011-09-09 01:45:06 +00009222void Sema::ActOnBlockStart(SourceLocation CaretLoc, Scope *CurScope) {
Douglas Gregor9ea9bdb2010-03-01 23:15:13 +00009223 BlockDecl *Block = BlockDecl::Create(Context, CurContext, CaretLoc);
Richard Trieuccd891a2011-09-09 01:45:06 +00009224 PushBlockScope(CurScope, Block);
Douglas Gregor9ea9bdb2010-03-01 23:15:13 +00009225 CurContext->addDecl(Block);
Richard Trieuccd891a2011-09-09 01:45:06 +00009226 if (CurScope)
9227 PushDeclContext(CurScope, Block);
Fariborz Jahaniana729da22010-07-09 18:44:02 +00009228 else
9229 CurContext = Block;
John McCall538773c2011-11-11 03:19:12 +00009230
Eli Friedman84b007f2012-01-26 03:00:14 +00009231 getCurBlock()->HasImplicitReturnType = true;
9232
John McCall538773c2011-11-11 03:19:12 +00009233 // Enter a new evaluation context to insulate the block from any
9234 // cleanups from the enclosing full-expression.
9235 PushExpressionEvaluationContext(PotentiallyEvaluated);
Steve Naroff090276f2008-10-10 01:28:17 +00009236}
9237
Douglas Gregor03f1eb02012-06-15 16:59:29 +00009238void Sema::ActOnBlockArguments(SourceLocation CaretLoc, Declarator &ParamInfo,
9239 Scope *CurScope) {
Mike Stumpaf199f32009-05-07 18:43:07 +00009240 assert(ParamInfo.getIdentifier()==0 && "block-id should have no identifier!");
John McCall711c52b2011-01-05 12:14:39 +00009241 assert(ParamInfo.getContext() == Declarator::BlockLiteralContext);
Douglas Gregor9ea9bdb2010-03-01 23:15:13 +00009242 BlockScopeInfo *CurBlock = getCurBlock();
Kovarththanan Rajaratnam19357542010-03-13 10:17:05 +00009243
John McCallbf1a0282010-06-04 23:28:52 +00009244 TypeSourceInfo *Sig = GetTypeForDeclarator(ParamInfo, CurScope);
John McCallbf1a0282010-06-04 23:28:52 +00009245 QualType T = Sig->getType();
Mike Stump98eb8a72009-02-04 22:31:32 +00009246
Douglas Gregor03f1eb02012-06-15 16:59:29 +00009247 // FIXME: We should allow unexpanded parameter packs here, but that would,
9248 // in turn, make the block expression contain unexpanded parameter packs.
9249 if (DiagnoseUnexpandedParameterPack(CaretLoc, Sig, UPPC_Block)) {
9250 // Drop the parameters.
9251 FunctionProtoType::ExtProtoInfo EPI;
9252 EPI.HasTrailingReturn = false;
9253 EPI.TypeQuals |= DeclSpec::TQ_const;
9254 T = Context.getFunctionType(Context.DependentTy, /*Args=*/0, /*NumArgs=*/0,
9255 EPI);
9256 Sig = Context.getTrivialTypeSourceInfo(T);
9257 }
9258
John McCall711c52b2011-01-05 12:14:39 +00009259 // GetTypeForDeclarator always produces a function type for a block
9260 // literal signature. Furthermore, it is always a FunctionProtoType
9261 // unless the function was written with a typedef.
9262 assert(T->isFunctionType() &&
9263 "GetTypeForDeclarator made a non-function block signature");
9264
9265 // Look for an explicit signature in that function type.
9266 FunctionProtoTypeLoc ExplicitSignature;
9267
9268 TypeLoc tmp = Sig->getTypeLoc().IgnoreParens();
9269 if (isa<FunctionProtoTypeLoc>(tmp)) {
9270 ExplicitSignature = cast<FunctionProtoTypeLoc>(tmp);
9271
9272 // Check whether that explicit signature was synthesized by
9273 // GetTypeForDeclarator. If so, don't save that as part of the
9274 // written signature.
Abramo Bagnara796aa442011-03-12 11:17:06 +00009275 if (ExplicitSignature.getLocalRangeBegin() ==
9276 ExplicitSignature.getLocalRangeEnd()) {
John McCall711c52b2011-01-05 12:14:39 +00009277 // This would be much cheaper if we stored TypeLocs instead of
9278 // TypeSourceInfos.
9279 TypeLoc Result = ExplicitSignature.getResultLoc();
9280 unsigned Size = Result.getFullDataSize();
9281 Sig = Context.CreateTypeSourceInfo(Result.getType(), Size);
9282 Sig->getTypeLoc().initializeFullCopy(Result, Size);
9283
9284 ExplicitSignature = FunctionProtoTypeLoc();
9285 }
John McCall82dc0092010-06-04 11:21:44 +00009286 }
Mike Stump1eb44332009-09-09 15:08:12 +00009287
John McCall711c52b2011-01-05 12:14:39 +00009288 CurBlock->TheDecl->setSignatureAsWritten(Sig);
9289 CurBlock->FunctionType = T;
9290
9291 const FunctionType *Fn = T->getAs<FunctionType>();
9292 QualType RetTy = Fn->getResultType();
9293 bool isVariadic =
9294 (isa<FunctionProtoType>(Fn) && cast<FunctionProtoType>(Fn)->isVariadic());
9295
John McCallc71a4912010-06-04 19:02:56 +00009296 CurBlock->TheDecl->setIsVariadic(isVariadic);
Douglas Gregora873dfc2010-02-03 00:27:59 +00009297
John McCall82dc0092010-06-04 11:21:44 +00009298 // Don't allow returning a objc interface by value.
9299 if (RetTy->isObjCObjectType()) {
Daniel Dunbar96a00142012-03-09 18:35:03 +00009300 Diag(ParamInfo.getLocStart(),
John McCall82dc0092010-06-04 11:21:44 +00009301 diag::err_object_cannot_be_passed_returned_by_value) << 0 << RetTy;
9302 return;
9303 }
Mike Stumpeed9cac2009-02-19 03:04:26 +00009304
John McCall82dc0092010-06-04 11:21:44 +00009305 // Context.DependentTy is used as a placeholder for a missing block
John McCallc71a4912010-06-04 19:02:56 +00009306 // return type. TODO: what should we do with declarators like:
9307 // ^ * { ... }
9308 // If the answer is "apply template argument deduction"....
Fariborz Jahanian05865202011-12-03 17:47:53 +00009309 if (RetTy != Context.DependentTy) {
John McCall82dc0092010-06-04 11:21:44 +00009310 CurBlock->ReturnType = RetTy;
Fariborz Jahanian05865202011-12-03 17:47:53 +00009311 CurBlock->TheDecl->setBlockMissingReturnType(false);
Eli Friedman84b007f2012-01-26 03:00:14 +00009312 CurBlock->HasImplicitReturnType = false;
Fariborz Jahanian05865202011-12-03 17:47:53 +00009313 }
Mike Stumpeed9cac2009-02-19 03:04:26 +00009314
John McCall82dc0092010-06-04 11:21:44 +00009315 // Push block parameters from the declarator if we had them.
Chris Lattner5f9e2722011-07-23 10:55:15 +00009316 SmallVector<ParmVarDecl*, 8> Params;
John McCall711c52b2011-01-05 12:14:39 +00009317 if (ExplicitSignature) {
9318 for (unsigned I = 0, E = ExplicitSignature.getNumArgs(); I != E; ++I) {
9319 ParmVarDecl *Param = ExplicitSignature.getArg(I);
Fariborz Jahanian9a66c302010-02-12 21:53:14 +00009320 if (Param->getIdentifier() == 0 &&
9321 !Param->isImplicit() &&
9322 !Param->isInvalidDecl() &&
David Blaikie4e4d0842012-03-11 07:00:24 +00009323 !getLangOpts().CPlusPlus)
Fariborz Jahanian9a66c302010-02-12 21:53:14 +00009324 Diag(Param->getLocation(), diag::err_parameter_name_omitted);
John McCallc71a4912010-06-04 19:02:56 +00009325 Params.push_back(Param);
Fariborz Jahanian9a66c302010-02-12 21:53:14 +00009326 }
John McCall82dc0092010-06-04 11:21:44 +00009327
9328 // Fake up parameter variables if we have a typedef, like
9329 // ^ fntype { ... }
9330 } else if (const FunctionProtoType *Fn = T->getAs<FunctionProtoType>()) {
9331 for (FunctionProtoType::arg_type_iterator
9332 I = Fn->arg_type_begin(), E = Fn->arg_type_end(); I != E; ++I) {
9333 ParmVarDecl *Param =
9334 BuildParmVarDeclForTypedef(CurBlock->TheDecl,
Daniel Dunbar96a00142012-03-09 18:35:03 +00009335 ParamInfo.getLocStart(),
John McCall82dc0092010-06-04 11:21:44 +00009336 *I);
John McCallc71a4912010-06-04 19:02:56 +00009337 Params.push_back(Param);
John McCall82dc0092010-06-04 11:21:44 +00009338 }
Steve Naroff4eb206b2008-09-03 18:15:37 +00009339 }
John McCall82dc0092010-06-04 11:21:44 +00009340
John McCallc71a4912010-06-04 19:02:56 +00009341 // Set the parameters on the block decl.
Douglas Gregor82aa7132010-11-01 18:37:59 +00009342 if (!Params.empty()) {
David Blaikie4278c652011-09-21 18:16:56 +00009343 CurBlock->TheDecl->setParams(Params);
Douglas Gregor82aa7132010-11-01 18:37:59 +00009344 CheckParmsForFunctionDef(CurBlock->TheDecl->param_begin(),
9345 CurBlock->TheDecl->param_end(),
9346 /*CheckParameterNames=*/false);
9347 }
9348
John McCall82dc0092010-06-04 11:21:44 +00009349 // Finally we can process decl attributes.
Douglas Gregor9cdda0c2009-06-17 21:51:59 +00009350 ProcessDeclAttributes(CurScope, CurBlock->TheDecl, ParamInfo);
John McCall053f4bd2010-03-22 09:20:08 +00009351
John McCall82dc0092010-06-04 11:21:44 +00009352 // Put the parameter variables in scope. We can bail out immediately
9353 // if we don't have any.
John McCallc71a4912010-06-04 19:02:56 +00009354 if (Params.empty())
John McCall82dc0092010-06-04 11:21:44 +00009355 return;
9356
Steve Naroff090276f2008-10-10 01:28:17 +00009357 for (BlockDecl::param_iterator AI = CurBlock->TheDecl->param_begin(),
John McCall7a9813c2010-01-22 00:28:27 +00009358 E = CurBlock->TheDecl->param_end(); AI != E; ++AI) {
9359 (*AI)->setOwningFunction(CurBlock->TheDecl);
9360
Steve Naroff090276f2008-10-10 01:28:17 +00009361 // If this has an identifier, add it to the scope stack.
John McCall053f4bd2010-03-22 09:20:08 +00009362 if ((*AI)->getIdentifier()) {
Argyrios Kyrtzidis08274082010-12-15 18:44:22 +00009363 CheckShadow(CurBlock->TheScope, *AI);
John McCall053f4bd2010-03-22 09:20:08 +00009364
Steve Naroff090276f2008-10-10 01:28:17 +00009365 PushOnScopeChains(*AI, CurBlock->TheScope);
John McCall053f4bd2010-03-22 09:20:08 +00009366 }
John McCall7a9813c2010-01-22 00:28:27 +00009367 }
Steve Naroff4eb206b2008-09-03 18:15:37 +00009368}
9369
9370/// ActOnBlockError - If there is an error parsing a block, this callback
9371/// is invoked to pop the information about the block from the action impl.
9372void Sema::ActOnBlockError(SourceLocation CaretLoc, Scope *CurScope) {
John McCall538773c2011-11-11 03:19:12 +00009373 // Leave the expression-evaluation context.
9374 DiscardCleanupsInEvaluationContext();
9375 PopExpressionEvaluationContext();
9376
Steve Naroff4eb206b2008-09-03 18:15:37 +00009377 // Pop off CurBlock, handle nested blocks.
Chris Lattner5c59e2b2009-04-21 22:38:46 +00009378 PopDeclContext();
Eli Friedmanec9ea722012-01-05 03:35:19 +00009379 PopFunctionScopeInfo();
Steve Naroff4eb206b2008-09-03 18:15:37 +00009380}
9381
9382/// ActOnBlockStmtExpr - This is called when the body of a block statement
9383/// literal was successfully completed. ^(int x){...}
John McCall60d7b3a2010-08-24 06:29:42 +00009384ExprResult Sema::ActOnBlockStmtExpr(SourceLocation CaretLoc,
Chris Lattnere476bdc2011-02-17 23:58:47 +00009385 Stmt *Body, Scope *CurScope) {
Chris Lattner9af55002009-03-27 04:18:06 +00009386 // If blocks are disabled, emit an error.
9387 if (!LangOpts.Blocks)
9388 Diag(CaretLoc, diag::err_blocks_disable);
Mike Stump1eb44332009-09-09 15:08:12 +00009389
John McCall538773c2011-11-11 03:19:12 +00009390 // Leave the expression-evaluation context.
John McCall1e5bc4f2012-03-08 22:00:17 +00009391 if (hasAnyUnrecoverableErrorsInThisFunction())
9392 DiscardCleanupsInEvaluationContext();
John McCall538773c2011-11-11 03:19:12 +00009393 assert(!ExprNeedsCleanups && "cleanups within block not correctly bound!");
9394 PopExpressionEvaluationContext();
9395
Douglas Gregor9ea9bdb2010-03-01 23:15:13 +00009396 BlockScopeInfo *BSI = cast<BlockScopeInfo>(FunctionScopes.back());
Jordan Rose7dd900e2012-07-02 21:19:23 +00009397
9398 if (BSI->HasImplicitReturnType)
9399 deduceClosureReturnType(*BSI);
9400
Steve Naroff090276f2008-10-10 01:28:17 +00009401 PopDeclContext();
9402
Steve Naroff4eb206b2008-09-03 18:15:37 +00009403 QualType RetTy = Context.VoidTy;
Fariborz Jahanian7d5c74e2009-06-19 23:37:08 +00009404 if (!BSI->ReturnType.isNull())
9405 RetTy = BSI->ReturnType;
Mike Stumpeed9cac2009-02-19 03:04:26 +00009406
Mike Stump56925862009-07-28 22:04:01 +00009407 bool NoReturn = BSI->TheDecl->getAttr<NoReturnAttr>();
Steve Naroff4eb206b2008-09-03 18:15:37 +00009408 QualType BlockTy;
John McCallc71a4912010-06-04 19:02:56 +00009409
John McCall469a1eb2011-02-02 13:00:07 +00009410 // Set the captured variables on the block.
Eli Friedmanb69b42c2012-01-11 02:36:31 +00009411 // FIXME: Share capture structure between BlockDecl and CapturingScopeInfo!
9412 SmallVector<BlockDecl::Capture, 4> Captures;
9413 for (unsigned i = 0, e = BSI->Captures.size(); i != e; i++) {
9414 CapturingScopeInfo::Capture &Cap = BSI->Captures[i];
9415 if (Cap.isThisCapture())
9416 continue;
Eli Friedmanb942cb22012-02-03 22:47:37 +00009417 BlockDecl::Capture NewCap(Cap.getVariable(), Cap.isBlockCapture(),
Eli Friedmanb69b42c2012-01-11 02:36:31 +00009418 Cap.isNested(), Cap.getCopyExpr());
9419 Captures.push_back(NewCap);
9420 }
9421 BSI->TheDecl->setCaptures(Context, Captures.begin(), Captures.end(),
9422 BSI->CXXThisCaptureIndex != 0);
John McCall469a1eb2011-02-02 13:00:07 +00009423
John McCallc71a4912010-06-04 19:02:56 +00009424 // If the user wrote a function type in some form, try to use that.
9425 if (!BSI->FunctionType.isNull()) {
9426 const FunctionType *FTy = BSI->FunctionType->getAs<FunctionType>();
9427
9428 FunctionType::ExtInfo Ext = FTy->getExtInfo();
9429 if (NoReturn && !Ext.getNoReturn()) Ext = Ext.withNoReturn(true);
9430
9431 // Turn protoless block types into nullary block types.
9432 if (isa<FunctionNoProtoType>(FTy)) {
John McCalle23cf432010-12-14 08:05:40 +00009433 FunctionProtoType::ExtProtoInfo EPI;
9434 EPI.ExtInfo = Ext;
9435 BlockTy = Context.getFunctionType(RetTy, 0, 0, EPI);
John McCallc71a4912010-06-04 19:02:56 +00009436
9437 // Otherwise, if we don't need to change anything about the function type,
9438 // preserve its sugar structure.
9439 } else if (FTy->getResultType() == RetTy &&
9440 (!NoReturn || FTy->getNoReturnAttr())) {
9441 BlockTy = BSI->FunctionType;
9442
9443 // Otherwise, make the minimal modifications to the function type.
9444 } else {
9445 const FunctionProtoType *FPT = cast<FunctionProtoType>(FTy);
John McCalle23cf432010-12-14 08:05:40 +00009446 FunctionProtoType::ExtProtoInfo EPI = FPT->getExtProtoInfo();
9447 EPI.TypeQuals = 0; // FIXME: silently?
9448 EPI.ExtInfo = Ext;
John McCallc71a4912010-06-04 19:02:56 +00009449 BlockTy = Context.getFunctionType(RetTy,
9450 FPT->arg_type_begin(),
9451 FPT->getNumArgs(),
John McCalle23cf432010-12-14 08:05:40 +00009452 EPI);
John McCallc71a4912010-06-04 19:02:56 +00009453 }
9454
9455 // If we don't have a function type, just build one from nothing.
9456 } else {
John McCalle23cf432010-12-14 08:05:40 +00009457 FunctionProtoType::ExtProtoInfo EPI;
John McCallf85e1932011-06-15 23:02:42 +00009458 EPI.ExtInfo = FunctionType::ExtInfo().withNoReturn(NoReturn);
John McCalle23cf432010-12-14 08:05:40 +00009459 BlockTy = Context.getFunctionType(RetTy, 0, 0, EPI);
John McCallc71a4912010-06-04 19:02:56 +00009460 }
Mike Stumpeed9cac2009-02-19 03:04:26 +00009461
John McCallc71a4912010-06-04 19:02:56 +00009462 DiagnoseUnusedParameters(BSI->TheDecl->param_begin(),
9463 BSI->TheDecl->param_end());
Steve Naroff4eb206b2008-09-03 18:15:37 +00009464 BlockTy = Context.getBlockPointerType(BlockTy);
Mike Stumpeed9cac2009-02-19 03:04:26 +00009465
Chris Lattner17a78302009-04-19 05:28:12 +00009466 // If needed, diagnose invalid gotos and switches in the block.
John McCallf85e1932011-06-15 23:02:42 +00009467 if (getCurFunction()->NeedsScopeChecking() &&
Douglas Gregor27bec772012-08-17 05:12:08 +00009468 !hasAnyUnrecoverableErrorsInThisFunction() &&
9469 !PP.isCodeCompletionEnabled())
John McCall9ae2f072010-08-23 23:25:46 +00009470 DiagnoseInvalidJumps(cast<CompoundStmt>(Body));
Mike Stump1eb44332009-09-09 15:08:12 +00009471
Chris Lattnere476bdc2011-02-17 23:58:47 +00009472 BSI->TheDecl->setBody(cast<CompoundStmt>(Body));
Kovarththanan Rajaratnam19357542010-03-13 10:17:05 +00009473
Jordan Rose7dd900e2012-07-02 21:19:23 +00009474 // Try to apply the named return value optimization. We have to check again
9475 // if we can do this, though, because blocks keep return statements around
9476 // to deduce an implicit return type.
9477 if (getLangOpts().CPlusPlus && RetTy->isRecordType() &&
9478 !BSI->TheDecl->isDependentContext())
9479 computeNRVO(Body, getCurBlock());
Douglas Gregorf8b7f712011-09-06 20:46:03 +00009480
Benjamin Kramerd2486192011-07-12 14:11:05 +00009481 BlockExpr *Result = new (Context) BlockExpr(BSI->TheDecl, BlockTy);
9482 const AnalysisBasedWarnings::Policy &WP = AnalysisWarnings.getDefaultPolicy();
Eli Friedmanec9ea722012-01-05 03:35:19 +00009483 PopFunctionScopeInfo(&WP, Result->getBlockDecl(), Result);
Benjamin Kramerd2486192011-07-12 14:11:05 +00009484
John McCall80ee6e82011-11-10 05:35:25 +00009485 // If the block isn't obviously global, i.e. it captures anything at
John McCall97b57a22012-04-13 01:08:17 +00009486 // all, then we need to do a few things in the surrounding context:
John McCall80ee6e82011-11-10 05:35:25 +00009487 if (Result->getBlockDecl()->hasCaptures()) {
John McCall97b57a22012-04-13 01:08:17 +00009488 // First, this expression has a new cleanup object.
John McCall80ee6e82011-11-10 05:35:25 +00009489 ExprCleanupObjects.push_back(Result->getBlockDecl());
9490 ExprNeedsCleanups = true;
John McCall97b57a22012-04-13 01:08:17 +00009491
9492 // It also gets a branch-protected scope if any of the captured
9493 // variables needs destruction.
9494 for (BlockDecl::capture_const_iterator
9495 ci = Result->getBlockDecl()->capture_begin(),
9496 ce = Result->getBlockDecl()->capture_end(); ci != ce; ++ci) {
9497 const VarDecl *var = ci->getVariable();
9498 if (var->getType().isDestructedType() != QualType::DK_none) {
9499 getCurFunction()->setHasBranchProtectedScope();
9500 break;
9501 }
9502 }
John McCall80ee6e82011-11-10 05:35:25 +00009503 }
Fariborz Jahanian27949f62012-03-06 18:41:35 +00009504
Douglas Gregor9ea9bdb2010-03-01 23:15:13 +00009505 return Owned(Result);
Steve Naroff4eb206b2008-09-03 18:15:37 +00009506}
9507
John McCall60d7b3a2010-08-24 06:29:42 +00009508ExprResult Sema::ActOnVAArg(SourceLocation BuiltinLoc,
Richard Trieuccd891a2011-09-09 01:45:06 +00009509 Expr *E, ParsedType Ty,
Sebastian Redlf53597f2009-03-15 17:47:39 +00009510 SourceLocation RPLoc) {
Abramo Bagnara2cad9002010-08-10 10:06:15 +00009511 TypeSourceInfo *TInfo;
Richard Trieuccd891a2011-09-09 01:45:06 +00009512 GetTypeFromParser(Ty, &TInfo);
9513 return BuildVAArgExpr(BuiltinLoc, E, TInfo, RPLoc);
Abramo Bagnara2cad9002010-08-10 10:06:15 +00009514}
9515
John McCall60d7b3a2010-08-24 06:29:42 +00009516ExprResult Sema::BuildVAArgExpr(SourceLocation BuiltinLoc,
John McCallf89e55a2010-11-18 06:31:45 +00009517 Expr *E, TypeSourceInfo *TInfo,
9518 SourceLocation RPLoc) {
Chris Lattner0d20b8a2009-04-05 15:49:53 +00009519 Expr *OrigExpr = E;
Mike Stump1eb44332009-09-09 15:08:12 +00009520
Eli Friedmanc34bcde2008-08-09 23:32:40 +00009521 // Get the va_list type
9522 QualType VaListType = Context.getBuiltinVaListType();
Eli Friedman5c091ba2009-05-16 12:46:54 +00009523 if (VaListType->isArrayType()) {
9524 // Deal with implicit array decay; for example, on x86-64,
9525 // va_list is an array, but it's supposed to decay to
9526 // a pointer for va_arg.
Eli Friedmanc34bcde2008-08-09 23:32:40 +00009527 VaListType = Context.getArrayDecayedType(VaListType);
Eli Friedman5c091ba2009-05-16 12:46:54 +00009528 // Make sure the input expression also decays appropriately.
John Wiegley429bb272011-04-08 18:41:53 +00009529 ExprResult Result = UsualUnaryConversions(E);
9530 if (Result.isInvalid())
9531 return ExprError();
9532 E = Result.take();
Eli Friedman5c091ba2009-05-16 12:46:54 +00009533 } else {
9534 // Otherwise, the va_list argument must be an l-value because
9535 // it is modified by va_arg.
Mike Stump1eb44332009-09-09 15:08:12 +00009536 if (!E->isTypeDependent() &&
Douglas Gregordd027302009-05-19 23:10:31 +00009537 CheckForModifiableLvalue(E, BuiltinLoc, *this))
Eli Friedman5c091ba2009-05-16 12:46:54 +00009538 return ExprError();
9539 }
Eli Friedmanc34bcde2008-08-09 23:32:40 +00009540
Douglas Gregordd027302009-05-19 23:10:31 +00009541 if (!E->isTypeDependent() &&
9542 !Context.hasSameType(VaListType, E->getType())) {
Sebastian Redlf53597f2009-03-15 17:47:39 +00009543 return ExprError(Diag(E->getLocStart(),
9544 diag::err_first_argument_to_va_arg_not_of_type_va_list)
Chris Lattner0d20b8a2009-04-05 15:49:53 +00009545 << OrigExpr->getType() << E->getSourceRange());
Chris Lattner9dc8f192009-04-05 00:59:53 +00009546 }
Mike Stumpeed9cac2009-02-19 03:04:26 +00009547
David Majnemer0adde122011-06-14 05:17:32 +00009548 if (!TInfo->getType()->isDependentType()) {
9549 if (RequireCompleteType(TInfo->getTypeLoc().getBeginLoc(), TInfo->getType(),
Douglas Gregord10099e2012-05-04 16:32:21 +00009550 diag::err_second_parameter_to_va_arg_incomplete,
9551 TInfo->getTypeLoc()))
David Majnemer0adde122011-06-14 05:17:32 +00009552 return ExprError();
David Majnemerdb11b012011-06-13 06:37:03 +00009553
David Majnemer0adde122011-06-14 05:17:32 +00009554 if (RequireNonAbstractType(TInfo->getTypeLoc().getBeginLoc(),
Douglas Gregor6a26e2e2012-05-04 17:09:59 +00009555 TInfo->getType(),
9556 diag::err_second_parameter_to_va_arg_abstract,
9557 TInfo->getTypeLoc()))
David Majnemer0adde122011-06-14 05:17:32 +00009558 return ExprError();
9559
Douglas Gregor4eb75222011-07-30 06:45:27 +00009560 if (!TInfo->getType().isPODType(Context)) {
David Majnemer0adde122011-06-14 05:17:32 +00009561 Diag(TInfo->getTypeLoc().getBeginLoc(),
Douglas Gregor4eb75222011-07-30 06:45:27 +00009562 TInfo->getType()->isObjCLifetimeType()
9563 ? diag::warn_second_parameter_to_va_arg_ownership_qualified
9564 : diag::warn_second_parameter_to_va_arg_not_pod)
David Majnemer0adde122011-06-14 05:17:32 +00009565 << TInfo->getType()
9566 << TInfo->getTypeLoc().getSourceRange();
Douglas Gregor4eb75222011-07-30 06:45:27 +00009567 }
Eli Friedman46d37c12011-07-11 21:45:59 +00009568
9569 // Check for va_arg where arguments of the given type will be promoted
9570 // (i.e. this va_arg is guaranteed to have undefined behavior).
9571 QualType PromoteType;
9572 if (TInfo->getType()->isPromotableIntegerType()) {
9573 PromoteType = Context.getPromotedIntegerType(TInfo->getType());
9574 if (Context.typesAreCompatible(PromoteType, TInfo->getType()))
9575 PromoteType = QualType();
9576 }
9577 if (TInfo->getType()->isSpecificBuiltinType(BuiltinType::Float))
9578 PromoteType = Context.DoubleTy;
9579 if (!PromoteType.isNull())
9580 Diag(TInfo->getTypeLoc().getBeginLoc(),
9581 diag::warn_second_parameter_to_va_arg_never_compatible)
9582 << TInfo->getType()
9583 << PromoteType
9584 << TInfo->getTypeLoc().getSourceRange();
David Majnemer0adde122011-06-14 05:17:32 +00009585 }
Mike Stumpeed9cac2009-02-19 03:04:26 +00009586
Abramo Bagnara2cad9002010-08-10 10:06:15 +00009587 QualType T = TInfo->getType().getNonLValueExprType(Context);
9588 return Owned(new (Context) VAArgExpr(BuiltinLoc, E, TInfo, RPLoc, T));
Anders Carlsson7c50aca2007-10-15 20:28:48 +00009589}
9590
John McCall60d7b3a2010-08-24 06:29:42 +00009591ExprResult Sema::ActOnGNUNullExpr(SourceLocation TokenLoc) {
Douglas Gregor2d8b2732008-11-29 04:51:27 +00009592 // The type of __null will be int or long, depending on the size of
9593 // pointers on the target.
9594 QualType Ty;
Douglas Gregorbcfd1f52011-09-02 00:18:52 +00009595 unsigned pw = Context.getTargetInfo().getPointerWidth(0);
9596 if (pw == Context.getTargetInfo().getIntWidth())
Douglas Gregor2d8b2732008-11-29 04:51:27 +00009597 Ty = Context.IntTy;
Douglas Gregorbcfd1f52011-09-02 00:18:52 +00009598 else if (pw == Context.getTargetInfo().getLongWidth())
Douglas Gregor2d8b2732008-11-29 04:51:27 +00009599 Ty = Context.LongTy;
Douglas Gregorbcfd1f52011-09-02 00:18:52 +00009600 else if (pw == Context.getTargetInfo().getLongLongWidth())
NAKAMURA Takumi6e5658d2011-01-19 00:11:41 +00009601 Ty = Context.LongLongTy;
9602 else {
David Blaikieb219cfc2011-09-23 05:06:16 +00009603 llvm_unreachable("I don't know size of pointer!");
NAKAMURA Takumi6e5658d2011-01-19 00:11:41 +00009604 }
Douglas Gregor2d8b2732008-11-29 04:51:27 +00009605
Sebastian Redlf53597f2009-03-15 17:47:39 +00009606 return Owned(new (Context) GNUNullExpr(Ty, TokenLoc));
Douglas Gregor2d8b2732008-11-29 04:51:27 +00009607}
9608
Sean Hunt1e3f5ba2010-04-28 23:02:27 +00009609static void MakeObjCStringLiteralFixItHint(Sema& SemaRef, QualType DstType,
Douglas Gregor849b2432010-03-31 17:46:05 +00009610 Expr *SrcExpr, FixItHint &Hint) {
David Blaikie4e4d0842012-03-11 07:00:24 +00009611 if (!SemaRef.getLangOpts().ObjC1)
Anders Carlssonb76cd3d2009-11-10 04:46:30 +00009612 return;
Kovarththanan Rajaratnam19357542010-03-13 10:17:05 +00009613
Anders Carlssonb76cd3d2009-11-10 04:46:30 +00009614 const ObjCObjectPointerType *PT = DstType->getAs<ObjCObjectPointerType>();
9615 if (!PT)
9616 return;
9617
9618 // Check if the destination is of type 'id'.
9619 if (!PT->isObjCIdType()) {
9620 // Check if the destination is the 'NSString' interface.
9621 const ObjCInterfaceDecl *ID = PT->getInterfaceDecl();
9622 if (!ID || !ID->getIdentifier()->isStr("NSString"))
9623 return;
9624 }
Kovarththanan Rajaratnam19357542010-03-13 10:17:05 +00009625
John McCall4b9c2d22011-11-06 09:01:30 +00009626 // Ignore any parens, implicit casts (should only be
9627 // array-to-pointer decays), and not-so-opaque values. The last is
9628 // important for making this trigger for property assignments.
9629 SrcExpr = SrcExpr->IgnoreParenImpCasts();
9630 if (OpaqueValueExpr *OV = dyn_cast<OpaqueValueExpr>(SrcExpr))
9631 if (OV->getSourceExpr())
9632 SrcExpr = OV->getSourceExpr()->IgnoreParenImpCasts();
9633
9634 StringLiteral *SL = dyn_cast<StringLiteral>(SrcExpr);
Douglas Gregor5cee1192011-07-27 05:40:30 +00009635 if (!SL || !SL->isAscii())
Anders Carlssonb76cd3d2009-11-10 04:46:30 +00009636 return;
Kovarththanan Rajaratnam19357542010-03-13 10:17:05 +00009637
Douglas Gregor849b2432010-03-31 17:46:05 +00009638 Hint = FixItHint::CreateInsertion(SL->getLocStart(), "@");
Anders Carlssonb76cd3d2009-11-10 04:46:30 +00009639}
9640
Chris Lattner5cf216b2008-01-04 18:04:52 +00009641bool Sema::DiagnoseAssignmentResult(AssignConvertType ConvTy,
9642 SourceLocation Loc,
9643 QualType DstType, QualType SrcType,
Douglas Gregora41a8c52010-04-22 00:20:18 +00009644 Expr *SrcExpr, AssignmentAction Action,
9645 bool *Complained) {
9646 if (Complained)
9647 *Complained = false;
9648
Chris Lattner5cf216b2008-01-04 18:04:52 +00009649 // Decode the result (notice that AST's are still created for extensions).
Douglas Gregor926df6c2011-06-11 01:09:30 +00009650 bool CheckInferredResultType = false;
Chris Lattner5cf216b2008-01-04 18:04:52 +00009651 bool isInvalid = false;
Eli Friedmanfd819782012-02-29 20:59:56 +00009652 unsigned DiagKind = 0;
Douglas Gregor849b2432010-03-31 17:46:05 +00009653 FixItHint Hint;
Anna Zaks67221552011-07-28 19:51:27 +00009654 ConversionFixItGenerator ConvHints;
9655 bool MayHaveConvFixit = false;
Richard Trieu6efd4c52011-11-23 22:32:32 +00009656 bool MayHaveFunctionDiff = false;
Kovarththanan Rajaratnam19357542010-03-13 10:17:05 +00009657
Chris Lattner5cf216b2008-01-04 18:04:52 +00009658 switch (ConvTy) {
Fariborz Jahanian379b2812012-07-17 18:00:08 +00009659 case Compatible:
9660 DiagnoseAssignmentEnum(DstType, SrcType, SrcExpr);
9661 return false;
9662
Chris Lattnerb7b61152008-01-04 18:22:42 +00009663 case PointerToInt:
Chris Lattner5cf216b2008-01-04 18:04:52 +00009664 DiagKind = diag::ext_typecheck_convert_pointer_int;
Anna Zaks67221552011-07-28 19:51:27 +00009665 ConvHints.tryToFixConversion(SrcExpr, SrcType, DstType, *this);
9666 MayHaveConvFixit = true;
Chris Lattner5cf216b2008-01-04 18:04:52 +00009667 break;
Chris Lattnerb7b61152008-01-04 18:22:42 +00009668 case IntToPointer:
9669 DiagKind = diag::ext_typecheck_convert_int_pointer;
Anna Zaks67221552011-07-28 19:51:27 +00009670 ConvHints.tryToFixConversion(SrcExpr, SrcType, DstType, *this);
9671 MayHaveConvFixit = true;
Chris Lattnerb7b61152008-01-04 18:22:42 +00009672 break;
Chris Lattner5cf216b2008-01-04 18:04:52 +00009673 case IncompatiblePointer:
Douglas Gregor849b2432010-03-31 17:46:05 +00009674 MakeObjCStringLiteralFixItHint(*this, DstType, SrcExpr, Hint);
Chris Lattner5cf216b2008-01-04 18:04:52 +00009675 DiagKind = diag::ext_typecheck_convert_incompatible_pointer;
Douglas Gregor926df6c2011-06-11 01:09:30 +00009676 CheckInferredResultType = DstType->isObjCObjectPointerType() &&
9677 SrcType->isObjCObjectPointerType();
Anna Zaks67221552011-07-28 19:51:27 +00009678 if (Hint.isNull() && !CheckInferredResultType) {
9679 ConvHints.tryToFixConversion(SrcExpr, SrcType, DstType, *this);
9680 }
9681 MayHaveConvFixit = true;
Chris Lattner5cf216b2008-01-04 18:04:52 +00009682 break;
Eli Friedmanf05c05d2009-03-22 23:59:44 +00009683 case IncompatiblePointerSign:
9684 DiagKind = diag::ext_typecheck_convert_incompatible_pointer_sign;
9685 break;
Chris Lattner5cf216b2008-01-04 18:04:52 +00009686 case FunctionVoidPointer:
9687 DiagKind = diag::ext_typecheck_convert_pointer_void_func;
9688 break;
John McCall86c05f32011-02-01 00:10:29 +00009689 case IncompatiblePointerDiscardsQualifiers: {
John McCall40249e72011-02-01 23:28:01 +00009690 // Perform array-to-pointer decay if necessary.
9691 if (SrcType->isArrayType()) SrcType = Context.getArrayDecayedType(SrcType);
9692
John McCall86c05f32011-02-01 00:10:29 +00009693 Qualifiers lhq = SrcType->getPointeeType().getQualifiers();
9694 Qualifiers rhq = DstType->getPointeeType().getQualifiers();
9695 if (lhq.getAddressSpace() != rhq.getAddressSpace()) {
9696 DiagKind = diag::err_typecheck_incompatible_address_space;
9697 break;
John McCallf85e1932011-06-15 23:02:42 +00009698
9699
9700 } else if (lhq.getObjCLifetime() != rhq.getObjCLifetime()) {
Argyrios Kyrtzidisb8b03132011-06-24 00:08:59 +00009701 DiagKind = diag::err_typecheck_incompatible_ownership;
John McCallf85e1932011-06-15 23:02:42 +00009702 break;
John McCall86c05f32011-02-01 00:10:29 +00009703 }
9704
9705 llvm_unreachable("unknown error case for discarding qualifiers!");
9706 // fallthrough
9707 }
Chris Lattner5cf216b2008-01-04 18:04:52 +00009708 case CompatiblePointerDiscardsQualifiers:
Douglas Gregor77a52232008-09-12 00:47:35 +00009709 // If the qualifiers lost were because we were applying the
9710 // (deprecated) C++ conversion from a string literal to a char*
9711 // (or wchar_t*), then there was no error (C++ 4.2p2). FIXME:
9712 // Ideally, this check would be performed in
John McCalle4be87e2011-01-31 23:13:11 +00009713 // checkPointerTypesForAssignment. However, that would require a
Douglas Gregor77a52232008-09-12 00:47:35 +00009714 // bit of refactoring (so that the second argument is an
9715 // expression, rather than a type), which should be done as part
John McCalle4be87e2011-01-31 23:13:11 +00009716 // of a larger effort to fix checkPointerTypesForAssignment for
Douglas Gregor77a52232008-09-12 00:47:35 +00009717 // C++ semantics.
David Blaikie4e4d0842012-03-11 07:00:24 +00009718 if (getLangOpts().CPlusPlus &&
Douglas Gregor77a52232008-09-12 00:47:35 +00009719 IsStringLiteralToNonConstPointerConversion(SrcExpr, DstType))
9720 return false;
Chris Lattner5cf216b2008-01-04 18:04:52 +00009721 DiagKind = diag::ext_typecheck_convert_discards_qualifiers;
9722 break;
Sean Huntc9132b62009-11-08 07:46:34 +00009723 case IncompatibleNestedPointerQualifiers:
Fariborz Jahanian3451e922009-11-09 22:16:37 +00009724 DiagKind = diag::ext_nested_pointer_qualifier_mismatch;
Fariborz Jahanian36a862f2009-11-07 20:20:40 +00009725 break;
Steve Naroff1c7d0672008-09-04 15:10:53 +00009726 case IntToBlockPointer:
9727 DiagKind = diag::err_int_to_block_pointer;
9728 break;
9729 case IncompatibleBlockPointer:
Mike Stump25efa102009-04-21 22:51:42 +00009730 DiagKind = diag::err_typecheck_convert_incompatible_block_pointer;
Steve Naroff1c7d0672008-09-04 15:10:53 +00009731 break;
Steve Naroff39579072008-10-14 22:18:38 +00009732 case IncompatibleObjCQualifiedId:
Mike Stumpeed9cac2009-02-19 03:04:26 +00009733 // FIXME: Diagnose the problem in ObjCQualifiedIdTypesAreCompatible, since
Steve Naroff39579072008-10-14 22:18:38 +00009734 // it can give a more specific diagnostic.
9735 DiagKind = diag::warn_incompatible_qualified_id;
9736 break;
Anders Carlssonb0f90cc2009-01-30 23:17:46 +00009737 case IncompatibleVectors:
9738 DiagKind = diag::warn_incompatible_vectors;
9739 break;
Fariborz Jahanian04e5a252011-07-07 18:55:47 +00009740 case IncompatibleObjCWeakRef:
9741 DiagKind = diag::err_arc_weak_unavailable_assign;
9742 break;
Chris Lattner5cf216b2008-01-04 18:04:52 +00009743 case Incompatible:
9744 DiagKind = diag::err_typecheck_convert_incompatible;
Anna Zaks67221552011-07-28 19:51:27 +00009745 ConvHints.tryToFixConversion(SrcExpr, SrcType, DstType, *this);
9746 MayHaveConvFixit = true;
Chris Lattner5cf216b2008-01-04 18:04:52 +00009747 isInvalid = true;
Richard Trieu6efd4c52011-11-23 22:32:32 +00009748 MayHaveFunctionDiff = true;
Chris Lattner5cf216b2008-01-04 18:04:52 +00009749 break;
9750 }
Mike Stumpeed9cac2009-02-19 03:04:26 +00009751
Douglas Gregord4eea832010-04-09 00:35:39 +00009752 QualType FirstType, SecondType;
9753 switch (Action) {
9754 case AA_Assigning:
9755 case AA_Initializing:
9756 // The destination type comes first.
9757 FirstType = DstType;
9758 SecondType = SrcType;
9759 break;
Sean Hunt1e3f5ba2010-04-28 23:02:27 +00009760
Douglas Gregord4eea832010-04-09 00:35:39 +00009761 case AA_Returning:
9762 case AA_Passing:
9763 case AA_Converting:
9764 case AA_Sending:
9765 case AA_Casting:
9766 // The source type comes first.
9767 FirstType = SrcType;
9768 SecondType = DstType;
9769 break;
9770 }
Sean Hunt1e3f5ba2010-04-28 23:02:27 +00009771
Anna Zaks67221552011-07-28 19:51:27 +00009772 PartialDiagnostic FDiag = PDiag(DiagKind);
9773 FDiag << FirstType << SecondType << Action << SrcExpr->getSourceRange();
9774
9775 // If we can fix the conversion, suggest the FixIts.
9776 assert(ConvHints.isNull() || Hint.isNull());
9777 if (!ConvHints.isNull()) {
Benjamin Kramer1136ef02012-01-14 21:05:10 +00009778 for (std::vector<FixItHint>::iterator HI = ConvHints.Hints.begin(),
9779 HE = ConvHints.Hints.end(); HI != HE; ++HI)
Anna Zaks67221552011-07-28 19:51:27 +00009780 FDiag << *HI;
9781 } else {
9782 FDiag << Hint;
9783 }
9784 if (MayHaveConvFixit) { FDiag << (unsigned) (ConvHints.Kind); }
9785
Richard Trieu6efd4c52011-11-23 22:32:32 +00009786 if (MayHaveFunctionDiff)
9787 HandleFunctionTypeMismatch(FDiag, SecondType, FirstType);
9788
Anna Zaks67221552011-07-28 19:51:27 +00009789 Diag(Loc, FDiag);
9790
Richard Trieu6efd4c52011-11-23 22:32:32 +00009791 if (SecondType == Context.OverloadTy)
9792 NoteAllOverloadCandidates(OverloadExpr::find(SrcExpr).Expression,
9793 FirstType);
9794
Douglas Gregor926df6c2011-06-11 01:09:30 +00009795 if (CheckInferredResultType)
9796 EmitRelatedResultTypeNote(SrcExpr);
9797
Douglas Gregora41a8c52010-04-22 00:20:18 +00009798 if (Complained)
9799 *Complained = true;
Chris Lattner5cf216b2008-01-04 18:04:52 +00009800 return isInvalid;
9801}
Anders Carlssone21555e2008-11-30 19:50:32 +00009802
Richard Smith282e7e62012-02-04 09:53:13 +00009803ExprResult Sema::VerifyIntegerConstantExpression(Expr *E,
9804 llvm::APSInt *Result) {
Douglas Gregorab41fe92012-05-04 22:38:52 +00009805 class SimpleICEDiagnoser : public VerifyICEDiagnoser {
9806 public:
9807 virtual void diagnoseNotICE(Sema &S, SourceLocation Loc, SourceRange SR) {
9808 S.Diag(Loc, diag::err_expr_not_ice) << S.LangOpts.CPlusPlus << SR;
9809 }
9810 } Diagnoser;
9811
9812 return VerifyIntegerConstantExpression(E, Result, Diagnoser);
9813}
9814
9815ExprResult Sema::VerifyIntegerConstantExpression(Expr *E,
9816 llvm::APSInt *Result,
9817 unsigned DiagID,
9818 bool AllowFold) {
9819 class IDDiagnoser : public VerifyICEDiagnoser {
9820 unsigned DiagID;
9821
9822 public:
9823 IDDiagnoser(unsigned DiagID)
9824 : VerifyICEDiagnoser(DiagID == 0), DiagID(DiagID) { }
9825
9826 virtual void diagnoseNotICE(Sema &S, SourceLocation Loc, SourceRange SR) {
9827 S.Diag(Loc, DiagID) << SR;
9828 }
9829 } Diagnoser(DiagID);
9830
9831 return VerifyIntegerConstantExpression(E, Result, Diagnoser, AllowFold);
9832}
9833
9834void Sema::VerifyICEDiagnoser::diagnoseFold(Sema &S, SourceLocation Loc,
9835 SourceRange SR) {
9836 S.Diag(Loc, diag::ext_expr_not_ice) << SR << S.LangOpts.CPlusPlus;
Richard Smith282e7e62012-02-04 09:53:13 +00009837}
9838
Benjamin Kramerd448ce02012-04-18 14:22:41 +00009839ExprResult
9840Sema::VerifyIntegerConstantExpression(Expr *E, llvm::APSInt *Result,
Douglas Gregorab41fe92012-05-04 22:38:52 +00009841 VerifyICEDiagnoser &Diagnoser,
9842 bool AllowFold) {
Daniel Dunbar96a00142012-03-09 18:35:03 +00009843 SourceLocation DiagLoc = E->getLocStart();
Richard Smith282e7e62012-02-04 09:53:13 +00009844
David Blaikie4e4d0842012-03-11 07:00:24 +00009845 if (getLangOpts().CPlusPlus0x) {
Richard Smith282e7e62012-02-04 09:53:13 +00009846 // C++11 [expr.const]p5:
9847 // If an expression of literal class type is used in a context where an
9848 // integral constant expression is required, then that class type shall
9849 // have a single non-explicit conversion function to an integral or
9850 // unscoped enumeration type
9851 ExprResult Converted;
Douglas Gregorab41fe92012-05-04 22:38:52 +00009852 if (!Diagnoser.Suppress) {
9853 class CXX11ConvertDiagnoser : public ICEConvertDiagnoser {
9854 public:
9855 CXX11ConvertDiagnoser() : ICEConvertDiagnoser(false, true) { }
9856
9857 virtual DiagnosticBuilder diagnoseNotInt(Sema &S, SourceLocation Loc,
9858 QualType T) {
9859 return S.Diag(Loc, diag::err_ice_not_integral) << T;
9860 }
9861
9862 virtual DiagnosticBuilder diagnoseIncomplete(Sema &S,
9863 SourceLocation Loc,
9864 QualType T) {
9865 return S.Diag(Loc, diag::err_ice_incomplete_type) << T;
9866 }
9867
9868 virtual DiagnosticBuilder diagnoseExplicitConv(Sema &S,
9869 SourceLocation Loc,
9870 QualType T,
9871 QualType ConvTy) {
9872 return S.Diag(Loc, diag::err_ice_explicit_conversion) << T << ConvTy;
9873 }
9874
9875 virtual DiagnosticBuilder noteExplicitConv(Sema &S,
9876 CXXConversionDecl *Conv,
9877 QualType ConvTy) {
9878 return S.Diag(Conv->getLocation(), diag::note_ice_conversion_here)
9879 << ConvTy->isEnumeralType() << ConvTy;
9880 }
9881
9882 virtual DiagnosticBuilder diagnoseAmbiguous(Sema &S, SourceLocation Loc,
9883 QualType T) {
9884 return S.Diag(Loc, diag::err_ice_ambiguous_conversion) << T;
9885 }
9886
9887 virtual DiagnosticBuilder noteAmbiguous(Sema &S,
9888 CXXConversionDecl *Conv,
9889 QualType ConvTy) {
9890 return S.Diag(Conv->getLocation(), diag::note_ice_conversion_here)
9891 << ConvTy->isEnumeralType() << ConvTy;
9892 }
9893
9894 virtual DiagnosticBuilder diagnoseConversion(Sema &S,
9895 SourceLocation Loc,
9896 QualType T,
9897 QualType ConvTy) {
9898 return DiagnosticBuilder::getEmpty();
9899 }
9900 } ConvertDiagnoser;
9901
9902 Converted = ConvertToIntegralOrEnumerationType(DiagLoc, E,
9903 ConvertDiagnoser,
9904 /*AllowScopedEnumerations*/ false);
Richard Smith282e7e62012-02-04 09:53:13 +00009905 } else {
9906 // The caller wants to silently enquire whether this is an ICE. Don't
9907 // produce any diagnostics if it isn't.
Douglas Gregorab41fe92012-05-04 22:38:52 +00009908 class SilentICEConvertDiagnoser : public ICEConvertDiagnoser {
9909 public:
9910 SilentICEConvertDiagnoser() : ICEConvertDiagnoser(true, true) { }
9911
9912 virtual DiagnosticBuilder diagnoseNotInt(Sema &S, SourceLocation Loc,
9913 QualType T) {
9914 return DiagnosticBuilder::getEmpty();
9915 }
9916
9917 virtual DiagnosticBuilder diagnoseIncomplete(Sema &S,
9918 SourceLocation Loc,
9919 QualType T) {
9920 return DiagnosticBuilder::getEmpty();
9921 }
9922
9923 virtual DiagnosticBuilder diagnoseExplicitConv(Sema &S,
9924 SourceLocation Loc,
9925 QualType T,
9926 QualType ConvTy) {
9927 return DiagnosticBuilder::getEmpty();
9928 }
9929
9930 virtual DiagnosticBuilder noteExplicitConv(Sema &S,
9931 CXXConversionDecl *Conv,
9932 QualType ConvTy) {
9933 return DiagnosticBuilder::getEmpty();
9934 }
9935
9936 virtual DiagnosticBuilder diagnoseAmbiguous(Sema &S, SourceLocation Loc,
9937 QualType T) {
9938 return DiagnosticBuilder::getEmpty();
9939 }
9940
9941 virtual DiagnosticBuilder noteAmbiguous(Sema &S,
9942 CXXConversionDecl *Conv,
9943 QualType ConvTy) {
9944 return DiagnosticBuilder::getEmpty();
9945 }
9946
9947 virtual DiagnosticBuilder diagnoseConversion(Sema &S,
9948 SourceLocation Loc,
9949 QualType T,
9950 QualType ConvTy) {
9951 return DiagnosticBuilder::getEmpty();
9952 }
9953 } ConvertDiagnoser;
9954
9955 Converted = ConvertToIntegralOrEnumerationType(DiagLoc, E,
9956 ConvertDiagnoser, false);
Richard Smith282e7e62012-02-04 09:53:13 +00009957 }
9958 if (Converted.isInvalid())
9959 return Converted;
9960 E = Converted.take();
9961 if (!E->getType()->isIntegralOrUnscopedEnumerationType())
9962 return ExprError();
9963 } else if (!E->getType()->isIntegralOrUnscopedEnumerationType()) {
9964 // An ICE must be of integral or unscoped enumeration type.
Douglas Gregorab41fe92012-05-04 22:38:52 +00009965 if (!Diagnoser.Suppress)
9966 Diagnoser.diagnoseNotICE(*this, DiagLoc, E->getSourceRange());
Richard Smith282e7e62012-02-04 09:53:13 +00009967 return ExprError();
9968 }
9969
Richard Smithdaaefc52011-12-14 23:32:26 +00009970 // Circumvent ICE checking in C++11 to avoid evaluating the expression twice
9971 // in the non-ICE case.
David Blaikie4e4d0842012-03-11 07:00:24 +00009972 if (!getLangOpts().CPlusPlus0x && E->isIntegerConstantExpr(Context)) {
Richard Smith282e7e62012-02-04 09:53:13 +00009973 if (Result)
9974 *Result = E->EvaluateKnownConstInt(Context);
9975 return Owned(E);
Eli Friedman3b5ccca2009-04-25 22:26:58 +00009976 }
9977
Anders Carlssone21555e2008-11-30 19:50:32 +00009978 Expr::EvalResult EvalResult;
Richard Smithdd1f29b2011-12-12 09:28:41 +00009979 llvm::SmallVector<PartialDiagnosticAt, 8> Notes;
9980 EvalResult.Diag = &Notes;
Anders Carlssone21555e2008-11-30 19:50:32 +00009981
Richard Smithdaaefc52011-12-14 23:32:26 +00009982 // Try to evaluate the expression, and produce diagnostics explaining why it's
9983 // not a constant expression as a side-effect.
9984 bool Folded = E->EvaluateAsRValue(EvalResult, Context) &&
9985 EvalResult.Val.isInt() && !EvalResult.HasSideEffects;
9986
9987 // In C++11, we can rely on diagnostics being produced for any expression
9988 // which is not a constant expression. If no diagnostics were produced, then
9989 // this is a constant expression.
David Blaikie4e4d0842012-03-11 07:00:24 +00009990 if (Folded && getLangOpts().CPlusPlus0x && Notes.empty()) {
Richard Smithdaaefc52011-12-14 23:32:26 +00009991 if (Result)
9992 *Result = EvalResult.Val.getInt();
Richard Smith282e7e62012-02-04 09:53:13 +00009993 return Owned(E);
9994 }
9995
9996 // If our only note is the usual "invalid subexpression" note, just point
9997 // the caret at its location rather than producing an essentially
9998 // redundant note.
9999 if (Notes.size() == 1 && Notes[0].second.getDiagID() ==
10000 diag::note_invalid_subexpr_in_const_expr) {
10001 DiagLoc = Notes[0].first;
10002 Notes.clear();
Richard Smithdaaefc52011-12-14 23:32:26 +000010003 }
10004
10005 if (!Folded || !AllowFold) {
Douglas Gregorab41fe92012-05-04 22:38:52 +000010006 if (!Diagnoser.Suppress) {
10007 Diagnoser.diagnoseNotICE(*this, DiagLoc, E->getSourceRange());
Richard Smithdd1f29b2011-12-12 09:28:41 +000010008 for (unsigned I = 0, N = Notes.size(); I != N; ++I)
10009 Diag(Notes[I].first, Notes[I].second);
Anders Carlssone21555e2008-11-30 19:50:32 +000010010 }
Mike Stumpeed9cac2009-02-19 03:04:26 +000010011
Richard Smith282e7e62012-02-04 09:53:13 +000010012 return ExprError();
Anders Carlssone21555e2008-11-30 19:50:32 +000010013 }
10014
Douglas Gregorab41fe92012-05-04 22:38:52 +000010015 Diagnoser.diagnoseFold(*this, DiagLoc, E->getSourceRange());
Richard Smith244ee7b2012-01-15 03:51:30 +000010016 for (unsigned I = 0, N = Notes.size(); I != N; ++I)
10017 Diag(Notes[I].first, Notes[I].second);
Mike Stumpeed9cac2009-02-19 03:04:26 +000010018
Anders Carlssone21555e2008-11-30 19:50:32 +000010019 if (Result)
10020 *Result = EvalResult.Val.getInt();
Richard Smith282e7e62012-02-04 09:53:13 +000010021 return Owned(E);
Anders Carlssone21555e2008-11-30 19:50:32 +000010022}
Douglas Gregore0762c92009-06-19 23:52:42 +000010023
Eli Friedmanef331b72012-01-20 01:26:23 +000010024namespace {
10025 // Handle the case where we conclude a expression which we speculatively
10026 // considered to be unevaluated is actually evaluated.
10027 class TransformToPE : public TreeTransform<TransformToPE> {
10028 typedef TreeTransform<TransformToPE> BaseTransform;
10029
10030 public:
10031 TransformToPE(Sema &SemaRef) : BaseTransform(SemaRef) { }
10032
10033 // Make sure we redo semantic analysis
10034 bool AlwaysRebuild() { return true; }
10035
Eli Friedman56ff2832012-02-06 23:29:57 +000010036 // Make sure we handle LabelStmts correctly.
10037 // FIXME: This does the right thing, but maybe we need a more general
10038 // fix to TreeTransform?
10039 StmtResult TransformLabelStmt(LabelStmt *S) {
10040 S->getDecl()->setStmt(0);
10041 return BaseTransform::TransformLabelStmt(S);
10042 }
10043
Eli Friedmanef331b72012-01-20 01:26:23 +000010044 // We need to special-case DeclRefExprs referring to FieldDecls which
10045 // are not part of a member pointer formation; normal TreeTransforming
10046 // doesn't catch this case because of the way we represent them in the AST.
10047 // FIXME: This is a bit ugly; is it really the best way to handle this
10048 // case?
10049 //
10050 // Error on DeclRefExprs referring to FieldDecls.
10051 ExprResult TransformDeclRefExpr(DeclRefExpr *E) {
10052 if (isa<FieldDecl>(E->getDecl()) &&
David Blaikie71f55f72012-08-06 22:47:24 +000010053 !SemaRef.isUnevaluatedContext())
Eli Friedmanef331b72012-01-20 01:26:23 +000010054 return SemaRef.Diag(E->getLocation(),
10055 diag::err_invalid_non_static_member_use)
10056 << E->getDecl() << E->getSourceRange();
10057
10058 return BaseTransform::TransformDeclRefExpr(E);
10059 }
10060
10061 // Exception: filter out member pointer formation
10062 ExprResult TransformUnaryOperator(UnaryOperator *E) {
10063 if (E->getOpcode() == UO_AddrOf && E->getType()->isMemberPointerType())
10064 return E;
10065
10066 return BaseTransform::TransformUnaryOperator(E);
10067 }
10068
Douglas Gregore2c59132012-02-09 08:14:43 +000010069 ExprResult TransformLambdaExpr(LambdaExpr *E) {
10070 // Lambdas never need to be transformed.
10071 return E;
10072 }
Eli Friedmanef331b72012-01-20 01:26:23 +000010073 };
Eli Friedman93c878e2012-01-18 01:05:54 +000010074}
10075
Eli Friedmanef331b72012-01-20 01:26:23 +000010076ExprResult Sema::TranformToPotentiallyEvaluated(Expr *E) {
Eli Friedman72b8b1e2012-02-29 04:03:55 +000010077 assert(ExprEvalContexts.back().Context == Unevaluated &&
10078 "Should only transform unevaluated expressions");
Eli Friedmanef331b72012-01-20 01:26:23 +000010079 ExprEvalContexts.back().Context =
10080 ExprEvalContexts[ExprEvalContexts.size()-2].Context;
10081 if (ExprEvalContexts.back().Context == Unevaluated)
10082 return E;
10083 return TransformToPE(*this).TransformExpr(E);
Eli Friedman93c878e2012-01-18 01:05:54 +000010084}
10085
Douglas Gregor2afce722009-11-26 00:44:06 +000010086void
Douglas Gregorccc1b5e2012-02-21 00:37:24 +000010087Sema::PushExpressionEvaluationContext(ExpressionEvaluationContext NewContext,
Richard Smith76f3f692012-02-22 02:04:18 +000010088 Decl *LambdaContextDecl,
10089 bool IsDecltype) {
Douglas Gregor2afce722009-11-26 00:44:06 +000010090 ExprEvalContexts.push_back(
John McCallf85e1932011-06-15 23:02:42 +000010091 ExpressionEvaluationContextRecord(NewContext,
John McCall80ee6e82011-11-10 05:35:25 +000010092 ExprCleanupObjects.size(),
Douglas Gregorccc1b5e2012-02-21 00:37:24 +000010093 ExprNeedsCleanups,
Richard Smith76f3f692012-02-22 02:04:18 +000010094 LambdaContextDecl,
10095 IsDecltype));
John McCallf85e1932011-06-15 23:02:42 +000010096 ExprNeedsCleanups = false;
Eli Friedmand2cce132012-02-02 23:15:15 +000010097 if (!MaybeODRUseExprs.empty())
10098 std::swap(MaybeODRUseExprs, ExprEvalContexts.back().SavedMaybeODRUseExprs);
Douglas Gregorac7610d2009-06-22 20:57:11 +000010099}
10100
Richard Trieu67e29332011-08-02 04:35:43 +000010101void Sema::PopExpressionEvaluationContext() {
Eli Friedman5f2987c2012-02-02 03:46:19 +000010102 ExpressionEvaluationContextRecord& Rec = ExprEvalContexts.back();
Douglas Gregorac7610d2009-06-22 20:57:11 +000010103
Douglas Gregore2c59132012-02-09 08:14:43 +000010104 if (!Rec.Lambdas.empty()) {
10105 if (Rec.Context == Unevaluated) {
10106 // C++11 [expr.prim.lambda]p2:
10107 // A lambda-expression shall not appear in an unevaluated operand
10108 // (Clause 5).
10109 for (unsigned I = 0, N = Rec.Lambdas.size(); I != N; ++I)
10110 Diag(Rec.Lambdas[I]->getLocStart(),
10111 diag::err_lambda_unevaluated_operand);
10112 } else {
10113 // Mark the capture expressions odr-used. This was deferred
10114 // during lambda expression creation.
10115 for (unsigned I = 0, N = Rec.Lambdas.size(); I != N; ++I) {
10116 LambdaExpr *Lambda = Rec.Lambdas[I];
10117 for (LambdaExpr::capture_init_iterator
10118 C = Lambda->capture_init_begin(),
10119 CEnd = Lambda->capture_init_end();
10120 C != CEnd; ++C) {
10121 MarkDeclarationsReferencedInExpr(*C);
10122 }
10123 }
10124 }
10125 }
10126
Douglas Gregor2afce722009-11-26 00:44:06 +000010127 // When are coming out of an unevaluated context, clear out any
10128 // temporaries that we may have created as part of the evaluation of
10129 // the expression in that context: they aren't relevant because they
10130 // will never be constructed.
Richard Smithf6702a32011-12-20 02:08:33 +000010131 if (Rec.Context == Unevaluated || Rec.Context == ConstantEvaluated) {
John McCall80ee6e82011-11-10 05:35:25 +000010132 ExprCleanupObjects.erase(ExprCleanupObjects.begin() + Rec.NumCleanupObjects,
10133 ExprCleanupObjects.end());
John McCallf85e1932011-06-15 23:02:42 +000010134 ExprNeedsCleanups = Rec.ParentNeedsCleanups;
Eli Friedmand2cce132012-02-02 23:15:15 +000010135 CleanupVarDeclMarking();
10136 std::swap(MaybeODRUseExprs, Rec.SavedMaybeODRUseExprs);
John McCallf85e1932011-06-15 23:02:42 +000010137 // Otherwise, merge the contexts together.
10138 } else {
10139 ExprNeedsCleanups |= Rec.ParentNeedsCleanups;
Eli Friedmand2cce132012-02-02 23:15:15 +000010140 MaybeODRUseExprs.insert(Rec.SavedMaybeODRUseExprs.begin(),
10141 Rec.SavedMaybeODRUseExprs.end());
John McCallf85e1932011-06-15 23:02:42 +000010142 }
Eli Friedman5f2987c2012-02-02 03:46:19 +000010143
10144 // Pop the current expression evaluation context off the stack.
10145 ExprEvalContexts.pop_back();
Douglas Gregorac7610d2009-06-22 20:57:11 +000010146}
Douglas Gregore0762c92009-06-19 23:52:42 +000010147
John McCallf85e1932011-06-15 23:02:42 +000010148void Sema::DiscardCleanupsInEvaluationContext() {
John McCall80ee6e82011-11-10 05:35:25 +000010149 ExprCleanupObjects.erase(
10150 ExprCleanupObjects.begin() + ExprEvalContexts.back().NumCleanupObjects,
10151 ExprCleanupObjects.end());
John McCallf85e1932011-06-15 23:02:42 +000010152 ExprNeedsCleanups = false;
Eli Friedmand2cce132012-02-02 23:15:15 +000010153 MaybeODRUseExprs.clear();
John McCallf85e1932011-06-15 23:02:42 +000010154}
10155
Eli Friedman71b8fb52012-01-21 01:01:51 +000010156ExprResult Sema::HandleExprEvaluationContextForTypeof(Expr *E) {
10157 if (!E->getType()->isVariablyModifiedType())
10158 return E;
10159 return TranformToPotentiallyEvaluated(E);
10160}
10161
Benjamin Kramer5bbc3852012-02-06 11:13:08 +000010162static bool IsPotentiallyEvaluatedContext(Sema &SemaRef) {
Douglas Gregore0762c92009-06-19 23:52:42 +000010163 // Do not mark anything as "used" within a dependent context; wait for
10164 // an instantiation.
Eli Friedman5f2987c2012-02-02 03:46:19 +000010165 if (SemaRef.CurContext->isDependentContext())
10166 return false;
Mike Stump1eb44332009-09-09 15:08:12 +000010167
Eli Friedman5f2987c2012-02-02 03:46:19 +000010168 switch (SemaRef.ExprEvalContexts.back().Context) {
10169 case Sema::Unevaluated:
Douglas Gregorac7610d2009-06-22 20:57:11 +000010170 // We are in an expression that is not potentially evaluated; do nothing.
Eli Friedman78a54242012-01-21 04:44:06 +000010171 // (Depending on how you read the standard, we actually do need to do
10172 // something here for null pointer constants, but the standard's
10173 // definition of a null pointer constant is completely crazy.)
Eli Friedman5f2987c2012-02-02 03:46:19 +000010174 return false;
Mike Stump1eb44332009-09-09 15:08:12 +000010175
Eli Friedman5f2987c2012-02-02 03:46:19 +000010176 case Sema::ConstantEvaluated:
10177 case Sema::PotentiallyEvaluated:
Eli Friedman78a54242012-01-21 04:44:06 +000010178 // We are in a potentially evaluated expression (or a constant-expression
10179 // in C++03); we need to do implicit template instantiation, implicitly
10180 // define class members, and mark most declarations as used.
Eli Friedman5f2987c2012-02-02 03:46:19 +000010181 return true;
Mike Stump1eb44332009-09-09 15:08:12 +000010182
Eli Friedman5f2987c2012-02-02 03:46:19 +000010183 case Sema::PotentiallyEvaluatedIfUsed:
Douglas Gregorbe0f7bd2010-09-11 20:24:53 +000010184 // Referenced declarations will only be used if the construct in the
10185 // containing expression is used.
Eli Friedman5f2987c2012-02-02 03:46:19 +000010186 return false;
Douglas Gregorac7610d2009-06-22 20:57:11 +000010187 }
Matt Beaumont-Gay4f7dcdb2012-02-02 18:35:35 +000010188 llvm_unreachable("Invalid context");
Eli Friedman5f2987c2012-02-02 03:46:19 +000010189}
10190
10191/// \brief Mark a function referenced, and check whether it is odr-used
10192/// (C++ [basic.def.odr]p2, C99 6.9p3)
10193void Sema::MarkFunctionReferenced(SourceLocation Loc, FunctionDecl *Func) {
10194 assert(Func && "No function?");
10195
10196 Func->setReferenced();
10197
Richard Smith57b9c4e2012-02-14 22:25:15 +000010198 // Don't mark this function as used multiple times, unless it's a constexpr
10199 // function which we need to instantiate.
10200 if (Func->isUsed(false) &&
10201 !(Func->isConstexpr() && !Func->getBody() &&
10202 Func->isImplicitlyInstantiable()))
Eli Friedman5f2987c2012-02-02 03:46:19 +000010203 return;
10204
10205 if (!IsPotentiallyEvaluatedContext(*this))
10206 return;
Mike Stump1eb44332009-09-09 15:08:12 +000010207
Douglas Gregore0762c92009-06-19 23:52:42 +000010208 // Note that this declaration has been used.
Eli Friedman5f2987c2012-02-02 03:46:19 +000010209 if (CXXConstructorDecl *Constructor = dyn_cast<CXXConstructorDecl>(Func)) {
Richard Smith03f68782012-02-26 07:51:39 +000010210 if (Constructor->isDefaulted() && !Constructor->isDeleted()) {
Sebastian Redl85ea7aa2011-08-30 19:58:05 +000010211 if (Constructor->isDefaultConstructor()) {
10212 if (Constructor->isTrivial())
10213 return;
10214 if (!Constructor->isUsed(false))
10215 DefineImplicitDefaultConstructor(Loc, Constructor);
10216 } else if (Constructor->isCopyConstructor()) {
10217 if (!Constructor->isUsed(false))
10218 DefineImplicitCopyConstructor(Loc, Constructor);
10219 } else if (Constructor->isMoveConstructor()) {
10220 if (!Constructor->isUsed(false))
10221 DefineImplicitMoveConstructor(Loc, Constructor);
10222 }
Fariborz Jahanian485f0872009-06-22 23:34:40 +000010223 }
Kovarththanan Rajaratnam19357542010-03-13 10:17:05 +000010224
Douglas Gregor6fb745b2010-05-13 16:44:06 +000010225 MarkVTableUsed(Loc, Constructor->getParent());
Eli Friedman5f2987c2012-02-02 03:46:19 +000010226 } else if (CXXDestructorDecl *Destructor =
10227 dyn_cast<CXXDestructorDecl>(Func)) {
Richard Smith03f68782012-02-26 07:51:39 +000010228 if (Destructor->isDefaulted() && !Destructor->isDeleted() &&
10229 !Destructor->isUsed(false))
Fariborz Jahanian8d2b3562009-06-26 23:49:16 +000010230 DefineImplicitDestructor(Loc, Destructor);
Douglas Gregor6fb745b2010-05-13 16:44:06 +000010231 if (Destructor->isVirtual())
10232 MarkVTableUsed(Loc, Destructor->getParent());
Eli Friedman5f2987c2012-02-02 03:46:19 +000010233 } else if (CXXMethodDecl *MethodDecl = dyn_cast<CXXMethodDecl>(Func)) {
Richard Smith03f68782012-02-26 07:51:39 +000010234 if (MethodDecl->isDefaulted() && !MethodDecl->isDeleted() &&
10235 MethodDecl->isOverloadedOperator() &&
Fariborz Jahanianc75bc2d2009-06-25 21:45:19 +000010236 MethodDecl->getOverloadedOperator() == OO_Equal) {
Sebastian Redl85ea7aa2011-08-30 19:58:05 +000010237 if (!MethodDecl->isUsed(false)) {
10238 if (MethodDecl->isCopyAssignmentOperator())
10239 DefineImplicitCopyAssignment(Loc, MethodDecl);
10240 else
10241 DefineImplicitMoveAssignment(Loc, MethodDecl);
10242 }
Douglas Gregorf6e2e022012-02-16 01:06:16 +000010243 } else if (isa<CXXConversionDecl>(MethodDecl) &&
10244 MethodDecl->getParent()->isLambda()) {
10245 CXXConversionDecl *Conversion = cast<CXXConversionDecl>(MethodDecl);
10246 if (Conversion->isLambdaToBlockPointerConversion())
10247 DefineImplicitLambdaToBlockPointerConversion(Loc, Conversion);
10248 else
10249 DefineImplicitLambdaToFunctionPointerConversion(Loc, Conversion);
Douglas Gregor6fb745b2010-05-13 16:44:06 +000010250 } else if (MethodDecl->isVirtual())
10251 MarkVTableUsed(Loc, MethodDecl->getParent());
Fariborz Jahanianc75bc2d2009-06-25 21:45:19 +000010252 }
John McCall15e310a2011-02-19 02:53:41 +000010253
Eli Friedman5f2987c2012-02-02 03:46:19 +000010254 // Recursive functions should be marked when used from another function.
10255 // FIXME: Is this really right?
10256 if (CurContext == Func) return;
Kovarththanan Rajaratnam19357542010-03-13 10:17:05 +000010257
Richard Smithb9d0b762012-07-27 04:22:15 +000010258 // Resolve the exception specification for any function which is
Richard Smithe6975e92012-04-17 00:58:00 +000010259 // used: CodeGen will need it.
Richard Smith13bffc52012-04-19 00:08:28 +000010260 const FunctionProtoType *FPT = Func->getType()->getAs<FunctionProtoType>();
Richard Smithb9d0b762012-07-27 04:22:15 +000010261 if (FPT && isUnresolvedExceptionSpec(FPT->getExceptionSpecType()))
10262 ResolveExceptionSpec(Loc, FPT);
Richard Smithe6975e92012-04-17 00:58:00 +000010263
Eli Friedman5f2987c2012-02-02 03:46:19 +000010264 // Implicit instantiation of function templates and member functions of
10265 // class templates.
10266 if (Func->isImplicitlyInstantiable()) {
10267 bool AlreadyInstantiated = false;
Richard Smith57b9c4e2012-02-14 22:25:15 +000010268 SourceLocation PointOfInstantiation = Loc;
Eli Friedman5f2987c2012-02-02 03:46:19 +000010269 if (FunctionTemplateSpecializationInfo *SpecInfo
10270 = Func->getTemplateSpecializationInfo()) {
10271 if (SpecInfo->getPointOfInstantiation().isInvalid())
10272 SpecInfo->setPointOfInstantiation(Loc);
10273 else if (SpecInfo->getTemplateSpecializationKind()
Richard Smith57b9c4e2012-02-14 22:25:15 +000010274 == TSK_ImplicitInstantiation) {
Eli Friedman5f2987c2012-02-02 03:46:19 +000010275 AlreadyInstantiated = true;
Richard Smith57b9c4e2012-02-14 22:25:15 +000010276 PointOfInstantiation = SpecInfo->getPointOfInstantiation();
10277 }
Eli Friedman5f2987c2012-02-02 03:46:19 +000010278 } else if (MemberSpecializationInfo *MSInfo
10279 = Func->getMemberSpecializationInfo()) {
10280 if (MSInfo->getPointOfInstantiation().isInvalid())
Douglas Gregorb3ae4fc2009-10-12 20:18:28 +000010281 MSInfo->setPointOfInstantiation(Loc);
Eli Friedman5f2987c2012-02-02 03:46:19 +000010282 else if (MSInfo->getTemplateSpecializationKind()
Richard Smith57b9c4e2012-02-14 22:25:15 +000010283 == TSK_ImplicitInstantiation) {
Eli Friedman5f2987c2012-02-02 03:46:19 +000010284 AlreadyInstantiated = true;
Richard Smith57b9c4e2012-02-14 22:25:15 +000010285 PointOfInstantiation = MSInfo->getPointOfInstantiation();
10286 }
Douglas Gregorb3ae4fc2009-10-12 20:18:28 +000010287 }
Mike Stump1eb44332009-09-09 15:08:12 +000010288
Richard Smith57b9c4e2012-02-14 22:25:15 +000010289 if (!AlreadyInstantiated || Func->isConstexpr()) {
Eli Friedman5f2987c2012-02-02 03:46:19 +000010290 if (isa<CXXRecordDecl>(Func->getDeclContext()) &&
10291 cast<CXXRecordDecl>(Func->getDeclContext())->isLocalClass())
Richard Smith57b9c4e2012-02-14 22:25:15 +000010292 PendingLocalImplicitInstantiations.push_back(
10293 std::make_pair(Func, PointOfInstantiation));
10294 else if (Func->isConstexpr())
Eli Friedman5f2987c2012-02-02 03:46:19 +000010295 // Do not defer instantiations of constexpr functions, to avoid the
10296 // expression evaluator needing to call back into Sema if it sees a
10297 // call to such a function.
Richard Smith57b9c4e2012-02-14 22:25:15 +000010298 InstantiateFunctionDefinition(PointOfInstantiation, Func);
Argyrios Kyrtzidis6d968362012-02-10 20:10:44 +000010299 else {
Richard Smith57b9c4e2012-02-14 22:25:15 +000010300 PendingInstantiations.push_back(std::make_pair(Func,
10301 PointOfInstantiation));
Argyrios Kyrtzidis6d968362012-02-10 20:10:44 +000010302 // Notify the consumer that a function was implicitly instantiated.
10303 Consumer.HandleCXXImplicitFunctionInstantiation(Func);
10304 }
John McCall15e310a2011-02-19 02:53:41 +000010305 }
Eli Friedman5f2987c2012-02-02 03:46:19 +000010306 } else {
10307 // Walk redefinitions, as some of them may be instantiable.
10308 for (FunctionDecl::redecl_iterator i(Func->redecls_begin()),
10309 e(Func->redecls_end()); i != e; ++i) {
10310 if (!i->isUsed(false) && i->isImplicitlyInstantiable())
10311 MarkFunctionReferenced(Loc, *i);
10312 }
Sam Weinigcce6ebc2009-09-11 03:29:30 +000010313 }
Eli Friedman5f2987c2012-02-02 03:46:19 +000010314
10315 // Keep track of used but undefined functions.
10316 if (!Func->isPure() && !Func->hasBody() &&
10317 Func->getLinkage() != ExternalLinkage) {
10318 SourceLocation &old = UndefinedInternals[Func->getCanonicalDecl()];
10319 if (old.isInvalid()) old = Loc;
10320 }
10321
10322 Func->setUsed(true);
10323}
10324
Eli Friedman3c0e80e2012-02-03 02:04:35 +000010325static void
10326diagnoseUncapturableValueReference(Sema &S, SourceLocation loc,
10327 VarDecl *var, DeclContext *DC) {
Eli Friedman0a294222012-02-07 00:15:00 +000010328 DeclContext *VarDC = var->getDeclContext();
10329
Eli Friedman3c0e80e2012-02-03 02:04:35 +000010330 // If the parameter still belongs to the translation unit, then
10331 // we're actually just using one parameter in the declaration of
10332 // the next.
10333 if (isa<ParmVarDecl>(var) &&
Eli Friedman0a294222012-02-07 00:15:00 +000010334 isa<TranslationUnitDecl>(VarDC))
Eli Friedman3c0e80e2012-02-03 02:04:35 +000010335 return;
10336
Eli Friedman0a294222012-02-07 00:15:00 +000010337 // For C code, don't diagnose about capture if we're not actually in code
10338 // right now; it's impossible to write a non-constant expression outside of
10339 // function context, so we'll get other (more useful) diagnostics later.
10340 //
10341 // For C++, things get a bit more nasty... it would be nice to suppress this
10342 // diagnostic for certain cases like using a local variable in an array bound
10343 // for a member of a local class, but the correct predicate is not obvious.
David Blaikie4e4d0842012-03-11 07:00:24 +000010344 if (!S.getLangOpts().CPlusPlus && !S.CurContext->isFunctionOrMethod())
Eli Friedman3c0e80e2012-02-03 02:04:35 +000010345 return;
10346
Eli Friedman0a294222012-02-07 00:15:00 +000010347 if (isa<CXXMethodDecl>(VarDC) &&
10348 cast<CXXRecordDecl>(VarDC->getParent())->isLambda()) {
10349 S.Diag(loc, diag::err_reference_to_local_var_in_enclosing_lambda)
10350 << var->getIdentifier();
10351 } else if (FunctionDecl *fn = dyn_cast<FunctionDecl>(VarDC)) {
10352 S.Diag(loc, diag::err_reference_to_local_var_in_enclosing_function)
10353 << var->getIdentifier() << fn->getDeclName();
10354 } else if (isa<BlockDecl>(VarDC)) {
10355 S.Diag(loc, diag::err_reference_to_local_var_in_enclosing_block)
10356 << var->getIdentifier();
10357 } else {
10358 // FIXME: Is there any other context where a local variable can be
10359 // declared?
10360 S.Diag(loc, diag::err_reference_to_local_var_in_enclosing_context)
10361 << var->getIdentifier();
10362 }
Eli Friedman3c0e80e2012-02-03 02:04:35 +000010363
Eli Friedman3c0e80e2012-02-03 02:04:35 +000010364 S.Diag(var->getLocation(), diag::note_local_variable_declared_here)
10365 << var->getIdentifier();
Eli Friedman0a294222012-02-07 00:15:00 +000010366
10367 // FIXME: Add additional diagnostic info about class etc. which prevents
10368 // capture.
Eli Friedman3c0e80e2012-02-03 02:04:35 +000010369}
10370
Douglas Gregorf8af9822012-02-12 18:42:33 +000010371/// \brief Capture the given variable in the given lambda expression.
10372static ExprResult captureInLambda(Sema &S, LambdaScopeInfo *LSI,
Douglas Gregor999713e2012-02-18 09:37:24 +000010373 VarDecl *Var, QualType FieldType,
10374 QualType DeclRefType,
Douglas Gregord57f52c2012-05-16 17:01:33 +000010375 SourceLocation Loc,
10376 bool RefersToEnclosingLocal) {
Douglas Gregorf8af9822012-02-12 18:42:33 +000010377 CXXRecordDecl *Lambda = LSI->Lambda;
Douglas Gregorf8af9822012-02-12 18:42:33 +000010378
Douglas Gregor1f9a5db2012-02-09 01:56:40 +000010379 // Build the non-static data member.
10380 FieldDecl *Field
10381 = FieldDecl::Create(S.Context, Lambda, Loc, Loc, 0, FieldType,
10382 S.Context.getTrivialTypeSourceInfo(FieldType, Loc),
Richard Smithca523302012-06-10 03:12:00 +000010383 0, false, ICIS_NoInit);
Douglas Gregor1f9a5db2012-02-09 01:56:40 +000010384 Field->setImplicit(true);
10385 Field->setAccess(AS_private);
Douglas Gregor20f87a42012-02-09 02:12:34 +000010386 Lambda->addDecl(Field);
Douglas Gregor1f9a5db2012-02-09 01:56:40 +000010387
10388 // C++11 [expr.prim.lambda]p21:
10389 // When the lambda-expression is evaluated, the entities that
10390 // are captured by copy are used to direct-initialize each
10391 // corresponding non-static data member of the resulting closure
10392 // object. (For array members, the array elements are
10393 // direct-initialized in increasing subscript order.) These
10394 // initializations are performed in the (unspecified) order in
10395 // which the non-static data members are declared.
Douglas Gregor1f9a5db2012-02-09 01:56:40 +000010396
Douglas Gregore2c59132012-02-09 08:14:43 +000010397 // Introduce a new evaluation context for the initialization, so
10398 // that temporaries introduced as part of the capture are retained
10399 // to be re-"exported" from the lambda expression itself.
Douglas Gregor1f9a5db2012-02-09 01:56:40 +000010400 S.PushExpressionEvaluationContext(Sema::PotentiallyEvaluated);
10401
Douglas Gregor73d90922012-02-10 09:26:04 +000010402 // C++ [expr.prim.labda]p12:
10403 // An entity captured by a lambda-expression is odr-used (3.2) in
10404 // the scope containing the lambda-expression.
Douglas Gregord57f52c2012-05-16 17:01:33 +000010405 Expr *Ref = new (S.Context) DeclRefExpr(Var, RefersToEnclosingLocal,
10406 DeclRefType, VK_LValue, Loc);
Eli Friedman88530d52012-03-01 21:32:56 +000010407 Var->setReferenced(true);
Douglas Gregor73d90922012-02-10 09:26:04 +000010408 Var->setUsed(true);
Douglas Gregor18fe0842012-02-09 02:45:47 +000010409
10410 // When the field has array type, create index variables for each
10411 // dimension of the array. We use these index variables to subscript
10412 // the source array, and other clients (e.g., CodeGen) will perform
10413 // the necessary iteration with these index variables.
10414 SmallVector<VarDecl *, 4> IndexVariables;
Douglas Gregor18fe0842012-02-09 02:45:47 +000010415 QualType BaseType = FieldType;
10416 QualType SizeType = S.Context.getSizeType();
Douglas Gregor9daa7bf2012-02-13 16:35:30 +000010417 LSI->ArrayIndexStarts.push_back(LSI->ArrayIndexVars.size());
Douglas Gregor18fe0842012-02-09 02:45:47 +000010418 while (const ConstantArrayType *Array
10419 = S.Context.getAsConstantArrayType(BaseType)) {
Douglas Gregor18fe0842012-02-09 02:45:47 +000010420 // Create the iteration variable for this array index.
10421 IdentifierInfo *IterationVarName = 0;
10422 {
10423 SmallString<8> Str;
10424 llvm::raw_svector_ostream OS(Str);
10425 OS << "__i" << IndexVariables.size();
10426 IterationVarName = &S.Context.Idents.get(OS.str());
10427 }
10428 VarDecl *IterationVar
10429 = VarDecl::Create(S.Context, S.CurContext, Loc, Loc,
10430 IterationVarName, SizeType,
10431 S.Context.getTrivialTypeSourceInfo(SizeType, Loc),
10432 SC_None, SC_None);
10433 IndexVariables.push_back(IterationVar);
Douglas Gregor9daa7bf2012-02-13 16:35:30 +000010434 LSI->ArrayIndexVars.push_back(IterationVar);
10435
Douglas Gregor18fe0842012-02-09 02:45:47 +000010436 // Create a reference to the iteration variable.
10437 ExprResult IterationVarRef
10438 = S.BuildDeclRefExpr(IterationVar, SizeType, VK_LValue, Loc);
10439 assert(!IterationVarRef.isInvalid() &&
10440 "Reference to invented variable cannot fail!");
10441 IterationVarRef = S.DefaultLvalueConversion(IterationVarRef.take());
10442 assert(!IterationVarRef.isInvalid() &&
10443 "Conversion of invented variable cannot fail!");
10444
10445 // Subscript the array with this iteration variable.
10446 ExprResult Subscript = S.CreateBuiltinArraySubscriptExpr(
10447 Ref, Loc, IterationVarRef.take(), Loc);
10448 if (Subscript.isInvalid()) {
10449 S.CleanupVarDeclMarking();
10450 S.DiscardCleanupsInEvaluationContext();
10451 S.PopExpressionEvaluationContext();
10452 return ExprError();
10453 }
10454
10455 Ref = Subscript.take();
10456 BaseType = Array->getElementType();
10457 }
10458
10459 // Construct the entity that we will be initializing. For an array, this
10460 // will be first element in the array, which may require several levels
10461 // of array-subscript entities.
10462 SmallVector<InitializedEntity, 4> Entities;
10463 Entities.reserve(1 + IndexVariables.size());
Douglas Gregor47736542012-02-15 16:57:26 +000010464 Entities.push_back(
10465 InitializedEntity::InitializeLambdaCapture(Var, Field, Loc));
Douglas Gregor18fe0842012-02-09 02:45:47 +000010466 for (unsigned I = 0, N = IndexVariables.size(); I != N; ++I)
10467 Entities.push_back(InitializedEntity::InitializeElement(S.Context,
10468 0,
10469 Entities.back()));
10470
Douglas Gregor1f9a5db2012-02-09 01:56:40 +000010471 InitializationKind InitKind
10472 = InitializationKind::CreateDirect(Loc, Loc, Loc);
Douglas Gregor18fe0842012-02-09 02:45:47 +000010473 InitializationSequence Init(S, Entities.back(), InitKind, &Ref, 1);
Douglas Gregor1f9a5db2012-02-09 01:56:40 +000010474 ExprResult Result(true);
Douglas Gregor18fe0842012-02-09 02:45:47 +000010475 if (!Init.Diagnose(S, Entities.back(), InitKind, &Ref, 1))
Benjamin Kramer5354e772012-08-23 23:38:35 +000010476 Result = Init.Perform(S, Entities.back(), InitKind, Ref);
Douglas Gregor1f9a5db2012-02-09 01:56:40 +000010477
10478 // If this initialization requires any cleanups (e.g., due to a
10479 // default argument to a copy constructor), note that for the
10480 // lambda.
10481 if (S.ExprNeedsCleanups)
10482 LSI->ExprNeedsCleanups = true;
10483
10484 // Exit the expression evaluation context used for the capture.
10485 S.CleanupVarDeclMarking();
10486 S.DiscardCleanupsInEvaluationContext();
10487 S.PopExpressionEvaluationContext();
10488 return Result;
Douglas Gregor18fe0842012-02-09 02:45:47 +000010489}
Douglas Gregor1f9a5db2012-02-09 01:56:40 +000010490
Douglas Gregor999713e2012-02-18 09:37:24 +000010491bool Sema::tryCaptureVariable(VarDecl *Var, SourceLocation Loc,
10492 TryCaptureKind Kind, SourceLocation EllipsisLoc,
10493 bool BuildAndDiagnose,
10494 QualType &CaptureType,
10495 QualType &DeclRefType) {
10496 bool Nested = false;
Douglas Gregorf8af9822012-02-12 18:42:33 +000010497
Eli Friedmanb942cb22012-02-03 22:47:37 +000010498 DeclContext *DC = CurContext;
Douglas Gregor999713e2012-02-18 09:37:24 +000010499 if (Var->getDeclContext() == DC) return true;
10500 if (!Var->hasLocalStorage()) return true;
Eli Friedman3c0e80e2012-02-03 02:04:35 +000010501
Douglas Gregorf8af9822012-02-12 18:42:33 +000010502 bool HasBlocksAttr = Var->hasAttr<BlocksAttr>();
Eli Friedman3c0e80e2012-02-03 02:04:35 +000010503
Douglas Gregor999713e2012-02-18 09:37:24 +000010504 // Walk up the stack to determine whether we can capture the variable,
10505 // performing the "simple" checks that don't depend on type. We stop when
10506 // we've either hit the declared scope of the variable or find an existing
10507 // capture of that variable.
10508 CaptureType = Var->getType();
10509 DeclRefType = CaptureType.getNonReferenceType();
10510 bool Explicit = (Kind != TryCapture_Implicit);
10511 unsigned FunctionScopesIndex = FunctionScopes.size() - 1;
Eli Friedman3c0e80e2012-02-03 02:04:35 +000010512 do {
Eli Friedmanb942cb22012-02-03 22:47:37 +000010513 // Only block literals and lambda expressions can capture; other
Eli Friedman3c0e80e2012-02-03 02:04:35 +000010514 // scopes don't work.
Eli Friedmanb942cb22012-02-03 22:47:37 +000010515 DeclContext *ParentDC;
10516 if (isa<BlockDecl>(DC))
10517 ParentDC = DC->getParent();
10518 else if (isa<CXXMethodDecl>(DC) &&
Douglas Gregorf8af9822012-02-12 18:42:33 +000010519 cast<CXXMethodDecl>(DC)->getOverloadedOperator() == OO_Call &&
Eli Friedmanb942cb22012-02-03 22:47:37 +000010520 cast<CXXRecordDecl>(DC->getParent())->isLambda())
10521 ParentDC = DC->getParent()->getParent();
Douglas Gregorf8af9822012-02-12 18:42:33 +000010522 else {
Douglas Gregor999713e2012-02-18 09:37:24 +000010523 if (BuildAndDiagnose)
Douglas Gregorf8af9822012-02-12 18:42:33 +000010524 diagnoseUncapturableValueReference(*this, Loc, Var, DC);
Douglas Gregor999713e2012-02-18 09:37:24 +000010525 return true;
Douglas Gregorf8af9822012-02-12 18:42:33 +000010526 }
Eli Friedman3c0e80e2012-02-03 02:04:35 +000010527
Eli Friedmanb942cb22012-02-03 22:47:37 +000010528 CapturingScopeInfo *CSI =
Douglas Gregorf8af9822012-02-12 18:42:33 +000010529 cast<CapturingScopeInfo>(FunctionScopes[FunctionScopesIndex]);
Eli Friedman3c0e80e2012-02-03 02:04:35 +000010530
Eli Friedmanb942cb22012-02-03 22:47:37 +000010531 // Check whether we've already captured it.
Douglas Gregorf8af9822012-02-12 18:42:33 +000010532 if (CSI->CaptureMap.count(Var)) {
Douglas Gregor999713e2012-02-18 09:37:24 +000010533 // If we found a capture, any subcaptures are nested.
Eli Friedman3c0e80e2012-02-03 02:04:35 +000010534 Nested = true;
Douglas Gregor999713e2012-02-18 09:37:24 +000010535
10536 // Retrieve the capture type for this variable.
10537 CaptureType = CSI->getCapture(Var).getCaptureType();
10538
10539 // Compute the type of an expression that refers to this variable.
10540 DeclRefType = CaptureType.getNonReferenceType();
10541
10542 const CapturingScopeInfo::Capture &Cap = CSI->getCapture(Var);
10543 if (Cap.isCopyCapture() &&
10544 !(isa<LambdaScopeInfo>(CSI) && cast<LambdaScopeInfo>(CSI)->Mutable))
10545 DeclRefType.addConst();
Eli Friedman3c0e80e2012-02-03 02:04:35 +000010546 break;
10547 }
10548
Douglas Gregorf8af9822012-02-12 18:42:33 +000010549 bool IsBlock = isa<BlockScopeInfo>(CSI);
Douglas Gregor999713e2012-02-18 09:37:24 +000010550 bool IsLambda = !IsBlock;
Eli Friedmanb942cb22012-02-03 22:47:37 +000010551
10552 // Lambdas are not allowed to capture unnamed variables
10553 // (e.g. anonymous unions).
10554 // FIXME: The C++11 rule don't actually state this explicitly, but I'm
10555 // assuming that's the intent.
Douglas Gregorf8af9822012-02-12 18:42:33 +000010556 if (IsLambda && !Var->getDeclName()) {
Douglas Gregor999713e2012-02-18 09:37:24 +000010557 if (BuildAndDiagnose) {
Douglas Gregorf8af9822012-02-12 18:42:33 +000010558 Diag(Loc, diag::err_lambda_capture_anonymous_var);
10559 Diag(Var->getLocation(), diag::note_declared_at);
10560 }
Douglas Gregor999713e2012-02-18 09:37:24 +000010561 return true;
Eli Friedmanb942cb22012-02-03 22:47:37 +000010562 }
10563
10564 // Prohibit variably-modified types; they're difficult to deal with.
Douglas Gregor999713e2012-02-18 09:37:24 +000010565 if (Var->getType()->isVariablyModifiedType()) {
10566 if (BuildAndDiagnose) {
Douglas Gregorf8af9822012-02-12 18:42:33 +000010567 if (IsBlock)
10568 Diag(Loc, diag::err_ref_vm_type);
10569 else
10570 Diag(Loc, diag::err_lambda_capture_vm_type) << Var->getDeclName();
10571 Diag(Var->getLocation(), diag::note_previous_decl)
10572 << Var->getDeclName();
10573 }
Douglas Gregor999713e2012-02-18 09:37:24 +000010574 return true;
Eli Friedman3c0e80e2012-02-03 02:04:35 +000010575 }
10576
Eli Friedmanb942cb22012-02-03 22:47:37 +000010577 // Lambdas are not allowed to capture __block variables; they don't
10578 // support the expected semantics.
Douglas Gregorf8af9822012-02-12 18:42:33 +000010579 if (IsLambda && HasBlocksAttr) {
Douglas Gregor999713e2012-02-18 09:37:24 +000010580 if (BuildAndDiagnose) {
Douglas Gregorf8af9822012-02-12 18:42:33 +000010581 Diag(Loc, diag::err_lambda_capture_block)
10582 << Var->getDeclName();
10583 Diag(Var->getLocation(), diag::note_previous_decl)
10584 << Var->getDeclName();
10585 }
Douglas Gregor999713e2012-02-18 09:37:24 +000010586 return true;
Eli Friedmanb942cb22012-02-03 22:47:37 +000010587 }
10588
Douglas Gregorf8af9822012-02-12 18:42:33 +000010589 if (CSI->ImpCaptureStyle == CapturingScopeInfo::ImpCap_None && !Explicit) {
10590 // No capture-default
Douglas Gregor999713e2012-02-18 09:37:24 +000010591 if (BuildAndDiagnose) {
Douglas Gregorf8af9822012-02-12 18:42:33 +000010592 Diag(Loc, diag::err_lambda_impcap) << Var->getDeclName();
10593 Diag(Var->getLocation(), diag::note_previous_decl)
10594 << Var->getDeclName();
10595 Diag(cast<LambdaScopeInfo>(CSI)->Lambda->getLocStart(),
10596 diag::note_lambda_decl);
10597 }
Douglas Gregor999713e2012-02-18 09:37:24 +000010598 return true;
Douglas Gregorf8af9822012-02-12 18:42:33 +000010599 }
10600
10601 FunctionScopesIndex--;
10602 DC = ParentDC;
10603 Explicit = false;
10604 } while (!Var->getDeclContext()->Equals(DC));
10605
Douglas Gregor999713e2012-02-18 09:37:24 +000010606 // Walk back down the scope stack, computing the type of the capture at
10607 // each step, checking type-specific requirements, and adding captures if
10608 // requested.
10609 for (unsigned I = ++FunctionScopesIndex, N = FunctionScopes.size(); I != N;
10610 ++I) {
10611 CapturingScopeInfo *CSI = cast<CapturingScopeInfo>(FunctionScopes[I]);
Douglas Gregor68932842012-02-18 05:51:20 +000010612
Douglas Gregor999713e2012-02-18 09:37:24 +000010613 // Compute the type of the capture and of a reference to the capture within
10614 // this scope.
10615 if (isa<BlockScopeInfo>(CSI)) {
10616 Expr *CopyExpr = 0;
10617 bool ByRef = false;
10618
10619 // Blocks are not allowed to capture arrays.
10620 if (CaptureType->isArrayType()) {
10621 if (BuildAndDiagnose) {
10622 Diag(Loc, diag::err_ref_array_type);
10623 Diag(Var->getLocation(), diag::note_previous_decl)
10624 << Var->getDeclName();
10625 }
10626 return true;
10627 }
10628
John McCall100c6492012-03-30 05:23:48 +000010629 // Forbid the block-capture of autoreleasing variables.
10630 if (CaptureType.getObjCLifetime() == Qualifiers::OCL_Autoreleasing) {
10631 if (BuildAndDiagnose) {
10632 Diag(Loc, diag::err_arc_autoreleasing_capture)
10633 << /*block*/ 0;
10634 Diag(Var->getLocation(), diag::note_previous_decl)
10635 << Var->getDeclName();
10636 }
10637 return true;
10638 }
10639
Douglas Gregor999713e2012-02-18 09:37:24 +000010640 if (HasBlocksAttr || CaptureType->isReferenceType()) {
10641 // Block capture by reference does not change the capture or
10642 // declaration reference types.
10643 ByRef = true;
10644 } else {
10645 // Block capture by copy introduces 'const'.
10646 CaptureType = CaptureType.getNonReferenceType().withConst();
10647 DeclRefType = CaptureType;
10648
David Blaikie4e4d0842012-03-11 07:00:24 +000010649 if (getLangOpts().CPlusPlus && BuildAndDiagnose) {
Douglas Gregor999713e2012-02-18 09:37:24 +000010650 if (const RecordType *Record = DeclRefType->getAs<RecordType>()) {
10651 // The capture logic needs the destructor, so make sure we mark it.
10652 // Usually this is unnecessary because most local variables have
10653 // their destructors marked at declaration time, but parameters are
10654 // an exception because it's technically only the call site that
10655 // actually requires the destructor.
10656 if (isa<ParmVarDecl>(Var))
10657 FinalizeVarWithDestructor(Var, Record);
10658
10659 // According to the blocks spec, the capture of a variable from
10660 // the stack requires a const copy constructor. This is not true
10661 // of the copy/move done to move a __block variable to the heap.
John McCallf4b88a42012-03-10 09:33:50 +000010662 Expr *DeclRef = new (Context) DeclRefExpr(Var, false,
Douglas Gregor999713e2012-02-18 09:37:24 +000010663 DeclRefType.withConst(),
10664 VK_LValue, Loc);
10665 ExprResult Result
10666 = PerformCopyInitialization(
10667 InitializedEntity::InitializeBlock(Var->getLocation(),
10668 CaptureType, false),
10669 Loc, Owned(DeclRef));
10670
10671 // Build a full-expression copy expression if initialization
10672 // succeeded and used a non-trivial constructor. Recover from
10673 // errors by pretending that the copy isn't necessary.
10674 if (!Result.isInvalid() &&
10675 !cast<CXXConstructExpr>(Result.get())->getConstructor()
10676 ->isTrivial()) {
10677 Result = MaybeCreateExprWithCleanups(Result);
10678 CopyExpr = Result.take();
10679 }
10680 }
10681 }
10682 }
10683
10684 // Actually capture the variable.
10685 if (BuildAndDiagnose)
10686 CSI->addCapture(Var, HasBlocksAttr, ByRef, Nested, Loc,
10687 SourceLocation(), CaptureType, CopyExpr);
10688 Nested = true;
10689 continue;
10690 }
Douglas Gregor68932842012-02-18 05:51:20 +000010691
Douglas Gregor999713e2012-02-18 09:37:24 +000010692 LambdaScopeInfo *LSI = cast<LambdaScopeInfo>(CSI);
10693
10694 // Determine whether we are capturing by reference or by value.
10695 bool ByRef = false;
10696 if (I == N - 1 && Kind != TryCapture_Implicit) {
10697 ByRef = (Kind == TryCapture_ExplicitByRef);
Eli Friedmanb942cb22012-02-03 22:47:37 +000010698 } else {
Douglas Gregor999713e2012-02-18 09:37:24 +000010699 ByRef = (LSI->ImpCaptureStyle == LambdaScopeInfo::ImpCap_LambdaByref);
Eli Friedmanb942cb22012-02-03 22:47:37 +000010700 }
Douglas Gregor999713e2012-02-18 09:37:24 +000010701
10702 // Compute the type of the field that will capture this variable.
10703 if (ByRef) {
10704 // C++11 [expr.prim.lambda]p15:
10705 // An entity is captured by reference if it is implicitly or
10706 // explicitly captured but not captured by copy. It is
10707 // unspecified whether additional unnamed non-static data
10708 // members are declared in the closure type for entities
10709 // captured by reference.
10710 //
10711 // FIXME: It is not clear whether we want to build an lvalue reference
10712 // to the DeclRefType or to CaptureType.getNonReferenceType(). GCC appears
10713 // to do the former, while EDG does the latter. Core issue 1249 will
10714 // clarify, but for now we follow GCC because it's a more permissive and
10715 // easily defensible position.
10716 CaptureType = Context.getLValueReferenceType(DeclRefType);
10717 } else {
10718 // C++11 [expr.prim.lambda]p14:
10719 // For each entity captured by copy, an unnamed non-static
10720 // data member is declared in the closure type. The
10721 // declaration order of these members is unspecified. The type
10722 // of such a data member is the type of the corresponding
10723 // captured entity if the entity is not a reference to an
10724 // object, or the referenced type otherwise. [Note: If the
10725 // captured entity is a reference to a function, the
10726 // corresponding data member is also a reference to a
10727 // function. - end note ]
10728 if (const ReferenceType *RefType = CaptureType->getAs<ReferenceType>()){
10729 if (!RefType->getPointeeType()->isFunctionType())
10730 CaptureType = RefType->getPointeeType();
Eli Friedman3c0e80e2012-02-03 02:04:35 +000010731 }
John McCall100c6492012-03-30 05:23:48 +000010732
10733 // Forbid the lambda copy-capture of autoreleasing variables.
10734 if (CaptureType.getObjCLifetime() == Qualifiers::OCL_Autoreleasing) {
10735 if (BuildAndDiagnose) {
10736 Diag(Loc, diag::err_arc_autoreleasing_capture) << /*lambda*/ 1;
10737 Diag(Var->getLocation(), diag::note_previous_decl)
10738 << Var->getDeclName();
10739 }
10740 return true;
10741 }
Eli Friedman3c0e80e2012-02-03 02:04:35 +000010742 }
10743
Douglas Gregor999713e2012-02-18 09:37:24 +000010744 // Capture this variable in the lambda.
10745 Expr *CopyExpr = 0;
10746 if (BuildAndDiagnose) {
10747 ExprResult Result = captureInLambda(*this, LSI, Var, CaptureType,
Douglas Gregord57f52c2012-05-16 17:01:33 +000010748 DeclRefType, Loc,
10749 I == N-1);
Douglas Gregor999713e2012-02-18 09:37:24 +000010750 if (!Result.isInvalid())
10751 CopyExpr = Result.take();
10752 }
10753
10754 // Compute the type of a reference to this captured variable.
10755 if (ByRef)
10756 DeclRefType = CaptureType.getNonReferenceType();
10757 else {
10758 // C++ [expr.prim.lambda]p5:
10759 // The closure type for a lambda-expression has a public inline
10760 // function call operator [...]. This function call operator is
10761 // declared const (9.3.1) if and only if the lambda-expression’s
10762 // parameter-declaration-clause is not followed by mutable.
10763 DeclRefType = CaptureType.getNonReferenceType();
10764 if (!LSI->Mutable && !CaptureType->isReferenceType())
10765 DeclRefType.addConst();
10766 }
10767
10768 // Add the capture.
10769 if (BuildAndDiagnose)
10770 CSI->addCapture(Var, /*IsBlock=*/false, ByRef, Nested, Loc,
10771 EllipsisLoc, CaptureType, CopyExpr);
Eli Friedman3c0e80e2012-02-03 02:04:35 +000010772 Nested = true;
10773 }
Douglas Gregor999713e2012-02-18 09:37:24 +000010774
10775 return false;
10776}
10777
10778bool Sema::tryCaptureVariable(VarDecl *Var, SourceLocation Loc,
10779 TryCaptureKind Kind, SourceLocation EllipsisLoc) {
10780 QualType CaptureType;
10781 QualType DeclRefType;
10782 return tryCaptureVariable(Var, Loc, Kind, EllipsisLoc,
10783 /*BuildAndDiagnose=*/true, CaptureType,
10784 DeclRefType);
10785}
10786
10787QualType Sema::getCapturedDeclRefType(VarDecl *Var, SourceLocation Loc) {
10788 QualType CaptureType;
10789 QualType DeclRefType;
10790
10791 // Determine whether we can capture this variable.
10792 if (tryCaptureVariable(Var, Loc, TryCapture_Implicit, SourceLocation(),
10793 /*BuildAndDiagnose=*/false, CaptureType, DeclRefType))
10794 return QualType();
10795
10796 return DeclRefType;
Eli Friedman3c0e80e2012-02-03 02:04:35 +000010797}
10798
Eli Friedmand2cce132012-02-02 23:15:15 +000010799static void MarkVarDeclODRUsed(Sema &SemaRef, VarDecl *Var,
10800 SourceLocation Loc) {
10801 // Keep track of used but undefined variables.
Eli Friedman0cc5d402012-02-04 00:54:05 +000010802 // FIXME: We shouldn't suppress this warning for static data members.
Daniel Dunbar3d13c5a2012-03-09 01:51:51 +000010803 if (Var->hasDefinition(SemaRef.Context) == VarDecl::DeclarationOnly &&
Eli Friedman0cc5d402012-02-04 00:54:05 +000010804 Var->getLinkage() != ExternalLinkage &&
10805 !(Var->isStaticDataMember() && Var->hasInit())) {
Eli Friedmand2cce132012-02-02 23:15:15 +000010806 SourceLocation &old = SemaRef.UndefinedInternals[Var->getCanonicalDecl()];
10807 if (old.isInvalid()) old = Loc;
10808 }
10809
Douglas Gregor999713e2012-02-18 09:37:24 +000010810 SemaRef.tryCaptureVariable(Var, Loc);
Eli Friedman3c0e80e2012-02-03 02:04:35 +000010811
Eli Friedmand2cce132012-02-02 23:15:15 +000010812 Var->setUsed(true);
10813}
10814
10815void Sema::UpdateMarkingForLValueToRValue(Expr *E) {
10816 // Per C++11 [basic.def.odr], a variable is odr-used "unless it is
10817 // an object that satisfies the requirements for appearing in a
10818 // constant expression (5.19) and the lvalue-to-rvalue conversion (4.1)
10819 // is immediately applied." This function handles the lvalue-to-rvalue
10820 // conversion part.
10821 MaybeODRUseExprs.erase(E->IgnoreParens());
10822}
10823
Eli Friedmanac626012012-02-29 03:16:56 +000010824ExprResult Sema::ActOnConstantExpression(ExprResult Res) {
10825 if (!Res.isUsable())
10826 return Res;
10827
10828 // If a constant-expression is a reference to a variable where we delay
10829 // deciding whether it is an odr-use, just assume we will apply the
10830 // lvalue-to-rvalue conversion. In the one case where this doesn't happen
10831 // (a non-type template argument), we have special handling anyway.
10832 UpdateMarkingForLValueToRValue(Res.get());
10833 return Res;
10834}
10835
Eli Friedmand2cce132012-02-02 23:15:15 +000010836void Sema::CleanupVarDeclMarking() {
10837 for (llvm::SmallPtrSetIterator<Expr*> i = MaybeODRUseExprs.begin(),
10838 e = MaybeODRUseExprs.end();
10839 i != e; ++i) {
10840 VarDecl *Var;
10841 SourceLocation Loc;
John McCallf4b88a42012-03-10 09:33:50 +000010842 if (DeclRefExpr *DRE = dyn_cast<DeclRefExpr>(*i)) {
Eli Friedmand2cce132012-02-02 23:15:15 +000010843 Var = cast<VarDecl>(DRE->getDecl());
10844 Loc = DRE->getLocation();
10845 } else if (MemberExpr *ME = dyn_cast<MemberExpr>(*i)) {
10846 Var = cast<VarDecl>(ME->getMemberDecl());
10847 Loc = ME->getMemberLoc();
10848 } else {
10849 llvm_unreachable("Unexpcted expression");
10850 }
10851
10852 MarkVarDeclODRUsed(*this, Var, Loc);
10853 }
10854
10855 MaybeODRUseExprs.clear();
10856}
10857
10858// Mark a VarDecl referenced, and perform the necessary handling to compute
10859// odr-uses.
10860static void DoMarkVarDeclReferenced(Sema &SemaRef, SourceLocation Loc,
10861 VarDecl *Var, Expr *E) {
Eli Friedman5f2987c2012-02-02 03:46:19 +000010862 Var->setReferenced();
10863
Eli Friedmand2cce132012-02-02 23:15:15 +000010864 if (!IsPotentiallyEvaluatedContext(SemaRef))
Eli Friedman5f2987c2012-02-02 03:46:19 +000010865 return;
10866
10867 // Implicit instantiation of static data members of class templates.
Richard Smith37ce0102012-02-15 02:42:50 +000010868 if (Var->isStaticDataMember() && Var->getInstantiatedFromStaticDataMember()) {
Eli Friedman5f2987c2012-02-02 03:46:19 +000010869 MemberSpecializationInfo *MSInfo = Var->getMemberSpecializationInfo();
10870 assert(MSInfo && "Missing member specialization information?");
Richard Smith37ce0102012-02-15 02:42:50 +000010871 bool AlreadyInstantiated = !MSInfo->getPointOfInstantiation().isInvalid();
10872 if (MSInfo->getTemplateSpecializationKind() == TSK_ImplicitInstantiation &&
Daniel Dunbar3d13c5a2012-03-09 01:51:51 +000010873 (!AlreadyInstantiated ||
10874 Var->isUsableInConstantExpressions(SemaRef.Context))) {
Richard Smith37ce0102012-02-15 02:42:50 +000010875 if (!AlreadyInstantiated) {
10876 // This is a modification of an existing AST node. Notify listeners.
10877 if (ASTMutationListener *L = SemaRef.getASTMutationListener())
10878 L->StaticDataMemberInstantiated(Var);
10879 MSInfo->setPointOfInstantiation(Loc);
10880 }
10881 SourceLocation PointOfInstantiation = MSInfo->getPointOfInstantiation();
Daniel Dunbar3d13c5a2012-03-09 01:51:51 +000010882 if (Var->isUsableInConstantExpressions(SemaRef.Context))
Eli Friedman5f2987c2012-02-02 03:46:19 +000010883 // Do not defer instantiations of variables which could be used in a
10884 // constant expression.
Richard Smith37ce0102012-02-15 02:42:50 +000010885 SemaRef.InstantiateStaticDataMemberDefinition(PointOfInstantiation,Var);
Eli Friedman5f2987c2012-02-02 03:46:19 +000010886 else
Richard Smith37ce0102012-02-15 02:42:50 +000010887 SemaRef.PendingInstantiations.push_back(
10888 std::make_pair(Var, PointOfInstantiation));
Eli Friedman5f2987c2012-02-02 03:46:19 +000010889 }
10890 }
10891
Eli Friedmand2cce132012-02-02 23:15:15 +000010892 // Per C++11 [basic.def.odr], a variable is odr-used "unless it is
10893 // an object that satisfies the requirements for appearing in a
10894 // constant expression (5.19) and the lvalue-to-rvalue conversion (4.1)
10895 // is immediately applied." We check the first part here, and
10896 // Sema::UpdateMarkingForLValueToRValue deals with the second part.
10897 // Note that we use the C++11 definition everywhere because nothing in
Richard Smith16581332012-03-02 04:14:40 +000010898 // C++03 depends on whether we get the C++03 version correct. This does not
10899 // apply to references, since they are not objects.
Eli Friedmand2cce132012-02-02 23:15:15 +000010900 const VarDecl *DefVD;
Richard Smith16581332012-03-02 04:14:40 +000010901 if (E && !isa<ParmVarDecl>(Var) && !Var->getType()->isReferenceType() &&
Daniel Dunbar3d13c5a2012-03-09 01:51:51 +000010902 Var->isUsableInConstantExpressions(SemaRef.Context) &&
Eli Friedmand2cce132012-02-02 23:15:15 +000010903 Var->getAnyInitializer(DefVD) && DefVD->checkInitIsICE())
10904 SemaRef.MaybeODRUseExprs.insert(E);
10905 else
10906 MarkVarDeclODRUsed(SemaRef, Var, Loc);
10907}
Eli Friedman5f2987c2012-02-02 03:46:19 +000010908
Eli Friedmand2cce132012-02-02 23:15:15 +000010909/// \brief Mark a variable referenced, and check whether it is odr-used
10910/// (C++ [basic.def.odr]p2, C99 6.9p3). Note that this should not be
10911/// used directly for normal expressions referring to VarDecl.
10912void Sema::MarkVariableReferenced(SourceLocation Loc, VarDecl *Var) {
10913 DoMarkVarDeclReferenced(*this, Loc, Var, 0);
Eli Friedman5f2987c2012-02-02 03:46:19 +000010914}
10915
10916static void MarkExprReferenced(Sema &SemaRef, SourceLocation Loc,
10917 Decl *D, Expr *E) {
Eli Friedmand2cce132012-02-02 23:15:15 +000010918 if (VarDecl *Var = dyn_cast<VarDecl>(D)) {
10919 DoMarkVarDeclReferenced(SemaRef, Loc, Var, E);
10920 return;
10921 }
10922
Eli Friedman5f2987c2012-02-02 03:46:19 +000010923 SemaRef.MarkAnyDeclReferenced(Loc, D);
Rafael Espindola0b4fe502012-06-26 17:45:31 +000010924
10925 // If this is a call to a method via a cast, also mark the method in the
10926 // derived class used in case codegen can devirtualize the call.
10927 const MemberExpr *ME = dyn_cast<MemberExpr>(E);
10928 if (!ME)
10929 return;
10930 CXXMethodDecl *MD = dyn_cast<CXXMethodDecl>(ME->getMemberDecl());
10931 if (!MD)
10932 return;
10933 const Expr *Base = ME->getBase();
Rafael Espindola8d852e32012-06-27 18:18:05 +000010934 const CXXRecordDecl *MostDerivedClassDecl = Base->getBestDynamicClassType();
Rafael Espindola0b4fe502012-06-26 17:45:31 +000010935 if (!MostDerivedClassDecl)
10936 return;
10937 CXXMethodDecl *DM = MD->getCorrespondingMethodInClass(MostDerivedClassDecl);
Rafael Espindola0713d992012-06-27 17:44:39 +000010938 if (!DM)
10939 return;
Rafael Espindola0b4fe502012-06-26 17:45:31 +000010940 SemaRef.MarkAnyDeclReferenced(Loc, DM);
Douglas Gregorf6e2e022012-02-16 01:06:16 +000010941}
Eli Friedman5f2987c2012-02-02 03:46:19 +000010942
Eli Friedman5f2987c2012-02-02 03:46:19 +000010943/// \brief Perform reference-marking and odr-use handling for a DeclRefExpr.
10944void Sema::MarkDeclRefReferenced(DeclRefExpr *E) {
10945 MarkExprReferenced(*this, E->getLocation(), E->getDecl(), E);
10946}
10947
10948/// \brief Perform reference-marking and odr-use handling for a MemberExpr.
10949void Sema::MarkMemberReferenced(MemberExpr *E) {
10950 MarkExprReferenced(*this, E->getMemberLoc(), E->getMemberDecl(), E);
10951}
10952
Douglas Gregor73d90922012-02-10 09:26:04 +000010953/// \brief Perform marking for a reference to an arbitrary declaration. It
Eli Friedman5f2987c2012-02-02 03:46:19 +000010954/// marks the declaration referenced, and performs odr-use checking for functions
10955/// and variables. This method should not be used when building an normal
10956/// expression which refers to a variable.
10957void Sema::MarkAnyDeclReferenced(SourceLocation Loc, Decl *D) {
10958 if (VarDecl *VD = dyn_cast<VarDecl>(D))
10959 MarkVariableReferenced(Loc, VD);
10960 else if (FunctionDecl *FD = dyn_cast<FunctionDecl>(D))
10961 MarkFunctionReferenced(Loc, FD);
10962 else
10963 D->setReferenced();
Douglas Gregore0762c92009-06-19 23:52:42 +000010964}
Anders Carlsson8c8d9192009-10-09 23:51:55 +000010965
Douglas Gregorb4eeaff2010-05-07 23:12:07 +000010966namespace {
Chandler Carruthdfc35e32010-06-09 08:17:30 +000010967 // Mark all of the declarations referenced
Douglas Gregorb4eeaff2010-05-07 23:12:07 +000010968 // FIXME: Not fully implemented yet! We need to have a better understanding
Chandler Carruthdfc35e32010-06-09 08:17:30 +000010969 // of when we're entering
Douglas Gregorb4eeaff2010-05-07 23:12:07 +000010970 class MarkReferencedDecls : public RecursiveASTVisitor<MarkReferencedDecls> {
10971 Sema &S;
10972 SourceLocation Loc;
Chandler Carruthdfc35e32010-06-09 08:17:30 +000010973
Douglas Gregorb4eeaff2010-05-07 23:12:07 +000010974 public:
10975 typedef RecursiveASTVisitor<MarkReferencedDecls> Inherited;
Chandler Carruthdfc35e32010-06-09 08:17:30 +000010976
Douglas Gregorb4eeaff2010-05-07 23:12:07 +000010977 MarkReferencedDecls(Sema &S, SourceLocation Loc) : S(S), Loc(Loc) { }
Chandler Carruthdfc35e32010-06-09 08:17:30 +000010978
10979 bool TraverseTemplateArgument(const TemplateArgument &Arg);
10980 bool TraverseRecordType(RecordType *T);
Douglas Gregorb4eeaff2010-05-07 23:12:07 +000010981 };
10982}
10983
Chandler Carruthdfc35e32010-06-09 08:17:30 +000010984bool MarkReferencedDecls::TraverseTemplateArgument(
10985 const TemplateArgument &Arg) {
Douglas Gregorb4eeaff2010-05-07 23:12:07 +000010986 if (Arg.getKind() == TemplateArgument::Declaration) {
Douglas Gregord2008e22012-04-06 22:40:38 +000010987 if (Decl *D = Arg.getAsDecl())
10988 S.MarkAnyDeclReferenced(Loc, D);
Douglas Gregorb4eeaff2010-05-07 23:12:07 +000010989 }
Chandler Carruthdfc35e32010-06-09 08:17:30 +000010990
10991 return Inherited::TraverseTemplateArgument(Arg);
Douglas Gregorb4eeaff2010-05-07 23:12:07 +000010992}
10993
Chandler Carruthdfc35e32010-06-09 08:17:30 +000010994bool MarkReferencedDecls::TraverseRecordType(RecordType *T) {
Douglas Gregorb4eeaff2010-05-07 23:12:07 +000010995 if (ClassTemplateSpecializationDecl *Spec
10996 = dyn_cast<ClassTemplateSpecializationDecl>(T->getDecl())) {
10997 const TemplateArgumentList &Args = Spec->getTemplateArgs();
Douglas Gregor910f8002010-11-07 23:05:16 +000010998 return TraverseTemplateArguments(Args.data(), Args.size());
Douglas Gregorb4eeaff2010-05-07 23:12:07 +000010999 }
11000
Chandler Carruthe3e210c2010-06-10 10:31:57 +000011001 return true;
Douglas Gregorb4eeaff2010-05-07 23:12:07 +000011002}
11003
11004void Sema::MarkDeclarationsReferencedInType(SourceLocation Loc, QualType T) {
11005 MarkReferencedDecls Marker(*this, Loc);
Chandler Carruthdfc35e32010-06-09 08:17:30 +000011006 Marker.TraverseType(Context.getCanonicalType(T));
Douglas Gregorb4eeaff2010-05-07 23:12:07 +000011007}
11008
Douglas Gregorbe0f7bd2010-09-11 20:24:53 +000011009namespace {
11010 /// \brief Helper class that marks all of the declarations referenced by
11011 /// potentially-evaluated subexpressions as "referenced".
11012 class EvaluatedExprMarker : public EvaluatedExprVisitor<EvaluatedExprMarker> {
11013 Sema &S;
Douglas Gregorf4b7de12012-02-21 19:11:17 +000011014 bool SkipLocalVariables;
Douglas Gregorbe0f7bd2010-09-11 20:24:53 +000011015
11016 public:
11017 typedef EvaluatedExprVisitor<EvaluatedExprMarker> Inherited;
11018
Douglas Gregorf4b7de12012-02-21 19:11:17 +000011019 EvaluatedExprMarker(Sema &S, bool SkipLocalVariables)
11020 : Inherited(S.Context), S(S), SkipLocalVariables(SkipLocalVariables) { }
Douglas Gregorbe0f7bd2010-09-11 20:24:53 +000011021
11022 void VisitDeclRefExpr(DeclRefExpr *E) {
Douglas Gregorf4b7de12012-02-21 19:11:17 +000011023 // If we were asked not to visit local variables, don't.
11024 if (SkipLocalVariables) {
11025 if (VarDecl *VD = dyn_cast<VarDecl>(E->getDecl()))
11026 if (VD->hasLocalStorage())
11027 return;
11028 }
11029
Eli Friedman5f2987c2012-02-02 03:46:19 +000011030 S.MarkDeclRefReferenced(E);
Douglas Gregorbe0f7bd2010-09-11 20:24:53 +000011031 }
11032
11033 void VisitMemberExpr(MemberExpr *E) {
Eli Friedman5f2987c2012-02-02 03:46:19 +000011034 S.MarkMemberReferenced(E);
Douglas Gregor4fcf5b22010-09-11 23:32:50 +000011035 Inherited::VisitMemberExpr(E);
Douglas Gregorbe0f7bd2010-09-11 20:24:53 +000011036 }
11037
John McCall80ee6e82011-11-10 05:35:25 +000011038 void VisitCXXBindTemporaryExpr(CXXBindTemporaryExpr *E) {
Eli Friedman5f2987c2012-02-02 03:46:19 +000011039 S.MarkFunctionReferenced(E->getLocStart(),
John McCall80ee6e82011-11-10 05:35:25 +000011040 const_cast<CXXDestructorDecl*>(E->getTemporary()->getDestructor()));
11041 Visit(E->getSubExpr());
11042 }
11043
Douglas Gregorbe0f7bd2010-09-11 20:24:53 +000011044 void VisitCXXNewExpr(CXXNewExpr *E) {
Douglas Gregorbe0f7bd2010-09-11 20:24:53 +000011045 if (E->getOperatorNew())
Eli Friedman5f2987c2012-02-02 03:46:19 +000011046 S.MarkFunctionReferenced(E->getLocStart(), E->getOperatorNew());
Douglas Gregorbe0f7bd2010-09-11 20:24:53 +000011047 if (E->getOperatorDelete())
Eli Friedman5f2987c2012-02-02 03:46:19 +000011048 S.MarkFunctionReferenced(E->getLocStart(), E->getOperatorDelete());
Douglas Gregor4fcf5b22010-09-11 23:32:50 +000011049 Inherited::VisitCXXNewExpr(E);
Douglas Gregorbe0f7bd2010-09-11 20:24:53 +000011050 }
Sebastian Redl2aed8b82012-02-16 12:22:20 +000011051
Douglas Gregorbe0f7bd2010-09-11 20:24:53 +000011052 void VisitCXXDeleteExpr(CXXDeleteExpr *E) {
11053 if (E->getOperatorDelete())
Eli Friedman5f2987c2012-02-02 03:46:19 +000011054 S.MarkFunctionReferenced(E->getLocStart(), E->getOperatorDelete());
Douglas Gregor5833b0b2010-09-14 22:55:20 +000011055 QualType Destroyed = S.Context.getBaseElementType(E->getDestroyedType());
11056 if (const RecordType *DestroyedRec = Destroyed->getAs<RecordType>()) {
11057 CXXRecordDecl *Record = cast<CXXRecordDecl>(DestroyedRec->getDecl());
Eli Friedman5f2987c2012-02-02 03:46:19 +000011058 S.MarkFunctionReferenced(E->getLocStart(),
Douglas Gregor5833b0b2010-09-14 22:55:20 +000011059 S.LookupDestructor(Record));
11060 }
11061
Douglas Gregor4fcf5b22010-09-11 23:32:50 +000011062 Inherited::VisitCXXDeleteExpr(E);
Douglas Gregorbe0f7bd2010-09-11 20:24:53 +000011063 }
11064
11065 void VisitCXXConstructExpr(CXXConstructExpr *E) {
Eli Friedman5f2987c2012-02-02 03:46:19 +000011066 S.MarkFunctionReferenced(E->getLocStart(), E->getConstructor());
Douglas Gregor4fcf5b22010-09-11 23:32:50 +000011067 Inherited::VisitCXXConstructExpr(E);
Douglas Gregorbe0f7bd2010-09-11 20:24:53 +000011068 }
11069
Douglas Gregor102ff972010-10-19 17:17:35 +000011070 void VisitCXXDefaultArgExpr(CXXDefaultArgExpr *E) {
11071 Visit(E->getExpr());
11072 }
Eli Friedmand2cce132012-02-02 23:15:15 +000011073
11074 void VisitImplicitCastExpr(ImplicitCastExpr *E) {
11075 Inherited::VisitImplicitCastExpr(E);
11076
11077 if (E->getCastKind() == CK_LValueToRValue)
11078 S.UpdateMarkingForLValueToRValue(E->getSubExpr());
11079 }
Douglas Gregorbe0f7bd2010-09-11 20:24:53 +000011080 };
11081}
11082
11083/// \brief Mark any declarations that appear within this expression or any
11084/// potentially-evaluated subexpressions as "referenced".
Douglas Gregorf4b7de12012-02-21 19:11:17 +000011085///
11086/// \param SkipLocalVariables If true, don't mark local variables as
11087/// 'referenced'.
11088void Sema::MarkDeclarationsReferencedInExpr(Expr *E,
11089 bool SkipLocalVariables) {
11090 EvaluatedExprMarker(*this, SkipLocalVariables).Visit(E);
Douglas Gregorbe0f7bd2010-09-11 20:24:53 +000011091}
11092
Douglas Gregor1c7c3fb2009-12-22 01:01:55 +000011093/// \brief Emit a diagnostic that describes an effect on the run-time behavior
11094/// of the program being compiled.
11095///
11096/// This routine emits the given diagnostic when the code currently being
Kovarththanan Rajaratnam19357542010-03-13 10:17:05 +000011097/// type-checked is "potentially evaluated", meaning that there is a
Douglas Gregor1c7c3fb2009-12-22 01:01:55 +000011098/// possibility that the code will actually be executable. Code in sizeof()
11099/// expressions, code used only during overload resolution, etc., are not
11100/// potentially evaluated. This routine will suppress such diagnostics or,
11101/// in the absolutely nutty case of potentially potentially evaluated
Kovarththanan Rajaratnam19357542010-03-13 10:17:05 +000011102/// expressions (C++ typeid), queue the diagnostic to potentially emit it
Douglas Gregor1c7c3fb2009-12-22 01:01:55 +000011103/// later.
Kovarththanan Rajaratnam19357542010-03-13 10:17:05 +000011104///
Douglas Gregor1c7c3fb2009-12-22 01:01:55 +000011105/// This routine should be used for all diagnostics that describe the run-time
11106/// behavior of a program, such as passing a non-POD value through an ellipsis.
11107/// Failure to do so will likely result in spurious diagnostics or failures
11108/// during overload resolution or within sizeof/alignof/typeof/typeid.
Richard Trieuccd891a2011-09-09 01:45:06 +000011109bool Sema::DiagRuntimeBehavior(SourceLocation Loc, const Stmt *Statement,
Douglas Gregor1c7c3fb2009-12-22 01:01:55 +000011110 const PartialDiagnostic &PD) {
John McCallf85e1932011-06-15 23:02:42 +000011111 switch (ExprEvalContexts.back().Context) {
Douglas Gregor1c7c3fb2009-12-22 01:01:55 +000011112 case Unevaluated:
11113 // The argument will never be evaluated, so don't complain.
11114 break;
Kovarththanan Rajaratnam19357542010-03-13 10:17:05 +000011115
Richard Smithf6702a32011-12-20 02:08:33 +000011116 case ConstantEvaluated:
11117 // Relevant diagnostics should be produced by constant evaluation.
11118 break;
11119
Douglas Gregor1c7c3fb2009-12-22 01:01:55 +000011120 case PotentiallyEvaluated:
Douglas Gregorbe0f7bd2010-09-11 20:24:53 +000011121 case PotentiallyEvaluatedIfUsed:
Richard Trieuccd891a2011-09-09 01:45:06 +000011122 if (Statement && getCurFunctionOrMethodDecl()) {
Ted Kremenek351ba912011-02-23 01:52:04 +000011123 FunctionScopes.back()->PossiblyUnreachableDiags.
Richard Trieuccd891a2011-09-09 01:45:06 +000011124 push_back(sema::PossiblyUnreachableDiag(PD, Loc, Statement));
Ted Kremenek351ba912011-02-23 01:52:04 +000011125 }
11126 else
11127 Diag(Loc, PD);
11128
Douglas Gregor1c7c3fb2009-12-22 01:01:55 +000011129 return true;
Douglas Gregor1c7c3fb2009-12-22 01:01:55 +000011130 }
11131
11132 return false;
11133}
11134
Anders Carlsson8c8d9192009-10-09 23:51:55 +000011135bool Sema::CheckCallReturnType(QualType ReturnType, SourceLocation Loc,
11136 CallExpr *CE, FunctionDecl *FD) {
11137 if (ReturnType->isVoidType() || !ReturnType->isIncompleteType())
11138 return false;
11139
Richard Smith76f3f692012-02-22 02:04:18 +000011140 // If we're inside a decltype's expression, don't check for a valid return
11141 // type or construct temporaries until we know whether this is the last call.
11142 if (ExprEvalContexts.back().IsDecltype) {
11143 ExprEvalContexts.back().DelayedDecltypeCalls.push_back(CE);
11144 return false;
11145 }
11146
Douglas Gregorf502d8e2012-05-04 16:48:41 +000011147 class CallReturnIncompleteDiagnoser : public TypeDiagnoser {
Douglas Gregord10099e2012-05-04 16:32:21 +000011148 FunctionDecl *FD;
11149 CallExpr *CE;
11150
11151 public:
11152 CallReturnIncompleteDiagnoser(FunctionDecl *FD, CallExpr *CE)
11153 : FD(FD), CE(CE) { }
11154
11155 virtual void diagnose(Sema &S, SourceLocation Loc, QualType T) {
11156 if (!FD) {
11157 S.Diag(Loc, diag::err_call_incomplete_return)
11158 << T << CE->getSourceRange();
11159 return;
11160 }
11161
11162 S.Diag(Loc, diag::err_call_function_incomplete_return)
11163 << CE->getSourceRange() << FD->getDeclName() << T;
11164 S.Diag(FD->getLocation(),
11165 diag::note_function_with_incomplete_return_type_declared_here)
11166 << FD->getDeclName();
11167 }
11168 } Diagnoser(FD, CE);
11169
11170 if (RequireCompleteType(Loc, ReturnType, Diagnoser))
Anders Carlsson8c8d9192009-10-09 23:51:55 +000011171 return true;
11172
11173 return false;
11174}
11175
Douglas Gregor92c3a042011-01-19 16:50:08 +000011176// Diagnose the s/=/==/ and s/\|=/!=/ typos. Note that adding parentheses
John McCall5a881bb2009-10-12 21:59:07 +000011177// will prevent this condition from triggering, which is what we want.
11178void Sema::DiagnoseAssignmentAsCondition(Expr *E) {
11179 SourceLocation Loc;
11180
John McCalla52ef082009-11-11 02:41:58 +000011181 unsigned diagnostic = diag::warn_condition_is_assignment;
Douglas Gregor92c3a042011-01-19 16:50:08 +000011182 bool IsOrAssign = false;
John McCalla52ef082009-11-11 02:41:58 +000011183
Chandler Carruthb33c19f2011-08-16 22:30:10 +000011184 if (BinaryOperator *Op = dyn_cast<BinaryOperator>(E)) {
Douglas Gregor92c3a042011-01-19 16:50:08 +000011185 if (Op->getOpcode() != BO_Assign && Op->getOpcode() != BO_OrAssign)
John McCall5a881bb2009-10-12 21:59:07 +000011186 return;
11187
Douglas Gregor92c3a042011-01-19 16:50:08 +000011188 IsOrAssign = Op->getOpcode() == BO_OrAssign;
11189
John McCallc8d8ac52009-11-12 00:06:05 +000011190 // Greylist some idioms by putting them into a warning subcategory.
11191 if (ObjCMessageExpr *ME
11192 = dyn_cast<ObjCMessageExpr>(Op->getRHS()->IgnoreParenCasts())) {
11193 Selector Sel = ME->getSelector();
11194
John McCallc8d8ac52009-11-12 00:06:05 +000011195 // self = [<foo> init...]
Douglas Gregorc737acb2011-09-27 16:10:05 +000011196 if (isSelfExpr(Op->getLHS()) && Sel.getNameForSlot(0).startswith("init"))
John McCallc8d8ac52009-11-12 00:06:05 +000011197 diagnostic = diag::warn_condition_is_idiomatic_assignment;
11198
11199 // <foo> = [<bar> nextObject]
Douglas Gregor813d8342011-02-18 22:29:55 +000011200 else if (Sel.isUnarySelector() && Sel.getNameForSlot(0) == "nextObject")
John McCallc8d8ac52009-11-12 00:06:05 +000011201 diagnostic = diag::warn_condition_is_idiomatic_assignment;
11202 }
John McCalla52ef082009-11-11 02:41:58 +000011203
John McCall5a881bb2009-10-12 21:59:07 +000011204 Loc = Op->getOperatorLoc();
Chandler Carruthb33c19f2011-08-16 22:30:10 +000011205 } else if (CXXOperatorCallExpr *Op = dyn_cast<CXXOperatorCallExpr>(E)) {
Douglas Gregor92c3a042011-01-19 16:50:08 +000011206 if (Op->getOperator() != OO_Equal && Op->getOperator() != OO_PipeEqual)
John McCall5a881bb2009-10-12 21:59:07 +000011207 return;
11208
Douglas Gregor92c3a042011-01-19 16:50:08 +000011209 IsOrAssign = Op->getOperator() == OO_PipeEqual;
John McCall5a881bb2009-10-12 21:59:07 +000011210 Loc = Op->getOperatorLoc();
Fariborz Jahaniana414a2f2012-08-29 17:17:11 +000011211 } else if (PseudoObjectExpr *POE = dyn_cast<PseudoObjectExpr>(E))
11212 return DiagnoseAssignmentAsCondition(POE->getSyntacticForm());
11213 else {
John McCall5a881bb2009-10-12 21:59:07 +000011214 // Not an assignment.
11215 return;
11216 }
11217
Douglas Gregor55b38842010-04-14 16:09:52 +000011218 Diag(Loc, diagnostic) << E->getSourceRange();
Douglas Gregor92c3a042011-01-19 16:50:08 +000011219
Daniel Dunbar96a00142012-03-09 18:35:03 +000011220 SourceLocation Open = E->getLocStart();
Argyrios Kyrtzidisabdd3b32011-04-25 23:01:29 +000011221 SourceLocation Close = PP.getLocForEndOfToken(E->getSourceRange().getEnd());
11222 Diag(Loc, diag::note_condition_assign_silence)
11223 << FixItHint::CreateInsertion(Open, "(")
11224 << FixItHint::CreateInsertion(Close, ")");
11225
Douglas Gregor92c3a042011-01-19 16:50:08 +000011226 if (IsOrAssign)
11227 Diag(Loc, diag::note_condition_or_assign_to_comparison)
11228 << FixItHint::CreateReplacement(Loc, "!=");
11229 else
11230 Diag(Loc, diag::note_condition_assign_to_comparison)
11231 << FixItHint::CreateReplacement(Loc, "==");
John McCall5a881bb2009-10-12 21:59:07 +000011232}
11233
Argyrios Kyrtzidis0e2dc3a2011-02-01 18:24:22 +000011234/// \brief Redundant parentheses over an equality comparison can indicate
11235/// that the user intended an assignment used as condition.
Richard Trieuccd891a2011-09-09 01:45:06 +000011236void Sema::DiagnoseEqualityWithExtraParens(ParenExpr *ParenE) {
Argyrios Kyrtzidiscf1620a2011-02-01 22:23:56 +000011237 // Don't warn if the parens came from a macro.
Richard Trieuccd891a2011-09-09 01:45:06 +000011238 SourceLocation parenLoc = ParenE->getLocStart();
Argyrios Kyrtzidiscf1620a2011-02-01 22:23:56 +000011239 if (parenLoc.isInvalid() || parenLoc.isMacroID())
11240 return;
Argyrios Kyrtzidis170a6a22011-03-28 23:52:04 +000011241 // Don't warn for dependent expressions.
Richard Trieuccd891a2011-09-09 01:45:06 +000011242 if (ParenE->isTypeDependent())
Argyrios Kyrtzidis170a6a22011-03-28 23:52:04 +000011243 return;
Argyrios Kyrtzidiscf1620a2011-02-01 22:23:56 +000011244
Richard Trieuccd891a2011-09-09 01:45:06 +000011245 Expr *E = ParenE->IgnoreParens();
Argyrios Kyrtzidis0e2dc3a2011-02-01 18:24:22 +000011246
11247 if (BinaryOperator *opE = dyn_cast<BinaryOperator>(E))
Argyrios Kyrtzidis70f23302011-02-01 19:32:59 +000011248 if (opE->getOpcode() == BO_EQ &&
11249 opE->getLHS()->IgnoreParenImpCasts()->isModifiableLvalue(Context)
11250 == Expr::MLV_Valid) {
Argyrios Kyrtzidis0e2dc3a2011-02-01 18:24:22 +000011251 SourceLocation Loc = opE->getOperatorLoc();
Ted Kremenek006ae382011-02-01 22:36:09 +000011252
Ted Kremenekf7275cd2011-02-02 02:20:30 +000011253 Diag(Loc, diag::warn_equality_with_extra_parens) << E->getSourceRange();
Daniel Dunbar96a00142012-03-09 18:35:03 +000011254 SourceRange ParenERange = ParenE->getSourceRange();
Ted Kremenekf7275cd2011-02-02 02:20:30 +000011255 Diag(Loc, diag::note_equality_comparison_silence)
Daniel Dunbar96a00142012-03-09 18:35:03 +000011256 << FixItHint::CreateRemoval(ParenERange.getBegin())
11257 << FixItHint::CreateRemoval(ParenERange.getEnd());
Argyrios Kyrtzidisabdd3b32011-04-25 23:01:29 +000011258 Diag(Loc, diag::note_equality_comparison_to_assign)
11259 << FixItHint::CreateReplacement(Loc, "=");
Argyrios Kyrtzidis0e2dc3a2011-02-01 18:24:22 +000011260 }
11261}
11262
John Wiegley429bb272011-04-08 18:41:53 +000011263ExprResult Sema::CheckBooleanCondition(Expr *E, SourceLocation Loc) {
John McCall5a881bb2009-10-12 21:59:07 +000011264 DiagnoseAssignmentAsCondition(E);
Argyrios Kyrtzidis0e2dc3a2011-02-01 18:24:22 +000011265 if (ParenExpr *parenE = dyn_cast<ParenExpr>(E))
11266 DiagnoseEqualityWithExtraParens(parenE);
John McCall5a881bb2009-10-12 21:59:07 +000011267
John McCall864c0412011-04-26 20:42:42 +000011268 ExprResult result = CheckPlaceholderExpr(E);
11269 if (result.isInvalid()) return ExprError();
11270 E = result.take();
Argyrios Kyrtzidis11ab7902010-11-01 18:49:26 +000011271
John McCall864c0412011-04-26 20:42:42 +000011272 if (!E->isTypeDependent()) {
David Blaikie4e4d0842012-03-11 07:00:24 +000011273 if (getLangOpts().CPlusPlus)
John McCallf6a16482010-12-04 03:47:34 +000011274 return CheckCXXBooleanCondition(E); // C++ 6.4p4
11275
John Wiegley429bb272011-04-08 18:41:53 +000011276 ExprResult ERes = DefaultFunctionArrayLvalueConversion(E);
11277 if (ERes.isInvalid())
11278 return ExprError();
11279 E = ERes.take();
John McCallabc56c72010-12-04 06:09:13 +000011280
11281 QualType T = E->getType();
John Wiegley429bb272011-04-08 18:41:53 +000011282 if (!T->isScalarType()) { // C99 6.8.4.1p1
11283 Diag(Loc, diag::err_typecheck_statement_requires_scalar)
11284 << T << E->getSourceRange();
11285 return ExprError();
11286 }
John McCall5a881bb2009-10-12 21:59:07 +000011287 }
11288
John Wiegley429bb272011-04-08 18:41:53 +000011289 return Owned(E);
John McCall5a881bb2009-10-12 21:59:07 +000011290}
Douglas Gregor586596f2010-05-06 17:25:47 +000011291
John McCall60d7b3a2010-08-24 06:29:42 +000011292ExprResult Sema::ActOnBooleanCondition(Scope *S, SourceLocation Loc,
Richard Trieuccd891a2011-09-09 01:45:06 +000011293 Expr *SubExpr) {
11294 if (!SubExpr)
Douglas Gregor586596f2010-05-06 17:25:47 +000011295 return ExprError();
John Wiegley429bb272011-04-08 18:41:53 +000011296
Richard Trieuccd891a2011-09-09 01:45:06 +000011297 return CheckBooleanCondition(SubExpr, Loc);
Douglas Gregor586596f2010-05-06 17:25:47 +000011298}
John McCall2a984ca2010-10-12 00:20:44 +000011299
John McCall1de4d4e2011-04-07 08:22:57 +000011300namespace {
John McCall755d8492011-04-12 00:42:48 +000011301 /// A visitor for rebuilding a call to an __unknown_any expression
11302 /// to have an appropriate type.
11303 struct RebuildUnknownAnyFunction
11304 : StmtVisitor<RebuildUnknownAnyFunction, ExprResult> {
11305
11306 Sema &S;
11307
11308 RebuildUnknownAnyFunction(Sema &S) : S(S) {}
11309
11310 ExprResult VisitStmt(Stmt *S) {
11311 llvm_unreachable("unexpected statement!");
John McCall755d8492011-04-12 00:42:48 +000011312 }
11313
Richard Trieu5e4c80b2011-09-09 03:59:41 +000011314 ExprResult VisitExpr(Expr *E) {
11315 S.Diag(E->getExprLoc(), diag::err_unsupported_unknown_any_call)
11316 << E->getSourceRange();
John McCall755d8492011-04-12 00:42:48 +000011317 return ExprError();
11318 }
11319
11320 /// Rebuild an expression which simply semantically wraps another
11321 /// expression which it shares the type and value kind of.
Richard Trieu5e4c80b2011-09-09 03:59:41 +000011322 template <class T> ExprResult rebuildSugarExpr(T *E) {
11323 ExprResult SubResult = Visit(E->getSubExpr());
11324 if (SubResult.isInvalid()) return ExprError();
John McCall755d8492011-04-12 00:42:48 +000011325
Richard Trieu5e4c80b2011-09-09 03:59:41 +000011326 Expr *SubExpr = SubResult.take();
11327 E->setSubExpr(SubExpr);
11328 E->setType(SubExpr->getType());
11329 E->setValueKind(SubExpr->getValueKind());
11330 assert(E->getObjectKind() == OK_Ordinary);
11331 return E;
John McCall755d8492011-04-12 00:42:48 +000011332 }
11333
Richard Trieu5e4c80b2011-09-09 03:59:41 +000011334 ExprResult VisitParenExpr(ParenExpr *E) {
11335 return rebuildSugarExpr(E);
John McCall755d8492011-04-12 00:42:48 +000011336 }
11337
Richard Trieu5e4c80b2011-09-09 03:59:41 +000011338 ExprResult VisitUnaryExtension(UnaryOperator *E) {
11339 return rebuildSugarExpr(E);
John McCall755d8492011-04-12 00:42:48 +000011340 }
11341
Richard Trieu5e4c80b2011-09-09 03:59:41 +000011342 ExprResult VisitUnaryAddrOf(UnaryOperator *E) {
11343 ExprResult SubResult = Visit(E->getSubExpr());
11344 if (SubResult.isInvalid()) return ExprError();
John McCall755d8492011-04-12 00:42:48 +000011345
Richard Trieu5e4c80b2011-09-09 03:59:41 +000011346 Expr *SubExpr = SubResult.take();
11347 E->setSubExpr(SubExpr);
11348 E->setType(S.Context.getPointerType(SubExpr->getType()));
11349 assert(E->getValueKind() == VK_RValue);
11350 assert(E->getObjectKind() == OK_Ordinary);
11351 return E;
John McCall755d8492011-04-12 00:42:48 +000011352 }
11353
Richard Trieu5e4c80b2011-09-09 03:59:41 +000011354 ExprResult resolveDecl(Expr *E, ValueDecl *VD) {
11355 if (!isa<FunctionDecl>(VD)) return VisitExpr(E);
John McCall755d8492011-04-12 00:42:48 +000011356
Richard Trieu5e4c80b2011-09-09 03:59:41 +000011357 E->setType(VD->getType());
John McCall755d8492011-04-12 00:42:48 +000011358
Richard Trieu5e4c80b2011-09-09 03:59:41 +000011359 assert(E->getValueKind() == VK_RValue);
David Blaikie4e4d0842012-03-11 07:00:24 +000011360 if (S.getLangOpts().CPlusPlus &&
Richard Trieu5e4c80b2011-09-09 03:59:41 +000011361 !(isa<CXXMethodDecl>(VD) &&
11362 cast<CXXMethodDecl>(VD)->isInstance()))
11363 E->setValueKind(VK_LValue);
John McCall755d8492011-04-12 00:42:48 +000011364
Richard Trieu5e4c80b2011-09-09 03:59:41 +000011365 return E;
John McCall755d8492011-04-12 00:42:48 +000011366 }
11367
Richard Trieu5e4c80b2011-09-09 03:59:41 +000011368 ExprResult VisitMemberExpr(MemberExpr *E) {
11369 return resolveDecl(E, E->getMemberDecl());
John McCall755d8492011-04-12 00:42:48 +000011370 }
11371
Richard Trieu5e4c80b2011-09-09 03:59:41 +000011372 ExprResult VisitDeclRefExpr(DeclRefExpr *E) {
11373 return resolveDecl(E, E->getDecl());
John McCall755d8492011-04-12 00:42:48 +000011374 }
11375 };
11376}
11377
11378/// Given a function expression of unknown-any type, try to rebuild it
11379/// to have a function type.
Richard Trieu5e4c80b2011-09-09 03:59:41 +000011380static ExprResult rebuildUnknownAnyFunction(Sema &S, Expr *FunctionExpr) {
11381 ExprResult Result = RebuildUnknownAnyFunction(S).Visit(FunctionExpr);
11382 if (Result.isInvalid()) return ExprError();
11383 return S.DefaultFunctionArrayConversion(Result.take());
John McCall755d8492011-04-12 00:42:48 +000011384}
11385
11386namespace {
John McCall379b5152011-04-11 07:02:50 +000011387 /// A visitor for rebuilding an expression of type __unknown_anytype
11388 /// into one which resolves the type directly on the referring
11389 /// expression. Strict preservation of the original source
11390 /// structure is not a goal.
John McCall1de4d4e2011-04-07 08:22:57 +000011391 struct RebuildUnknownAnyExpr
John McCalla5fc4722011-04-09 22:50:59 +000011392 : StmtVisitor<RebuildUnknownAnyExpr, ExprResult> {
John McCall1de4d4e2011-04-07 08:22:57 +000011393
11394 Sema &S;
11395
11396 /// The current destination type.
11397 QualType DestType;
11398
Richard Trieu5e4c80b2011-09-09 03:59:41 +000011399 RebuildUnknownAnyExpr(Sema &S, QualType CastType)
11400 : S(S), DestType(CastType) {}
John McCall1de4d4e2011-04-07 08:22:57 +000011401
John McCalla5fc4722011-04-09 22:50:59 +000011402 ExprResult VisitStmt(Stmt *S) {
John McCall379b5152011-04-11 07:02:50 +000011403 llvm_unreachable("unexpected statement!");
John McCall1de4d4e2011-04-07 08:22:57 +000011404 }
11405
Richard Trieu5e4c80b2011-09-09 03:59:41 +000011406 ExprResult VisitExpr(Expr *E) {
11407 S.Diag(E->getExprLoc(), diag::err_unsupported_unknown_any_expr)
11408 << E->getSourceRange();
John McCall379b5152011-04-11 07:02:50 +000011409 return ExprError();
John McCall1de4d4e2011-04-07 08:22:57 +000011410 }
11411
Richard Trieu5e4c80b2011-09-09 03:59:41 +000011412 ExprResult VisitCallExpr(CallExpr *E);
11413 ExprResult VisitObjCMessageExpr(ObjCMessageExpr *E);
John McCall379b5152011-04-11 07:02:50 +000011414
John McCalla5fc4722011-04-09 22:50:59 +000011415 /// Rebuild an expression which simply semantically wraps another
11416 /// expression which it shares the type and value kind of.
Richard Trieu5e4c80b2011-09-09 03:59:41 +000011417 template <class T> ExprResult rebuildSugarExpr(T *E) {
11418 ExprResult SubResult = Visit(E->getSubExpr());
11419 if (SubResult.isInvalid()) return ExprError();
11420 Expr *SubExpr = SubResult.take();
11421 E->setSubExpr(SubExpr);
11422 E->setType(SubExpr->getType());
11423 E->setValueKind(SubExpr->getValueKind());
11424 assert(E->getObjectKind() == OK_Ordinary);
11425 return E;
John McCalla5fc4722011-04-09 22:50:59 +000011426 }
John McCall1de4d4e2011-04-07 08:22:57 +000011427
Richard Trieu5e4c80b2011-09-09 03:59:41 +000011428 ExprResult VisitParenExpr(ParenExpr *E) {
11429 return rebuildSugarExpr(E);
John McCalla5fc4722011-04-09 22:50:59 +000011430 }
11431
Richard Trieu5e4c80b2011-09-09 03:59:41 +000011432 ExprResult VisitUnaryExtension(UnaryOperator *E) {
11433 return rebuildSugarExpr(E);
John McCalla5fc4722011-04-09 22:50:59 +000011434 }
11435
Richard Trieu5e4c80b2011-09-09 03:59:41 +000011436 ExprResult VisitUnaryAddrOf(UnaryOperator *E) {
11437 const PointerType *Ptr = DestType->getAs<PointerType>();
11438 if (!Ptr) {
11439 S.Diag(E->getOperatorLoc(), diag::err_unknown_any_addrof)
11440 << E->getSourceRange();
John McCall755d8492011-04-12 00:42:48 +000011441 return ExprError();
11442 }
Richard Trieu5e4c80b2011-09-09 03:59:41 +000011443 assert(E->getValueKind() == VK_RValue);
11444 assert(E->getObjectKind() == OK_Ordinary);
11445 E->setType(DestType);
John McCall755d8492011-04-12 00:42:48 +000011446
11447 // Build the sub-expression as if it were an object of the pointee type.
Richard Trieu5e4c80b2011-09-09 03:59:41 +000011448 DestType = Ptr->getPointeeType();
11449 ExprResult SubResult = Visit(E->getSubExpr());
11450 if (SubResult.isInvalid()) return ExprError();
11451 E->setSubExpr(SubResult.take());
11452 return E;
John McCall755d8492011-04-12 00:42:48 +000011453 }
11454
Richard Trieu5e4c80b2011-09-09 03:59:41 +000011455 ExprResult VisitImplicitCastExpr(ImplicitCastExpr *E);
John McCalla5fc4722011-04-09 22:50:59 +000011456
Richard Trieu5e4c80b2011-09-09 03:59:41 +000011457 ExprResult resolveDecl(Expr *E, ValueDecl *VD);
John McCalla5fc4722011-04-09 22:50:59 +000011458
Richard Trieu5e4c80b2011-09-09 03:59:41 +000011459 ExprResult VisitMemberExpr(MemberExpr *E) {
11460 return resolveDecl(E, E->getMemberDecl());
John McCall755d8492011-04-12 00:42:48 +000011461 }
John McCalla5fc4722011-04-09 22:50:59 +000011462
Richard Trieu5e4c80b2011-09-09 03:59:41 +000011463 ExprResult VisitDeclRefExpr(DeclRefExpr *E) {
11464 return resolveDecl(E, E->getDecl());
John McCall1de4d4e2011-04-07 08:22:57 +000011465 }
11466 };
11467}
11468
John McCall379b5152011-04-11 07:02:50 +000011469/// Rebuilds a call expression which yielded __unknown_anytype.
Richard Trieu5e4c80b2011-09-09 03:59:41 +000011470ExprResult RebuildUnknownAnyExpr::VisitCallExpr(CallExpr *E) {
11471 Expr *CalleeExpr = E->getCallee();
John McCall379b5152011-04-11 07:02:50 +000011472
11473 enum FnKind {
John McCallf5307512011-04-27 00:36:17 +000011474 FK_MemberFunction,
John McCall379b5152011-04-11 07:02:50 +000011475 FK_FunctionPointer,
11476 FK_BlockPointer
11477 };
11478
Richard Trieu5e4c80b2011-09-09 03:59:41 +000011479 FnKind Kind;
11480 QualType CalleeType = CalleeExpr->getType();
11481 if (CalleeType == S.Context.BoundMemberTy) {
11482 assert(isa<CXXMemberCallExpr>(E) || isa<CXXOperatorCallExpr>(E));
11483 Kind = FK_MemberFunction;
11484 CalleeType = Expr::findBoundMemberType(CalleeExpr);
11485 } else if (const PointerType *Ptr = CalleeType->getAs<PointerType>()) {
11486 CalleeType = Ptr->getPointeeType();
11487 Kind = FK_FunctionPointer;
John McCall379b5152011-04-11 07:02:50 +000011488 } else {
Richard Trieu5e4c80b2011-09-09 03:59:41 +000011489 CalleeType = CalleeType->castAs<BlockPointerType>()->getPointeeType();
11490 Kind = FK_BlockPointer;
John McCall379b5152011-04-11 07:02:50 +000011491 }
Richard Trieu5e4c80b2011-09-09 03:59:41 +000011492 const FunctionType *FnType = CalleeType->castAs<FunctionType>();
John McCall379b5152011-04-11 07:02:50 +000011493
11494 // Verify that this is a legal result type of a function.
11495 if (DestType->isArrayType() || DestType->isFunctionType()) {
11496 unsigned diagID = diag::err_func_returning_array_function;
Richard Trieu5e4c80b2011-09-09 03:59:41 +000011497 if (Kind == FK_BlockPointer)
John McCall379b5152011-04-11 07:02:50 +000011498 diagID = diag::err_block_returning_array_function;
11499
Richard Trieu5e4c80b2011-09-09 03:59:41 +000011500 S.Diag(E->getExprLoc(), diagID)
John McCall379b5152011-04-11 07:02:50 +000011501 << DestType->isFunctionType() << DestType;
11502 return ExprError();
11503 }
11504
11505 // Otherwise, go ahead and set DestType as the call's result.
Richard Trieu5e4c80b2011-09-09 03:59:41 +000011506 E->setType(DestType.getNonLValueExprType(S.Context));
11507 E->setValueKind(Expr::getValueKindForType(DestType));
11508 assert(E->getObjectKind() == OK_Ordinary);
John McCall379b5152011-04-11 07:02:50 +000011509
11510 // Rebuild the function type, replacing the result type with DestType.
Richard Trieu5e4c80b2011-09-09 03:59:41 +000011511 if (const FunctionProtoType *Proto = dyn_cast<FunctionProtoType>(FnType))
John McCall379b5152011-04-11 07:02:50 +000011512 DestType = S.Context.getFunctionType(DestType,
Richard Trieu5e4c80b2011-09-09 03:59:41 +000011513 Proto->arg_type_begin(),
11514 Proto->getNumArgs(),
11515 Proto->getExtProtoInfo());
John McCall379b5152011-04-11 07:02:50 +000011516 else
11517 DestType = S.Context.getFunctionNoProtoType(DestType,
Richard Trieu5e4c80b2011-09-09 03:59:41 +000011518 FnType->getExtInfo());
John McCall379b5152011-04-11 07:02:50 +000011519
11520 // Rebuild the appropriate pointer-to-function type.
Richard Trieu5e4c80b2011-09-09 03:59:41 +000011521 switch (Kind) {
John McCallf5307512011-04-27 00:36:17 +000011522 case FK_MemberFunction:
John McCall379b5152011-04-11 07:02:50 +000011523 // Nothing to do.
11524 break;
11525
11526 case FK_FunctionPointer:
11527 DestType = S.Context.getPointerType(DestType);
11528 break;
11529
11530 case FK_BlockPointer:
11531 DestType = S.Context.getBlockPointerType(DestType);
11532 break;
11533 }
11534
11535 // Finally, we can recurse.
Richard Trieu5e4c80b2011-09-09 03:59:41 +000011536 ExprResult CalleeResult = Visit(CalleeExpr);
11537 if (!CalleeResult.isUsable()) return ExprError();
11538 E->setCallee(CalleeResult.take());
John McCall379b5152011-04-11 07:02:50 +000011539
11540 // Bind a temporary if necessary.
Richard Trieu5e4c80b2011-09-09 03:59:41 +000011541 return S.MaybeBindToTemporary(E);
John McCall379b5152011-04-11 07:02:50 +000011542}
11543
Richard Trieu5e4c80b2011-09-09 03:59:41 +000011544ExprResult RebuildUnknownAnyExpr::VisitObjCMessageExpr(ObjCMessageExpr *E) {
John McCall755d8492011-04-12 00:42:48 +000011545 // Verify that this is a legal result type of a call.
11546 if (DestType->isArrayType() || DestType->isFunctionType()) {
Richard Trieu5e4c80b2011-09-09 03:59:41 +000011547 S.Diag(E->getExprLoc(), diag::err_func_returning_array_function)
John McCall755d8492011-04-12 00:42:48 +000011548 << DestType->isFunctionType() << DestType;
11549 return ExprError();
John McCall379b5152011-04-11 07:02:50 +000011550 }
11551
John McCall48218c62011-07-13 17:56:40 +000011552 // Rewrite the method result type if available.
Richard Trieu5e4c80b2011-09-09 03:59:41 +000011553 if (ObjCMethodDecl *Method = E->getMethodDecl()) {
11554 assert(Method->getResultType() == S.Context.UnknownAnyTy);
11555 Method->setResultType(DestType);
John McCall48218c62011-07-13 17:56:40 +000011556 }
John McCall755d8492011-04-12 00:42:48 +000011557
John McCall379b5152011-04-11 07:02:50 +000011558 // Change the type of the message.
Richard Trieu5e4c80b2011-09-09 03:59:41 +000011559 E->setType(DestType.getNonReferenceType());
11560 E->setValueKind(Expr::getValueKindForType(DestType));
John McCall379b5152011-04-11 07:02:50 +000011561
Richard Trieu5e4c80b2011-09-09 03:59:41 +000011562 return S.MaybeBindToTemporary(E);
John McCall379b5152011-04-11 07:02:50 +000011563}
11564
Richard Trieu5e4c80b2011-09-09 03:59:41 +000011565ExprResult RebuildUnknownAnyExpr::VisitImplicitCastExpr(ImplicitCastExpr *E) {
John McCall755d8492011-04-12 00:42:48 +000011566 // The only case we should ever see here is a function-to-pointer decay.
Sean Callananba66c6c2012-03-06 23:12:57 +000011567 if (E->getCastKind() == CK_FunctionToPointerDecay) {
Sean Callanance9c8312012-03-06 21:34:12 +000011568 assert(E->getValueKind() == VK_RValue);
11569 assert(E->getObjectKind() == OK_Ordinary);
11570
11571 E->setType(DestType);
11572
11573 // Rebuild the sub-expression as the pointee (function) type.
11574 DestType = DestType->castAs<PointerType>()->getPointeeType();
11575
11576 ExprResult Result = Visit(E->getSubExpr());
11577 if (!Result.isUsable()) return ExprError();
11578
11579 E->setSubExpr(Result.take());
11580 return S.Owned(E);
Sean Callananba66c6c2012-03-06 23:12:57 +000011581 } else if (E->getCastKind() == CK_LValueToRValue) {
Sean Callanance9c8312012-03-06 21:34:12 +000011582 assert(E->getValueKind() == VK_RValue);
11583 assert(E->getObjectKind() == OK_Ordinary);
John McCall379b5152011-04-11 07:02:50 +000011584
Sean Callanance9c8312012-03-06 21:34:12 +000011585 assert(isa<BlockPointerType>(E->getType()));
John McCall755d8492011-04-12 00:42:48 +000011586
Sean Callanance9c8312012-03-06 21:34:12 +000011587 E->setType(DestType);
John McCall379b5152011-04-11 07:02:50 +000011588
Sean Callanance9c8312012-03-06 21:34:12 +000011589 // The sub-expression has to be a lvalue reference, so rebuild it as such.
11590 DestType = S.Context.getLValueReferenceType(DestType);
John McCall379b5152011-04-11 07:02:50 +000011591
Sean Callanance9c8312012-03-06 21:34:12 +000011592 ExprResult Result = Visit(E->getSubExpr());
11593 if (!Result.isUsable()) return ExprError();
11594
11595 E->setSubExpr(Result.take());
11596 return S.Owned(E);
Sean Callananba66c6c2012-03-06 23:12:57 +000011597 } else {
Sean Callanance9c8312012-03-06 21:34:12 +000011598 llvm_unreachable("Unhandled cast type!");
11599 }
John McCall379b5152011-04-11 07:02:50 +000011600}
11601
Richard Trieu5e4c80b2011-09-09 03:59:41 +000011602ExprResult RebuildUnknownAnyExpr::resolveDecl(Expr *E, ValueDecl *VD) {
11603 ExprValueKind ValueKind = VK_LValue;
11604 QualType Type = DestType;
John McCall379b5152011-04-11 07:02:50 +000011605
11606 // We know how to make this work for certain kinds of decls:
11607
11608 // - functions
Richard Trieu5e4c80b2011-09-09 03:59:41 +000011609 if (FunctionDecl *FD = dyn_cast<FunctionDecl>(VD)) {
11610 if (const PointerType *Ptr = Type->getAs<PointerType>()) {
11611 DestType = Ptr->getPointeeType();
11612 ExprResult Result = resolveDecl(E, VD);
11613 if (Result.isInvalid()) return ExprError();
11614 return S.ImpCastExprToType(Result.take(), Type,
John McCalla19950e2011-08-10 04:12:23 +000011615 CK_FunctionToPointerDecay, VK_RValue);
11616 }
11617
Richard Trieu5e4c80b2011-09-09 03:59:41 +000011618 if (!Type->isFunctionType()) {
11619 S.Diag(E->getExprLoc(), diag::err_unknown_any_function)
11620 << VD << E->getSourceRange();
John McCalla19950e2011-08-10 04:12:23 +000011621 return ExprError();
11622 }
John McCall379b5152011-04-11 07:02:50 +000011623
Richard Trieu5e4c80b2011-09-09 03:59:41 +000011624 if (CXXMethodDecl *MD = dyn_cast<CXXMethodDecl>(FD))
11625 if (MD->isInstance()) {
11626 ValueKind = VK_RValue;
11627 Type = S.Context.BoundMemberTy;
John McCallf5307512011-04-27 00:36:17 +000011628 }
11629
John McCall379b5152011-04-11 07:02:50 +000011630 // Function references aren't l-values in C.
David Blaikie4e4d0842012-03-11 07:00:24 +000011631 if (!S.getLangOpts().CPlusPlus)
Richard Trieu5e4c80b2011-09-09 03:59:41 +000011632 ValueKind = VK_RValue;
John McCall379b5152011-04-11 07:02:50 +000011633
11634 // - variables
Richard Trieu5e4c80b2011-09-09 03:59:41 +000011635 } else if (isa<VarDecl>(VD)) {
11636 if (const ReferenceType *RefTy = Type->getAs<ReferenceType>()) {
11637 Type = RefTy->getPointeeType();
11638 } else if (Type->isFunctionType()) {
11639 S.Diag(E->getExprLoc(), diag::err_unknown_any_var_function_type)
11640 << VD << E->getSourceRange();
John McCall755d8492011-04-12 00:42:48 +000011641 return ExprError();
John McCall379b5152011-04-11 07:02:50 +000011642 }
11643
11644 // - nothing else
11645 } else {
Richard Trieu5e4c80b2011-09-09 03:59:41 +000011646 S.Diag(E->getExprLoc(), diag::err_unsupported_unknown_any_decl)
11647 << VD << E->getSourceRange();
John McCall379b5152011-04-11 07:02:50 +000011648 return ExprError();
11649 }
11650
Richard Trieu5e4c80b2011-09-09 03:59:41 +000011651 VD->setType(DestType);
11652 E->setType(Type);
11653 E->setValueKind(ValueKind);
11654 return S.Owned(E);
John McCall379b5152011-04-11 07:02:50 +000011655}
11656
John McCall1de4d4e2011-04-07 08:22:57 +000011657/// Check a cast of an unknown-any type. We intentionally only
11658/// trigger this for C-style casts.
Richard Trieuccd891a2011-09-09 01:45:06 +000011659ExprResult Sema::checkUnknownAnyCast(SourceRange TypeRange, QualType CastType,
11660 Expr *CastExpr, CastKind &CastKind,
11661 ExprValueKind &VK, CXXCastPath &Path) {
John McCall1de4d4e2011-04-07 08:22:57 +000011662 // Rewrite the casted expression from scratch.
Richard Trieuccd891a2011-09-09 01:45:06 +000011663 ExprResult result = RebuildUnknownAnyExpr(*this, CastType).Visit(CastExpr);
John McCalla5fc4722011-04-09 22:50:59 +000011664 if (!result.isUsable()) return ExprError();
John McCall1de4d4e2011-04-07 08:22:57 +000011665
Richard Trieuccd891a2011-09-09 01:45:06 +000011666 CastExpr = result.take();
11667 VK = CastExpr->getValueKind();
11668 CastKind = CK_NoOp;
John McCalla5fc4722011-04-09 22:50:59 +000011669
Richard Trieuccd891a2011-09-09 01:45:06 +000011670 return CastExpr;
John McCall1de4d4e2011-04-07 08:22:57 +000011671}
11672
Douglas Gregorf1d1ca52011-12-01 01:37:36 +000011673ExprResult Sema::forceUnknownAnyToType(Expr *E, QualType ToType) {
11674 return RebuildUnknownAnyExpr(*this, ToType).Visit(E);
11675}
11676
Richard Trieuccd891a2011-09-09 01:45:06 +000011677static ExprResult diagnoseUnknownAnyExpr(Sema &S, Expr *E) {
11678 Expr *orig = E;
John McCall379b5152011-04-11 07:02:50 +000011679 unsigned diagID = diag::err_uncasted_use_of_unknown_any;
John McCall1de4d4e2011-04-07 08:22:57 +000011680 while (true) {
Richard Trieuccd891a2011-09-09 01:45:06 +000011681 E = E->IgnoreParenImpCasts();
11682 if (CallExpr *call = dyn_cast<CallExpr>(E)) {
11683 E = call->getCallee();
John McCall379b5152011-04-11 07:02:50 +000011684 diagID = diag::err_uncasted_call_of_unknown_any;
11685 } else {
John McCall1de4d4e2011-04-07 08:22:57 +000011686 break;
John McCall379b5152011-04-11 07:02:50 +000011687 }
John McCall1de4d4e2011-04-07 08:22:57 +000011688 }
11689
John McCall379b5152011-04-11 07:02:50 +000011690 SourceLocation loc;
11691 NamedDecl *d;
Richard Trieuccd891a2011-09-09 01:45:06 +000011692 if (DeclRefExpr *ref = dyn_cast<DeclRefExpr>(E)) {
John McCall379b5152011-04-11 07:02:50 +000011693 loc = ref->getLocation();
11694 d = ref->getDecl();
Richard Trieuccd891a2011-09-09 01:45:06 +000011695 } else if (MemberExpr *mem = dyn_cast<MemberExpr>(E)) {
John McCall379b5152011-04-11 07:02:50 +000011696 loc = mem->getMemberLoc();
11697 d = mem->getMemberDecl();
Richard Trieuccd891a2011-09-09 01:45:06 +000011698 } else if (ObjCMessageExpr *msg = dyn_cast<ObjCMessageExpr>(E)) {
John McCall379b5152011-04-11 07:02:50 +000011699 diagID = diag::err_uncasted_call_of_unknown_any;
Argyrios Kyrtzidis20718082011-10-03 06:36:51 +000011700 loc = msg->getSelectorStartLoc();
John McCall379b5152011-04-11 07:02:50 +000011701 d = msg->getMethodDecl();
John McCall819e7452011-08-31 20:57:36 +000011702 if (!d) {
11703 S.Diag(loc, diag::err_uncasted_send_to_unknown_any_method)
11704 << static_cast<unsigned>(msg->isClassMessage()) << msg->getSelector()
11705 << orig->getSourceRange();
11706 return ExprError();
11707 }
John McCall379b5152011-04-11 07:02:50 +000011708 } else {
Richard Trieuccd891a2011-09-09 01:45:06 +000011709 S.Diag(E->getExprLoc(), diag::err_unsupported_unknown_any_expr)
11710 << E->getSourceRange();
John McCall379b5152011-04-11 07:02:50 +000011711 return ExprError();
11712 }
11713
11714 S.Diag(loc, diagID) << d << orig->getSourceRange();
John McCall1de4d4e2011-04-07 08:22:57 +000011715
11716 // Never recoverable.
11717 return ExprError();
11718}
11719
John McCall2a984ca2010-10-12 00:20:44 +000011720/// Check for operands with placeholder types and complain if found.
11721/// Returns true if there was an error and no recovery was possible.
John McCallfb8721c2011-04-10 19:13:55 +000011722ExprResult Sema::CheckPlaceholderExpr(Expr *E) {
John McCall5acb0c92011-10-17 18:40:02 +000011723 const BuiltinType *placeholderType = E->getType()->getAsPlaceholderType();
11724 if (!placeholderType) return Owned(E);
11725
11726 switch (placeholderType->getKind()) {
John McCall2a984ca2010-10-12 00:20:44 +000011727
John McCall1de4d4e2011-04-07 08:22:57 +000011728 // Overloaded expressions.
John McCall5acb0c92011-10-17 18:40:02 +000011729 case BuiltinType::Overload: {
John McCall6dbba4f2011-10-11 23:14:30 +000011730 // Try to resolve a single function template specialization.
11731 // This is obligatory.
11732 ExprResult result = Owned(E);
11733 if (ResolveAndFixSingleFunctionTemplateSpecialization(result, false)) {
11734 return result;
11735
11736 // If that failed, try to recover with a call.
11737 } else {
11738 tryToRecoverWithCall(result, PDiag(diag::err_ovl_unresolvable),
11739 /*complain*/ true);
11740 return result;
11741 }
11742 }
John McCall1de4d4e2011-04-07 08:22:57 +000011743
John McCall864c0412011-04-26 20:42:42 +000011744 // Bound member functions.
John McCall5acb0c92011-10-17 18:40:02 +000011745 case BuiltinType::BoundMember: {
John McCall6dbba4f2011-10-11 23:14:30 +000011746 ExprResult result = Owned(E);
11747 tryToRecoverWithCall(result, PDiag(diag::err_bound_member_function),
11748 /*complain*/ true);
11749 return result;
John McCall5acb0c92011-10-17 18:40:02 +000011750 }
11751
11752 // ARC unbridged casts.
11753 case BuiltinType::ARCUnbridgedCast: {
11754 Expr *realCast = stripARCUnbridgedCast(E);
11755 diagnoseARCUnbridgedCast(realCast);
11756 return Owned(realCast);
11757 }
John McCall864c0412011-04-26 20:42:42 +000011758
John McCall1de4d4e2011-04-07 08:22:57 +000011759 // Expressions of unknown type.
John McCall5acb0c92011-10-17 18:40:02 +000011760 case BuiltinType::UnknownAny:
John McCall1de4d4e2011-04-07 08:22:57 +000011761 return diagnoseUnknownAnyExpr(*this, E);
11762
John McCall3c3b7f92011-10-25 17:37:35 +000011763 // Pseudo-objects.
11764 case BuiltinType::PseudoObject:
11765 return checkPseudoObjectRValue(E);
11766
Eli Friedmana6c66ce2012-08-31 00:14:07 +000011767 case BuiltinType::BuiltinFn:
11768 Diag(E->getLocStart(), diag::err_builtin_fn_use);
11769 return ExprError();
11770
John McCalle0a22d02011-10-18 21:02:43 +000011771 // Everything else should be impossible.
11772#define BUILTIN_TYPE(Id, SingletonId) \
11773 case BuiltinType::Id:
11774#define PLACEHOLDER_TYPE(Id, SingletonId)
11775#include "clang/AST/BuiltinTypes.def"
John McCall5acb0c92011-10-17 18:40:02 +000011776 break;
11777 }
11778
11779 llvm_unreachable("invalid placeholder type!");
John McCall2a984ca2010-10-12 00:20:44 +000011780}
Richard Trieubb9b80c2011-04-21 21:44:26 +000011781
Richard Trieuccd891a2011-09-09 01:45:06 +000011782bool Sema::CheckCaseExpression(Expr *E) {
11783 if (E->isTypeDependent())
Richard Trieubb9b80c2011-04-21 21:44:26 +000011784 return true;
Richard Trieuccd891a2011-09-09 01:45:06 +000011785 if (E->isValueDependent() || E->isIntegerConstantExpr(Context))
11786 return E->getType()->isIntegralOrEnumerationType();
Richard Trieubb9b80c2011-04-21 21:44:26 +000011787 return false;
11788}
Ted Kremenekebcb57a2012-03-06 20:05:56 +000011789
11790/// ActOnObjCBoolLiteral - Parse {__objc_yes,__objc_no} literals.
11791ExprResult
11792Sema::ActOnObjCBoolLiteral(SourceLocation OpLoc, tok::TokenKind Kind) {
11793 assert((Kind == tok::kw___objc_yes || Kind == tok::kw___objc_no) &&
11794 "Unknown Objective-C Boolean value!");
Fariborz Jahanian96171302012-08-30 18:49:41 +000011795 QualType BoolT = Context.ObjCBuiltinBoolTy;
11796 if (!Context.getBOOLDecl()) {
11797 LookupResult Result(*this, &Context.Idents.get("BOOL"), SourceLocation(),
11798 Sema::LookupOrdinaryName);
11799 if (LookupName(Result, getCurScope())) {
11800 NamedDecl *ND = Result.getFoundDecl();
11801 if (TypedefDecl *TD = dyn_cast<TypedefDecl>(ND))
11802 Context.setBOOLDecl(TD);
11803 }
11804 }
11805 if (Context.getBOOLDecl())
11806 BoolT = Context.getBOOLType();
Ted Kremenekebcb57a2012-03-06 20:05:56 +000011807 return Owned(new (Context) ObjCBoolLiteralExpr(Kind == tok::kw___objc_yes,
Fariborz Jahanian96171302012-08-30 18:49:41 +000011808 BoolT, OpLoc));
Ted Kremenekebcb57a2012-03-06 20:05:56 +000011809}